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