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