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