xref: /qemu/hw/net/vmxnet3.c (revision d64db833d6e3cbe9ea5f36342480f920f3675cea)
1 /*
2  * QEMU VMWARE VMXNET3 paravirtual NIC
3  *
4  * Copyright (c) 2012 Ravello Systems LTD (http://ravellosystems.com)
5  *
6  * Developed by Daynix Computing LTD (http://www.daynix.com)
7  *
8  * Authors:
9  * Dmitry Fleytman <dmitry@daynix.com>
10  * Tamir Shomer <tamirs@daynix.com>
11  * Yan Vugenfirer <yan@daynix.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.
14  * See the COPYING file in the top-level directory.
15  *
16  */
17 
18 #include "qemu/osdep.h"
19 #include "hw/hw.h"
20 #include "hw/pci/pci.h"
21 #include "hw/qdev-properties.h"
22 #include "net/tap.h"
23 #include "net/checksum.h"
24 #include "system/system.h"
25 #include "qemu/bswap.h"
26 #include "qemu/log.h"
27 #include "qemu/module.h"
28 #include "hw/pci/msix.h"
29 #include "hw/pci/msi.h"
30 #include "migration/register.h"
31 #include "migration/vmstate.h"
32 
33 #include "vmxnet3.h"
34 #include "vmxnet3_defs.h"
35 #include "vmxnet_debug.h"
36 #include "vmware_utils.h"
37 #include "net_tx_pkt.h"
38 #include "net_rx_pkt.h"
39 #include "qom/object.h"
40 
41 #define PCI_DEVICE_ID_VMWARE_VMXNET3_REVISION 0x1
42 #define VMXNET3_MSIX_BAR_SIZE 0x2000
43 
44 /* Compatibility flags for migration */
45 #define VMXNET3_COMPAT_FLAG_OLD_MSI_OFFSETS_BIT 0
46 #define VMXNET3_COMPAT_FLAG_OLD_MSI_OFFSETS \
47     (1 << VMXNET3_COMPAT_FLAG_OLD_MSI_OFFSETS_BIT)
48 #define VMXNET3_COMPAT_FLAG_DISABLE_PCIE_BIT 1
49 #define VMXNET3_COMPAT_FLAG_DISABLE_PCIE \
50     (1 << VMXNET3_COMPAT_FLAG_DISABLE_PCIE_BIT)
51 
52 #define VMXNET3_EXP_EP_OFFSET (0x48)
53 #define VMXNET3_MSI_OFFSET(s) \
54     ((s)->compat_flags & VMXNET3_COMPAT_FLAG_OLD_MSI_OFFSETS ? 0x50 : 0x84)
55 #define VMXNET3_MSIX_OFFSET(s) \
56     ((s)->compat_flags & VMXNET3_COMPAT_FLAG_OLD_MSI_OFFSETS ? 0 : 0x9c)
57 #define VMXNET3_DSN_OFFSET     (0x100)
58 
59 #define VMXNET3_BAR0_IDX      (0)
60 #define VMXNET3_BAR1_IDX      (1)
61 #define VMXNET3_MSIX_BAR_IDX  (2)
62 
63 #define VMXNET3_OFF_MSIX_TABLE (0x000)
64 #define VMXNET3_OFF_MSIX_PBA(s) \
65     ((s)->compat_flags & VMXNET3_COMPAT_FLAG_OLD_MSI_OFFSETS ? 0x800 : 0x1000)
66 
67 /* Link speed in Mbps should be shifted by 16 */
68 #define VMXNET3_LINK_SPEED      (1000 << 16)
69 
70 /* Link status: 1 - up, 0 - down. */
71 #define VMXNET3_LINK_STATUS_UP  0x1
72 
73 /* Least significant bit should be set for revision and version */
74 #define VMXNET3_UPT_REVISION      0x1
75 #define VMXNET3_DEVICE_REVISION   0x1
76 
77 /* Number of interrupt vectors for non-MSIx modes */
78 #define VMXNET3_MAX_NMSIX_INTRS   (1)
79 
80 /* Macros for rings descriptors access */
81 #define VMXNET3_READ_TX_QUEUE_DESCR8(_d, dpa, field) \
82     (vmw_shmem_ld8(_d, dpa + offsetof(struct Vmxnet3_TxQueueDesc, field)))
83 
84 #define VMXNET3_WRITE_TX_QUEUE_DESCR8(_d, dpa, field, value) \
85     (vmw_shmem_st8(_d, dpa + offsetof(struct Vmxnet3_TxQueueDesc, field, value)))
86 
87 #define VMXNET3_READ_TX_QUEUE_DESCR32(_d, dpa, field) \
88     (vmw_shmem_ld32(_d, dpa + offsetof(struct Vmxnet3_TxQueueDesc, field)))
89 
90 #define VMXNET3_WRITE_TX_QUEUE_DESCR32(_d, dpa, field, value) \
91     (vmw_shmem_st32(_d, dpa + offsetof(struct Vmxnet3_TxQueueDesc, field), value))
92 
93 #define VMXNET3_READ_TX_QUEUE_DESCR64(_d, dpa, field) \
94     (vmw_shmem_ld64(_d, dpa + offsetof(struct Vmxnet3_TxQueueDesc, field)))
95 
96 #define VMXNET3_WRITE_TX_QUEUE_DESCR64(_d, dpa, field, value) \
97     (vmw_shmem_st64(_d, dpa + offsetof(struct Vmxnet3_TxQueueDesc, field), value))
98 
99 #define VMXNET3_READ_RX_QUEUE_DESCR64(_d, dpa, field) \
100     (vmw_shmem_ld64(_d, dpa + offsetof(struct Vmxnet3_RxQueueDesc, field)))
101 
102 #define VMXNET3_READ_RX_QUEUE_DESCR32(_d, dpa, field) \
103     (vmw_shmem_ld32(_d, dpa + offsetof(struct Vmxnet3_RxQueueDesc, field)))
104 
105 #define VMXNET3_WRITE_RX_QUEUE_DESCR64(_d, dpa, field, value) \
106     (vmw_shmem_st64(_d, dpa + offsetof(struct Vmxnet3_RxQueueDesc, field), value))
107 
108 #define VMXNET3_WRITE_RX_QUEUE_DESCR8(_d, dpa, field, value) \
109     (vmw_shmem_st8(_d, dpa + offsetof(struct Vmxnet3_RxQueueDesc, field), value))
110 
111 /* Macros for guest driver shared area access */
112 #define VMXNET3_READ_DRV_SHARED64(_d, shpa, field) \
113     (vmw_shmem_ld64(_d, shpa + offsetof(struct Vmxnet3_DriverShared, field)))
114 
115 #define VMXNET3_READ_DRV_SHARED32(_d, shpa, field) \
116     (vmw_shmem_ld32(_d, shpa + offsetof(struct Vmxnet3_DriverShared, field)))
117 
118 #define VMXNET3_WRITE_DRV_SHARED32(_d, shpa, field, val) \
119     (vmw_shmem_st32(_d, shpa + offsetof(struct Vmxnet3_DriverShared, field), val))
120 
121 #define VMXNET3_READ_DRV_SHARED16(_d, shpa, field) \
122     (vmw_shmem_ld16(_d, shpa + offsetof(struct Vmxnet3_DriverShared, field)))
123 
124 #define VMXNET3_READ_DRV_SHARED8(_d, shpa, field) \
125     (vmw_shmem_ld8(_d, shpa + offsetof(struct Vmxnet3_DriverShared, field)))
126 
127 #define VMXNET3_READ_DRV_SHARED(_d, shpa, field, b, l) \
128     (vmw_shmem_read(_d, shpa + offsetof(struct Vmxnet3_DriverShared, field), b, l))
129 
130 #define VMXNET_FLAG_IS_SET(field, flag) (((field) & (flag)) == (flag))
131 
132 struct VMXNET3Class {
133     PCIDeviceClass parent_class;
134     DeviceRealize parent_dc_realize;
135 };
136 typedef struct VMXNET3Class VMXNET3Class;
137 
138 DECLARE_CLASS_CHECKERS(VMXNET3Class, VMXNET3_DEVICE,
139                        TYPE_VMXNET3)
140 
141 static inline void vmxnet3_ring_init(PCIDevice *d,
142                                      Vmxnet3Ring *ring,
143                                      hwaddr pa,
144                                      uint32_t size,
145                                      uint32_t cell_size,
146                                      bool zero_region)
147 {
148     ring->pa = pa;
149     ring->size = size;
150     ring->cell_size = cell_size;
151     ring->gen = VMXNET3_INIT_GEN;
152     ring->next = 0;
153 
154     if (zero_region) {
155         vmw_shmem_set(d, pa, 0, size * cell_size);
156     }
157 }
158 
159 #define VMXNET3_RING_DUMP(macro, ring_name, ridx, r)                         \
160     macro("%s#%d: base %" PRIx64 " size %u cell_size %u gen %d next %u",  \
161           (ring_name), (ridx),                                               \
162           (r)->pa, (r)->size, (r)->cell_size, (r)->gen, (r)->next)
163 
164 static inline void vmxnet3_ring_inc(Vmxnet3Ring *ring)
165 {
166     if (++ring->next >= ring->size) {
167         ring->next = 0;
168         ring->gen ^= 1;
169     }
170 }
171 
172 static inline void vmxnet3_ring_dec(Vmxnet3Ring *ring)
173 {
174     if (ring->next-- == 0) {
175         ring->next = ring->size - 1;
176         ring->gen ^= 1;
177     }
178 }
179 
180 static inline hwaddr vmxnet3_ring_curr_cell_pa(Vmxnet3Ring *ring)
181 {
182     return ring->pa + ring->next * ring->cell_size;
183 }
184 
185 static inline void vmxnet3_ring_read_curr_cell(PCIDevice *d, Vmxnet3Ring *ring,
186                                                void *buff)
187 {
188     vmw_shmem_read(d, vmxnet3_ring_curr_cell_pa(ring), buff, ring->cell_size);
189 }
190 
191 static inline void vmxnet3_ring_write_curr_cell(PCIDevice *d, Vmxnet3Ring *ring,
192                                                 void *buff)
193 {
194     vmw_shmem_write(d, vmxnet3_ring_curr_cell_pa(ring), buff, ring->cell_size);
195 }
196 
197 static inline size_t vmxnet3_ring_curr_cell_idx(Vmxnet3Ring *ring)
198 {
199     return ring->next;
200 }
201 
202 static inline uint8_t vmxnet3_ring_curr_gen(Vmxnet3Ring *ring)
203 {
204     return ring->gen;
205 }
206 
207 /* Debug trace-related functions */
208 static inline void
209 vmxnet3_dump_tx_descr(struct Vmxnet3_TxDesc *descr)
210 {
211     VMW_PKPRN("TX DESCR: "
212               "addr %" PRIx64 ", len: %d, gen: %d, rsvd: %d, "
213               "dtype: %d, ext1: %d, msscof: %d, hlen: %d, om: %d, "
214               "eop: %d, cq: %d, ext2: %d, ti: %d, tci: %d",
215               descr->addr, descr->len, descr->gen, descr->rsvd,
216               descr->dtype, descr->ext1, descr->msscof, descr->hlen, descr->om,
217               descr->eop, descr->cq, descr->ext2, descr->ti, descr->tci);
218 }
219 
220 static inline void
221 vmxnet3_dump_virt_hdr(struct virtio_net_hdr *vhdr)
222 {
223     VMW_PKPRN("VHDR: flags 0x%x, gso_type: 0x%x, hdr_len: %d, gso_size: %d, "
224               "csum_start: %d, csum_offset: %d",
225               vhdr->flags, vhdr->gso_type, vhdr->hdr_len, vhdr->gso_size,
226               vhdr->csum_start, vhdr->csum_offset);
227 }
228 
229 static inline void
230 vmxnet3_dump_rx_descr(struct Vmxnet3_RxDesc *descr)
231 {
232     VMW_PKPRN("RX DESCR: addr %" PRIx64 ", len: %d, gen: %d, rsvd: %d, "
233               "dtype: %d, ext1: %d, btype: %d",
234               descr->addr, descr->len, descr->gen,
235               descr->rsvd, descr->dtype, descr->ext1, descr->btype);
236 }
237 
238 /* Interrupt management */
239 
240 /*
241  * This function returns sign whether interrupt line is in asserted state
242  * This depends on the type of interrupt used. For INTX interrupt line will
243  * be asserted until explicit deassertion, for MSI(X) interrupt line will
244  * be deasserted automatically due to notification semantics of the MSI(X)
245  * interrupts
246  */
247 static bool _vmxnet3_assert_interrupt_line(VMXNET3State *s, uint32_t int_idx)
248 {
249     PCIDevice *d = PCI_DEVICE(s);
250 
251     if (s->msix_used && msix_enabled(d)) {
252         VMW_IRPRN("Sending MSI-X notification for vector %u", int_idx);
253         msix_notify(d, int_idx);
254         return false;
255     }
256     if (msi_enabled(d)) {
257         VMW_IRPRN("Sending MSI notification for vector %u", int_idx);
258         msi_notify(d, int_idx);
259         return false;
260     }
261 
262     VMW_IRPRN("Asserting line for interrupt %u", int_idx);
263     pci_irq_assert(d);
264     return true;
265 }
266 
267 static void _vmxnet3_deassert_interrupt_line(VMXNET3State *s, int lidx)
268 {
269     PCIDevice *d = PCI_DEVICE(s);
270 
271     /*
272      * This function should never be called for MSI(X) interrupts
273      * because deassertion never required for message interrupts
274      */
275     assert(!s->msix_used || !msix_enabled(d));
276     /*
277      * This function should never be called for MSI(X) interrupts
278      * because deassertion never required for message interrupts
279      */
280     assert(!msi_enabled(d));
281 
282     VMW_IRPRN("Deasserting line for interrupt %u", lidx);
283     pci_irq_deassert(d);
284 }
285 
286 static void vmxnet3_update_interrupt_line_state(VMXNET3State *s, int lidx)
287 {
288     if (!s->interrupt_states[lidx].is_pending &&
289        s->interrupt_states[lidx].is_asserted) {
290         VMW_IRPRN("New interrupt line state for index %d is DOWN", lidx);
291         _vmxnet3_deassert_interrupt_line(s, lidx);
292         s->interrupt_states[lidx].is_asserted = false;
293         return;
294     }
295 
296     if (s->interrupt_states[lidx].is_pending &&
297        !s->interrupt_states[lidx].is_masked &&
298        !s->interrupt_states[lidx].is_asserted) {
299         VMW_IRPRN("New interrupt line state for index %d is UP", lidx);
300         s->interrupt_states[lidx].is_asserted =
301             _vmxnet3_assert_interrupt_line(s, lidx);
302         s->interrupt_states[lidx].is_pending = false;
303         return;
304     }
305 }
306 
307 static void vmxnet3_trigger_interrupt(VMXNET3State *s, int lidx)
308 {
309     PCIDevice *d = PCI_DEVICE(s);
310     s->interrupt_states[lidx].is_pending = true;
311     vmxnet3_update_interrupt_line_state(s, lidx);
312 
313     if (s->msix_used && msix_enabled(d) && s->auto_int_masking) {
314         goto do_automask;
315     }
316 
317     if (msi_enabled(d) && s->auto_int_masking) {
318         goto do_automask;
319     }
320 
321     return;
322 
323 do_automask:
324     s->interrupt_states[lidx].is_masked = true;
325     vmxnet3_update_interrupt_line_state(s, lidx);
326 }
327 
328 static bool vmxnet3_interrupt_asserted(VMXNET3State *s, int lidx)
329 {
330     return s->interrupt_states[lidx].is_asserted;
331 }
332 
333 static void vmxnet3_clear_interrupt(VMXNET3State *s, int int_idx)
334 {
335     s->interrupt_states[int_idx].is_pending = false;
336     if (s->auto_int_masking) {
337         s->interrupt_states[int_idx].is_masked = true;
338     }
339     vmxnet3_update_interrupt_line_state(s, int_idx);
340 }
341 
342 static void
343 vmxnet3_on_interrupt_mask_changed(VMXNET3State *s, int lidx, bool is_masked)
344 {
345     s->interrupt_states[lidx].is_masked = is_masked;
346     vmxnet3_update_interrupt_line_state(s, lidx);
347 }
348 
349 static bool vmxnet3_verify_driver_magic(PCIDevice *d, hwaddr dshmem)
350 {
351     return (VMXNET3_READ_DRV_SHARED32(d, dshmem, magic) == VMXNET3_REV1_MAGIC);
352 }
353 
354 #define VMXNET3_GET_BYTE(x, byte_num) (((x) >> (byte_num)*8) & 0xFF)
355 #define VMXNET3_MAKE_BYTE(byte_num, val) \
356     (((uint32_t)((val) & 0xFF)) << (byte_num)*8)
357 
358 static void vmxnet3_set_variable_mac(VMXNET3State *s, uint32_t h, uint32_t l)
359 {
360     s->conf.macaddr.a[0] = VMXNET3_GET_BYTE(l,  0);
361     s->conf.macaddr.a[1] = VMXNET3_GET_BYTE(l,  1);
362     s->conf.macaddr.a[2] = VMXNET3_GET_BYTE(l,  2);
363     s->conf.macaddr.a[3] = VMXNET3_GET_BYTE(l,  3);
364     s->conf.macaddr.a[4] = VMXNET3_GET_BYTE(h, 0);
365     s->conf.macaddr.a[5] = VMXNET3_GET_BYTE(h, 1);
366 
367     VMW_CFPRN("Variable MAC: " MAC_FMT, MAC_ARG(s->conf.macaddr.a));
368 
369     qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a);
370 }
371 
372 static uint64_t vmxnet3_get_mac_low(MACAddr *addr)
373 {
374     return VMXNET3_MAKE_BYTE(0, addr->a[0]) |
375            VMXNET3_MAKE_BYTE(1, addr->a[1]) |
376            VMXNET3_MAKE_BYTE(2, addr->a[2]) |
377            VMXNET3_MAKE_BYTE(3, addr->a[3]);
378 }
379 
380 static uint64_t vmxnet3_get_mac_high(MACAddr *addr)
381 {
382     return VMXNET3_MAKE_BYTE(0, addr->a[4]) |
383            VMXNET3_MAKE_BYTE(1, addr->a[5]);
384 }
385 
386 static void
387 vmxnet3_inc_tx_consumption_counter(VMXNET3State *s, int qidx)
388 {
389     vmxnet3_ring_inc(&s->txq_descr[qidx].tx_ring);
390 }
391 
392 static inline void
393 vmxnet3_inc_rx_consumption_counter(VMXNET3State *s, int qidx, int ridx)
394 {
395     vmxnet3_ring_inc(&s->rxq_descr[qidx].rx_ring[ridx]);
396 }
397 
398 static inline void
399 vmxnet3_inc_tx_completion_counter(VMXNET3State *s, int qidx)
400 {
401     vmxnet3_ring_inc(&s->txq_descr[qidx].comp_ring);
402 }
403 
404 static void
405 vmxnet3_inc_rx_completion_counter(VMXNET3State *s, int qidx)
406 {
407     vmxnet3_ring_inc(&s->rxq_descr[qidx].comp_ring);
408 }
409 
410 static void
411 vmxnet3_dec_rx_completion_counter(VMXNET3State *s, int qidx)
412 {
413     vmxnet3_ring_dec(&s->rxq_descr[qidx].comp_ring);
414 }
415 
416 static void vmxnet3_complete_packet(VMXNET3State *s, int qidx, uint32_t tx_ridx)
417 {
418     struct Vmxnet3_TxCompDesc txcq_descr;
419     PCIDevice *d = PCI_DEVICE(s);
420 
421     VMXNET3_RING_DUMP(VMW_RIPRN, "TXC", qidx, &s->txq_descr[qidx].comp_ring);
422 
423     memset(&txcq_descr, 0, sizeof(txcq_descr));
424     txcq_descr.txdIdx = tx_ridx;
425     txcq_descr.gen = vmxnet3_ring_curr_gen(&s->txq_descr[qidx].comp_ring);
426     txcq_descr.val1 = cpu_to_le32(txcq_descr.val1);
427     txcq_descr.val2 = cpu_to_le32(txcq_descr.val2);
428     vmxnet3_ring_write_curr_cell(d, &s->txq_descr[qidx].comp_ring, &txcq_descr);
429 
430     /* Flush changes in TX descriptor before changing the counter value */
431     smp_wmb();
432 
433     vmxnet3_inc_tx_completion_counter(s, qidx);
434     vmxnet3_trigger_interrupt(s, s->txq_descr[qidx].intr_idx);
435 }
436 
437 static bool
438 vmxnet3_setup_tx_offloads(VMXNET3State *s)
439 {
440     switch (s->offload_mode) {
441     case VMXNET3_OM_NONE:
442         return net_tx_pkt_build_vheader(s->tx_pkt, false, false, 0);
443 
444     case VMXNET3_OM_CSUM:
445         VMW_PKPRN("L4 CSO requested\n");
446         return net_tx_pkt_build_vheader(s->tx_pkt, false, true, 0);
447 
448     case VMXNET3_OM_TSO:
449         VMW_PKPRN("GSO offload requested.");
450         if (!net_tx_pkt_build_vheader(s->tx_pkt, true, true,
451             s->cso_or_gso_size)) {
452             return false;
453         }
454         net_tx_pkt_update_ip_checksums(s->tx_pkt);
455         break;
456 
457     default:
458         g_assert_not_reached();
459     }
460 
461     return true;
462 }
463 
464 static void
465 vmxnet3_tx_retrieve_metadata(VMXNET3State *s,
466                              const struct Vmxnet3_TxDesc *txd)
467 {
468     s->offload_mode = txd->om;
469     s->cso_or_gso_size = txd->msscof;
470     s->tci = txd->tci;
471     s->needs_vlan = txd->ti;
472 }
473 
474 typedef enum {
475     VMXNET3_PKT_STATUS_OK,
476     VMXNET3_PKT_STATUS_ERROR,
477     VMXNET3_PKT_STATUS_DISCARD,/* only for tx */
478     VMXNET3_PKT_STATUS_OUT_OF_BUF /* only for rx */
479 } Vmxnet3PktStatus;
480 
481 static void
482 vmxnet3_on_tx_done_update_stats(VMXNET3State *s, int qidx,
483     Vmxnet3PktStatus status)
484 {
485     size_t tot_len = net_tx_pkt_get_total_len(s->tx_pkt);
486     struct UPT1_TxStats *stats = &s->txq_descr[qidx].txq_stats;
487 
488     switch (status) {
489     case VMXNET3_PKT_STATUS_OK:
490         switch (net_tx_pkt_get_packet_type(s->tx_pkt)) {
491         case ETH_PKT_BCAST:
492             stats->bcastPktsTxOK++;
493             stats->bcastBytesTxOK += tot_len;
494             break;
495         case ETH_PKT_MCAST:
496             stats->mcastPktsTxOK++;
497             stats->mcastBytesTxOK += tot_len;
498             break;
499         case ETH_PKT_UCAST:
500             stats->ucastPktsTxOK++;
501             stats->ucastBytesTxOK += tot_len;
502             break;
503         default:
504             g_assert_not_reached();
505         }
506 
507         if (s->offload_mode == VMXNET3_OM_TSO) {
508             /*
509              * According to VMWARE headers this statistic is a number
510              * of packets after segmentation but since we don't have
511              * this information in QEMU model, the best we can do is to
512              * provide number of non-segmented packets
513              */
514             stats->TSOPktsTxOK++;
515             stats->TSOBytesTxOK += tot_len;
516         }
517         break;
518 
519     case VMXNET3_PKT_STATUS_DISCARD:
520         stats->pktsTxDiscard++;
521         break;
522 
523     case VMXNET3_PKT_STATUS_ERROR:
524         stats->pktsTxError++;
525         break;
526 
527     default:
528         g_assert_not_reached();
529     }
530 }
531 
532 static void
533 vmxnet3_on_rx_done_update_stats(VMXNET3State *s,
534                                 int qidx,
535                                 Vmxnet3PktStatus status)
536 {
537     struct UPT1_RxStats *stats = &s->rxq_descr[qidx].rxq_stats;
538     size_t tot_len = net_rx_pkt_get_total_len(s->rx_pkt);
539 
540     switch (status) {
541     case VMXNET3_PKT_STATUS_OUT_OF_BUF:
542         stats->pktsRxOutOfBuf++;
543         break;
544 
545     case VMXNET3_PKT_STATUS_ERROR:
546         stats->pktsRxError++;
547         break;
548     case VMXNET3_PKT_STATUS_OK:
549         switch (net_rx_pkt_get_packet_type(s->rx_pkt)) {
550         case ETH_PKT_BCAST:
551             stats->bcastPktsRxOK++;
552             stats->bcastBytesRxOK += tot_len;
553             break;
554         case ETH_PKT_MCAST:
555             stats->mcastPktsRxOK++;
556             stats->mcastBytesRxOK += tot_len;
557             break;
558         case ETH_PKT_UCAST:
559             stats->ucastPktsRxOK++;
560             stats->ucastBytesRxOK += tot_len;
561             break;
562         default:
563             g_assert_not_reached();
564         }
565 
566         if (tot_len > s->mtu) {
567             stats->LROPktsRxOK++;
568             stats->LROBytesRxOK += tot_len;
569         }
570         break;
571     default:
572         g_assert_not_reached();
573     }
574 }
575 
576 static inline void
577 vmxnet3_ring_read_curr_txdesc(PCIDevice *pcidev, Vmxnet3Ring *ring,
578                               struct Vmxnet3_TxDesc *txd)
579 {
580     vmxnet3_ring_read_curr_cell(pcidev, ring, txd);
581     txd->addr = le64_to_cpu(txd->addr);
582     txd->val1 = le32_to_cpu(txd->val1);
583     txd->val2 = le32_to_cpu(txd->val2);
584 }
585 
586 static inline bool
587 vmxnet3_pop_next_tx_descr(VMXNET3State *s,
588                           int qidx,
589                           struct Vmxnet3_TxDesc *txd,
590                           uint32_t *descr_idx)
591 {
592     Vmxnet3Ring *ring = &s->txq_descr[qidx].tx_ring;
593     PCIDevice *d = PCI_DEVICE(s);
594 
595     vmxnet3_ring_read_curr_txdesc(d, ring, txd);
596     if (txd->gen == vmxnet3_ring_curr_gen(ring)) {
597         /* Only read after generation field verification */
598         smp_rmb();
599         /* Re-read to be sure we got the latest version */
600         vmxnet3_ring_read_curr_txdesc(d, ring, txd);
601         VMXNET3_RING_DUMP(VMW_RIPRN, "TX", qidx, ring);
602         *descr_idx = vmxnet3_ring_curr_cell_idx(ring);
603         vmxnet3_inc_tx_consumption_counter(s, qidx);
604         return true;
605     }
606 
607     return false;
608 }
609 
610 static bool
611 vmxnet3_send_packet(VMXNET3State *s, uint32_t qidx)
612 {
613     Vmxnet3PktStatus status = VMXNET3_PKT_STATUS_OK;
614 
615     if (!vmxnet3_setup_tx_offloads(s)) {
616         status = VMXNET3_PKT_STATUS_ERROR;
617         goto func_exit;
618     }
619 
620     /* debug prints */
621     vmxnet3_dump_virt_hdr(net_tx_pkt_get_vhdr(s->tx_pkt));
622     net_tx_pkt_dump(s->tx_pkt);
623 
624     if (!net_tx_pkt_send(s->tx_pkt, qemu_get_queue(s->nic))) {
625         status = VMXNET3_PKT_STATUS_DISCARD;
626         goto func_exit;
627     }
628 
629 func_exit:
630     vmxnet3_on_tx_done_update_stats(s, qidx, status);
631     return (status == VMXNET3_PKT_STATUS_OK);
632 }
633 
634 static void vmxnet3_process_tx_queue(VMXNET3State *s, int qidx)
635 {
636     struct Vmxnet3_TxDesc txd;
637     uint32_t txd_idx;
638     uint32_t data_len;
639     hwaddr data_pa;
640 
641     for (;;) {
642         if (!vmxnet3_pop_next_tx_descr(s, qidx, &txd, &txd_idx)) {
643             break;
644         }
645 
646         vmxnet3_dump_tx_descr(&txd);
647 
648         if (!s->skip_current_tx_pkt) {
649             data_len = (txd.len > 0) ? txd.len : VMXNET3_MAX_TX_BUF_SIZE;
650             data_pa = txd.addr;
651 
652             if (!net_tx_pkt_add_raw_fragment_pci(s->tx_pkt, PCI_DEVICE(s),
653                                                  data_pa, data_len)) {
654                 s->skip_current_tx_pkt = true;
655             }
656         }
657 
658         if (s->tx_sop) {
659             vmxnet3_tx_retrieve_metadata(s, &txd);
660             s->tx_sop = false;
661         }
662 
663         if (txd.eop) {
664             if (!s->skip_current_tx_pkt && net_tx_pkt_parse(s->tx_pkt)) {
665                 if (s->needs_vlan) {
666                     net_tx_pkt_setup_vlan_header(s->tx_pkt, s->tci);
667                 }
668 
669                 vmxnet3_send_packet(s, qidx);
670             } else {
671                 vmxnet3_on_tx_done_update_stats(s, qidx,
672                                                 VMXNET3_PKT_STATUS_ERROR);
673             }
674 
675             vmxnet3_complete_packet(s, qidx, txd_idx);
676             s->tx_sop = true;
677             s->skip_current_tx_pkt = false;
678             net_tx_pkt_reset(s->tx_pkt,
679                              net_tx_pkt_unmap_frag_pci, PCI_DEVICE(s));
680         }
681     }
682 
683     net_tx_pkt_reset(s->tx_pkt, net_tx_pkt_unmap_frag_pci, PCI_DEVICE(s));
684 }
685 
686 static inline void
687 vmxnet3_read_next_rx_descr(VMXNET3State *s, int qidx, int ridx,
688                            struct Vmxnet3_RxDesc *dbuf, uint32_t *didx)
689 {
690     PCIDevice *d = PCI_DEVICE(s);
691 
692     Vmxnet3Ring *ring = &s->rxq_descr[qidx].rx_ring[ridx];
693     *didx = vmxnet3_ring_curr_cell_idx(ring);
694     vmxnet3_ring_read_curr_cell(d, ring, dbuf);
695     dbuf->addr = le64_to_cpu(dbuf->addr);
696     dbuf->val1 = le32_to_cpu(dbuf->val1);
697     dbuf->ext1 = le32_to_cpu(dbuf->ext1);
698 }
699 
700 static inline uint8_t
701 vmxnet3_get_rx_ring_gen(VMXNET3State *s, int qidx, int ridx)
702 {
703     return s->rxq_descr[qidx].rx_ring[ridx].gen;
704 }
705 
706 static inline hwaddr
707 vmxnet3_pop_rxc_descr(VMXNET3State *s, int qidx, uint32_t *descr_gen)
708 {
709     uint8_t ring_gen;
710     struct Vmxnet3_RxCompDesc rxcd;
711 
712     hwaddr daddr =
713         vmxnet3_ring_curr_cell_pa(&s->rxq_descr[qidx].comp_ring);
714 
715     pci_dma_read(PCI_DEVICE(s),
716                  daddr, &rxcd, sizeof(struct Vmxnet3_RxCompDesc));
717     rxcd.val1 = le32_to_cpu(rxcd.val1);
718     rxcd.val2 = le32_to_cpu(rxcd.val2);
719     rxcd.val3 = le32_to_cpu(rxcd.val3);
720     ring_gen = vmxnet3_ring_curr_gen(&s->rxq_descr[qidx].comp_ring);
721 
722     if (rxcd.gen != ring_gen) {
723         *descr_gen = ring_gen;
724         vmxnet3_inc_rx_completion_counter(s, qidx);
725         return daddr;
726     }
727 
728     return 0;
729 }
730 
731 static inline void
732 vmxnet3_revert_rxc_descr(VMXNET3State *s, int qidx)
733 {
734     vmxnet3_dec_rx_completion_counter(s, qidx);
735 }
736 
737 #define RXQ_IDX      (0)
738 #define RX_HEAD_BODY_RING (0)
739 #define RX_BODY_ONLY_RING (1)
740 
741 static bool
742 vmxnet3_get_next_head_rx_descr(VMXNET3State *s,
743                                struct Vmxnet3_RxDesc *descr_buf,
744                                uint32_t *descr_idx,
745                                uint32_t *ridx)
746 {
747     for (;;) {
748         uint32_t ring_gen;
749         vmxnet3_read_next_rx_descr(s, RXQ_IDX, RX_HEAD_BODY_RING,
750                                    descr_buf, descr_idx);
751 
752         /* If no more free descriptors - return */
753         ring_gen = vmxnet3_get_rx_ring_gen(s, RXQ_IDX, RX_HEAD_BODY_RING);
754         if (descr_buf->gen != ring_gen) {
755             return false;
756         }
757 
758         /* Only read after generation field verification */
759         smp_rmb();
760         /* Re-read to be sure we got the latest version */
761         vmxnet3_read_next_rx_descr(s, RXQ_IDX, RX_HEAD_BODY_RING,
762                                    descr_buf, descr_idx);
763 
764         /* Mark current descriptor as used/skipped */
765         vmxnet3_inc_rx_consumption_counter(s, RXQ_IDX, RX_HEAD_BODY_RING);
766 
767         /* If this is what we are looking for - return */
768         if (descr_buf->btype == VMXNET3_RXD_BTYPE_HEAD) {
769             *ridx = RX_HEAD_BODY_RING;
770             return true;
771         }
772     }
773 }
774 
775 static bool
776 vmxnet3_get_next_body_rx_descr(VMXNET3State *s,
777                                struct Vmxnet3_RxDesc *d,
778                                uint32_t *didx,
779                                uint32_t *ridx)
780 {
781     vmxnet3_read_next_rx_descr(s, RXQ_IDX, RX_HEAD_BODY_RING, d, didx);
782 
783     /* Try to find corresponding descriptor in head/body ring */
784     if (d->gen == vmxnet3_get_rx_ring_gen(s, RXQ_IDX, RX_HEAD_BODY_RING)) {
785         /* Only read after generation field verification */
786         smp_rmb();
787         /* Re-read to be sure we got the latest version */
788         vmxnet3_read_next_rx_descr(s, RXQ_IDX, RX_HEAD_BODY_RING, d, didx);
789         if (d->btype == VMXNET3_RXD_BTYPE_BODY) {
790             vmxnet3_inc_rx_consumption_counter(s, RXQ_IDX, RX_HEAD_BODY_RING);
791             *ridx = RX_HEAD_BODY_RING;
792             return true;
793         }
794     }
795 
796     /*
797      * If there is no free descriptors on head/body ring or next free
798      * descriptor is a head descriptor switch to body only ring
799      */
800     vmxnet3_read_next_rx_descr(s, RXQ_IDX, RX_BODY_ONLY_RING, d, didx);
801 
802     /* If no more free descriptors - return */
803     if (d->gen == vmxnet3_get_rx_ring_gen(s, RXQ_IDX, RX_BODY_ONLY_RING)) {
804         /* Only read after generation field verification */
805         smp_rmb();
806         /* Re-read to be sure we got the latest version */
807         vmxnet3_read_next_rx_descr(s, RXQ_IDX, RX_BODY_ONLY_RING, d, didx);
808         assert(d->btype == VMXNET3_RXD_BTYPE_BODY);
809         *ridx = RX_BODY_ONLY_RING;
810         vmxnet3_inc_rx_consumption_counter(s, RXQ_IDX, RX_BODY_ONLY_RING);
811         return true;
812     }
813 
814     return false;
815 }
816 
817 static inline bool
818 vmxnet3_get_next_rx_descr(VMXNET3State *s, bool is_head,
819                           struct Vmxnet3_RxDesc *descr_buf,
820                           uint32_t *descr_idx,
821                           uint32_t *ridx)
822 {
823     if (is_head || !s->rx_packets_compound) {
824         return vmxnet3_get_next_head_rx_descr(s, descr_buf, descr_idx, ridx);
825     } else {
826         return vmxnet3_get_next_body_rx_descr(s, descr_buf, descr_idx, ridx);
827     }
828 }
829 
830 /* In case packet was csum offloaded (either NEEDS_CSUM or DATA_VALID),
831  * the implementation always passes an RxCompDesc with a "Checksum
832  * calculated and found correct" to the OS (cnc=0 and tuc=1, see
833  * vmxnet3_rx_update_descr). This emulates the observed ESXi behavior.
834  *
835  * Therefore, if packet has the NEEDS_CSUM set, we must calculate
836  * and place a fully computed checksum into the tcp/udp header.
837  * Otherwise, the OS driver will receive a checksum-correct indication
838  * (CHECKSUM_UNNECESSARY), but with the actual tcp/udp checksum field
839  * having just the pseudo header csum value.
840  *
841  * While this is not a problem if packet is destined for local delivery,
842  * in the case the host OS performs forwarding, it will forward an
843  * incorrectly checksummed packet.
844  */
845 static void vmxnet3_rx_need_csum_calculate(struct NetRxPkt *pkt,
846                                            const void *pkt_data,
847                                            size_t pkt_len)
848 {
849     struct virtio_net_hdr *vhdr;
850     bool hasip4, hasip6;
851     EthL4HdrProto l4hdr_proto;
852     uint8_t *data;
853     int len;
854 
855     vhdr = net_rx_pkt_get_vhdr(pkt);
856     if (!VMXNET_FLAG_IS_SET(vhdr->flags, VIRTIO_NET_HDR_F_NEEDS_CSUM)) {
857         return;
858     }
859 
860     net_rx_pkt_get_protocols(pkt, &hasip4, &hasip6, &l4hdr_proto);
861     if (!(hasip4 || hasip6) ||
862         (l4hdr_proto != ETH_L4_HDR_PROTO_TCP &&
863          l4hdr_proto != ETH_L4_HDR_PROTO_UDP)) {
864         return;
865     }
866 
867     vmxnet3_dump_virt_hdr(vhdr);
868 
869     /* Validate packet len: csum_start + scum_offset + length of csum field */
870     if (pkt_len < (vhdr->csum_start + vhdr->csum_offset + 2)) {
871         VMW_PKPRN("packet len:%zu < csum_start(%d) + csum_offset(%d) + 2, "
872                   "cannot calculate checksum",
873                   pkt_len, vhdr->csum_start, vhdr->csum_offset);
874         return;
875     }
876 
877     data = (uint8_t *)pkt_data + vhdr->csum_start;
878     len = pkt_len - vhdr->csum_start;
879     /* Put the checksum obtained into the packet */
880     stw_be_p(data + vhdr->csum_offset,
881              net_checksum_finish_nozero(net_checksum_add(len, data)));
882 
883     vhdr->flags &= ~VIRTIO_NET_HDR_F_NEEDS_CSUM;
884     vhdr->flags |= VIRTIO_NET_HDR_F_DATA_VALID;
885 }
886 
887 static void vmxnet3_rx_update_descr(struct NetRxPkt *pkt,
888     struct Vmxnet3_RxCompDesc *rxcd)
889 {
890     int csum_ok, is_gso;
891     bool hasip4, hasip6;
892     EthL4HdrProto l4hdr_proto;
893     struct virtio_net_hdr *vhdr;
894     uint8_t offload_type;
895 
896     if (net_rx_pkt_is_vlan_stripped(pkt)) {
897         rxcd->ts = 1;
898         rxcd->tci = net_rx_pkt_get_vlan_tag(pkt);
899     }
900 
901     vhdr = net_rx_pkt_get_vhdr(pkt);
902     /*
903      * Checksum is valid when lower level tell so or when lower level
904      * requires checksum offload telling that packet produced/bridged
905      * locally and did travel over network after last checksum calculation
906      * or production
907      */
908     csum_ok = VMXNET_FLAG_IS_SET(vhdr->flags, VIRTIO_NET_HDR_F_DATA_VALID) ||
909               VMXNET_FLAG_IS_SET(vhdr->flags, VIRTIO_NET_HDR_F_NEEDS_CSUM);
910 
911     offload_type = vhdr->gso_type & ~VIRTIO_NET_HDR_GSO_ECN;
912     is_gso = (offload_type != VIRTIO_NET_HDR_GSO_NONE) ? 1 : 0;
913 
914     if (!csum_ok && !is_gso) {
915         goto nocsum;
916     }
917 
918     net_rx_pkt_get_protocols(pkt, &hasip4, &hasip6, &l4hdr_proto);
919     if ((l4hdr_proto != ETH_L4_HDR_PROTO_TCP &&
920          l4hdr_proto != ETH_L4_HDR_PROTO_UDP) ||
921         (!hasip4 && !hasip6)) {
922         goto nocsum;
923     }
924 
925     rxcd->cnc = 0;
926     rxcd->v4 = hasip4 ? 1 : 0;
927     rxcd->v6 = hasip6 ? 1 : 0;
928     rxcd->tcp = l4hdr_proto == ETH_L4_HDR_PROTO_TCP;
929     rxcd->udp = l4hdr_proto == ETH_L4_HDR_PROTO_UDP;
930     rxcd->fcs = rxcd->tuc = rxcd->ipc = 1;
931     return;
932 
933 nocsum:
934     rxcd->cnc = 1;
935 }
936 
937 static void
938 vmxnet3_pci_dma_writev(PCIDevice *pci_dev,
939                        const struct iovec *iov,
940                        size_t start_iov_off,
941                        hwaddr target_addr,
942                        size_t bytes_to_copy)
943 {
944     size_t curr_off = 0;
945     size_t copied = 0;
946 
947     while (bytes_to_copy) {
948         if (start_iov_off < (curr_off + iov->iov_len)) {
949             size_t chunk_len =
950                 MIN((curr_off + iov->iov_len) - start_iov_off, bytes_to_copy);
951 
952             pci_dma_write(pci_dev, target_addr + copied,
953                           iov->iov_base + start_iov_off - curr_off,
954                           chunk_len);
955 
956             copied += chunk_len;
957             start_iov_off += chunk_len;
958             curr_off = start_iov_off;
959             bytes_to_copy -= chunk_len;
960         } else {
961             curr_off += iov->iov_len;
962         }
963         iov++;
964     }
965 }
966 
967 static void
968 vmxnet3_pci_dma_write_rxcd(PCIDevice *pcidev, dma_addr_t pa,
969                            struct Vmxnet3_RxCompDesc *rxcd)
970 {
971     rxcd->val1 = cpu_to_le32(rxcd->val1);
972     rxcd->val2 = cpu_to_le32(rxcd->val2);
973     rxcd->val3 = cpu_to_le32(rxcd->val3);
974     pci_dma_write(pcidev, pa, rxcd, sizeof(*rxcd));
975 }
976 
977 static bool
978 vmxnet3_indicate_packet(VMXNET3State *s)
979 {
980     struct Vmxnet3_RxDesc rxd;
981     PCIDevice *d = PCI_DEVICE(s);
982     bool is_head = true;
983     uint32_t rxd_idx;
984     uint32_t rx_ridx = 0;
985 
986     struct Vmxnet3_RxCompDesc rxcd;
987     uint32_t new_rxcd_gen = VMXNET3_INIT_GEN;
988     hwaddr new_rxcd_pa = 0;
989     hwaddr ready_rxcd_pa = 0;
990     struct iovec *data = net_rx_pkt_get_iovec(s->rx_pkt);
991     size_t bytes_copied = 0;
992     size_t bytes_left = net_rx_pkt_get_total_len(s->rx_pkt);
993     uint16_t num_frags = 0;
994     size_t chunk_size;
995 
996     net_rx_pkt_dump(s->rx_pkt);
997 
998     while (bytes_left > 0) {
999 
1000         /* cannot add more frags to packet */
1001         if (num_frags == s->max_rx_frags) {
1002             break;
1003         }
1004 
1005         new_rxcd_pa = vmxnet3_pop_rxc_descr(s, RXQ_IDX, &new_rxcd_gen);
1006         if (!new_rxcd_pa) {
1007             break;
1008         }
1009 
1010         if (!vmxnet3_get_next_rx_descr(s, is_head, &rxd, &rxd_idx, &rx_ridx)) {
1011             break;
1012         }
1013 
1014         chunk_size = MIN(bytes_left, rxd.len);
1015         vmxnet3_pci_dma_writev(d, data, bytes_copied, rxd.addr, chunk_size);
1016         bytes_copied += chunk_size;
1017         bytes_left -= chunk_size;
1018 
1019         vmxnet3_dump_rx_descr(&rxd);
1020 
1021         if (ready_rxcd_pa != 0) {
1022             vmxnet3_pci_dma_write_rxcd(d, ready_rxcd_pa, &rxcd);
1023         }
1024 
1025         memset(&rxcd, 0, sizeof(struct Vmxnet3_RxCompDesc));
1026         rxcd.rxdIdx = rxd_idx;
1027         rxcd.len = chunk_size;
1028         rxcd.sop = is_head;
1029         rxcd.gen = new_rxcd_gen;
1030         rxcd.rqID = RXQ_IDX + rx_ridx * s->rxq_num;
1031 
1032         if (bytes_left == 0) {
1033             vmxnet3_rx_update_descr(s->rx_pkt, &rxcd);
1034         }
1035 
1036         VMW_RIPRN("RX Completion descriptor: rxRing: %lu rxIdx %lu len %lu "
1037                   "sop %d csum_correct %lu",
1038                   (unsigned long) rx_ridx,
1039                   (unsigned long) rxcd.rxdIdx,
1040                   (unsigned long) rxcd.len,
1041                   (int) rxcd.sop,
1042                   (unsigned long) rxcd.tuc);
1043 
1044         is_head = false;
1045         ready_rxcd_pa = new_rxcd_pa;
1046         new_rxcd_pa = 0;
1047         num_frags++;
1048     }
1049 
1050     if (ready_rxcd_pa != 0) {
1051         rxcd.eop = 1;
1052         rxcd.err = (bytes_left != 0);
1053 
1054         vmxnet3_pci_dma_write_rxcd(d, ready_rxcd_pa, &rxcd);
1055 
1056         /* Flush RX descriptor changes */
1057         smp_wmb();
1058     }
1059 
1060     if (new_rxcd_pa != 0) {
1061         vmxnet3_revert_rxc_descr(s, RXQ_IDX);
1062     }
1063 
1064     vmxnet3_trigger_interrupt(s, s->rxq_descr[RXQ_IDX].intr_idx);
1065 
1066     if (bytes_left == 0) {
1067         vmxnet3_on_rx_done_update_stats(s, RXQ_IDX, VMXNET3_PKT_STATUS_OK);
1068         return true;
1069     } else if (num_frags == s->max_rx_frags) {
1070         vmxnet3_on_rx_done_update_stats(s, RXQ_IDX, VMXNET3_PKT_STATUS_ERROR);
1071         return false;
1072     } else {
1073         vmxnet3_on_rx_done_update_stats(s, RXQ_IDX,
1074                                         VMXNET3_PKT_STATUS_OUT_OF_BUF);
1075         return false;
1076     }
1077 }
1078 
1079 static void
1080 vmxnet3_io_bar0_write(void *opaque, hwaddr addr,
1081                       uint64_t val, unsigned size)
1082 {
1083     VMXNET3State *s = opaque;
1084 
1085     if (!s->device_active) {
1086         return;
1087     }
1088 
1089     if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_TXPROD,
1090                         VMXNET3_DEVICE_MAX_TX_QUEUES, VMXNET3_REG_ALIGN)) {
1091         int tx_queue_idx =
1092             VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_TXPROD,
1093                                      VMXNET3_REG_ALIGN);
1094         if (tx_queue_idx <= s->txq_num) {
1095             vmxnet3_process_tx_queue(s, tx_queue_idx);
1096         } else {
1097             qemu_log_mask(LOG_GUEST_ERROR, "vmxnet3: Illegal TX queue %d/%d\n",
1098                           tx_queue_idx, s->txq_num);
1099         }
1100         return;
1101     }
1102 
1103     if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR,
1104                         VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) {
1105         int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR,
1106                                          VMXNET3_REG_ALIGN);
1107 
1108         VMW_CBPRN("Interrupt mask for line %d written: 0x%" PRIx64, l, val);
1109 
1110         vmxnet3_on_interrupt_mask_changed(s, l, val);
1111         return;
1112     }
1113 
1114     if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD,
1115                         VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN) ||
1116        VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_RXPROD2,
1117                         VMXNET3_DEVICE_MAX_RX_QUEUES, VMXNET3_REG_ALIGN)) {
1118         return;
1119     }
1120 
1121     VMW_WRPRN("BAR0 unknown write [%" PRIx64 "] = %" PRIx64 ", size %d",
1122               (uint64_t) addr, val, size);
1123 }
1124 
1125 static uint64_t
1126 vmxnet3_io_bar0_read(void *opaque, hwaddr addr, unsigned size)
1127 {
1128     VMXNET3State *s = opaque;
1129 
1130     if (VMW_IS_MULTIREG_ADDR(addr, VMXNET3_REG_IMR,
1131                         VMXNET3_MAX_INTRS, VMXNET3_REG_ALIGN)) {
1132         int l = VMW_MULTIREG_IDX_BY_ADDR(addr, VMXNET3_REG_IMR,
1133                                          VMXNET3_REG_ALIGN);
1134         return s->interrupt_states[l].is_masked;
1135     }
1136 
1137     VMW_CBPRN("BAR0 unknown read [%" PRIx64 "], size %d", addr, size);
1138     return 0;
1139 }
1140 
1141 static void vmxnet3_reset_interrupt_states(VMXNET3State *s)
1142 {
1143     int i;
1144     for (i = 0; i < ARRAY_SIZE(s->interrupt_states); i++) {
1145         s->interrupt_states[i].is_asserted = false;
1146         s->interrupt_states[i].is_pending = false;
1147         s->interrupt_states[i].is_masked = true;
1148     }
1149 }
1150 
1151 static void vmxnet3_reset_mac(VMXNET3State *s)
1152 {
1153     memcpy(&s->conf.macaddr.a, &s->perm_mac.a, sizeof(s->perm_mac.a));
1154     VMW_CFPRN("MAC address set to: " MAC_FMT, MAC_ARG(s->conf.macaddr.a));
1155 }
1156 
1157 static void vmxnet3_deactivate_device(VMXNET3State *s)
1158 {
1159     if (s->device_active) {
1160         VMW_CBPRN("Deactivating vmxnet3...");
1161         net_tx_pkt_uninit(s->tx_pkt);
1162         net_rx_pkt_uninit(s->rx_pkt);
1163         s->device_active = false;
1164     }
1165 }
1166 
1167 static void vmxnet3_reset(VMXNET3State *s)
1168 {
1169     VMW_CBPRN("Resetting vmxnet3...");
1170 
1171     vmxnet3_deactivate_device(s);
1172     vmxnet3_reset_interrupt_states(s);
1173     s->drv_shmem = 0;
1174     s->tx_sop = true;
1175     s->skip_current_tx_pkt = false;
1176 }
1177 
1178 static void vmxnet3_update_rx_mode(VMXNET3State *s)
1179 {
1180     PCIDevice *d = PCI_DEVICE(s);
1181 
1182     s->rx_mode = VMXNET3_READ_DRV_SHARED32(d, s->drv_shmem,
1183                                            devRead.rxFilterConf.rxMode);
1184     VMW_CFPRN("RX mode: 0x%08X", s->rx_mode);
1185 }
1186 
1187 static void vmxnet3_update_vlan_filters(VMXNET3State *s)
1188 {
1189     int i;
1190     PCIDevice *d = PCI_DEVICE(s);
1191 
1192     /* Copy configuration from shared memory */
1193     VMXNET3_READ_DRV_SHARED(d, s->drv_shmem,
1194                             devRead.rxFilterConf.vfTable,
1195                             s->vlan_table,
1196                             sizeof(s->vlan_table));
1197 
1198     /* Invert byte order when needed */
1199     for (i = 0; i < ARRAY_SIZE(s->vlan_table); i++) {
1200         s->vlan_table[i] = le32_to_cpu(s->vlan_table[i]);
1201     }
1202 
1203     /* Dump configuration for debugging purposes */
1204     VMW_CFPRN("Configured VLANs:");
1205     for (i = 0; i < sizeof(s->vlan_table) * 8; i++) {
1206         if (VMXNET3_VFTABLE_ENTRY_IS_SET(s->vlan_table, i)) {
1207             VMW_CFPRN("\tVLAN %d is present", i);
1208         }
1209     }
1210 }
1211 
1212 static void vmxnet3_update_mcast_filters(VMXNET3State *s)
1213 {
1214     PCIDevice *d = PCI_DEVICE(s);
1215 
1216     uint16_t list_bytes =
1217         VMXNET3_READ_DRV_SHARED16(d, s->drv_shmem,
1218                                   devRead.rxFilterConf.mfTableLen);
1219 
1220     s->mcast_list_len = list_bytes / sizeof(s->mcast_list[0]);
1221 
1222     s->mcast_list = g_realloc(s->mcast_list, list_bytes);
1223     if (!s->mcast_list) {
1224         if (s->mcast_list_len == 0) {
1225             VMW_CFPRN("Current multicast list is empty");
1226         } else {
1227             VMW_ERPRN("Failed to allocate multicast list of %d elements",
1228                       s->mcast_list_len);
1229         }
1230         s->mcast_list_len = 0;
1231     } else {
1232         int i;
1233         hwaddr mcast_list_pa =
1234             VMXNET3_READ_DRV_SHARED64(d, s->drv_shmem,
1235                                       devRead.rxFilterConf.mfTablePA);
1236 
1237         pci_dma_read(d, mcast_list_pa, s->mcast_list, list_bytes);
1238 
1239         VMW_CFPRN("Current multicast list len is %d:", s->mcast_list_len);
1240         for (i = 0; i < s->mcast_list_len; i++) {
1241             VMW_CFPRN("\t" MAC_FMT, MAC_ARG(s->mcast_list[i].a));
1242         }
1243     }
1244 }
1245 
1246 static void vmxnet3_setup_rx_filtering(VMXNET3State *s)
1247 {
1248     vmxnet3_update_rx_mode(s);
1249     vmxnet3_update_vlan_filters(s);
1250     vmxnet3_update_mcast_filters(s);
1251 }
1252 
1253 static uint32_t vmxnet3_get_interrupt_config(VMXNET3State *s)
1254 {
1255     uint32_t interrupt_mode = VMXNET3_IT_AUTO | (VMXNET3_IMM_AUTO << 2);
1256     VMW_CFPRN("Interrupt config is 0x%X", interrupt_mode);
1257     return interrupt_mode;
1258 }
1259 
1260 static void vmxnet3_fill_stats(VMXNET3State *s)
1261 {
1262     int i;
1263     PCIDevice *d = PCI_DEVICE(s);
1264 
1265     if (!s->device_active)
1266         return;
1267 
1268     for (i = 0; i < s->txq_num; i++) {
1269         pci_dma_write(d,
1270                       s->txq_descr[i].tx_stats_pa,
1271                       &s->txq_descr[i].txq_stats,
1272                       sizeof(s->txq_descr[i].txq_stats));
1273     }
1274 
1275     for (i = 0; i < s->rxq_num; i++) {
1276         pci_dma_write(d,
1277                       s->rxq_descr[i].rx_stats_pa,
1278                       &s->rxq_descr[i].rxq_stats,
1279                       sizeof(s->rxq_descr[i].rxq_stats));
1280     }
1281 }
1282 
1283 static void vmxnet3_adjust_by_guest_type(VMXNET3State *s)
1284 {
1285     struct Vmxnet3_GOSInfo gos;
1286     PCIDevice *d = PCI_DEVICE(s);
1287 
1288     VMXNET3_READ_DRV_SHARED(d, s->drv_shmem, devRead.misc.driverInfo.gos,
1289                             &gos, sizeof(gos));
1290     s->rx_packets_compound =
1291         (gos.gosType == VMXNET3_GOS_TYPE_WIN) ? false : true;
1292 
1293     VMW_CFPRN("Guest type specifics: RXCOMPOUND: %d", s->rx_packets_compound);
1294 }
1295 
1296 static void
1297 vmxnet3_dump_conf_descr(const char *name,
1298                         struct Vmxnet3_VariableLenConfDesc *pm_descr)
1299 {
1300     VMW_CFPRN("%s descriptor dump: Version %u, Length %u",
1301               name, pm_descr->confVer, pm_descr->confLen);
1302 
1303 };
1304 
1305 static void vmxnet3_update_pm_state(VMXNET3State *s)
1306 {
1307     struct Vmxnet3_VariableLenConfDesc pm_descr;
1308     PCIDevice *d = PCI_DEVICE(s);
1309 
1310     pm_descr.confLen =
1311         VMXNET3_READ_DRV_SHARED32(d, s->drv_shmem, devRead.pmConfDesc.confLen);
1312     pm_descr.confVer =
1313         VMXNET3_READ_DRV_SHARED32(d, s->drv_shmem, devRead.pmConfDesc.confVer);
1314     pm_descr.confPA =
1315         VMXNET3_READ_DRV_SHARED64(d, s->drv_shmem, devRead.pmConfDesc.confPA);
1316 
1317     vmxnet3_dump_conf_descr("PM State", &pm_descr);
1318 }
1319 
1320 static void vmxnet3_update_features(VMXNET3State *s)
1321 {
1322     uint32_t guest_features;
1323     int rxcso_supported;
1324     PCIDevice *d = PCI_DEVICE(s);
1325 
1326     guest_features = VMXNET3_READ_DRV_SHARED32(d, s->drv_shmem,
1327                                                devRead.misc.uptFeatures);
1328 
1329     rxcso_supported = VMXNET_FLAG_IS_SET(guest_features, UPT1_F_RXCSUM);
1330     s->rx_vlan_stripping = VMXNET_FLAG_IS_SET(guest_features, UPT1_F_RXVLAN);
1331     s->lro_supported = VMXNET_FLAG_IS_SET(guest_features, UPT1_F_LRO);
1332 
1333     VMW_CFPRN("Features configuration: LRO: %d, RXCSUM: %d, VLANSTRIP: %d",
1334               s->lro_supported, rxcso_supported,
1335               s->rx_vlan_stripping);
1336     if (s->peer_has_vhdr) {
1337         qemu_set_offload(qemu_get_queue(s->nic)->peer,
1338                          rxcso_supported,
1339                          s->lro_supported,
1340                          s->lro_supported,
1341                          0,
1342                          0,
1343                          0,
1344                          0);
1345     }
1346 }
1347 
1348 static bool vmxnet3_verify_intx(VMXNET3State *s, int intx)
1349 {
1350     return s->msix_used || msi_enabled(PCI_DEVICE(s))
1351         || intx == pci_get_byte(s->parent_obj.config + PCI_INTERRUPT_PIN) - 1;
1352 }
1353 
1354 static void vmxnet3_validate_interrupt_idx(bool is_msix, int idx)
1355 {
1356     int max_ints = is_msix ? VMXNET3_MAX_INTRS : VMXNET3_MAX_NMSIX_INTRS;
1357     if (idx >= max_ints) {
1358         hw_error("Bad interrupt index: %d\n", idx);
1359     }
1360 }
1361 
1362 static void vmxnet3_validate_interrupts(VMXNET3State *s)
1363 {
1364     int i;
1365 
1366     VMW_CFPRN("Verifying event interrupt index (%d)", s->event_int_idx);
1367     vmxnet3_validate_interrupt_idx(s->msix_used, s->event_int_idx);
1368 
1369     for (i = 0; i < s->txq_num; i++) {
1370         int idx = s->txq_descr[i].intr_idx;
1371         VMW_CFPRN("Verifying TX queue %d interrupt index (%d)", i, idx);
1372         vmxnet3_validate_interrupt_idx(s->msix_used, idx);
1373     }
1374 
1375     for (i = 0; i < s->rxq_num; i++) {
1376         int idx = s->rxq_descr[i].intr_idx;
1377         VMW_CFPRN("Verifying RX queue %d interrupt index (%d)", i, idx);
1378         vmxnet3_validate_interrupt_idx(s->msix_used, idx);
1379     }
1380 }
1381 
1382 static bool vmxnet3_validate_queues(VMXNET3State *s)
1383 {
1384     /*
1385     * txq_num and rxq_num are total number of queues
1386     * configured by guest. These numbers must not
1387     * exceed corresponding maximal values.
1388     */
1389 
1390     if (s->txq_num > VMXNET3_DEVICE_MAX_TX_QUEUES) {
1391         qemu_log_mask(LOG_GUEST_ERROR, "vmxnet3: Bad TX queues number: %d\n",
1392                       s->txq_num);
1393         return false;
1394     }
1395 
1396     if (s->rxq_num > VMXNET3_DEVICE_MAX_RX_QUEUES) {
1397         qemu_log_mask(LOG_GUEST_ERROR, "vmxnet3: Bad RX queues number: %d\n",
1398                       s->rxq_num);
1399         return false;
1400     }
1401 
1402     return true;
1403 }
1404 
1405 static void vmxnet3_activate_device(VMXNET3State *s)
1406 {
1407     int i;
1408     static const uint32_t VMXNET3_DEF_TX_THRESHOLD = 1;
1409     PCIDevice *d = PCI_DEVICE(s);
1410     hwaddr qdescr_table_pa;
1411     uint64_t pa;
1412     uint32_t size;
1413 
1414     /* Verify configuration consistency */
1415     if (!vmxnet3_verify_driver_magic(d, s->drv_shmem)) {
1416         VMW_ERPRN("Device configuration received from driver is invalid");
1417         return;
1418     }
1419 
1420     /* Verify if device is active */
1421     if (s->device_active) {
1422         VMW_CFPRN("Vmxnet3 device is active");
1423         return;
1424     }
1425 
1426     s->txq_num =
1427         VMXNET3_READ_DRV_SHARED8(d, s->drv_shmem, devRead.misc.numTxQueues);
1428     s->rxq_num =
1429         VMXNET3_READ_DRV_SHARED8(d, s->drv_shmem, devRead.misc.numRxQueues);
1430 
1431     VMW_CFPRN("Number of TX/RX queues %u/%u", s->txq_num, s->rxq_num);
1432     if (!vmxnet3_validate_queues(s)) {
1433         return;
1434     }
1435 
1436     vmxnet3_adjust_by_guest_type(s);
1437     vmxnet3_update_features(s);
1438     vmxnet3_update_pm_state(s);
1439     vmxnet3_setup_rx_filtering(s);
1440     /* Cache fields from shared memory */
1441     s->mtu = VMXNET3_READ_DRV_SHARED32(d, s->drv_shmem, devRead.misc.mtu);
1442     if (s->mtu < VMXNET3_MIN_MTU || s->mtu > VMXNET3_MAX_MTU) {
1443         qemu_log_mask(LOG_GUEST_ERROR, "vmxnet3: Bad MTU size: %u\n", s->mtu);
1444         return;
1445     }
1446     VMW_CFPRN("MTU is %u", s->mtu);
1447 
1448     s->max_rx_frags =
1449         VMXNET3_READ_DRV_SHARED16(d, s->drv_shmem, devRead.misc.maxNumRxSG);
1450 
1451     if (s->max_rx_frags == 0) {
1452         s->max_rx_frags = 1;
1453     }
1454 
1455     VMW_CFPRN("Max RX fragments is %u", s->max_rx_frags);
1456 
1457     s->event_int_idx =
1458         VMXNET3_READ_DRV_SHARED8(d, s->drv_shmem, devRead.intrConf.eventIntrIdx);
1459     assert(vmxnet3_verify_intx(s, s->event_int_idx));
1460     VMW_CFPRN("Events interrupt line is %u", s->event_int_idx);
1461 
1462     s->auto_int_masking =
1463         VMXNET3_READ_DRV_SHARED8(d, s->drv_shmem, devRead.intrConf.autoMask);
1464     VMW_CFPRN("Automatic interrupt masking is %d", (int)s->auto_int_masking);
1465 
1466     qdescr_table_pa =
1467         VMXNET3_READ_DRV_SHARED64(d, s->drv_shmem, devRead.misc.queueDescPA);
1468     VMW_CFPRN("TX queues descriptors table is at 0x%" PRIx64, qdescr_table_pa);
1469 
1470     /*
1471      * Worst-case scenario is a packet that holds all TX rings space so
1472      * we calculate total size of all TX rings for max TX fragments number
1473      */
1474     s->max_tx_frags = 0;
1475 
1476     /* TX queues */
1477     for (i = 0; i < s->txq_num; i++) {
1478         hwaddr qdescr_pa =
1479             qdescr_table_pa + i * sizeof(struct Vmxnet3_TxQueueDesc);
1480 
1481         /* Read interrupt number for this TX queue */
1482         s->txq_descr[i].intr_idx =
1483             VMXNET3_READ_TX_QUEUE_DESCR8(d, qdescr_pa, conf.intrIdx);
1484         assert(vmxnet3_verify_intx(s, s->txq_descr[i].intr_idx));
1485 
1486         VMW_CFPRN("TX Queue %d interrupt: %d", i, s->txq_descr[i].intr_idx);
1487 
1488         /* Read rings memory locations for TX queues */
1489         pa = VMXNET3_READ_TX_QUEUE_DESCR64(d, qdescr_pa, conf.txRingBasePA);
1490         size = VMXNET3_READ_TX_QUEUE_DESCR32(d, qdescr_pa, conf.txRingSize);
1491         if (size > VMXNET3_TX_RING_MAX_SIZE) {
1492             size = VMXNET3_TX_RING_MAX_SIZE;
1493         }
1494 
1495         vmxnet3_ring_init(d, &s->txq_descr[i].tx_ring, pa, size,
1496                           sizeof(struct Vmxnet3_TxDesc), false);
1497         VMXNET3_RING_DUMP(VMW_CFPRN, "TX", i, &s->txq_descr[i].tx_ring);
1498 
1499         s->max_tx_frags += size;
1500 
1501         /* TXC ring */
1502         pa = VMXNET3_READ_TX_QUEUE_DESCR64(d, qdescr_pa, conf.compRingBasePA);
1503         size = VMXNET3_READ_TX_QUEUE_DESCR32(d, qdescr_pa, conf.compRingSize);
1504         if (size > VMXNET3_TC_RING_MAX_SIZE) {
1505             size = VMXNET3_TC_RING_MAX_SIZE;
1506         }
1507         vmxnet3_ring_init(d, &s->txq_descr[i].comp_ring, pa, size,
1508                           sizeof(struct Vmxnet3_TxCompDesc), true);
1509         VMXNET3_RING_DUMP(VMW_CFPRN, "TXC", i, &s->txq_descr[i].comp_ring);
1510 
1511         s->txq_descr[i].tx_stats_pa =
1512             qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats);
1513 
1514         memset(&s->txq_descr[i].txq_stats, 0,
1515                sizeof(s->txq_descr[i].txq_stats));
1516 
1517         /* Fill device-managed parameters for queues */
1518         VMXNET3_WRITE_TX_QUEUE_DESCR32(d, qdescr_pa,
1519                                        ctrl.txThreshold,
1520                                        VMXNET3_DEF_TX_THRESHOLD);
1521     }
1522 
1523     /* Preallocate TX packet wrapper */
1524     VMW_CFPRN("Max TX fragments is %u", s->max_tx_frags);
1525     net_tx_pkt_init(&s->tx_pkt, s->max_tx_frags);
1526     net_rx_pkt_init(&s->rx_pkt);
1527 
1528     /* Read rings memory locations for RX queues */
1529     for (i = 0; i < s->rxq_num; i++) {
1530         int j;
1531         hwaddr qd_pa =
1532             qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) +
1533             i * sizeof(struct Vmxnet3_RxQueueDesc);
1534 
1535         /* Read interrupt number for this RX queue */
1536         s->rxq_descr[i].intr_idx =
1537             VMXNET3_READ_TX_QUEUE_DESCR8(d, qd_pa, conf.intrIdx);
1538         assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx));
1539 
1540         VMW_CFPRN("RX Queue %d interrupt: %d", i, s->rxq_descr[i].intr_idx);
1541 
1542         /* Read rings memory locations */
1543         for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) {
1544             /* RX rings */
1545             pa = VMXNET3_READ_RX_QUEUE_DESCR64(d, qd_pa, conf.rxRingBasePA[j]);
1546             size = VMXNET3_READ_RX_QUEUE_DESCR32(d, qd_pa, conf.rxRingSize[j]);
1547             if (size > VMXNET3_RX_RING_MAX_SIZE) {
1548                 size = VMXNET3_RX_RING_MAX_SIZE;
1549             }
1550             vmxnet3_ring_init(d, &s->rxq_descr[i].rx_ring[j], pa, size,
1551                               sizeof(struct Vmxnet3_RxDesc), false);
1552             VMW_CFPRN("RX queue %d:%d: Base: %" PRIx64 ", Size: %d",
1553                       i, j, pa, size);
1554         }
1555 
1556         /* RXC ring */
1557         pa = VMXNET3_READ_RX_QUEUE_DESCR64(d, qd_pa, conf.compRingBasePA);
1558         size = VMXNET3_READ_RX_QUEUE_DESCR32(d, qd_pa, conf.compRingSize);
1559         if (size > VMXNET3_RC_RING_MAX_SIZE) {
1560             size = VMXNET3_RC_RING_MAX_SIZE;
1561         }
1562         vmxnet3_ring_init(d, &s->rxq_descr[i].comp_ring, pa, size,
1563                           sizeof(struct Vmxnet3_RxCompDesc), true);
1564         VMW_CFPRN("RXC queue %d: Base: %" PRIx64 ", Size: %d", i, pa, size);
1565 
1566         s->rxq_descr[i].rx_stats_pa =
1567             qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats);
1568         memset(&s->rxq_descr[i].rxq_stats, 0,
1569                sizeof(s->rxq_descr[i].rxq_stats));
1570     }
1571 
1572     vmxnet3_validate_interrupts(s);
1573 
1574     /* Make sure everything is in place before device activation */
1575     smp_wmb();
1576 
1577     vmxnet3_reset_mac(s);
1578 
1579     s->device_active = true;
1580 }
1581 
1582 static void vmxnet3_handle_command(VMXNET3State *s, uint64_t cmd)
1583 {
1584     s->last_command = cmd;
1585 
1586     switch (cmd) {
1587     case VMXNET3_CMD_GET_PERM_MAC_HI:
1588         VMW_CBPRN("Set: Get upper part of permanent MAC");
1589         break;
1590 
1591     case VMXNET3_CMD_GET_PERM_MAC_LO:
1592         VMW_CBPRN("Set: Get lower part of permanent MAC");
1593         break;
1594 
1595     case VMXNET3_CMD_GET_STATS:
1596         VMW_CBPRN("Set: Get device statistics");
1597         vmxnet3_fill_stats(s);
1598         break;
1599 
1600     case VMXNET3_CMD_ACTIVATE_DEV:
1601         VMW_CBPRN("Set: Activating vmxnet3 device");
1602         vmxnet3_activate_device(s);
1603         break;
1604 
1605     case VMXNET3_CMD_UPDATE_RX_MODE:
1606         VMW_CBPRN("Set: Update rx mode");
1607         vmxnet3_update_rx_mode(s);
1608         break;
1609 
1610     case VMXNET3_CMD_UPDATE_VLAN_FILTERS:
1611         VMW_CBPRN("Set: Update VLAN filters");
1612         vmxnet3_update_vlan_filters(s);
1613         break;
1614 
1615     case VMXNET3_CMD_UPDATE_MAC_FILTERS:
1616         VMW_CBPRN("Set: Update MAC filters");
1617         vmxnet3_update_mcast_filters(s);
1618         break;
1619 
1620     case VMXNET3_CMD_UPDATE_FEATURE:
1621         VMW_CBPRN("Set: Update features");
1622         vmxnet3_update_features(s);
1623         break;
1624 
1625     case VMXNET3_CMD_UPDATE_PMCFG:
1626         VMW_CBPRN("Set: Update power management config");
1627         vmxnet3_update_pm_state(s);
1628         break;
1629 
1630     case VMXNET3_CMD_GET_LINK:
1631         VMW_CBPRN("Set: Get link");
1632         break;
1633 
1634     case VMXNET3_CMD_RESET_DEV:
1635         VMW_CBPRN("Set: Reset device");
1636         vmxnet3_reset(s);
1637         break;
1638 
1639     case VMXNET3_CMD_QUIESCE_DEV:
1640         VMW_CBPRN("Set: VMXNET3_CMD_QUIESCE_DEV - deactivate the device");
1641         vmxnet3_deactivate_device(s);
1642         break;
1643 
1644     case VMXNET3_CMD_GET_CONF_INTR:
1645         VMW_CBPRN("Set: VMXNET3_CMD_GET_CONF_INTR - interrupt configuration");
1646         break;
1647 
1648     case VMXNET3_CMD_GET_ADAPTIVE_RING_INFO:
1649         VMW_CBPRN("Set: VMXNET3_CMD_GET_ADAPTIVE_RING_INFO - "
1650                   "adaptive ring info flags");
1651         break;
1652 
1653     case VMXNET3_CMD_GET_DID_LO:
1654         VMW_CBPRN("Set: Get lower part of device ID");
1655         break;
1656 
1657     case VMXNET3_CMD_GET_DID_HI:
1658         VMW_CBPRN("Set: Get upper part of device ID");
1659         break;
1660 
1661     case VMXNET3_CMD_GET_DEV_EXTRA_INFO:
1662         VMW_CBPRN("Set: Get device extra info");
1663         break;
1664 
1665     default:
1666         VMW_CBPRN("Received unknown command: %" PRIx64, cmd);
1667         break;
1668     }
1669 }
1670 
1671 static uint64_t vmxnet3_get_command_status(VMXNET3State *s)
1672 {
1673     uint64_t ret;
1674 
1675     switch (s->last_command) {
1676     case VMXNET3_CMD_ACTIVATE_DEV:
1677         ret = (s->device_active) ? 0 : 1;
1678         VMW_CFPRN("Device active: %" PRIx64, ret);
1679         break;
1680 
1681     case VMXNET3_CMD_RESET_DEV:
1682     case VMXNET3_CMD_QUIESCE_DEV:
1683     case VMXNET3_CMD_GET_QUEUE_STATUS:
1684     case VMXNET3_CMD_GET_DEV_EXTRA_INFO:
1685         ret = 0;
1686         break;
1687 
1688     case VMXNET3_CMD_GET_LINK:
1689         ret = s->link_status_and_speed;
1690         VMW_CFPRN("Link and speed: %" PRIx64, ret);
1691         break;
1692 
1693     case VMXNET3_CMD_GET_PERM_MAC_LO:
1694         ret = vmxnet3_get_mac_low(&s->perm_mac);
1695         break;
1696 
1697     case VMXNET3_CMD_GET_PERM_MAC_HI:
1698         ret = vmxnet3_get_mac_high(&s->perm_mac);
1699         break;
1700 
1701     case VMXNET3_CMD_GET_CONF_INTR:
1702         ret = vmxnet3_get_interrupt_config(s);
1703         break;
1704 
1705     case VMXNET3_CMD_GET_ADAPTIVE_RING_INFO:
1706         ret = VMXNET3_DISABLE_ADAPTIVE_RING;
1707         break;
1708 
1709     case VMXNET3_CMD_GET_DID_LO:
1710         ret = PCI_DEVICE_ID_VMWARE_VMXNET3;
1711         break;
1712 
1713     case VMXNET3_CMD_GET_DID_HI:
1714         ret = VMXNET3_DEVICE_REVISION;
1715         break;
1716 
1717     default:
1718         VMW_WRPRN("Received request for unknown command: %x", s->last_command);
1719         ret = 0;
1720         break;
1721     }
1722 
1723     return ret;
1724 }
1725 
1726 static void vmxnet3_set_events(VMXNET3State *s, uint32_t val)
1727 {
1728     uint32_t events;
1729     PCIDevice *d = PCI_DEVICE(s);
1730 
1731     VMW_CBPRN("Setting events: 0x%x", val);
1732     events = VMXNET3_READ_DRV_SHARED32(d, s->drv_shmem, ecr) | val;
1733     VMXNET3_WRITE_DRV_SHARED32(d, s->drv_shmem, ecr, events);
1734 }
1735 
1736 static void vmxnet3_ack_events(VMXNET3State *s, uint32_t val)
1737 {
1738     PCIDevice *d = PCI_DEVICE(s);
1739     uint32_t events;
1740 
1741     VMW_CBPRN("Clearing events: 0x%x", val);
1742     events = VMXNET3_READ_DRV_SHARED32(d, s->drv_shmem, ecr) & ~val;
1743     VMXNET3_WRITE_DRV_SHARED32(d, s->drv_shmem, ecr, events);
1744 }
1745 
1746 static void
1747 vmxnet3_io_bar1_write(void *opaque,
1748                       hwaddr addr,
1749                       uint64_t val,
1750                       unsigned size)
1751 {
1752     VMXNET3State *s = opaque;
1753 
1754     switch (addr) {
1755     /* Vmxnet3 Revision Report Selection */
1756     case VMXNET3_REG_VRRS:
1757         VMW_CBPRN("Write BAR1 [VMXNET3_REG_VRRS] = %" PRIx64 ", size %d",
1758                   val, size);
1759         break;
1760 
1761     /* UPT Version Report Selection */
1762     case VMXNET3_REG_UVRS:
1763         VMW_CBPRN("Write BAR1 [VMXNET3_REG_UVRS] = %" PRIx64 ", size %d",
1764                   val, size);
1765         break;
1766 
1767     /* Driver Shared Address Low */
1768     case VMXNET3_REG_DSAL:
1769         VMW_CBPRN("Write BAR1 [VMXNET3_REG_DSAL] = %" PRIx64 ", size %d",
1770                   val, size);
1771         /*
1772          * Guest driver will first write the low part of the shared
1773          * memory address. We save it to temp variable and set the
1774          * shared address only after we get the high part
1775          */
1776         if (val == 0) {
1777             vmxnet3_deactivate_device(s);
1778         }
1779         s->temp_shared_guest_driver_memory = val;
1780         s->drv_shmem = 0;
1781         break;
1782 
1783     /* Driver Shared Address High */
1784     case VMXNET3_REG_DSAH:
1785         VMW_CBPRN("Write BAR1 [VMXNET3_REG_DSAH] = %" PRIx64 ", size %d",
1786                   val, size);
1787         /*
1788          * Set the shared memory between guest driver and device.
1789          * We already should have low address part.
1790          */
1791         s->drv_shmem = s->temp_shared_guest_driver_memory | (val << 32);
1792         break;
1793 
1794     /* Command */
1795     case VMXNET3_REG_CMD:
1796         VMW_CBPRN("Write BAR1 [VMXNET3_REG_CMD] = %" PRIx64 ", size %d",
1797                   val, size);
1798         vmxnet3_handle_command(s, val);
1799         break;
1800 
1801     /* MAC Address Low */
1802     case VMXNET3_REG_MACL:
1803         VMW_CBPRN("Write BAR1 [VMXNET3_REG_MACL] = %" PRIx64 ", size %d",
1804                   val, size);
1805         s->temp_mac = val;
1806         break;
1807 
1808     /* MAC Address High */
1809     case VMXNET3_REG_MACH:
1810         VMW_CBPRN("Write BAR1 [VMXNET3_REG_MACH] = %" PRIx64 ", size %d",
1811                   val, size);
1812         vmxnet3_set_variable_mac(s, val, s->temp_mac);
1813         break;
1814 
1815     /* Interrupt Cause Register */
1816     case VMXNET3_REG_ICR:
1817         VMW_CBPRN("Write BAR1 [VMXNET3_REG_ICR] = %" PRIx64 ", size %d",
1818                   val, size);
1819         qemu_log_mask(LOG_GUEST_ERROR,
1820                       "%s: write to read-only register VMXNET3_REG_ICR\n",
1821                       TYPE_VMXNET3);
1822         break;
1823 
1824     /* Event Cause Register */
1825     case VMXNET3_REG_ECR:
1826         VMW_CBPRN("Write BAR1 [VMXNET3_REG_ECR] = %" PRIx64 ", size %d",
1827                   val, size);
1828         vmxnet3_ack_events(s, val);
1829         break;
1830 
1831     default:
1832         VMW_CBPRN("Unknown Write to BAR1 [%" PRIx64 "] = %" PRIx64 ", size %d",
1833                   addr, val, size);
1834         break;
1835     }
1836 }
1837 
1838 static uint64_t
1839 vmxnet3_io_bar1_read(void *opaque, hwaddr addr, unsigned size)
1840 {
1841         VMXNET3State *s = opaque;
1842         uint64_t ret = 0;
1843 
1844         switch (addr) {
1845         /* Vmxnet3 Revision Report Selection */
1846         case VMXNET3_REG_VRRS:
1847             VMW_CBPRN("Read BAR1 [VMXNET3_REG_VRRS], size %d", size);
1848             ret = VMXNET3_DEVICE_REVISION;
1849             break;
1850 
1851         /* UPT Version Report Selection */
1852         case VMXNET3_REG_UVRS:
1853             VMW_CBPRN("Read BAR1 [VMXNET3_REG_UVRS], size %d", size);
1854             ret = VMXNET3_UPT_REVISION;
1855             break;
1856 
1857         /* Command */
1858         case VMXNET3_REG_CMD:
1859             VMW_CBPRN("Read BAR1 [VMXNET3_REG_CMD], size %d", size);
1860             ret = vmxnet3_get_command_status(s);
1861             break;
1862 
1863         /* MAC Address Low */
1864         case VMXNET3_REG_MACL:
1865             VMW_CBPRN("Read BAR1 [VMXNET3_REG_MACL], size %d", size);
1866             ret = vmxnet3_get_mac_low(&s->conf.macaddr);
1867             break;
1868 
1869         /* MAC Address High */
1870         case VMXNET3_REG_MACH:
1871             VMW_CBPRN("Read BAR1 [VMXNET3_REG_MACH], size %d", size);
1872             ret = vmxnet3_get_mac_high(&s->conf.macaddr);
1873             break;
1874 
1875         /*
1876          * Interrupt Cause Register
1877          * Used for legacy interrupts only so interrupt index always 0
1878          */
1879         case VMXNET3_REG_ICR:
1880             VMW_CBPRN("Read BAR1 [VMXNET3_REG_ICR], size %d", size);
1881             if (vmxnet3_interrupt_asserted(s, 0)) {
1882                 vmxnet3_clear_interrupt(s, 0);
1883                 ret = true;
1884             } else {
1885                 ret = false;
1886             }
1887             break;
1888 
1889         default:
1890             VMW_CBPRN("Unknown read BAR1[%" PRIx64 "], %d bytes", addr, size);
1891             break;
1892         }
1893 
1894         return ret;
1895 }
1896 
1897 static int
1898 vmxnet3_can_receive(NetClientState *nc)
1899 {
1900     VMXNET3State *s = qemu_get_nic_opaque(nc);
1901     return s->device_active &&
1902            VMXNET_FLAG_IS_SET(s->link_status_and_speed, VMXNET3_LINK_STATUS_UP);
1903 }
1904 
1905 static inline bool
1906 vmxnet3_is_registered_vlan(VMXNET3State *s, const void *data)
1907 {
1908     uint16_t vlan_tag = eth_get_pkt_tci(data) & VLAN_VID_MASK;
1909     if (IS_SPECIAL_VLAN_ID(vlan_tag)) {
1910         return true;
1911     }
1912 
1913     return VMXNET3_VFTABLE_ENTRY_IS_SET(s->vlan_table, vlan_tag);
1914 }
1915 
1916 static bool
1917 vmxnet3_is_allowed_mcast_group(VMXNET3State *s, const uint8_t *group_mac)
1918 {
1919     int i;
1920     for (i = 0; i < s->mcast_list_len; i++) {
1921         if (!memcmp(group_mac, s->mcast_list[i].a, sizeof(s->mcast_list[i]))) {
1922             return true;
1923         }
1924     }
1925     return false;
1926 }
1927 
1928 static bool
1929 vmxnet3_rx_filter_may_indicate(VMXNET3State *s, const void *data,
1930     size_t size)
1931 {
1932     struct eth_header *ehdr = PKT_GET_ETH_HDR(data);
1933 
1934     if (VMXNET_FLAG_IS_SET(s->rx_mode, VMXNET3_RXM_PROMISC)) {
1935         return true;
1936     }
1937 
1938     if (!vmxnet3_is_registered_vlan(s, data)) {
1939         return false;
1940     }
1941 
1942     switch (net_rx_pkt_get_packet_type(s->rx_pkt)) {
1943     case ETH_PKT_UCAST:
1944         if (!VMXNET_FLAG_IS_SET(s->rx_mode, VMXNET3_RXM_UCAST)) {
1945             return false;
1946         }
1947         if (memcmp(s->conf.macaddr.a, ehdr->h_dest, ETH_ALEN)) {
1948             return false;
1949         }
1950         break;
1951 
1952     case ETH_PKT_BCAST:
1953         if (!VMXNET_FLAG_IS_SET(s->rx_mode, VMXNET3_RXM_BCAST)) {
1954             return false;
1955         }
1956         break;
1957 
1958     case ETH_PKT_MCAST:
1959         if (VMXNET_FLAG_IS_SET(s->rx_mode, VMXNET3_RXM_ALL_MULTI)) {
1960             return true;
1961         }
1962         if (!VMXNET_FLAG_IS_SET(s->rx_mode, VMXNET3_RXM_MCAST)) {
1963             return false;
1964         }
1965         if (!vmxnet3_is_allowed_mcast_group(s, ehdr->h_dest)) {
1966             return false;
1967         }
1968         break;
1969 
1970     default:
1971         g_assert_not_reached();
1972     }
1973 
1974     return true;
1975 }
1976 
1977 static ssize_t
1978 vmxnet3_receive(NetClientState *nc, const uint8_t *buf, size_t size)
1979 {
1980     VMXNET3State *s = qemu_get_nic_opaque(nc);
1981     size_t bytes_indicated;
1982 
1983     if (!vmxnet3_can_receive(nc)) {
1984         VMW_PKPRN("Cannot receive now");
1985         return -1;
1986     }
1987 
1988     if (s->peer_has_vhdr) {
1989         net_rx_pkt_set_vhdr(s->rx_pkt, (struct virtio_net_hdr *)buf);
1990         buf += sizeof(struct virtio_net_hdr);
1991         size -= sizeof(struct virtio_net_hdr);
1992     }
1993 
1994     net_rx_pkt_set_packet_type(s->rx_pkt,
1995         get_eth_packet_type(PKT_GET_ETH_HDR(buf)));
1996 
1997     if (vmxnet3_rx_filter_may_indicate(s, buf, size)) {
1998         struct iovec iov = {
1999             .iov_base = (void *)buf,
2000             .iov_len = size
2001         };
2002 
2003         net_rx_pkt_set_protocols(s->rx_pkt, &iov, 1, 0);
2004         vmxnet3_rx_need_csum_calculate(s->rx_pkt, buf, size);
2005         net_rx_pkt_attach_data(s->rx_pkt, buf, size, s->rx_vlan_stripping);
2006         bytes_indicated = vmxnet3_indicate_packet(s) ? size : -1;
2007         if (bytes_indicated < size) {
2008             VMW_PKPRN("RX: %zu of %zu bytes indicated", bytes_indicated, size);
2009         }
2010     } else {
2011         VMW_PKPRN("Packet dropped by RX filter");
2012         bytes_indicated = size;
2013     }
2014 
2015     assert(size > 0);
2016     assert(bytes_indicated != 0);
2017     return bytes_indicated;
2018 }
2019 
2020 static void vmxnet3_set_link_status(NetClientState *nc)
2021 {
2022     VMXNET3State *s = qemu_get_nic_opaque(nc);
2023 
2024     if (nc->link_down) {
2025         s->link_status_and_speed &= ~VMXNET3_LINK_STATUS_UP;
2026     } else {
2027         s->link_status_and_speed |= VMXNET3_LINK_STATUS_UP;
2028     }
2029 
2030     vmxnet3_set_events(s, VMXNET3_ECR_LINK);
2031     vmxnet3_trigger_interrupt(s, s->event_int_idx);
2032 }
2033 
2034 static NetClientInfo net_vmxnet3_info = {
2035         .type = NET_CLIENT_DRIVER_NIC,
2036         .size = sizeof(NICState),
2037         .receive = vmxnet3_receive,
2038         .link_status_changed = vmxnet3_set_link_status,
2039 };
2040 
2041 static bool vmxnet3_peer_has_vnet_hdr(VMXNET3State *s)
2042 {
2043     NetClientState *nc = qemu_get_queue(s->nic);
2044 
2045     if (qemu_has_vnet_hdr(nc->peer)) {
2046         return true;
2047     }
2048 
2049     return false;
2050 }
2051 
2052 static void vmxnet3_net_uninit(VMXNET3State *s)
2053 {
2054     g_free(s->mcast_list);
2055     vmxnet3_deactivate_device(s);
2056     qemu_del_nic(s->nic);
2057 }
2058 
2059 static void vmxnet3_net_init(VMXNET3State *s)
2060 {
2061     DeviceState *d = DEVICE(s);
2062 
2063     VMW_CBPRN("vmxnet3_net_init called...");
2064 
2065     qemu_macaddr_default_if_unset(&s->conf.macaddr);
2066 
2067     /* Windows guest will query the address that was set on init */
2068     memcpy(&s->perm_mac.a, &s->conf.macaddr.a, sizeof(s->perm_mac.a));
2069 
2070     s->mcast_list = NULL;
2071     s->mcast_list_len = 0;
2072 
2073     s->link_status_and_speed = VMXNET3_LINK_SPEED | VMXNET3_LINK_STATUS_UP;
2074 
2075     VMW_CFPRN("Permanent MAC: " MAC_FMT, MAC_ARG(s->perm_mac.a));
2076 
2077     s->nic = qemu_new_nic(&net_vmxnet3_info, &s->conf,
2078                           object_get_typename(OBJECT(s)),
2079                           d->id, &d->mem_reentrancy_guard, s);
2080 
2081     s->peer_has_vhdr = vmxnet3_peer_has_vnet_hdr(s);
2082     s->tx_sop = true;
2083     s->skip_current_tx_pkt = false;
2084     s->tx_pkt = NULL;
2085     s->rx_pkt = NULL;
2086     s->rx_vlan_stripping = false;
2087     s->lro_supported = false;
2088 
2089     if (s->peer_has_vhdr) {
2090         qemu_set_vnet_hdr_len(qemu_get_queue(s->nic)->peer,
2091             sizeof(struct virtio_net_hdr));
2092     }
2093 
2094     qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a);
2095 }
2096 
2097 static void
2098 vmxnet3_unuse_msix_vectors(VMXNET3State *s, int num_vectors)
2099 {
2100     PCIDevice *d = PCI_DEVICE(s);
2101     int i;
2102     for (i = 0; i < num_vectors; i++) {
2103         msix_vector_unuse(d, i);
2104     }
2105 }
2106 
2107 static void
2108 vmxnet3_use_msix_vectors(VMXNET3State *s, int num_vectors)
2109 {
2110     PCIDevice *d = PCI_DEVICE(s);
2111     int i;
2112     for (i = 0; i < num_vectors; i++) {
2113         msix_vector_use(d, i);
2114     }
2115 }
2116 
2117 static bool
2118 vmxnet3_init_msix(VMXNET3State *s)
2119 {
2120     PCIDevice *d = PCI_DEVICE(s);
2121     int res = msix_init(d, VMXNET3_MAX_INTRS,
2122                         &s->msix_bar,
2123                         VMXNET3_MSIX_BAR_IDX, VMXNET3_OFF_MSIX_TABLE,
2124                         &s->msix_bar,
2125                         VMXNET3_MSIX_BAR_IDX, VMXNET3_OFF_MSIX_PBA(s),
2126                         VMXNET3_MSIX_OFFSET(s), NULL);
2127 
2128     if (0 > res) {
2129         VMW_WRPRN("Failed to initialize MSI-X, error %d", res);
2130         s->msix_used = false;
2131     } else {
2132         vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS);
2133         s->msix_used = true;
2134     }
2135     return s->msix_used;
2136 }
2137 
2138 static void
2139 vmxnet3_cleanup_msix(VMXNET3State *s)
2140 {
2141     PCIDevice *d = PCI_DEVICE(s);
2142 
2143     if (s->msix_used) {
2144         vmxnet3_unuse_msix_vectors(s, VMXNET3_MAX_INTRS);
2145         msix_uninit(d, &s->msix_bar, &s->msix_bar);
2146     }
2147 }
2148 
2149 static void
2150 vmxnet3_cleanup_msi(VMXNET3State *s)
2151 {
2152     PCIDevice *d = PCI_DEVICE(s);
2153 
2154     msi_uninit(d);
2155 }
2156 
2157 static const MemoryRegionOps b0_ops = {
2158     .read = vmxnet3_io_bar0_read,
2159     .write = vmxnet3_io_bar0_write,
2160     .endianness = DEVICE_LITTLE_ENDIAN,
2161     .impl = {
2162             .min_access_size = 4,
2163             .max_access_size = 4,
2164     },
2165 };
2166 
2167 static const MemoryRegionOps b1_ops = {
2168     .read = vmxnet3_io_bar1_read,
2169     .write = vmxnet3_io_bar1_write,
2170     .endianness = DEVICE_LITTLE_ENDIAN,
2171     .impl = {
2172             .min_access_size = 4,
2173             .max_access_size = 4,
2174     },
2175 };
2176 
2177 static uint64_t vmxnet3_device_serial_num(VMXNET3State *s)
2178 {
2179     uint64_t dsn_payload;
2180     uint8_t *dsnp = (uint8_t *)&dsn_payload;
2181 
2182     dsnp[0] = 0xfe;
2183     dsnp[1] = s->conf.macaddr.a[3];
2184     dsnp[2] = s->conf.macaddr.a[4];
2185     dsnp[3] = s->conf.macaddr.a[5];
2186     dsnp[4] = s->conf.macaddr.a[0];
2187     dsnp[5] = s->conf.macaddr.a[1];
2188     dsnp[6] = s->conf.macaddr.a[2];
2189     dsnp[7] = 0xff;
2190     return dsn_payload;
2191 }
2192 
2193 
2194 #define VMXNET3_USE_64BIT         (true)
2195 #define VMXNET3_PER_VECTOR_MASK   (false)
2196 
2197 static void vmxnet3_pci_realize(PCIDevice *pci_dev, Error **errp)
2198 {
2199     VMXNET3State *s = VMXNET3(pci_dev);
2200     int ret;
2201 
2202     VMW_CBPRN("Starting init...");
2203 
2204     memory_region_init_io(&s->bar0, OBJECT(s), &b0_ops, s,
2205                           "vmxnet3-b0", VMXNET3_PT_REG_SIZE);
2206     pci_register_bar(pci_dev, VMXNET3_BAR0_IDX,
2207                      PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar0);
2208 
2209     memory_region_init_io(&s->bar1, OBJECT(s), &b1_ops, s,
2210                           "vmxnet3-b1", VMXNET3_VD_REG_SIZE);
2211     pci_register_bar(pci_dev, VMXNET3_BAR1_IDX,
2212                      PCI_BASE_ADDRESS_SPACE_MEMORY, &s->bar1);
2213 
2214     memory_region_init(&s->msix_bar, OBJECT(s), "vmxnet3-msix-bar",
2215                        VMXNET3_MSIX_BAR_SIZE);
2216     pci_register_bar(pci_dev, VMXNET3_MSIX_BAR_IDX,
2217                      PCI_BASE_ADDRESS_SPACE_MEMORY, &s->msix_bar);
2218 
2219     vmxnet3_reset_interrupt_states(s);
2220 
2221     /* Interrupt pin A */
2222     pci_dev->config[PCI_INTERRUPT_PIN] = 0x01;
2223 
2224     ret = msi_init(pci_dev, VMXNET3_MSI_OFFSET(s), VMXNET3_MAX_NMSIX_INTRS,
2225                    VMXNET3_USE_64BIT, VMXNET3_PER_VECTOR_MASK, NULL);
2226     /* Any error other than -ENOTSUP(board's MSI support is broken)
2227      * is a programming error. Fall back to INTx silently on -ENOTSUP */
2228     assert(!ret || ret == -ENOTSUP);
2229 
2230     if (!vmxnet3_init_msix(s)) {
2231         VMW_WRPRN("Failed to initialize MSI-X, configuration is inconsistent.");
2232     }
2233 
2234     vmxnet3_net_init(s);
2235 
2236     if (pci_is_express(pci_dev)) {
2237         if (pci_bus_is_express(pci_get_bus(pci_dev))) {
2238             pcie_endpoint_cap_init(pci_dev, VMXNET3_EXP_EP_OFFSET);
2239         }
2240 
2241         pcie_dev_ser_num_init(pci_dev, VMXNET3_DSN_OFFSET,
2242                               vmxnet3_device_serial_num(s));
2243     }
2244 }
2245 
2246 static void vmxnet3_instance_init(Object *obj)
2247 {
2248     VMXNET3State *s = VMXNET3(obj);
2249     device_add_bootindex_property(obj, &s->conf.bootindex,
2250                                   "bootindex", "/ethernet-phy@0",
2251                                   DEVICE(obj));
2252 }
2253 
2254 static void vmxnet3_pci_uninit(PCIDevice *pci_dev)
2255 {
2256     VMXNET3State *s = VMXNET3(pci_dev);
2257 
2258     VMW_CBPRN("Starting uninit...");
2259 
2260     vmxnet3_net_uninit(s);
2261 
2262     vmxnet3_cleanup_msix(s);
2263 
2264     vmxnet3_cleanup_msi(s);
2265 }
2266 
2267 static void vmxnet3_qdev_reset(DeviceState *dev)
2268 {
2269     PCIDevice *d = PCI_DEVICE(dev);
2270     VMXNET3State *s = VMXNET3(d);
2271 
2272     VMW_CBPRN("Starting QDEV reset...");
2273     vmxnet3_reset(s);
2274 }
2275 
2276 static bool vmxnet3_mc_list_needed(void *opaque)
2277 {
2278     return true;
2279 }
2280 
2281 static int vmxnet3_mcast_list_pre_load(void *opaque)
2282 {
2283     VMXNET3State *s = opaque;
2284 
2285     s->mcast_list = g_malloc(s->mcast_list_buff_size);
2286 
2287     return 0;
2288 }
2289 
2290 
2291 static int vmxnet3_pre_save(void *opaque)
2292 {
2293     VMXNET3State *s = opaque;
2294 
2295     s->mcast_list_buff_size = s->mcast_list_len * sizeof(MACAddr);
2296 
2297     return 0;
2298 }
2299 
2300 static const VMStateDescription vmxstate_vmxnet3_mcast_list = {
2301     .name = "vmxnet3/mcast_list",
2302     .version_id = 1,
2303     .minimum_version_id = 1,
2304     .pre_load = vmxnet3_mcast_list_pre_load,
2305     .needed = vmxnet3_mc_list_needed,
2306     .fields = (const VMStateField[]) {
2307         VMSTATE_VBUFFER_UINT32(mcast_list, VMXNET3State, 0, NULL,
2308             mcast_list_buff_size),
2309         VMSTATE_END_OF_LIST()
2310     }
2311 };
2312 
2313 static const VMStateDescription vmstate_vmxnet3_ring = {
2314     .name = "vmxnet3-ring",
2315     .version_id = 0,
2316     .fields = (const VMStateField[]) {
2317         VMSTATE_UINT64(pa, Vmxnet3Ring),
2318         VMSTATE_UINT32(size, Vmxnet3Ring),
2319         VMSTATE_UINT32(cell_size, Vmxnet3Ring),
2320         VMSTATE_UINT32(next, Vmxnet3Ring),
2321         VMSTATE_UINT8(gen, Vmxnet3Ring),
2322         VMSTATE_END_OF_LIST()
2323     }
2324 };
2325 
2326 static const VMStateDescription vmstate_vmxnet3_tx_stats = {
2327     .name = "vmxnet3-tx-stats",
2328     .version_id = 0,
2329     .fields = (const VMStateField[]) {
2330         VMSTATE_UINT64(TSOPktsTxOK, struct UPT1_TxStats),
2331         VMSTATE_UINT64(TSOBytesTxOK, struct UPT1_TxStats),
2332         VMSTATE_UINT64(ucastPktsTxOK, struct UPT1_TxStats),
2333         VMSTATE_UINT64(ucastBytesTxOK, struct UPT1_TxStats),
2334         VMSTATE_UINT64(mcastPktsTxOK, struct UPT1_TxStats),
2335         VMSTATE_UINT64(mcastBytesTxOK, struct UPT1_TxStats),
2336         VMSTATE_UINT64(bcastPktsTxOK, struct UPT1_TxStats),
2337         VMSTATE_UINT64(bcastBytesTxOK, struct UPT1_TxStats),
2338         VMSTATE_UINT64(pktsTxError, struct UPT1_TxStats),
2339         VMSTATE_UINT64(pktsTxDiscard, struct UPT1_TxStats),
2340         VMSTATE_END_OF_LIST()
2341     }
2342 };
2343 
2344 static const VMStateDescription vmstate_vmxnet3_txq_descr = {
2345     .name = "vmxnet3-txq-descr",
2346     .version_id = 0,
2347     .fields = (const VMStateField[]) {
2348         VMSTATE_STRUCT(tx_ring, Vmxnet3TxqDescr, 0, vmstate_vmxnet3_ring,
2349                        Vmxnet3Ring),
2350         VMSTATE_STRUCT(comp_ring, Vmxnet3TxqDescr, 0, vmstate_vmxnet3_ring,
2351                        Vmxnet3Ring),
2352         VMSTATE_UINT8(intr_idx, Vmxnet3TxqDescr),
2353         VMSTATE_UINT64(tx_stats_pa, Vmxnet3TxqDescr),
2354         VMSTATE_STRUCT(txq_stats, Vmxnet3TxqDescr, 0, vmstate_vmxnet3_tx_stats,
2355                        struct UPT1_TxStats),
2356         VMSTATE_END_OF_LIST()
2357     }
2358 };
2359 
2360 static const VMStateDescription vmstate_vmxnet3_rx_stats = {
2361     .name = "vmxnet3-rx-stats",
2362     .version_id = 0,
2363     .fields = (const VMStateField[]) {
2364         VMSTATE_UINT64(LROPktsRxOK, struct UPT1_RxStats),
2365         VMSTATE_UINT64(LROBytesRxOK, struct UPT1_RxStats),
2366         VMSTATE_UINT64(ucastPktsRxOK, struct UPT1_RxStats),
2367         VMSTATE_UINT64(ucastBytesRxOK, struct UPT1_RxStats),
2368         VMSTATE_UINT64(mcastPktsRxOK, struct UPT1_RxStats),
2369         VMSTATE_UINT64(mcastBytesRxOK, struct UPT1_RxStats),
2370         VMSTATE_UINT64(bcastPktsRxOK, struct UPT1_RxStats),
2371         VMSTATE_UINT64(bcastBytesRxOK, struct UPT1_RxStats),
2372         VMSTATE_UINT64(pktsRxOutOfBuf, struct UPT1_RxStats),
2373         VMSTATE_UINT64(pktsRxError, struct UPT1_RxStats),
2374         VMSTATE_END_OF_LIST()
2375     }
2376 };
2377 
2378 static const VMStateDescription vmstate_vmxnet3_rxq_descr = {
2379     .name = "vmxnet3-rxq-descr",
2380     .version_id = 0,
2381     .fields = (const VMStateField[]) {
2382         VMSTATE_STRUCT_ARRAY(rx_ring, Vmxnet3RxqDescr,
2383                              VMXNET3_RX_RINGS_PER_QUEUE, 0,
2384                              vmstate_vmxnet3_ring, Vmxnet3Ring),
2385         VMSTATE_STRUCT(comp_ring, Vmxnet3RxqDescr, 0, vmstate_vmxnet3_ring,
2386                        Vmxnet3Ring),
2387         VMSTATE_UINT8(intr_idx, Vmxnet3RxqDescr),
2388         VMSTATE_UINT64(rx_stats_pa, Vmxnet3RxqDescr),
2389         VMSTATE_STRUCT(rxq_stats, Vmxnet3RxqDescr, 0, vmstate_vmxnet3_rx_stats,
2390                        struct UPT1_RxStats),
2391         VMSTATE_END_OF_LIST()
2392     }
2393 };
2394 
2395 static int vmxnet3_post_load(void *opaque, int version_id)
2396 {
2397     VMXNET3State *s = opaque;
2398 
2399     net_tx_pkt_init(&s->tx_pkt, s->max_tx_frags);
2400     net_rx_pkt_init(&s->rx_pkt);
2401 
2402     if (s->msix_used) {
2403         vmxnet3_use_msix_vectors(s, VMXNET3_MAX_INTRS);
2404     }
2405 
2406     if (!vmxnet3_validate_queues(s)) {
2407         return -1;
2408     }
2409     vmxnet3_validate_interrupts(s);
2410 
2411     return 0;
2412 }
2413 
2414 static const VMStateDescription vmstate_vmxnet3_int_state = {
2415     .name = "vmxnet3-int-state",
2416     .version_id = 0,
2417     .fields = (const VMStateField[]) {
2418         VMSTATE_BOOL(is_masked, Vmxnet3IntState),
2419         VMSTATE_BOOL(is_pending, Vmxnet3IntState),
2420         VMSTATE_BOOL(is_asserted, Vmxnet3IntState),
2421         VMSTATE_END_OF_LIST()
2422     }
2423 };
2424 
2425 static const VMStateDescription vmstate_vmxnet3 = {
2426     .name = "vmxnet3",
2427     .version_id = 1,
2428     .minimum_version_id = 1,
2429     .pre_save = vmxnet3_pre_save,
2430     .post_load = vmxnet3_post_load,
2431     .fields = (const VMStateField[]) {
2432             VMSTATE_PCI_DEVICE(parent_obj, VMXNET3State),
2433             VMSTATE_MSIX(parent_obj, VMXNET3State),
2434             VMSTATE_BOOL(rx_packets_compound, VMXNET3State),
2435             VMSTATE_BOOL(rx_vlan_stripping, VMXNET3State),
2436             VMSTATE_BOOL(lro_supported, VMXNET3State),
2437             VMSTATE_UINT32(rx_mode, VMXNET3State),
2438             VMSTATE_UINT32(mcast_list_len, VMXNET3State),
2439             VMSTATE_UINT32(mcast_list_buff_size, VMXNET3State),
2440             VMSTATE_UINT32_ARRAY(vlan_table, VMXNET3State, VMXNET3_VFT_SIZE),
2441             VMSTATE_UINT32(mtu, VMXNET3State),
2442             VMSTATE_UINT16(max_rx_frags, VMXNET3State),
2443             VMSTATE_UINT32(max_tx_frags, VMXNET3State),
2444             VMSTATE_UINT8(event_int_idx, VMXNET3State),
2445             VMSTATE_BOOL(auto_int_masking, VMXNET3State),
2446             VMSTATE_UINT8(txq_num, VMXNET3State),
2447             VMSTATE_UINT8(rxq_num, VMXNET3State),
2448             VMSTATE_UINT32(device_active, VMXNET3State),
2449             VMSTATE_UINT32(last_command, VMXNET3State),
2450             VMSTATE_UINT32(link_status_and_speed, VMXNET3State),
2451             VMSTATE_UINT32(temp_mac, VMXNET3State),
2452             VMSTATE_UINT64(drv_shmem, VMXNET3State),
2453             VMSTATE_UINT64(temp_shared_guest_driver_memory, VMXNET3State),
2454 
2455             VMSTATE_STRUCT_ARRAY(txq_descr, VMXNET3State,
2456                 VMXNET3_DEVICE_MAX_TX_QUEUES, 0, vmstate_vmxnet3_txq_descr,
2457                 Vmxnet3TxqDescr),
2458             VMSTATE_STRUCT_ARRAY(rxq_descr, VMXNET3State,
2459                 VMXNET3_DEVICE_MAX_RX_QUEUES, 0, vmstate_vmxnet3_rxq_descr,
2460                 Vmxnet3RxqDescr),
2461             VMSTATE_STRUCT_ARRAY(interrupt_states, VMXNET3State,
2462                 VMXNET3_MAX_INTRS, 0, vmstate_vmxnet3_int_state,
2463                 Vmxnet3IntState),
2464 
2465             VMSTATE_END_OF_LIST()
2466     },
2467     .subsections = (const VMStateDescription * const []) {
2468         &vmxstate_vmxnet3_mcast_list,
2469         NULL
2470     }
2471 };
2472 
2473 static const Property vmxnet3_properties[] = {
2474     DEFINE_NIC_PROPERTIES(VMXNET3State, conf),
2475     DEFINE_PROP_BIT("x-old-msi-offsets", VMXNET3State, compat_flags,
2476                     VMXNET3_COMPAT_FLAG_OLD_MSI_OFFSETS_BIT, false),
2477     DEFINE_PROP_BIT("x-disable-pcie", VMXNET3State, compat_flags,
2478                     VMXNET3_COMPAT_FLAG_DISABLE_PCIE_BIT, false),
2479 };
2480 
2481 static void vmxnet3_realize(DeviceState *qdev, Error **errp)
2482 {
2483     VMXNET3Class *vc = VMXNET3_DEVICE_GET_CLASS(qdev);
2484     PCIDevice *pci_dev = PCI_DEVICE(qdev);
2485     VMXNET3State *s = VMXNET3(qdev);
2486 
2487     if (!(s->compat_flags & VMXNET3_COMPAT_FLAG_DISABLE_PCIE)) {
2488         pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;
2489     }
2490 
2491     vc->parent_dc_realize(qdev, errp);
2492 }
2493 
2494 static void vmxnet3_class_init(ObjectClass *class, const void *data)
2495 {
2496     DeviceClass *dc = DEVICE_CLASS(class);
2497     PCIDeviceClass *c = PCI_DEVICE_CLASS(class);
2498     VMXNET3Class *vc = VMXNET3_DEVICE_CLASS(class);
2499 
2500     c->realize = vmxnet3_pci_realize;
2501     c->exit = vmxnet3_pci_uninit;
2502     c->vendor_id = PCI_VENDOR_ID_VMWARE;
2503     c->device_id = PCI_DEVICE_ID_VMWARE_VMXNET3;
2504     c->revision = PCI_DEVICE_ID_VMWARE_VMXNET3_REVISION;
2505     c->romfile = "efi-vmxnet3.rom";
2506     c->class_id = PCI_CLASS_NETWORK_ETHERNET;
2507     c->subsystem_vendor_id = PCI_VENDOR_ID_VMWARE;
2508     c->subsystem_id = PCI_DEVICE_ID_VMWARE_VMXNET3;
2509     device_class_set_parent_realize(dc, vmxnet3_realize,
2510                                     &vc->parent_dc_realize);
2511     dc->desc = "VMWare Paravirtualized Ethernet v3";
2512     device_class_set_legacy_reset(dc, vmxnet3_qdev_reset);
2513     dc->vmsd = &vmstate_vmxnet3;
2514     device_class_set_props(dc, vmxnet3_properties);
2515     set_bit(DEVICE_CATEGORY_NETWORK, dc->categories);
2516 }
2517 
2518 static const TypeInfo vmxnet3_info = {
2519     .name          = TYPE_VMXNET3,
2520     .parent        = TYPE_PCI_DEVICE,
2521     .class_size    = sizeof(VMXNET3Class),
2522     .instance_size = sizeof(VMXNET3State),
2523     .class_init    = vmxnet3_class_init,
2524     .instance_init = vmxnet3_instance_init,
2525     .interfaces = (const InterfaceInfo[]) {
2526         { INTERFACE_PCIE_DEVICE },
2527         { INTERFACE_CONVENTIONAL_PCI_DEVICE },
2528         { }
2529     },
2530 };
2531 
2532 static void vmxnet3_register_types(void)
2533 {
2534     VMW_CBPRN("vmxnet3_register_types called...");
2535     type_register_static(&vmxnet3_info);
2536 }
2537 
2538 type_init(vmxnet3_register_types)
2539