xref: /qemu/hw/net/virtio-net.c (revision e3404e01)
1 /*
2  * Virtio Network Device
3  *
4  * Copyright IBM, Corp. 2007
5  *
6  * Authors:
7  *  Anthony Liguori   <aliguori@us.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 #include "qemu/atomic.h"
16 #include "qemu/iov.h"
17 #include "qemu/log.h"
18 #include "qemu/main-loop.h"
19 #include "qemu/module.h"
20 #include "hw/virtio/virtio.h"
21 #include "net/net.h"
22 #include "net/checksum.h"
23 #include "net/tap.h"
24 #include "qemu/error-report.h"
25 #include "qemu/timer.h"
26 #include "qemu/option.h"
27 #include "qemu/option_int.h"
28 #include "qemu/config-file.h"
29 #include "qapi/qmp/qdict.h"
30 #include "hw/virtio/virtio-net.h"
31 #include "net/vhost_net.h"
32 #include "net/announce.h"
33 #include "hw/virtio/virtio-bus.h"
34 #include "qapi/error.h"
35 #include "qapi/qapi-events-net.h"
36 #include "hw/qdev-properties.h"
37 #include "qapi/qapi-types-migration.h"
38 #include "qapi/qapi-events-migration.h"
39 #include "hw/virtio/virtio-access.h"
40 #include "migration/misc.h"
41 #include "standard-headers/linux/ethtool.h"
42 #include "sysemu/sysemu.h"
43 #include "trace.h"
44 #include "monitor/qdev.h"
45 #include "monitor/monitor.h"
46 #include "hw/pci/pci_device.h"
47 #include "net_rx_pkt.h"
48 #include "hw/virtio/vhost.h"
49 #include "sysemu/qtest.h"
50 
51 #define VIRTIO_NET_VM_VERSION    11
52 
53 /* previously fixed value */
54 #define VIRTIO_NET_RX_QUEUE_DEFAULT_SIZE 256
55 #define VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE 256
56 
57 /* for now, only allow larger queue_pairs; with virtio-1, guest can downsize */
58 #define VIRTIO_NET_RX_QUEUE_MIN_SIZE VIRTIO_NET_RX_QUEUE_DEFAULT_SIZE
59 #define VIRTIO_NET_TX_QUEUE_MIN_SIZE VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE
60 
61 #define VIRTIO_NET_IP4_ADDR_SIZE   8        /* ipv4 saddr + daddr */
62 
63 #define VIRTIO_NET_TCP_FLAG         0x3F
64 #define VIRTIO_NET_TCP_HDR_LENGTH   0xF000
65 
66 /* IPv4 max payload, 16 bits in the header */
67 #define VIRTIO_NET_MAX_IP4_PAYLOAD (65535 - sizeof(struct ip_header))
68 #define VIRTIO_NET_MAX_TCP_PAYLOAD 65535
69 
70 /* header length value in ip header without option */
71 #define VIRTIO_NET_IP4_HEADER_LENGTH 5
72 
73 #define VIRTIO_NET_IP6_ADDR_SIZE   32      /* ipv6 saddr + daddr */
74 #define VIRTIO_NET_MAX_IP6_PAYLOAD VIRTIO_NET_MAX_TCP_PAYLOAD
75 
76 /* Purge coalesced packets timer interval, This value affects the performance
77    a lot, and should be tuned carefully, '300000'(300us) is the recommended
78    value to pass the WHQL test, '50000' can gain 2x netperf throughput with
79    tso/gso/gro 'off'. */
80 #define VIRTIO_NET_RSC_DEFAULT_INTERVAL 300000
81 
82 #define VIRTIO_NET_RSS_SUPPORTED_HASHES (VIRTIO_NET_RSS_HASH_TYPE_IPv4 | \
83                                          VIRTIO_NET_RSS_HASH_TYPE_TCPv4 | \
84                                          VIRTIO_NET_RSS_HASH_TYPE_UDPv4 | \
85                                          VIRTIO_NET_RSS_HASH_TYPE_IPv6 | \
86                                          VIRTIO_NET_RSS_HASH_TYPE_TCPv6 | \
87                                          VIRTIO_NET_RSS_HASH_TYPE_UDPv6 | \
88                                          VIRTIO_NET_RSS_HASH_TYPE_IP_EX | \
89                                          VIRTIO_NET_RSS_HASH_TYPE_TCP_EX | \
90                                          VIRTIO_NET_RSS_HASH_TYPE_UDP_EX)
91 
92 static const VirtIOFeature feature_sizes[] = {
93     {.flags = 1ULL << VIRTIO_NET_F_MAC,
94      .end = endof(struct virtio_net_config, mac)},
95     {.flags = 1ULL << VIRTIO_NET_F_STATUS,
96      .end = endof(struct virtio_net_config, status)},
97     {.flags = 1ULL << VIRTIO_NET_F_MQ,
98      .end = endof(struct virtio_net_config, max_virtqueue_pairs)},
99     {.flags = 1ULL << VIRTIO_NET_F_MTU,
100      .end = endof(struct virtio_net_config, mtu)},
101     {.flags = 1ULL << VIRTIO_NET_F_SPEED_DUPLEX,
102      .end = endof(struct virtio_net_config, duplex)},
103     {.flags = (1ULL << VIRTIO_NET_F_RSS) | (1ULL << VIRTIO_NET_F_HASH_REPORT),
104      .end = endof(struct virtio_net_config, supported_hash_types)},
105     {}
106 };
107 
108 static const VirtIOConfigSizeParams cfg_size_params = {
109     .min_size = endof(struct virtio_net_config, mac),
110     .max_size = sizeof(struct virtio_net_config),
111     .feature_sizes = feature_sizes
112 };
113 
114 static VirtIONetQueue *virtio_net_get_subqueue(NetClientState *nc)
115 {
116     VirtIONet *n = qemu_get_nic_opaque(nc);
117 
118     return &n->vqs[nc->queue_index];
119 }
120 
121 static int vq2q(int queue_index)
122 {
123     return queue_index / 2;
124 }
125 
126 static void flush_or_purge_queued_packets(NetClientState *nc)
127 {
128     if (!nc->peer) {
129         return;
130     }
131 
132     qemu_flush_or_purge_queued_packets(nc->peer, true);
133     assert(!virtio_net_get_subqueue(nc)->async_tx.elem);
134 }
135 
136 /* TODO
137  * - we could suppress RX interrupt if we were so inclined.
138  */
139 
140 static void virtio_net_get_config(VirtIODevice *vdev, uint8_t *config)
141 {
142     VirtIONet *n = VIRTIO_NET(vdev);
143     struct virtio_net_config netcfg;
144     NetClientState *nc = qemu_get_queue(n->nic);
145     static const MACAddr zero = { .a = { 0, 0, 0, 0, 0, 0 } };
146 
147     int ret = 0;
148     memset(&netcfg, 0 , sizeof(struct virtio_net_config));
149     virtio_stw_p(vdev, &netcfg.status, n->status);
150     virtio_stw_p(vdev, &netcfg.max_virtqueue_pairs, n->max_queue_pairs);
151     virtio_stw_p(vdev, &netcfg.mtu, n->net_conf.mtu);
152     memcpy(netcfg.mac, n->mac, ETH_ALEN);
153     virtio_stl_p(vdev, &netcfg.speed, n->net_conf.speed);
154     netcfg.duplex = n->net_conf.duplex;
155     netcfg.rss_max_key_size = VIRTIO_NET_RSS_MAX_KEY_SIZE;
156     virtio_stw_p(vdev, &netcfg.rss_max_indirection_table_length,
157                  virtio_host_has_feature(vdev, VIRTIO_NET_F_RSS) ?
158                  VIRTIO_NET_RSS_MAX_TABLE_LEN : 1);
159     virtio_stl_p(vdev, &netcfg.supported_hash_types,
160                  VIRTIO_NET_RSS_SUPPORTED_HASHES);
161     memcpy(config, &netcfg, n->config_size);
162 
163     /*
164      * Is this VDPA? No peer means not VDPA: there's no way to
165      * disconnect/reconnect a VDPA peer.
166      */
167     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_VDPA) {
168         ret = vhost_net_get_config(get_vhost_net(nc->peer), (uint8_t *)&netcfg,
169                                    n->config_size);
170         if (ret == -1) {
171             return;
172         }
173 
174         /*
175          * Some NIC/kernel combinations present 0 as the mac address.  As that
176          * is not a legal address, try to proceed with the address from the
177          * QEMU command line in the hope that the address has been configured
178          * correctly elsewhere - just not reported by the device.
179          */
180         if (memcmp(&netcfg.mac, &zero, sizeof(zero)) == 0) {
181             info_report("Zero hardware mac address detected. Ignoring.");
182             memcpy(netcfg.mac, n->mac, ETH_ALEN);
183         }
184 
185         netcfg.status |= virtio_tswap16(vdev,
186                                         n->status & VIRTIO_NET_S_ANNOUNCE);
187         memcpy(config, &netcfg, n->config_size);
188     }
189 }
190 
191 static void virtio_net_set_config(VirtIODevice *vdev, const uint8_t *config)
192 {
193     VirtIONet *n = VIRTIO_NET(vdev);
194     struct virtio_net_config netcfg = {};
195     NetClientState *nc = qemu_get_queue(n->nic);
196 
197     memcpy(&netcfg, config, n->config_size);
198 
199     if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_MAC_ADDR) &&
200         !virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1) &&
201         memcmp(netcfg.mac, n->mac, ETH_ALEN)) {
202         memcpy(n->mac, netcfg.mac, ETH_ALEN);
203         qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
204     }
205 
206     /*
207      * Is this VDPA? No peer means not VDPA: there's no way to
208      * disconnect/reconnect a VDPA peer.
209      */
210     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_VDPA) {
211         vhost_net_set_config(get_vhost_net(nc->peer),
212                              (uint8_t *)&netcfg, 0, n->config_size,
213                              VHOST_SET_CONFIG_TYPE_FRONTEND);
214       }
215 }
216 
217 static bool virtio_net_started(VirtIONet *n, uint8_t status)
218 {
219     VirtIODevice *vdev = VIRTIO_DEVICE(n);
220     return (status & VIRTIO_CONFIG_S_DRIVER_OK) &&
221         (n->status & VIRTIO_NET_S_LINK_UP) && vdev->vm_running;
222 }
223 
224 static void virtio_net_announce_notify(VirtIONet *net)
225 {
226     VirtIODevice *vdev = VIRTIO_DEVICE(net);
227     trace_virtio_net_announce_notify();
228 
229     net->status |= VIRTIO_NET_S_ANNOUNCE;
230     virtio_notify_config(vdev);
231 }
232 
233 static void virtio_net_announce_timer(void *opaque)
234 {
235     VirtIONet *n = opaque;
236     trace_virtio_net_announce_timer(n->announce_timer.round);
237 
238     n->announce_timer.round--;
239     virtio_net_announce_notify(n);
240 }
241 
242 static void virtio_net_announce(NetClientState *nc)
243 {
244     VirtIONet *n = qemu_get_nic_opaque(nc);
245     VirtIODevice *vdev = VIRTIO_DEVICE(n);
246 
247     /*
248      * Make sure the virtio migration announcement timer isn't running
249      * If it is, let it trigger announcement so that we do not cause
250      * confusion.
251      */
252     if (n->announce_timer.round) {
253         return;
254     }
255 
256     if (virtio_vdev_has_feature(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE) &&
257         virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
258             virtio_net_announce_notify(n);
259     }
260 }
261 
262 static void virtio_net_vhost_status(VirtIONet *n, uint8_t status)
263 {
264     VirtIODevice *vdev = VIRTIO_DEVICE(n);
265     NetClientState *nc = qemu_get_queue(n->nic);
266     int queue_pairs = n->multiqueue ? n->max_queue_pairs : 1;
267     int cvq = virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ) ?
268               n->max_ncs - n->max_queue_pairs : 0;
269 
270     if (!get_vhost_net(nc->peer)) {
271         return;
272     }
273 
274     if ((virtio_net_started(n, status) && !nc->peer->link_down) ==
275         !!n->vhost_started) {
276         return;
277     }
278     if (!n->vhost_started) {
279         int r, i;
280 
281         if (n->needs_vnet_hdr_swap) {
282             error_report("backend does not support %s vnet headers; "
283                          "falling back on userspace virtio",
284                          virtio_is_big_endian(vdev) ? "BE" : "LE");
285             return;
286         }
287 
288         /* Any packets outstanding? Purge them to avoid touching rings
289          * when vhost is running.
290          */
291         for (i = 0;  i < queue_pairs; i++) {
292             NetClientState *qnc = qemu_get_subqueue(n->nic, i);
293 
294             /* Purge both directions: TX and RX. */
295             qemu_net_queue_purge(qnc->peer->incoming_queue, qnc);
296             qemu_net_queue_purge(qnc->incoming_queue, qnc->peer);
297         }
298 
299         if (virtio_has_feature(vdev->guest_features, VIRTIO_NET_F_MTU)) {
300             r = vhost_net_set_mtu(get_vhost_net(nc->peer), n->net_conf.mtu);
301             if (r < 0) {
302                 error_report("%uBytes MTU not supported by the backend",
303                              n->net_conf.mtu);
304 
305                 return;
306             }
307         }
308 
309         n->vhost_started = 1;
310         r = vhost_net_start(vdev, n->nic->ncs, queue_pairs, cvq);
311         if (r < 0) {
312             error_report("unable to start vhost net: %d: "
313                          "falling back on userspace virtio", -r);
314             n->vhost_started = 0;
315         }
316     } else {
317         vhost_net_stop(vdev, n->nic->ncs, queue_pairs, cvq);
318         n->vhost_started = 0;
319     }
320 }
321 
322 static int virtio_net_set_vnet_endian_one(VirtIODevice *vdev,
323                                           NetClientState *peer,
324                                           bool enable)
325 {
326     if (virtio_is_big_endian(vdev)) {
327         return qemu_set_vnet_be(peer, enable);
328     } else {
329         return qemu_set_vnet_le(peer, enable);
330     }
331 }
332 
333 static bool virtio_net_set_vnet_endian(VirtIODevice *vdev, NetClientState *ncs,
334                                        int queue_pairs, bool enable)
335 {
336     int i;
337 
338     for (i = 0; i < queue_pairs; i++) {
339         if (virtio_net_set_vnet_endian_one(vdev, ncs[i].peer, enable) < 0 &&
340             enable) {
341             while (--i >= 0) {
342                 virtio_net_set_vnet_endian_one(vdev, ncs[i].peer, false);
343             }
344 
345             return true;
346         }
347     }
348 
349     return false;
350 }
351 
352 static void virtio_net_vnet_endian_status(VirtIONet *n, uint8_t status)
353 {
354     VirtIODevice *vdev = VIRTIO_DEVICE(n);
355     int queue_pairs = n->multiqueue ? n->max_queue_pairs : 1;
356 
357     if (virtio_net_started(n, status)) {
358         /* Before using the device, we tell the network backend about the
359          * endianness to use when parsing vnet headers. If the backend
360          * can't do it, we fallback onto fixing the headers in the core
361          * virtio-net code.
362          */
363         n->needs_vnet_hdr_swap = virtio_net_set_vnet_endian(vdev, n->nic->ncs,
364                                                             queue_pairs, true);
365     } else if (virtio_net_started(n, vdev->status)) {
366         /* After using the device, we need to reset the network backend to
367          * the default (guest native endianness), otherwise the guest may
368          * lose network connectivity if it is rebooted into a different
369          * endianness.
370          */
371         virtio_net_set_vnet_endian(vdev, n->nic->ncs, queue_pairs, false);
372     }
373 }
374 
375 static void virtio_net_drop_tx_queue_data(VirtIODevice *vdev, VirtQueue *vq)
376 {
377     unsigned int dropped = virtqueue_drop_all(vq);
378     if (dropped) {
379         virtio_notify(vdev, vq);
380     }
381 }
382 
383 static void virtio_net_set_status(struct VirtIODevice *vdev, uint8_t status)
384 {
385     VirtIONet *n = VIRTIO_NET(vdev);
386     VirtIONetQueue *q;
387     int i;
388     uint8_t queue_status;
389 
390     virtio_net_vnet_endian_status(n, status);
391     virtio_net_vhost_status(n, status);
392 
393     for (i = 0; i < n->max_queue_pairs; i++) {
394         NetClientState *ncs = qemu_get_subqueue(n->nic, i);
395         bool queue_started;
396         q = &n->vqs[i];
397 
398         if ((!n->multiqueue && i != 0) || i >= n->curr_queue_pairs) {
399             queue_status = 0;
400         } else {
401             queue_status = status;
402         }
403         queue_started =
404             virtio_net_started(n, queue_status) && !n->vhost_started;
405 
406         if (queue_started) {
407             qemu_flush_queued_packets(ncs);
408         }
409 
410         if (!q->tx_waiting) {
411             continue;
412         }
413 
414         if (queue_started) {
415             if (q->tx_timer) {
416                 timer_mod(q->tx_timer,
417                                qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
418             } else {
419                 qemu_bh_schedule(q->tx_bh);
420             }
421         } else {
422             if (q->tx_timer) {
423                 timer_del(q->tx_timer);
424             } else {
425                 qemu_bh_cancel(q->tx_bh);
426             }
427             if ((n->status & VIRTIO_NET_S_LINK_UP) == 0 &&
428                 (queue_status & VIRTIO_CONFIG_S_DRIVER_OK) &&
429                 vdev->vm_running) {
430                 /* if tx is waiting we are likely have some packets in tx queue
431                  * and disabled notification */
432                 q->tx_waiting = 0;
433                 virtio_queue_set_notification(q->tx_vq, 1);
434                 virtio_net_drop_tx_queue_data(vdev, q->tx_vq);
435             }
436         }
437     }
438 }
439 
440 static void virtio_net_set_link_status(NetClientState *nc)
441 {
442     VirtIONet *n = qemu_get_nic_opaque(nc);
443     VirtIODevice *vdev = VIRTIO_DEVICE(n);
444     uint16_t old_status = n->status;
445 
446     if (nc->link_down)
447         n->status &= ~VIRTIO_NET_S_LINK_UP;
448     else
449         n->status |= VIRTIO_NET_S_LINK_UP;
450 
451     if (n->status != old_status)
452         virtio_notify_config(vdev);
453 
454     virtio_net_set_status(vdev, vdev->status);
455 }
456 
457 static void rxfilter_notify(NetClientState *nc)
458 {
459     VirtIONet *n = qemu_get_nic_opaque(nc);
460 
461     if (nc->rxfilter_notify_enabled) {
462         char *path = object_get_canonical_path(OBJECT(n->qdev));
463         qapi_event_send_nic_rx_filter_changed(n->netclient_name, path);
464         g_free(path);
465 
466         /* disable event notification to avoid events flooding */
467         nc->rxfilter_notify_enabled = 0;
468     }
469 }
470 
471 static intList *get_vlan_table(VirtIONet *n)
472 {
473     intList *list;
474     int i, j;
475 
476     list = NULL;
477     for (i = 0; i < MAX_VLAN >> 5; i++) {
478         for (j = 0; n->vlans[i] && j <= 0x1f; j++) {
479             if (n->vlans[i] & (1U << j)) {
480                 QAPI_LIST_PREPEND(list, (i << 5) + j);
481             }
482         }
483     }
484 
485     return list;
486 }
487 
488 static RxFilterInfo *virtio_net_query_rxfilter(NetClientState *nc)
489 {
490     VirtIONet *n = qemu_get_nic_opaque(nc);
491     VirtIODevice *vdev = VIRTIO_DEVICE(n);
492     RxFilterInfo *info;
493     strList *str_list;
494     int i;
495 
496     info = g_malloc0(sizeof(*info));
497     info->name = g_strdup(nc->name);
498     info->promiscuous = n->promisc;
499 
500     if (n->nouni) {
501         info->unicast = RX_STATE_NONE;
502     } else if (n->alluni) {
503         info->unicast = RX_STATE_ALL;
504     } else {
505         info->unicast = RX_STATE_NORMAL;
506     }
507 
508     if (n->nomulti) {
509         info->multicast = RX_STATE_NONE;
510     } else if (n->allmulti) {
511         info->multicast = RX_STATE_ALL;
512     } else {
513         info->multicast = RX_STATE_NORMAL;
514     }
515 
516     info->broadcast_allowed = n->nobcast;
517     info->multicast_overflow = n->mac_table.multi_overflow;
518     info->unicast_overflow = n->mac_table.uni_overflow;
519 
520     info->main_mac = qemu_mac_strdup_printf(n->mac);
521 
522     str_list = NULL;
523     for (i = 0; i < n->mac_table.first_multi; i++) {
524         QAPI_LIST_PREPEND(str_list,
525                       qemu_mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN));
526     }
527     info->unicast_table = str_list;
528 
529     str_list = NULL;
530     for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {
531         QAPI_LIST_PREPEND(str_list,
532                       qemu_mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN));
533     }
534     info->multicast_table = str_list;
535     info->vlan_table = get_vlan_table(n);
536 
537     if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VLAN)) {
538         info->vlan = RX_STATE_ALL;
539     } else if (!info->vlan_table) {
540         info->vlan = RX_STATE_NONE;
541     } else {
542         info->vlan = RX_STATE_NORMAL;
543     }
544 
545     /* enable event notification after query */
546     nc->rxfilter_notify_enabled = 1;
547 
548     return info;
549 }
550 
551 static void virtio_net_queue_reset(VirtIODevice *vdev, uint32_t queue_index)
552 {
553     VirtIONet *n = VIRTIO_NET(vdev);
554     NetClientState *nc;
555 
556     /* validate queue_index and skip for cvq */
557     if (queue_index >= n->max_queue_pairs * 2) {
558         return;
559     }
560 
561     nc = qemu_get_subqueue(n->nic, vq2q(queue_index));
562 
563     if (!nc->peer) {
564         return;
565     }
566 
567     if (get_vhost_net(nc->peer) &&
568         nc->peer->info->type == NET_CLIENT_DRIVER_TAP) {
569         vhost_net_virtqueue_reset(vdev, nc, queue_index);
570     }
571 
572     flush_or_purge_queued_packets(nc);
573 }
574 
575 static void virtio_net_queue_enable(VirtIODevice *vdev, uint32_t queue_index)
576 {
577     VirtIONet *n = VIRTIO_NET(vdev);
578     NetClientState *nc;
579     int r;
580 
581     /* validate queue_index and skip for cvq */
582     if (queue_index >= n->max_queue_pairs * 2) {
583         return;
584     }
585 
586     nc = qemu_get_subqueue(n->nic, vq2q(queue_index));
587 
588     if (!nc->peer || !vdev->vhost_started) {
589         return;
590     }
591 
592     if (get_vhost_net(nc->peer) &&
593         nc->peer->info->type == NET_CLIENT_DRIVER_TAP) {
594         r = vhost_net_virtqueue_restart(vdev, nc, queue_index);
595         if (r < 0) {
596             error_report("unable to restart vhost net virtqueue: %d, "
597                             "when resetting the queue", queue_index);
598         }
599     }
600 }
601 
602 static void virtio_net_reset(VirtIODevice *vdev)
603 {
604     VirtIONet *n = VIRTIO_NET(vdev);
605     int i;
606 
607     /* Reset back to compatibility mode */
608     n->promisc = 1;
609     n->allmulti = 0;
610     n->alluni = 0;
611     n->nomulti = 0;
612     n->nouni = 0;
613     n->nobcast = 0;
614     /* multiqueue is disabled by default */
615     n->curr_queue_pairs = 1;
616     timer_del(n->announce_timer.tm);
617     n->announce_timer.round = 0;
618     n->status &= ~VIRTIO_NET_S_ANNOUNCE;
619 
620     /* Flush any MAC and VLAN filter table state */
621     n->mac_table.in_use = 0;
622     n->mac_table.first_multi = 0;
623     n->mac_table.multi_overflow = 0;
624     n->mac_table.uni_overflow = 0;
625     memset(n->mac_table.macs, 0, MAC_TABLE_ENTRIES * ETH_ALEN);
626     memcpy(&n->mac[0], &n->nic->conf->macaddr, sizeof(n->mac));
627     qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
628     memset(n->vlans, 0, MAX_VLAN >> 3);
629 
630     /* Flush any async TX */
631     for (i = 0;  i < n->max_queue_pairs; i++) {
632         flush_or_purge_queued_packets(qemu_get_subqueue(n->nic, i));
633     }
634 }
635 
636 static void peer_test_vnet_hdr(VirtIONet *n)
637 {
638     NetClientState *nc = qemu_get_queue(n->nic);
639     if (!nc->peer) {
640         return;
641     }
642 
643     n->has_vnet_hdr = qemu_has_vnet_hdr(nc->peer);
644 }
645 
646 static int peer_has_vnet_hdr(VirtIONet *n)
647 {
648     return n->has_vnet_hdr;
649 }
650 
651 static int peer_has_ufo(VirtIONet *n)
652 {
653     if (!peer_has_vnet_hdr(n))
654         return 0;
655 
656     n->has_ufo = qemu_has_ufo(qemu_get_queue(n->nic)->peer);
657 
658     return n->has_ufo;
659 }
660 
661 static int peer_has_uso(VirtIONet *n)
662 {
663     if (!peer_has_vnet_hdr(n)) {
664         return 0;
665     }
666 
667     return qemu_has_uso(qemu_get_queue(n->nic)->peer);
668 }
669 
670 static void virtio_net_set_mrg_rx_bufs(VirtIONet *n, int mergeable_rx_bufs,
671                                        int version_1, int hash_report)
672 {
673     int i;
674     NetClientState *nc;
675 
676     n->mergeable_rx_bufs = mergeable_rx_bufs;
677 
678     /*
679      * Note: when extending the vnet header, please make sure to
680      * change the vnet header copying logic in virtio_net_flush_tx()
681      * as well.
682      */
683     if (version_1) {
684         n->guest_hdr_len = hash_report ?
685             sizeof(struct virtio_net_hdr_v1_hash) :
686             sizeof(struct virtio_net_hdr_mrg_rxbuf);
687         n->rss_data.populate_hash = !!hash_report;
688     } else {
689         n->guest_hdr_len = n->mergeable_rx_bufs ?
690             sizeof(struct virtio_net_hdr_mrg_rxbuf) :
691             sizeof(struct virtio_net_hdr);
692     }
693 
694     for (i = 0; i < n->max_queue_pairs; i++) {
695         nc = qemu_get_subqueue(n->nic, i);
696 
697         if (peer_has_vnet_hdr(n) &&
698             qemu_has_vnet_hdr_len(nc->peer, n->guest_hdr_len)) {
699             qemu_set_vnet_hdr_len(nc->peer, n->guest_hdr_len);
700             n->host_hdr_len = n->guest_hdr_len;
701         }
702     }
703 }
704 
705 static int virtio_net_max_tx_queue_size(VirtIONet *n)
706 {
707     NetClientState *peer = n->nic_conf.peers.ncs[0];
708 
709     /*
710      * Backends other than vhost-user or vhost-vdpa don't support max queue
711      * size.
712      */
713     if (!peer) {
714         return VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE;
715     }
716 
717     switch(peer->info->type) {
718     case NET_CLIENT_DRIVER_VHOST_USER:
719     case NET_CLIENT_DRIVER_VHOST_VDPA:
720         return VIRTQUEUE_MAX_SIZE;
721     default:
722         return VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE;
723     };
724 }
725 
726 static int peer_attach(VirtIONet *n, int index)
727 {
728     NetClientState *nc = qemu_get_subqueue(n->nic, index);
729 
730     if (!nc->peer) {
731         return 0;
732     }
733 
734     if (nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_USER) {
735         vhost_set_vring_enable(nc->peer, 1);
736     }
737 
738     if (nc->peer->info->type != NET_CLIENT_DRIVER_TAP) {
739         return 0;
740     }
741 
742     if (n->max_queue_pairs == 1) {
743         return 0;
744     }
745 
746     return tap_enable(nc->peer);
747 }
748 
749 static int peer_detach(VirtIONet *n, int index)
750 {
751     NetClientState *nc = qemu_get_subqueue(n->nic, index);
752 
753     if (!nc->peer) {
754         return 0;
755     }
756 
757     if (nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_USER) {
758         vhost_set_vring_enable(nc->peer, 0);
759     }
760 
761     if (nc->peer->info->type !=  NET_CLIENT_DRIVER_TAP) {
762         return 0;
763     }
764 
765     return tap_disable(nc->peer);
766 }
767 
768 static void virtio_net_set_queue_pairs(VirtIONet *n)
769 {
770     int i;
771     int r;
772 
773     if (n->nic->peer_deleted) {
774         return;
775     }
776 
777     for (i = 0; i < n->max_queue_pairs; i++) {
778         if (i < n->curr_queue_pairs) {
779             r = peer_attach(n, i);
780             assert(!r);
781         } else {
782             r = peer_detach(n, i);
783             assert(!r);
784         }
785     }
786 }
787 
788 static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue);
789 
790 static uint64_t virtio_net_get_features(VirtIODevice *vdev, uint64_t features,
791                                         Error **errp)
792 {
793     VirtIONet *n = VIRTIO_NET(vdev);
794     NetClientState *nc = qemu_get_queue(n->nic);
795 
796     /* Firstly sync all virtio-net possible supported features */
797     features |= n->host_features;
798 
799     virtio_add_feature(&features, VIRTIO_NET_F_MAC);
800 
801     if (!peer_has_vnet_hdr(n)) {
802         virtio_clear_feature(&features, VIRTIO_NET_F_CSUM);
803         virtio_clear_feature(&features, VIRTIO_NET_F_HOST_TSO4);
804         virtio_clear_feature(&features, VIRTIO_NET_F_HOST_TSO6);
805         virtio_clear_feature(&features, VIRTIO_NET_F_HOST_ECN);
806 
807         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_CSUM);
808         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_TSO4);
809         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_TSO6);
810         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_ECN);
811 
812         virtio_clear_feature(&features, VIRTIO_NET_F_HOST_USO);
813         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_USO4);
814         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_USO6);
815 
816         virtio_clear_feature(&features, VIRTIO_NET_F_HASH_REPORT);
817     }
818 
819     if (!peer_has_vnet_hdr(n) || !peer_has_ufo(n)) {
820         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_UFO);
821         virtio_clear_feature(&features, VIRTIO_NET_F_HOST_UFO);
822     }
823 
824     if (!peer_has_uso(n)) {
825         virtio_clear_feature(&features, VIRTIO_NET_F_HOST_USO);
826         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_USO4);
827         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_USO6);
828     }
829 
830     if (!get_vhost_net(nc->peer)) {
831         return features;
832     }
833 
834     if (!ebpf_rss_is_loaded(&n->ebpf_rss)) {
835         virtio_clear_feature(&features, VIRTIO_NET_F_RSS);
836     }
837     features = vhost_net_get_features(get_vhost_net(nc->peer), features);
838     vdev->backend_features = features;
839 
840     if (n->mtu_bypass_backend &&
841             (n->host_features & 1ULL << VIRTIO_NET_F_MTU)) {
842         features |= (1ULL << VIRTIO_NET_F_MTU);
843     }
844 
845     /*
846      * Since GUEST_ANNOUNCE is emulated the feature bit could be set without
847      * enabled. This happens in the vDPA case.
848      *
849      * Make sure the feature set is not incoherent, as the driver could refuse
850      * to start.
851      *
852      * TODO: QEMU is able to emulate a CVQ just for guest_announce purposes,
853      * helping guest to notify the new location with vDPA devices that does not
854      * support it.
855      */
856     if (!virtio_has_feature(vdev->backend_features, VIRTIO_NET_F_CTRL_VQ)) {
857         virtio_clear_feature(&features, VIRTIO_NET_F_GUEST_ANNOUNCE);
858     }
859 
860     return features;
861 }
862 
863 static uint64_t virtio_net_bad_features(VirtIODevice *vdev)
864 {
865     uint64_t features = 0;
866 
867     /* Linux kernel 2.6.25.  It understood MAC (as everyone must),
868      * but also these: */
869     virtio_add_feature(&features, VIRTIO_NET_F_MAC);
870     virtio_add_feature(&features, VIRTIO_NET_F_CSUM);
871     virtio_add_feature(&features, VIRTIO_NET_F_HOST_TSO4);
872     virtio_add_feature(&features, VIRTIO_NET_F_HOST_TSO6);
873     virtio_add_feature(&features, VIRTIO_NET_F_HOST_ECN);
874 
875     return features;
876 }
877 
878 static void virtio_net_apply_guest_offloads(VirtIONet *n)
879 {
880     qemu_set_offload(qemu_get_queue(n->nic)->peer,
881             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_CSUM)),
882             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO4)),
883             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO6)),
884             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_ECN)),
885             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_UFO)),
886             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_USO4)),
887             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_USO6)));
888 }
889 
890 static uint64_t virtio_net_guest_offloads_by_features(uint64_t features)
891 {
892     static const uint64_t guest_offloads_mask =
893         (1ULL << VIRTIO_NET_F_GUEST_CSUM) |
894         (1ULL << VIRTIO_NET_F_GUEST_TSO4) |
895         (1ULL << VIRTIO_NET_F_GUEST_TSO6) |
896         (1ULL << VIRTIO_NET_F_GUEST_ECN)  |
897         (1ULL << VIRTIO_NET_F_GUEST_UFO)  |
898         (1ULL << VIRTIO_NET_F_GUEST_USO4) |
899         (1ULL << VIRTIO_NET_F_GUEST_USO6);
900 
901     return guest_offloads_mask & features;
902 }
903 
904 uint64_t virtio_net_supported_guest_offloads(const VirtIONet *n)
905 {
906     VirtIODevice *vdev = VIRTIO_DEVICE(n);
907     return virtio_net_guest_offloads_by_features(vdev->guest_features);
908 }
909 
910 typedef struct {
911     VirtIONet *n;
912     DeviceState *dev;
913 } FailoverDevice;
914 
915 /**
916  * Set the failover primary device
917  *
918  * @opaque: FailoverId to setup
919  * @opts: opts for device we are handling
920  * @errp: returns an error if this function fails
921  */
922 static int failover_set_primary(DeviceState *dev, void *opaque)
923 {
924     FailoverDevice *fdev = opaque;
925     PCIDevice *pci_dev = (PCIDevice *)
926         object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE);
927 
928     if (!pci_dev) {
929         return 0;
930     }
931 
932     if (!g_strcmp0(pci_dev->failover_pair_id, fdev->n->netclient_name)) {
933         fdev->dev = dev;
934         return 1;
935     }
936 
937     return 0;
938 }
939 
940 /**
941  * Find the primary device for this failover virtio-net
942  *
943  * @n: VirtIONet device
944  * @errp: returns an error if this function fails
945  */
946 static DeviceState *failover_find_primary_device(VirtIONet *n)
947 {
948     FailoverDevice fdev = {
949         .n = n,
950     };
951 
952     qbus_walk_children(sysbus_get_default(), failover_set_primary, NULL,
953                        NULL, NULL, &fdev);
954     return fdev.dev;
955 }
956 
957 static void failover_add_primary(VirtIONet *n, Error **errp)
958 {
959     Error *err = NULL;
960     DeviceState *dev = failover_find_primary_device(n);
961 
962     if (dev) {
963         return;
964     }
965 
966     if (!n->primary_opts) {
967         error_setg(errp, "Primary device not found");
968         error_append_hint(errp, "Virtio-net failover will not work. Make "
969                           "sure primary device has parameter"
970                           " failover_pair_id=%s\n", n->netclient_name);
971         return;
972     }
973 
974     dev = qdev_device_add_from_qdict(n->primary_opts,
975                                      n->primary_opts_from_json,
976                                      &err);
977     if (err) {
978         qobject_unref(n->primary_opts);
979         n->primary_opts = NULL;
980     } else {
981         object_unref(OBJECT(dev));
982     }
983     error_propagate(errp, err);
984 }
985 
986 static void virtio_net_set_features(VirtIODevice *vdev, uint64_t features)
987 {
988     VirtIONet *n = VIRTIO_NET(vdev);
989     Error *err = NULL;
990     int i;
991 
992     if (n->mtu_bypass_backend &&
993             !virtio_has_feature(vdev->backend_features, VIRTIO_NET_F_MTU)) {
994         features &= ~(1ULL << VIRTIO_NET_F_MTU);
995     }
996 
997     virtio_net_set_multiqueue(n,
998                               virtio_has_feature(features, VIRTIO_NET_F_RSS) ||
999                               virtio_has_feature(features, VIRTIO_NET_F_MQ));
1000 
1001     virtio_net_set_mrg_rx_bufs(n,
1002                                virtio_has_feature(features,
1003                                                   VIRTIO_NET_F_MRG_RXBUF),
1004                                virtio_has_feature(features,
1005                                                   VIRTIO_F_VERSION_1),
1006                                virtio_has_feature(features,
1007                                                   VIRTIO_NET_F_HASH_REPORT));
1008 
1009     n->rsc4_enabled = virtio_has_feature(features, VIRTIO_NET_F_RSC_EXT) &&
1010         virtio_has_feature(features, VIRTIO_NET_F_GUEST_TSO4);
1011     n->rsc6_enabled = virtio_has_feature(features, VIRTIO_NET_F_RSC_EXT) &&
1012         virtio_has_feature(features, VIRTIO_NET_F_GUEST_TSO6);
1013     n->rss_data.redirect = virtio_has_feature(features, VIRTIO_NET_F_RSS);
1014 
1015     if (n->has_vnet_hdr) {
1016         n->curr_guest_offloads =
1017             virtio_net_guest_offloads_by_features(features);
1018         virtio_net_apply_guest_offloads(n);
1019     }
1020 
1021     for (i = 0;  i < n->max_queue_pairs; i++) {
1022         NetClientState *nc = qemu_get_subqueue(n->nic, i);
1023 
1024         if (!get_vhost_net(nc->peer)) {
1025             continue;
1026         }
1027         vhost_net_ack_features(get_vhost_net(nc->peer), features);
1028 
1029         /*
1030          * keep acked_features in NetVhostUserState up-to-date so it
1031          * can't miss any features configured by guest virtio driver.
1032          */
1033         vhost_net_save_acked_features(nc->peer);
1034     }
1035 
1036     if (!virtio_has_feature(features, VIRTIO_NET_F_CTRL_VLAN)) {
1037         memset(n->vlans, 0xff, MAX_VLAN >> 3);
1038     }
1039 
1040     if (virtio_has_feature(features, VIRTIO_NET_F_STANDBY)) {
1041         qapi_event_send_failover_negotiated(n->netclient_name);
1042         qatomic_set(&n->failover_primary_hidden, false);
1043         failover_add_primary(n, &err);
1044         if (err) {
1045             if (!qtest_enabled()) {
1046                 warn_report_err(err);
1047             } else {
1048                 error_free(err);
1049             }
1050         }
1051     }
1052 }
1053 
1054 static int virtio_net_handle_rx_mode(VirtIONet *n, uint8_t cmd,
1055                                      struct iovec *iov, unsigned int iov_cnt)
1056 {
1057     uint8_t on;
1058     size_t s;
1059     NetClientState *nc = qemu_get_queue(n->nic);
1060 
1061     s = iov_to_buf(iov, iov_cnt, 0, &on, sizeof(on));
1062     if (s != sizeof(on)) {
1063         return VIRTIO_NET_ERR;
1064     }
1065 
1066     if (cmd == VIRTIO_NET_CTRL_RX_PROMISC) {
1067         n->promisc = on;
1068     } else if (cmd == VIRTIO_NET_CTRL_RX_ALLMULTI) {
1069         n->allmulti = on;
1070     } else if (cmd == VIRTIO_NET_CTRL_RX_ALLUNI) {
1071         n->alluni = on;
1072     } else if (cmd == VIRTIO_NET_CTRL_RX_NOMULTI) {
1073         n->nomulti = on;
1074     } else if (cmd == VIRTIO_NET_CTRL_RX_NOUNI) {
1075         n->nouni = on;
1076     } else if (cmd == VIRTIO_NET_CTRL_RX_NOBCAST) {
1077         n->nobcast = on;
1078     } else {
1079         return VIRTIO_NET_ERR;
1080     }
1081 
1082     rxfilter_notify(nc);
1083 
1084     return VIRTIO_NET_OK;
1085 }
1086 
1087 static int virtio_net_handle_offloads(VirtIONet *n, uint8_t cmd,
1088                                      struct iovec *iov, unsigned int iov_cnt)
1089 {
1090     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1091     uint64_t offloads;
1092     size_t s;
1093 
1094     if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {
1095         return VIRTIO_NET_ERR;
1096     }
1097 
1098     s = iov_to_buf(iov, iov_cnt, 0, &offloads, sizeof(offloads));
1099     if (s != sizeof(offloads)) {
1100         return VIRTIO_NET_ERR;
1101     }
1102 
1103     if (cmd == VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET) {
1104         uint64_t supported_offloads;
1105 
1106         offloads = virtio_ldq_p(vdev, &offloads);
1107 
1108         if (!n->has_vnet_hdr) {
1109             return VIRTIO_NET_ERR;
1110         }
1111 
1112         n->rsc4_enabled = virtio_has_feature(offloads, VIRTIO_NET_F_RSC_EXT) &&
1113             virtio_has_feature(offloads, VIRTIO_NET_F_GUEST_TSO4);
1114         n->rsc6_enabled = virtio_has_feature(offloads, VIRTIO_NET_F_RSC_EXT) &&
1115             virtio_has_feature(offloads, VIRTIO_NET_F_GUEST_TSO6);
1116         virtio_clear_feature(&offloads, VIRTIO_NET_F_RSC_EXT);
1117 
1118         supported_offloads = virtio_net_supported_guest_offloads(n);
1119         if (offloads & ~supported_offloads) {
1120             return VIRTIO_NET_ERR;
1121         }
1122 
1123         n->curr_guest_offloads = offloads;
1124         virtio_net_apply_guest_offloads(n);
1125 
1126         return VIRTIO_NET_OK;
1127     } else {
1128         return VIRTIO_NET_ERR;
1129     }
1130 }
1131 
1132 static int virtio_net_handle_mac(VirtIONet *n, uint8_t cmd,
1133                                  struct iovec *iov, unsigned int iov_cnt)
1134 {
1135     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1136     struct virtio_net_ctrl_mac mac_data;
1137     size_t s;
1138     NetClientState *nc = qemu_get_queue(n->nic);
1139 
1140     if (cmd == VIRTIO_NET_CTRL_MAC_ADDR_SET) {
1141         if (iov_size(iov, iov_cnt) != sizeof(n->mac)) {
1142             return VIRTIO_NET_ERR;
1143         }
1144         s = iov_to_buf(iov, iov_cnt, 0, &n->mac, sizeof(n->mac));
1145         assert(s == sizeof(n->mac));
1146         qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
1147         rxfilter_notify(nc);
1148 
1149         return VIRTIO_NET_OK;
1150     }
1151 
1152     if (cmd != VIRTIO_NET_CTRL_MAC_TABLE_SET) {
1153         return VIRTIO_NET_ERR;
1154     }
1155 
1156     int in_use = 0;
1157     int first_multi = 0;
1158     uint8_t uni_overflow = 0;
1159     uint8_t multi_overflow = 0;
1160     uint8_t *macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);
1161 
1162     s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,
1163                    sizeof(mac_data.entries));
1164     mac_data.entries = virtio_ldl_p(vdev, &mac_data.entries);
1165     if (s != sizeof(mac_data.entries)) {
1166         goto error;
1167     }
1168     iov_discard_front(&iov, &iov_cnt, s);
1169 
1170     if (mac_data.entries * ETH_ALEN > iov_size(iov, iov_cnt)) {
1171         goto error;
1172     }
1173 
1174     if (mac_data.entries <= MAC_TABLE_ENTRIES) {
1175         s = iov_to_buf(iov, iov_cnt, 0, macs,
1176                        mac_data.entries * ETH_ALEN);
1177         if (s != mac_data.entries * ETH_ALEN) {
1178             goto error;
1179         }
1180         in_use += mac_data.entries;
1181     } else {
1182         uni_overflow = 1;
1183     }
1184 
1185     iov_discard_front(&iov, &iov_cnt, mac_data.entries * ETH_ALEN);
1186 
1187     first_multi = in_use;
1188 
1189     s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,
1190                    sizeof(mac_data.entries));
1191     mac_data.entries = virtio_ldl_p(vdev, &mac_data.entries);
1192     if (s != sizeof(mac_data.entries)) {
1193         goto error;
1194     }
1195 
1196     iov_discard_front(&iov, &iov_cnt, s);
1197 
1198     if (mac_data.entries * ETH_ALEN != iov_size(iov, iov_cnt)) {
1199         goto error;
1200     }
1201 
1202     if (mac_data.entries <= MAC_TABLE_ENTRIES - in_use) {
1203         s = iov_to_buf(iov, iov_cnt, 0, &macs[in_use * ETH_ALEN],
1204                        mac_data.entries * ETH_ALEN);
1205         if (s != mac_data.entries * ETH_ALEN) {
1206             goto error;
1207         }
1208         in_use += mac_data.entries;
1209     } else {
1210         multi_overflow = 1;
1211     }
1212 
1213     n->mac_table.in_use = in_use;
1214     n->mac_table.first_multi = first_multi;
1215     n->mac_table.uni_overflow = uni_overflow;
1216     n->mac_table.multi_overflow = multi_overflow;
1217     memcpy(n->mac_table.macs, macs, MAC_TABLE_ENTRIES * ETH_ALEN);
1218     g_free(macs);
1219     rxfilter_notify(nc);
1220 
1221     return VIRTIO_NET_OK;
1222 
1223 error:
1224     g_free(macs);
1225     return VIRTIO_NET_ERR;
1226 }
1227 
1228 static int virtio_net_handle_vlan_table(VirtIONet *n, uint8_t cmd,
1229                                         struct iovec *iov, unsigned int iov_cnt)
1230 {
1231     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1232     uint16_t vid;
1233     size_t s;
1234     NetClientState *nc = qemu_get_queue(n->nic);
1235 
1236     s = iov_to_buf(iov, iov_cnt, 0, &vid, sizeof(vid));
1237     vid = virtio_lduw_p(vdev, &vid);
1238     if (s != sizeof(vid)) {
1239         return VIRTIO_NET_ERR;
1240     }
1241 
1242     if (vid >= MAX_VLAN)
1243         return VIRTIO_NET_ERR;
1244 
1245     if (cmd == VIRTIO_NET_CTRL_VLAN_ADD)
1246         n->vlans[vid >> 5] |= (1U << (vid & 0x1f));
1247     else if (cmd == VIRTIO_NET_CTRL_VLAN_DEL)
1248         n->vlans[vid >> 5] &= ~(1U << (vid & 0x1f));
1249     else
1250         return VIRTIO_NET_ERR;
1251 
1252     rxfilter_notify(nc);
1253 
1254     return VIRTIO_NET_OK;
1255 }
1256 
1257 static int virtio_net_handle_announce(VirtIONet *n, uint8_t cmd,
1258                                       struct iovec *iov, unsigned int iov_cnt)
1259 {
1260     trace_virtio_net_handle_announce(n->announce_timer.round);
1261     if (cmd == VIRTIO_NET_CTRL_ANNOUNCE_ACK &&
1262         n->status & VIRTIO_NET_S_ANNOUNCE) {
1263         n->status &= ~VIRTIO_NET_S_ANNOUNCE;
1264         if (n->announce_timer.round) {
1265             qemu_announce_timer_step(&n->announce_timer);
1266         }
1267         return VIRTIO_NET_OK;
1268     } else {
1269         return VIRTIO_NET_ERR;
1270     }
1271 }
1272 
1273 static void virtio_net_detach_epbf_rss(VirtIONet *n);
1274 
1275 static void virtio_net_disable_rss(VirtIONet *n)
1276 {
1277     if (n->rss_data.enabled) {
1278         trace_virtio_net_rss_disable();
1279     }
1280     n->rss_data.enabled = false;
1281 
1282     virtio_net_detach_epbf_rss(n);
1283 }
1284 
1285 static bool virtio_net_attach_ebpf_to_backend(NICState *nic, int prog_fd)
1286 {
1287     NetClientState *nc = qemu_get_peer(qemu_get_queue(nic), 0);
1288     if (nc == NULL || nc->info->set_steering_ebpf == NULL) {
1289         return false;
1290     }
1291 
1292     return nc->info->set_steering_ebpf(nc, prog_fd);
1293 }
1294 
1295 static void rss_data_to_rss_config(struct VirtioNetRssData *data,
1296                                    struct EBPFRSSConfig *config)
1297 {
1298     config->redirect = data->redirect;
1299     config->populate_hash = data->populate_hash;
1300     config->hash_types = data->hash_types;
1301     config->indirections_len = data->indirections_len;
1302     config->default_queue = data->default_queue;
1303 }
1304 
1305 static bool virtio_net_attach_epbf_rss(VirtIONet *n)
1306 {
1307     struct EBPFRSSConfig config = {};
1308 
1309     if (!ebpf_rss_is_loaded(&n->ebpf_rss)) {
1310         return false;
1311     }
1312 
1313     rss_data_to_rss_config(&n->rss_data, &config);
1314 
1315     if (!ebpf_rss_set_all(&n->ebpf_rss, &config,
1316                           n->rss_data.indirections_table, n->rss_data.key)) {
1317         return false;
1318     }
1319 
1320     if (!virtio_net_attach_ebpf_to_backend(n->nic, n->ebpf_rss.program_fd)) {
1321         return false;
1322     }
1323 
1324     return true;
1325 }
1326 
1327 static void virtio_net_detach_epbf_rss(VirtIONet *n)
1328 {
1329     virtio_net_attach_ebpf_to_backend(n->nic, -1);
1330 }
1331 
1332 static bool virtio_net_load_ebpf_fds(VirtIONet *n, Error **errp)
1333 {
1334     int fds[EBPF_RSS_MAX_FDS] = { [0 ... EBPF_RSS_MAX_FDS - 1] = -1};
1335     int ret = true;
1336     int i = 0;
1337 
1338     ERRP_GUARD();
1339 
1340     if (n->nr_ebpf_rss_fds != EBPF_RSS_MAX_FDS) {
1341         error_setg(errp,
1342                   "Expected %d file descriptors but got %d",
1343                   EBPF_RSS_MAX_FDS, n->nr_ebpf_rss_fds);
1344        return false;
1345    }
1346 
1347     for (i = 0; i < n->nr_ebpf_rss_fds; i++) {
1348         fds[i] = monitor_fd_param(monitor_cur(), n->ebpf_rss_fds[i], errp);
1349         if (*errp) {
1350             ret = false;
1351             goto exit;
1352         }
1353     }
1354 
1355     ret = ebpf_rss_load_fds(&n->ebpf_rss, fds[0], fds[1], fds[2], fds[3]);
1356 
1357 exit:
1358     if (!ret || *errp) {
1359         for (i = 0; i < n->nr_ebpf_rss_fds && fds[i] != -1; i++) {
1360             close(fds[i]);
1361         }
1362     }
1363 
1364     return ret;
1365 }
1366 
1367 static bool virtio_net_load_ebpf(VirtIONet *n, Error **errp)
1368 {
1369     bool ret = false;
1370 
1371     if (virtio_net_attach_ebpf_to_backend(n->nic, -1)) {
1372         if (!(n->ebpf_rss_fds
1373                 && virtio_net_load_ebpf_fds(n, errp))) {
1374             ret = ebpf_rss_load(&n->ebpf_rss);
1375         }
1376     }
1377 
1378     return ret;
1379 }
1380 
1381 static void virtio_net_unload_ebpf(VirtIONet *n)
1382 {
1383     virtio_net_attach_ebpf_to_backend(n->nic, -1);
1384     ebpf_rss_unload(&n->ebpf_rss);
1385 }
1386 
1387 static uint16_t virtio_net_handle_rss(VirtIONet *n,
1388                                       struct iovec *iov,
1389                                       unsigned int iov_cnt,
1390                                       bool do_rss)
1391 {
1392     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1393     struct virtio_net_rss_config cfg;
1394     size_t s, offset = 0, size_get;
1395     uint16_t queue_pairs, i;
1396     struct {
1397         uint16_t us;
1398         uint8_t b;
1399     } QEMU_PACKED temp;
1400     const char *err_msg = "";
1401     uint32_t err_value = 0;
1402 
1403     if (do_rss && !virtio_vdev_has_feature(vdev, VIRTIO_NET_F_RSS)) {
1404         err_msg = "RSS is not negotiated";
1405         goto error;
1406     }
1407     if (!do_rss && !virtio_vdev_has_feature(vdev, VIRTIO_NET_F_HASH_REPORT)) {
1408         err_msg = "Hash report is not negotiated";
1409         goto error;
1410     }
1411     size_get = offsetof(struct virtio_net_rss_config, indirection_table);
1412     s = iov_to_buf(iov, iov_cnt, offset, &cfg, size_get);
1413     if (s != size_get) {
1414         err_msg = "Short command buffer";
1415         err_value = (uint32_t)s;
1416         goto error;
1417     }
1418     n->rss_data.hash_types = virtio_ldl_p(vdev, &cfg.hash_types);
1419     n->rss_data.indirections_len =
1420         virtio_lduw_p(vdev, &cfg.indirection_table_mask);
1421     n->rss_data.indirections_len++;
1422     if (!do_rss) {
1423         n->rss_data.indirections_len = 1;
1424     }
1425     if (!is_power_of_2(n->rss_data.indirections_len)) {
1426         err_msg = "Invalid size of indirection table";
1427         err_value = n->rss_data.indirections_len;
1428         goto error;
1429     }
1430     if (n->rss_data.indirections_len > VIRTIO_NET_RSS_MAX_TABLE_LEN) {
1431         err_msg = "Too large indirection table";
1432         err_value = n->rss_data.indirections_len;
1433         goto error;
1434     }
1435     n->rss_data.default_queue = do_rss ?
1436         virtio_lduw_p(vdev, &cfg.unclassified_queue) : 0;
1437     if (n->rss_data.default_queue >= n->max_queue_pairs) {
1438         err_msg = "Invalid default queue";
1439         err_value = n->rss_data.default_queue;
1440         goto error;
1441     }
1442     offset += size_get;
1443     size_get = sizeof(uint16_t) * n->rss_data.indirections_len;
1444     g_free(n->rss_data.indirections_table);
1445     n->rss_data.indirections_table = g_malloc(size_get);
1446     if (!n->rss_data.indirections_table) {
1447         err_msg = "Can't allocate indirections table";
1448         err_value = n->rss_data.indirections_len;
1449         goto error;
1450     }
1451     s = iov_to_buf(iov, iov_cnt, offset,
1452                    n->rss_data.indirections_table, size_get);
1453     if (s != size_get) {
1454         err_msg = "Short indirection table buffer";
1455         err_value = (uint32_t)s;
1456         goto error;
1457     }
1458     for (i = 0; i < n->rss_data.indirections_len; ++i) {
1459         uint16_t val = n->rss_data.indirections_table[i];
1460         n->rss_data.indirections_table[i] = virtio_lduw_p(vdev, &val);
1461     }
1462     offset += size_get;
1463     size_get = sizeof(temp);
1464     s = iov_to_buf(iov, iov_cnt, offset, &temp, size_get);
1465     if (s != size_get) {
1466         err_msg = "Can't get queue_pairs";
1467         err_value = (uint32_t)s;
1468         goto error;
1469     }
1470     queue_pairs = do_rss ? virtio_lduw_p(vdev, &temp.us) : n->curr_queue_pairs;
1471     if (queue_pairs == 0 || queue_pairs > n->max_queue_pairs) {
1472         err_msg = "Invalid number of queue_pairs";
1473         err_value = queue_pairs;
1474         goto error;
1475     }
1476     if (temp.b > VIRTIO_NET_RSS_MAX_KEY_SIZE) {
1477         err_msg = "Invalid key size";
1478         err_value = temp.b;
1479         goto error;
1480     }
1481     if (!temp.b && n->rss_data.hash_types) {
1482         err_msg = "No key provided";
1483         err_value = 0;
1484         goto error;
1485     }
1486     if (!temp.b && !n->rss_data.hash_types) {
1487         virtio_net_disable_rss(n);
1488         return queue_pairs;
1489     }
1490     offset += size_get;
1491     size_get = temp.b;
1492     s = iov_to_buf(iov, iov_cnt, offset, n->rss_data.key, size_get);
1493     if (s != size_get) {
1494         err_msg = "Can get key buffer";
1495         err_value = (uint32_t)s;
1496         goto error;
1497     }
1498     n->rss_data.enabled = true;
1499 
1500     if (!n->rss_data.populate_hash) {
1501         if (!virtio_net_attach_epbf_rss(n)) {
1502             /* EBPF must be loaded for vhost */
1503             if (get_vhost_net(qemu_get_queue(n->nic)->peer)) {
1504                 warn_report("Can't load eBPF RSS for vhost");
1505                 goto error;
1506             }
1507             /* fallback to software RSS */
1508             warn_report("Can't load eBPF RSS - fallback to software RSS");
1509             n->rss_data.enabled_software_rss = true;
1510         }
1511     } else {
1512         /* use software RSS for hash populating */
1513         /* and detach eBPF if was loaded before */
1514         virtio_net_detach_epbf_rss(n);
1515         n->rss_data.enabled_software_rss = true;
1516     }
1517 
1518     trace_virtio_net_rss_enable(n->rss_data.hash_types,
1519                                 n->rss_data.indirections_len,
1520                                 temp.b);
1521     return queue_pairs;
1522 error:
1523     trace_virtio_net_rss_error(err_msg, err_value);
1524     virtio_net_disable_rss(n);
1525     return 0;
1526 }
1527 
1528 static int virtio_net_handle_mq(VirtIONet *n, uint8_t cmd,
1529                                 struct iovec *iov, unsigned int iov_cnt)
1530 {
1531     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1532     uint16_t queue_pairs;
1533     NetClientState *nc = qemu_get_queue(n->nic);
1534 
1535     virtio_net_disable_rss(n);
1536     if (cmd == VIRTIO_NET_CTRL_MQ_HASH_CONFIG) {
1537         queue_pairs = virtio_net_handle_rss(n, iov, iov_cnt, false);
1538         return queue_pairs ? VIRTIO_NET_OK : VIRTIO_NET_ERR;
1539     }
1540     if (cmd == VIRTIO_NET_CTRL_MQ_RSS_CONFIG) {
1541         queue_pairs = virtio_net_handle_rss(n, iov, iov_cnt, true);
1542     } else if (cmd == VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET) {
1543         struct virtio_net_ctrl_mq mq;
1544         size_t s;
1545         if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_MQ)) {
1546             return VIRTIO_NET_ERR;
1547         }
1548         s = iov_to_buf(iov, iov_cnt, 0, &mq, sizeof(mq));
1549         if (s != sizeof(mq)) {
1550             return VIRTIO_NET_ERR;
1551         }
1552         queue_pairs = virtio_lduw_p(vdev, &mq.virtqueue_pairs);
1553 
1554     } else {
1555         return VIRTIO_NET_ERR;
1556     }
1557 
1558     if (queue_pairs < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
1559         queue_pairs > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
1560         queue_pairs > n->max_queue_pairs ||
1561         !n->multiqueue) {
1562         return VIRTIO_NET_ERR;
1563     }
1564 
1565     n->curr_queue_pairs = queue_pairs;
1566     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_VDPA) {
1567         /*
1568          * Avoid updating the backend for a vdpa device: We're only interested
1569          * in updating the device model queues.
1570          */
1571         return VIRTIO_NET_OK;
1572     }
1573     /* stop the backend before changing the number of queue_pairs to avoid handling a
1574      * disabled queue */
1575     virtio_net_set_status(vdev, vdev->status);
1576     virtio_net_set_queue_pairs(n);
1577 
1578     return VIRTIO_NET_OK;
1579 }
1580 
1581 size_t virtio_net_handle_ctrl_iov(VirtIODevice *vdev,
1582                                   const struct iovec *in_sg, unsigned in_num,
1583                                   const struct iovec *out_sg,
1584                                   unsigned out_num)
1585 {
1586     VirtIONet *n = VIRTIO_NET(vdev);
1587     struct virtio_net_ctrl_hdr ctrl;
1588     virtio_net_ctrl_ack status = VIRTIO_NET_ERR;
1589     size_t s;
1590     struct iovec *iov, *iov2;
1591 
1592     if (iov_size(in_sg, in_num) < sizeof(status) ||
1593         iov_size(out_sg, out_num) < sizeof(ctrl)) {
1594         virtio_error(vdev, "virtio-net ctrl missing headers");
1595         return 0;
1596     }
1597 
1598     iov2 = iov = g_memdup2(out_sg, sizeof(struct iovec) * out_num);
1599     s = iov_to_buf(iov, out_num, 0, &ctrl, sizeof(ctrl));
1600     iov_discard_front(&iov, &out_num, sizeof(ctrl));
1601     if (s != sizeof(ctrl)) {
1602         status = VIRTIO_NET_ERR;
1603     } else if (ctrl.class == VIRTIO_NET_CTRL_RX) {
1604         status = virtio_net_handle_rx_mode(n, ctrl.cmd, iov, out_num);
1605     } else if (ctrl.class == VIRTIO_NET_CTRL_MAC) {
1606         status = virtio_net_handle_mac(n, ctrl.cmd, iov, out_num);
1607     } else if (ctrl.class == VIRTIO_NET_CTRL_VLAN) {
1608         status = virtio_net_handle_vlan_table(n, ctrl.cmd, iov, out_num);
1609     } else if (ctrl.class == VIRTIO_NET_CTRL_ANNOUNCE) {
1610         status = virtio_net_handle_announce(n, ctrl.cmd, iov, out_num);
1611     } else if (ctrl.class == VIRTIO_NET_CTRL_MQ) {
1612         status = virtio_net_handle_mq(n, ctrl.cmd, iov, out_num);
1613     } else if (ctrl.class == VIRTIO_NET_CTRL_GUEST_OFFLOADS) {
1614         status = virtio_net_handle_offloads(n, ctrl.cmd, iov, out_num);
1615     }
1616 
1617     s = iov_from_buf(in_sg, in_num, 0, &status, sizeof(status));
1618     assert(s == sizeof(status));
1619 
1620     g_free(iov2);
1621     return sizeof(status);
1622 }
1623 
1624 static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
1625 {
1626     VirtQueueElement *elem;
1627 
1628     for (;;) {
1629         size_t written;
1630         elem = virtqueue_pop(vq, sizeof(VirtQueueElement));
1631         if (!elem) {
1632             break;
1633         }
1634 
1635         written = virtio_net_handle_ctrl_iov(vdev, elem->in_sg, elem->in_num,
1636                                              elem->out_sg, elem->out_num);
1637         if (written > 0) {
1638             virtqueue_push(vq, elem, written);
1639             virtio_notify(vdev, vq);
1640             g_free(elem);
1641         } else {
1642             virtqueue_detach_element(vq, elem, 0);
1643             g_free(elem);
1644             break;
1645         }
1646     }
1647 }
1648 
1649 /* RX */
1650 
1651 static void virtio_net_handle_rx(VirtIODevice *vdev, VirtQueue *vq)
1652 {
1653     VirtIONet *n = VIRTIO_NET(vdev);
1654     int queue_index = vq2q(virtio_get_queue_index(vq));
1655 
1656     qemu_flush_queued_packets(qemu_get_subqueue(n->nic, queue_index));
1657 }
1658 
1659 static bool virtio_net_can_receive(NetClientState *nc)
1660 {
1661     VirtIONet *n = qemu_get_nic_opaque(nc);
1662     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1663     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
1664 
1665     if (!vdev->vm_running) {
1666         return false;
1667     }
1668 
1669     if (nc->queue_index >= n->curr_queue_pairs) {
1670         return false;
1671     }
1672 
1673     if (!virtio_queue_ready(q->rx_vq) ||
1674         !(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1675         return false;
1676     }
1677 
1678     return true;
1679 }
1680 
1681 static int virtio_net_has_buffers(VirtIONetQueue *q, int bufsize)
1682 {
1683     VirtIONet *n = q->n;
1684     if (virtio_queue_empty(q->rx_vq) ||
1685         (n->mergeable_rx_bufs &&
1686          !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
1687         virtio_queue_set_notification(q->rx_vq, 1);
1688 
1689         /* To avoid a race condition where the guest has made some buffers
1690          * available after the above check but before notification was
1691          * enabled, check for available buffers again.
1692          */
1693         if (virtio_queue_empty(q->rx_vq) ||
1694             (n->mergeable_rx_bufs &&
1695              !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
1696             return 0;
1697         }
1698     }
1699 
1700     virtio_queue_set_notification(q->rx_vq, 0);
1701     return 1;
1702 }
1703 
1704 static void virtio_net_hdr_swap(VirtIODevice *vdev, struct virtio_net_hdr *hdr)
1705 {
1706     virtio_tswap16s(vdev, &hdr->hdr_len);
1707     virtio_tswap16s(vdev, &hdr->gso_size);
1708     virtio_tswap16s(vdev, &hdr->csum_start);
1709     virtio_tswap16s(vdev, &hdr->csum_offset);
1710 }
1711 
1712 /* dhclient uses AF_PACKET but doesn't pass auxdata to the kernel so
1713  * it never finds out that the packets don't have valid checksums.  This
1714  * causes dhclient to get upset.  Fedora's carried a patch for ages to
1715  * fix this with Xen but it hasn't appeared in an upstream release of
1716  * dhclient yet.
1717  *
1718  * To avoid breaking existing guests, we catch udp packets and add
1719  * checksums.  This is terrible but it's better than hacking the guest
1720  * kernels.
1721  *
1722  * N.B. if we introduce a zero-copy API, this operation is no longer free so
1723  * we should provide a mechanism to disable it to avoid polluting the host
1724  * cache.
1725  */
1726 static void work_around_broken_dhclient(struct virtio_net_hdr *hdr,
1727                                         uint8_t *buf, size_t size)
1728 {
1729     if ((hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && /* missing csum */
1730         (size > 27 && size < 1500) && /* normal sized MTU */
1731         (buf[12] == 0x08 && buf[13] == 0x00) && /* ethertype == IPv4 */
1732         (buf[23] == 17) && /* ip.protocol == UDP */
1733         (buf[34] == 0 && buf[35] == 67)) { /* udp.srcport == bootps */
1734         net_checksum_calculate(buf, size, CSUM_UDP);
1735         hdr->flags &= ~VIRTIO_NET_HDR_F_NEEDS_CSUM;
1736     }
1737 }
1738 
1739 static void receive_header(VirtIONet *n, const struct iovec *iov, int iov_cnt,
1740                            const void *buf, size_t size)
1741 {
1742     if (n->has_vnet_hdr) {
1743         /* FIXME this cast is evil */
1744         void *wbuf = (void *)buf;
1745         work_around_broken_dhclient(wbuf, wbuf + n->host_hdr_len,
1746                                     size - n->host_hdr_len);
1747 
1748         if (n->needs_vnet_hdr_swap) {
1749             virtio_net_hdr_swap(VIRTIO_DEVICE(n), wbuf);
1750         }
1751         iov_from_buf(iov, iov_cnt, 0, buf, sizeof(struct virtio_net_hdr));
1752     } else {
1753         struct virtio_net_hdr hdr = {
1754             .flags = 0,
1755             .gso_type = VIRTIO_NET_HDR_GSO_NONE
1756         };
1757         iov_from_buf(iov, iov_cnt, 0, &hdr, sizeof hdr);
1758     }
1759 }
1760 
1761 static int receive_filter(VirtIONet *n, const uint8_t *buf, int size)
1762 {
1763     static const uint8_t bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
1764     static const uint8_t vlan[] = {0x81, 0x00};
1765     uint8_t *ptr = (uint8_t *)buf;
1766     int i;
1767 
1768     if (n->promisc)
1769         return 1;
1770 
1771     ptr += n->host_hdr_len;
1772 
1773     if (!memcmp(&ptr[12], vlan, sizeof(vlan))) {
1774         int vid = lduw_be_p(ptr + 14) & 0xfff;
1775         if (!(n->vlans[vid >> 5] & (1U << (vid & 0x1f))))
1776             return 0;
1777     }
1778 
1779     if (ptr[0] & 1) { // multicast
1780         if (!memcmp(ptr, bcast, sizeof(bcast))) {
1781             return !n->nobcast;
1782         } else if (n->nomulti) {
1783             return 0;
1784         } else if (n->allmulti || n->mac_table.multi_overflow) {
1785             return 1;
1786         }
1787 
1788         for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {
1789             if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
1790                 return 1;
1791             }
1792         }
1793     } else { // unicast
1794         if (n->nouni) {
1795             return 0;
1796         } else if (n->alluni || n->mac_table.uni_overflow) {
1797             return 1;
1798         } else if (!memcmp(ptr, n->mac, ETH_ALEN)) {
1799             return 1;
1800         }
1801 
1802         for (i = 0; i < n->mac_table.first_multi; i++) {
1803             if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
1804                 return 1;
1805             }
1806         }
1807     }
1808 
1809     return 0;
1810 }
1811 
1812 static uint8_t virtio_net_get_hash_type(bool hasip4,
1813                                         bool hasip6,
1814                                         EthL4HdrProto l4hdr_proto,
1815                                         uint32_t types)
1816 {
1817     if (hasip4) {
1818         switch (l4hdr_proto) {
1819         case ETH_L4_HDR_PROTO_TCP:
1820             if (types & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
1821                 return NetPktRssIpV4Tcp;
1822             }
1823             break;
1824 
1825         case ETH_L4_HDR_PROTO_UDP:
1826             if (types & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
1827                 return NetPktRssIpV4Udp;
1828             }
1829             break;
1830 
1831         default:
1832             break;
1833         }
1834 
1835         if (types & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
1836             return NetPktRssIpV4;
1837         }
1838     } else if (hasip6) {
1839         switch (l4hdr_proto) {
1840         case ETH_L4_HDR_PROTO_TCP:
1841             if (types & VIRTIO_NET_RSS_HASH_TYPE_TCP_EX) {
1842                 return NetPktRssIpV6TcpEx;
1843             }
1844             if (types & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
1845                 return NetPktRssIpV6Tcp;
1846             }
1847             break;
1848 
1849         case ETH_L4_HDR_PROTO_UDP:
1850             if (types & VIRTIO_NET_RSS_HASH_TYPE_UDP_EX) {
1851                 return NetPktRssIpV6UdpEx;
1852             }
1853             if (types & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
1854                 return NetPktRssIpV6Udp;
1855             }
1856             break;
1857 
1858         default:
1859             break;
1860         }
1861 
1862         if (types & VIRTIO_NET_RSS_HASH_TYPE_IP_EX) {
1863             return NetPktRssIpV6Ex;
1864         }
1865         if (types & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
1866             return NetPktRssIpV6;
1867         }
1868     }
1869     return 0xff;
1870 }
1871 
1872 static void virtio_set_packet_hash(const uint8_t *buf, uint8_t report,
1873                                    uint32_t hash)
1874 {
1875     struct virtio_net_hdr_v1_hash *hdr = (void *)buf;
1876     hdr->hash_value = hash;
1877     hdr->hash_report = report;
1878 }
1879 
1880 static int virtio_net_process_rss(NetClientState *nc, const uint8_t *buf,
1881                                   size_t size)
1882 {
1883     VirtIONet *n = qemu_get_nic_opaque(nc);
1884     unsigned int index = nc->queue_index, new_index = index;
1885     struct NetRxPkt *pkt = n->rx_pkt;
1886     uint8_t net_hash_type;
1887     uint32_t hash;
1888     bool hasip4, hasip6;
1889     EthL4HdrProto l4hdr_proto;
1890     static const uint8_t reports[NetPktRssIpV6UdpEx + 1] = {
1891         VIRTIO_NET_HASH_REPORT_IPv4,
1892         VIRTIO_NET_HASH_REPORT_TCPv4,
1893         VIRTIO_NET_HASH_REPORT_TCPv6,
1894         VIRTIO_NET_HASH_REPORT_IPv6,
1895         VIRTIO_NET_HASH_REPORT_IPv6_EX,
1896         VIRTIO_NET_HASH_REPORT_TCPv6_EX,
1897         VIRTIO_NET_HASH_REPORT_UDPv4,
1898         VIRTIO_NET_HASH_REPORT_UDPv6,
1899         VIRTIO_NET_HASH_REPORT_UDPv6_EX
1900     };
1901     struct iovec iov = {
1902         .iov_base = (void *)buf,
1903         .iov_len = size
1904     };
1905 
1906     net_rx_pkt_set_protocols(pkt, &iov, 1, n->host_hdr_len);
1907     net_rx_pkt_get_protocols(pkt, &hasip4, &hasip6, &l4hdr_proto);
1908     net_hash_type = virtio_net_get_hash_type(hasip4, hasip6, l4hdr_proto,
1909                                              n->rss_data.hash_types);
1910     if (net_hash_type > NetPktRssIpV6UdpEx) {
1911         if (n->rss_data.populate_hash) {
1912             virtio_set_packet_hash(buf, VIRTIO_NET_HASH_REPORT_NONE, 0);
1913         }
1914         return n->rss_data.redirect ? n->rss_data.default_queue : -1;
1915     }
1916 
1917     hash = net_rx_pkt_calc_rss_hash(pkt, net_hash_type, n->rss_data.key);
1918 
1919     if (n->rss_data.populate_hash) {
1920         virtio_set_packet_hash(buf, reports[net_hash_type], hash);
1921     }
1922 
1923     if (n->rss_data.redirect) {
1924         new_index = hash & (n->rss_data.indirections_len - 1);
1925         new_index = n->rss_data.indirections_table[new_index];
1926     }
1927 
1928     return (index == new_index) ? -1 : new_index;
1929 }
1930 
1931 static ssize_t virtio_net_receive_rcu(NetClientState *nc, const uint8_t *buf,
1932                                       size_t size, bool no_rss)
1933 {
1934     VirtIONet *n = qemu_get_nic_opaque(nc);
1935     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
1936     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1937     VirtQueueElement *elems[VIRTQUEUE_MAX_SIZE];
1938     size_t lens[VIRTQUEUE_MAX_SIZE];
1939     struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];
1940     struct virtio_net_hdr_mrg_rxbuf mhdr;
1941     unsigned mhdr_cnt = 0;
1942     size_t offset, i, guest_offset, j;
1943     ssize_t err;
1944 
1945     if (!virtio_net_can_receive(nc)) {
1946         return -1;
1947     }
1948 
1949     if (!no_rss && n->rss_data.enabled && n->rss_data.enabled_software_rss) {
1950         int index = virtio_net_process_rss(nc, buf, size);
1951         if (index >= 0) {
1952             NetClientState *nc2 = qemu_get_subqueue(n->nic, index);
1953             return virtio_net_receive_rcu(nc2, buf, size, true);
1954         }
1955     }
1956 
1957     /* hdr_len refers to the header we supply to the guest */
1958     if (!virtio_net_has_buffers(q, size + n->guest_hdr_len - n->host_hdr_len)) {
1959         return 0;
1960     }
1961 
1962     if (!receive_filter(n, buf, size))
1963         return size;
1964 
1965     offset = i = 0;
1966 
1967     while (offset < size) {
1968         VirtQueueElement *elem;
1969         int len, total;
1970         const struct iovec *sg;
1971 
1972         total = 0;
1973 
1974         if (i == VIRTQUEUE_MAX_SIZE) {
1975             virtio_error(vdev, "virtio-net unexpected long buffer chain");
1976             err = size;
1977             goto err;
1978         }
1979 
1980         elem = virtqueue_pop(q->rx_vq, sizeof(VirtQueueElement));
1981         if (!elem) {
1982             if (i) {
1983                 virtio_error(vdev, "virtio-net unexpected empty queue: "
1984                              "i %zd mergeable %d offset %zd, size %zd, "
1985                              "guest hdr len %zd, host hdr len %zd "
1986                              "guest features 0x%" PRIx64,
1987                              i, n->mergeable_rx_bufs, offset, size,
1988                              n->guest_hdr_len, n->host_hdr_len,
1989                              vdev->guest_features);
1990             }
1991             err = -1;
1992             goto err;
1993         }
1994 
1995         if (elem->in_num < 1) {
1996             virtio_error(vdev,
1997                          "virtio-net receive queue contains no in buffers");
1998             virtqueue_detach_element(q->rx_vq, elem, 0);
1999             g_free(elem);
2000             err = -1;
2001             goto err;
2002         }
2003 
2004         sg = elem->in_sg;
2005         if (i == 0) {
2006             assert(offset == 0);
2007             if (n->mergeable_rx_bufs) {
2008                 mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),
2009                                     sg, elem->in_num,
2010                                     offsetof(typeof(mhdr), num_buffers),
2011                                     sizeof(mhdr.num_buffers));
2012             }
2013 
2014             receive_header(n, sg, elem->in_num, buf, size);
2015             if (n->rss_data.populate_hash) {
2016                 offset = sizeof(mhdr);
2017                 iov_from_buf(sg, elem->in_num, offset,
2018                              buf + offset, n->host_hdr_len - sizeof(mhdr));
2019             }
2020             offset = n->host_hdr_len;
2021             total += n->guest_hdr_len;
2022             guest_offset = n->guest_hdr_len;
2023         } else {
2024             guest_offset = 0;
2025         }
2026 
2027         /* copy in packet.  ugh */
2028         len = iov_from_buf(sg, elem->in_num, guest_offset,
2029                            buf + offset, size - offset);
2030         total += len;
2031         offset += len;
2032         /* If buffers can't be merged, at this point we
2033          * must have consumed the complete packet.
2034          * Otherwise, drop it. */
2035         if (!n->mergeable_rx_bufs && offset < size) {
2036             virtqueue_unpop(q->rx_vq, elem, total);
2037             g_free(elem);
2038             err = size;
2039             goto err;
2040         }
2041 
2042         /* Mark dirty page's bitmap of guest memory */
2043         if (vdev->lm_logging_ctrl == LM_ENABLE) {
2044             uint64_t chunk = elem->in_addr[i] / VHOST_LOG_CHUNK;
2045             /* Get chunk index */
2046             BitmapMemoryRegionCaches *caches = qatomic_rcu_read(&vdev->caches);
2047             uint64_t index = chunk / 8;
2048             uint64_t shift = chunk % 8;
2049             uint8_t val = 0;
2050             address_space_read_cached(&caches->bitmap, index, &val,
2051                                       sizeof(val));
2052             val |= 1 << shift;
2053             address_space_write_cached(&caches->bitmap, index, &val,
2054                                        sizeof(val));
2055             address_space_cache_invalidate(&caches->bitmap, index, sizeof(val));
2056         }
2057 
2058         elems[i] = elem;
2059         lens[i] = total;
2060         i++;
2061     }
2062 
2063     if (mhdr_cnt) {
2064         virtio_stw_p(vdev, &mhdr.num_buffers, i);
2065         iov_from_buf(mhdr_sg, mhdr_cnt,
2066                      0,
2067                      &mhdr.num_buffers, sizeof mhdr.num_buffers);
2068     }
2069 
2070     for (j = 0; j < i; j++) {
2071         /* signal other side */
2072         virtqueue_fill(q->rx_vq, elems[j], lens[j], j);
2073         g_free(elems[j]);
2074     }
2075 
2076     virtqueue_flush(q->rx_vq, i);
2077     virtio_notify(vdev, q->rx_vq);
2078 
2079     return size;
2080 
2081 err:
2082     for (j = 0; j < i; j++) {
2083         virtqueue_detach_element(q->rx_vq, elems[j], lens[j]);
2084         g_free(elems[j]);
2085     }
2086 
2087     return err;
2088 }
2089 
2090 static ssize_t virtio_net_do_receive(NetClientState *nc, const uint8_t *buf,
2091                                   size_t size)
2092 {
2093     RCU_READ_LOCK_GUARD();
2094 
2095     return virtio_net_receive_rcu(nc, buf, size, false);
2096 }
2097 
2098 static void virtio_net_rsc_extract_unit4(VirtioNetRscChain *chain,
2099                                          const uint8_t *buf,
2100                                          VirtioNetRscUnit *unit)
2101 {
2102     uint16_t ip_hdrlen;
2103     struct ip_header *ip;
2104 
2105     ip = (struct ip_header *)(buf + chain->n->guest_hdr_len
2106                               + sizeof(struct eth_header));
2107     unit->ip = (void *)ip;
2108     ip_hdrlen = (ip->ip_ver_len & 0xF) << 2;
2109     unit->ip_plen = &ip->ip_len;
2110     unit->tcp = (struct tcp_header *)(((uint8_t *)unit->ip) + ip_hdrlen);
2111     unit->tcp_hdrlen = (htons(unit->tcp->th_offset_flags) & 0xF000) >> 10;
2112     unit->payload = htons(*unit->ip_plen) - ip_hdrlen - unit->tcp_hdrlen;
2113 }
2114 
2115 static void virtio_net_rsc_extract_unit6(VirtioNetRscChain *chain,
2116                                          const uint8_t *buf,
2117                                          VirtioNetRscUnit *unit)
2118 {
2119     struct ip6_header *ip6;
2120 
2121     ip6 = (struct ip6_header *)(buf + chain->n->guest_hdr_len
2122                                  + sizeof(struct eth_header));
2123     unit->ip = ip6;
2124     unit->ip_plen = &(ip6->ip6_ctlun.ip6_un1.ip6_un1_plen);
2125     unit->tcp = (struct tcp_header *)(((uint8_t *)unit->ip)
2126                                         + sizeof(struct ip6_header));
2127     unit->tcp_hdrlen = (htons(unit->tcp->th_offset_flags) & 0xF000) >> 10;
2128 
2129     /* There is a difference between payload length in ipv4 and v6,
2130        ip header is excluded in ipv6 */
2131     unit->payload = htons(*unit->ip_plen) - unit->tcp_hdrlen;
2132 }
2133 
2134 static size_t virtio_net_rsc_drain_seg(VirtioNetRscChain *chain,
2135                                        VirtioNetRscSeg *seg)
2136 {
2137     int ret;
2138     struct virtio_net_hdr_v1 *h;
2139 
2140     h = (struct virtio_net_hdr_v1 *)seg->buf;
2141     h->flags = 0;
2142     h->gso_type = VIRTIO_NET_HDR_GSO_NONE;
2143 
2144     if (seg->is_coalesced) {
2145         h->rsc.segments = seg->packets;
2146         h->rsc.dup_acks = seg->dup_ack;
2147         h->flags = VIRTIO_NET_HDR_F_RSC_INFO;
2148         if (chain->proto == ETH_P_IP) {
2149             h->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
2150         } else {
2151             h->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
2152         }
2153     }
2154 
2155     ret = virtio_net_do_receive(seg->nc, seg->buf, seg->size);
2156     QTAILQ_REMOVE(&chain->buffers, seg, next);
2157     g_free(seg->buf);
2158     g_free(seg);
2159 
2160     return ret;
2161 }
2162 
2163 static void virtio_net_rsc_purge(void *opq)
2164 {
2165     VirtioNetRscSeg *seg, *rn;
2166     VirtioNetRscChain *chain = (VirtioNetRscChain *)opq;
2167 
2168     QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, rn) {
2169         if (virtio_net_rsc_drain_seg(chain, seg) == 0) {
2170             chain->stat.purge_failed++;
2171             continue;
2172         }
2173     }
2174 
2175     chain->stat.timer++;
2176     if (!QTAILQ_EMPTY(&chain->buffers)) {
2177         timer_mod(chain->drain_timer,
2178               qemu_clock_get_ns(QEMU_CLOCK_HOST) + chain->n->rsc_timeout);
2179     }
2180 }
2181 
2182 static void virtio_net_rsc_cleanup(VirtIONet *n)
2183 {
2184     VirtioNetRscChain *chain, *rn_chain;
2185     VirtioNetRscSeg *seg, *rn_seg;
2186 
2187     QTAILQ_FOREACH_SAFE(chain, &n->rsc_chains, next, rn_chain) {
2188         QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, rn_seg) {
2189             QTAILQ_REMOVE(&chain->buffers, seg, next);
2190             g_free(seg->buf);
2191             g_free(seg);
2192         }
2193 
2194         timer_free(chain->drain_timer);
2195         QTAILQ_REMOVE(&n->rsc_chains, chain, next);
2196         g_free(chain);
2197     }
2198 }
2199 
2200 static void virtio_net_rsc_cache_buf(VirtioNetRscChain *chain,
2201                                      NetClientState *nc,
2202                                      const uint8_t *buf, size_t size)
2203 {
2204     uint16_t hdr_len;
2205     VirtioNetRscSeg *seg;
2206 
2207     hdr_len = chain->n->guest_hdr_len;
2208     seg = g_new(VirtioNetRscSeg, 1);
2209     seg->buf = g_malloc(hdr_len + sizeof(struct eth_header)
2210         + sizeof(struct ip6_header) + VIRTIO_NET_MAX_TCP_PAYLOAD);
2211     memcpy(seg->buf, buf, size);
2212     seg->size = size;
2213     seg->packets = 1;
2214     seg->dup_ack = 0;
2215     seg->is_coalesced = 0;
2216     seg->nc = nc;
2217 
2218     QTAILQ_INSERT_TAIL(&chain->buffers, seg, next);
2219     chain->stat.cache++;
2220 
2221     switch (chain->proto) {
2222     case ETH_P_IP:
2223         virtio_net_rsc_extract_unit4(chain, seg->buf, &seg->unit);
2224         break;
2225     case ETH_P_IPV6:
2226         virtio_net_rsc_extract_unit6(chain, seg->buf, &seg->unit);
2227         break;
2228     default:
2229         g_assert_not_reached();
2230     }
2231 }
2232 
2233 static int32_t virtio_net_rsc_handle_ack(VirtioNetRscChain *chain,
2234                                          VirtioNetRscSeg *seg,
2235                                          const uint8_t *buf,
2236                                          struct tcp_header *n_tcp,
2237                                          struct tcp_header *o_tcp)
2238 {
2239     uint32_t nack, oack;
2240     uint16_t nwin, owin;
2241 
2242     nack = htonl(n_tcp->th_ack);
2243     nwin = htons(n_tcp->th_win);
2244     oack = htonl(o_tcp->th_ack);
2245     owin = htons(o_tcp->th_win);
2246 
2247     if ((nack - oack) >= VIRTIO_NET_MAX_TCP_PAYLOAD) {
2248         chain->stat.ack_out_of_win++;
2249         return RSC_FINAL;
2250     } else if (nack == oack) {
2251         /* duplicated ack or window probe */
2252         if (nwin == owin) {
2253             /* duplicated ack, add dup ack count due to whql test up to 1 */
2254             chain->stat.dup_ack++;
2255             return RSC_FINAL;
2256         } else {
2257             /* Coalesce window update */
2258             o_tcp->th_win = n_tcp->th_win;
2259             chain->stat.win_update++;
2260             return RSC_COALESCE;
2261         }
2262     } else {
2263         /* pure ack, go to 'C', finalize*/
2264         chain->stat.pure_ack++;
2265         return RSC_FINAL;
2266     }
2267 }
2268 
2269 static int32_t virtio_net_rsc_coalesce_data(VirtioNetRscChain *chain,
2270                                             VirtioNetRscSeg *seg,
2271                                             const uint8_t *buf,
2272                                             VirtioNetRscUnit *n_unit)
2273 {
2274     void *data;
2275     uint16_t o_ip_len;
2276     uint32_t nseq, oseq;
2277     VirtioNetRscUnit *o_unit;
2278 
2279     o_unit = &seg->unit;
2280     o_ip_len = htons(*o_unit->ip_plen);
2281     nseq = htonl(n_unit->tcp->th_seq);
2282     oseq = htonl(o_unit->tcp->th_seq);
2283 
2284     /* out of order or retransmitted. */
2285     if ((nseq - oseq) > VIRTIO_NET_MAX_TCP_PAYLOAD) {
2286         chain->stat.data_out_of_win++;
2287         return RSC_FINAL;
2288     }
2289 
2290     data = ((uint8_t *)n_unit->tcp) + n_unit->tcp_hdrlen;
2291     if (nseq == oseq) {
2292         if ((o_unit->payload == 0) && n_unit->payload) {
2293             /* From no payload to payload, normal case, not a dup ack or etc */
2294             chain->stat.data_after_pure_ack++;
2295             goto coalesce;
2296         } else {
2297             return virtio_net_rsc_handle_ack(chain, seg, buf,
2298                                              n_unit->tcp, o_unit->tcp);
2299         }
2300     } else if ((nseq - oseq) != o_unit->payload) {
2301         /* Not a consistent packet, out of order */
2302         chain->stat.data_out_of_order++;
2303         return RSC_FINAL;
2304     } else {
2305 coalesce:
2306         if ((o_ip_len + n_unit->payload) > chain->max_payload) {
2307             chain->stat.over_size++;
2308             return RSC_FINAL;
2309         }
2310 
2311         /* Here comes the right data, the payload length in v4/v6 is different,
2312            so use the field value to update and record the new data len */
2313         o_unit->payload += n_unit->payload; /* update new data len */
2314 
2315         /* update field in ip header */
2316         *o_unit->ip_plen = htons(o_ip_len + n_unit->payload);
2317 
2318         /* Bring 'PUSH' big, the whql test guide says 'PUSH' can be coalesced
2319            for windows guest, while this may change the behavior for linux
2320            guest (only if it uses RSC feature). */
2321         o_unit->tcp->th_offset_flags = n_unit->tcp->th_offset_flags;
2322 
2323         o_unit->tcp->th_ack = n_unit->tcp->th_ack;
2324         o_unit->tcp->th_win = n_unit->tcp->th_win;
2325 
2326         memmove(seg->buf + seg->size, data, n_unit->payload);
2327         seg->size += n_unit->payload;
2328         seg->packets++;
2329         chain->stat.coalesced++;
2330         return RSC_COALESCE;
2331     }
2332 }
2333 
2334 static int32_t virtio_net_rsc_coalesce4(VirtioNetRscChain *chain,
2335                                         VirtioNetRscSeg *seg,
2336                                         const uint8_t *buf, size_t size,
2337                                         VirtioNetRscUnit *unit)
2338 {
2339     struct ip_header *ip1, *ip2;
2340 
2341     ip1 = (struct ip_header *)(unit->ip);
2342     ip2 = (struct ip_header *)(seg->unit.ip);
2343     if ((ip1->ip_src ^ ip2->ip_src) || (ip1->ip_dst ^ ip2->ip_dst)
2344         || (unit->tcp->th_sport ^ seg->unit.tcp->th_sport)
2345         || (unit->tcp->th_dport ^ seg->unit.tcp->th_dport)) {
2346         chain->stat.no_match++;
2347         return RSC_NO_MATCH;
2348     }
2349 
2350     return virtio_net_rsc_coalesce_data(chain, seg, buf, unit);
2351 }
2352 
2353 static int32_t virtio_net_rsc_coalesce6(VirtioNetRscChain *chain,
2354                                         VirtioNetRscSeg *seg,
2355                                         const uint8_t *buf, size_t size,
2356                                         VirtioNetRscUnit *unit)
2357 {
2358     struct ip6_header *ip1, *ip2;
2359 
2360     ip1 = (struct ip6_header *)(unit->ip);
2361     ip2 = (struct ip6_header *)(seg->unit.ip);
2362     if (memcmp(&ip1->ip6_src, &ip2->ip6_src, sizeof(struct in6_address))
2363         || memcmp(&ip1->ip6_dst, &ip2->ip6_dst, sizeof(struct in6_address))
2364         || (unit->tcp->th_sport ^ seg->unit.tcp->th_sport)
2365         || (unit->tcp->th_dport ^ seg->unit.tcp->th_dport)) {
2366             chain->stat.no_match++;
2367             return RSC_NO_MATCH;
2368     }
2369 
2370     return virtio_net_rsc_coalesce_data(chain, seg, buf, unit);
2371 }
2372 
2373 /* Packets with 'SYN' should bypass, other flag should be sent after drain
2374  * to prevent out of order */
2375 static int virtio_net_rsc_tcp_ctrl_check(VirtioNetRscChain *chain,
2376                                          struct tcp_header *tcp)
2377 {
2378     uint16_t tcp_hdr;
2379     uint16_t tcp_flag;
2380 
2381     tcp_flag = htons(tcp->th_offset_flags);
2382     tcp_hdr = (tcp_flag & VIRTIO_NET_TCP_HDR_LENGTH) >> 10;
2383     tcp_flag &= VIRTIO_NET_TCP_FLAG;
2384     if (tcp_flag & TH_SYN) {
2385         chain->stat.tcp_syn++;
2386         return RSC_BYPASS;
2387     }
2388 
2389     if (tcp_flag & (TH_FIN | TH_URG | TH_RST | TH_ECE | TH_CWR)) {
2390         chain->stat.tcp_ctrl_drain++;
2391         return RSC_FINAL;
2392     }
2393 
2394     if (tcp_hdr > sizeof(struct tcp_header)) {
2395         chain->stat.tcp_all_opt++;
2396         return RSC_FINAL;
2397     }
2398 
2399     return RSC_CANDIDATE;
2400 }
2401 
2402 static size_t virtio_net_rsc_do_coalesce(VirtioNetRscChain *chain,
2403                                          NetClientState *nc,
2404                                          const uint8_t *buf, size_t size,
2405                                          VirtioNetRscUnit *unit)
2406 {
2407     int ret;
2408     VirtioNetRscSeg *seg, *nseg;
2409 
2410     if (QTAILQ_EMPTY(&chain->buffers)) {
2411         chain->stat.empty_cache++;
2412         virtio_net_rsc_cache_buf(chain, nc, buf, size);
2413         timer_mod(chain->drain_timer,
2414               qemu_clock_get_ns(QEMU_CLOCK_HOST) + chain->n->rsc_timeout);
2415         return size;
2416     }
2417 
2418     QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, nseg) {
2419         if (chain->proto == ETH_P_IP) {
2420             ret = virtio_net_rsc_coalesce4(chain, seg, buf, size, unit);
2421         } else {
2422             ret = virtio_net_rsc_coalesce6(chain, seg, buf, size, unit);
2423         }
2424 
2425         if (ret == RSC_FINAL) {
2426             if (virtio_net_rsc_drain_seg(chain, seg) == 0) {
2427                 /* Send failed */
2428                 chain->stat.final_failed++;
2429                 return 0;
2430             }
2431 
2432             /* Send current packet */
2433             return virtio_net_do_receive(nc, buf, size);
2434         } else if (ret == RSC_NO_MATCH) {
2435             continue;
2436         } else {
2437             /* Coalesced, mark coalesced flag to tell calc cksum for ipv4 */
2438             seg->is_coalesced = 1;
2439             return size;
2440         }
2441     }
2442 
2443     chain->stat.no_match_cache++;
2444     virtio_net_rsc_cache_buf(chain, nc, buf, size);
2445     return size;
2446 }
2447 
2448 /* Drain a connection data, this is to avoid out of order segments */
2449 static size_t virtio_net_rsc_drain_flow(VirtioNetRscChain *chain,
2450                                         NetClientState *nc,
2451                                         const uint8_t *buf, size_t size,
2452                                         uint16_t ip_start, uint16_t ip_size,
2453                                         uint16_t tcp_port)
2454 {
2455     VirtioNetRscSeg *seg, *nseg;
2456     uint32_t ppair1, ppair2;
2457 
2458     ppair1 = *(uint32_t *)(buf + tcp_port);
2459     QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, nseg) {
2460         ppair2 = *(uint32_t *)(seg->buf + tcp_port);
2461         if (memcmp(buf + ip_start, seg->buf + ip_start, ip_size)
2462             || (ppair1 != ppair2)) {
2463             continue;
2464         }
2465         if (virtio_net_rsc_drain_seg(chain, seg) == 0) {
2466             chain->stat.drain_failed++;
2467         }
2468 
2469         break;
2470     }
2471 
2472     return virtio_net_do_receive(nc, buf, size);
2473 }
2474 
2475 static int32_t virtio_net_rsc_sanity_check4(VirtioNetRscChain *chain,
2476                                             struct ip_header *ip,
2477                                             const uint8_t *buf, size_t size)
2478 {
2479     uint16_t ip_len;
2480 
2481     /* Not an ipv4 packet */
2482     if (((ip->ip_ver_len & 0xF0) >> 4) != IP_HEADER_VERSION_4) {
2483         chain->stat.ip_option++;
2484         return RSC_BYPASS;
2485     }
2486 
2487     /* Don't handle packets with ip option */
2488     if ((ip->ip_ver_len & 0xF) != VIRTIO_NET_IP4_HEADER_LENGTH) {
2489         chain->stat.ip_option++;
2490         return RSC_BYPASS;
2491     }
2492 
2493     if (ip->ip_p != IPPROTO_TCP) {
2494         chain->stat.bypass_not_tcp++;
2495         return RSC_BYPASS;
2496     }
2497 
2498     /* Don't handle packets with ip fragment */
2499     if (!(htons(ip->ip_off) & IP_DF)) {
2500         chain->stat.ip_frag++;
2501         return RSC_BYPASS;
2502     }
2503 
2504     /* Don't handle packets with ecn flag */
2505     if (IPTOS_ECN(ip->ip_tos)) {
2506         chain->stat.ip_ecn++;
2507         return RSC_BYPASS;
2508     }
2509 
2510     ip_len = htons(ip->ip_len);
2511     if (ip_len < (sizeof(struct ip_header) + sizeof(struct tcp_header))
2512         || ip_len > (size - chain->n->guest_hdr_len -
2513                      sizeof(struct eth_header))) {
2514         chain->stat.ip_hacked++;
2515         return RSC_BYPASS;
2516     }
2517 
2518     return RSC_CANDIDATE;
2519 }
2520 
2521 static size_t virtio_net_rsc_receive4(VirtioNetRscChain *chain,
2522                                       NetClientState *nc,
2523                                       const uint8_t *buf, size_t size)
2524 {
2525     int32_t ret;
2526     uint16_t hdr_len;
2527     VirtioNetRscUnit unit;
2528 
2529     hdr_len = ((VirtIONet *)(chain->n))->guest_hdr_len;
2530 
2531     if (size < (hdr_len + sizeof(struct eth_header) + sizeof(struct ip_header)
2532         + sizeof(struct tcp_header))) {
2533         chain->stat.bypass_not_tcp++;
2534         return virtio_net_do_receive(nc, buf, size);
2535     }
2536 
2537     virtio_net_rsc_extract_unit4(chain, buf, &unit);
2538     if (virtio_net_rsc_sanity_check4(chain, unit.ip, buf, size)
2539         != RSC_CANDIDATE) {
2540         return virtio_net_do_receive(nc, buf, size);
2541     }
2542 
2543     ret = virtio_net_rsc_tcp_ctrl_check(chain, unit.tcp);
2544     if (ret == RSC_BYPASS) {
2545         return virtio_net_do_receive(nc, buf, size);
2546     } else if (ret == RSC_FINAL) {
2547         return virtio_net_rsc_drain_flow(chain, nc, buf, size,
2548                 ((hdr_len + sizeof(struct eth_header)) + 12),
2549                 VIRTIO_NET_IP4_ADDR_SIZE,
2550                 hdr_len + sizeof(struct eth_header) + sizeof(struct ip_header));
2551     }
2552 
2553     return virtio_net_rsc_do_coalesce(chain, nc, buf, size, &unit);
2554 }
2555 
2556 static int32_t virtio_net_rsc_sanity_check6(VirtioNetRscChain *chain,
2557                                             struct ip6_header *ip6,
2558                                             const uint8_t *buf, size_t size)
2559 {
2560     uint16_t ip_len;
2561 
2562     if (((ip6->ip6_ctlun.ip6_un1.ip6_un1_flow & 0xF0) >> 4)
2563         != IP_HEADER_VERSION_6) {
2564         return RSC_BYPASS;
2565     }
2566 
2567     /* Both option and protocol is checked in this */
2568     if (ip6->ip6_ctlun.ip6_un1.ip6_un1_nxt != IPPROTO_TCP) {
2569         chain->stat.bypass_not_tcp++;
2570         return RSC_BYPASS;
2571     }
2572 
2573     ip_len = htons(ip6->ip6_ctlun.ip6_un1.ip6_un1_plen);
2574     if (ip_len < sizeof(struct tcp_header) ||
2575         ip_len > (size - chain->n->guest_hdr_len - sizeof(struct eth_header)
2576                   - sizeof(struct ip6_header))) {
2577         chain->stat.ip_hacked++;
2578         return RSC_BYPASS;
2579     }
2580 
2581     /* Don't handle packets with ecn flag */
2582     if (IP6_ECN(ip6->ip6_ctlun.ip6_un3.ip6_un3_ecn)) {
2583         chain->stat.ip_ecn++;
2584         return RSC_BYPASS;
2585     }
2586 
2587     return RSC_CANDIDATE;
2588 }
2589 
2590 static size_t virtio_net_rsc_receive6(void *opq, NetClientState *nc,
2591                                       const uint8_t *buf, size_t size)
2592 {
2593     int32_t ret;
2594     uint16_t hdr_len;
2595     VirtioNetRscChain *chain;
2596     VirtioNetRscUnit unit;
2597 
2598     chain = opq;
2599     hdr_len = ((VirtIONet *)(chain->n))->guest_hdr_len;
2600 
2601     if (size < (hdr_len + sizeof(struct eth_header) + sizeof(struct ip6_header)
2602         + sizeof(tcp_header))) {
2603         return virtio_net_do_receive(nc, buf, size);
2604     }
2605 
2606     virtio_net_rsc_extract_unit6(chain, buf, &unit);
2607     if (RSC_CANDIDATE != virtio_net_rsc_sanity_check6(chain,
2608                                                  unit.ip, buf, size)) {
2609         return virtio_net_do_receive(nc, buf, size);
2610     }
2611 
2612     ret = virtio_net_rsc_tcp_ctrl_check(chain, unit.tcp);
2613     if (ret == RSC_BYPASS) {
2614         return virtio_net_do_receive(nc, buf, size);
2615     } else if (ret == RSC_FINAL) {
2616         return virtio_net_rsc_drain_flow(chain, nc, buf, size,
2617                 ((hdr_len + sizeof(struct eth_header)) + 8),
2618                 VIRTIO_NET_IP6_ADDR_SIZE,
2619                 hdr_len + sizeof(struct eth_header)
2620                 + sizeof(struct ip6_header));
2621     }
2622 
2623     return virtio_net_rsc_do_coalesce(chain, nc, buf, size, &unit);
2624 }
2625 
2626 static VirtioNetRscChain *virtio_net_rsc_lookup_chain(VirtIONet *n,
2627                                                       NetClientState *nc,
2628                                                       uint16_t proto)
2629 {
2630     VirtioNetRscChain *chain;
2631 
2632     if ((proto != (uint16_t)ETH_P_IP) && (proto != (uint16_t)ETH_P_IPV6)) {
2633         return NULL;
2634     }
2635 
2636     QTAILQ_FOREACH(chain, &n->rsc_chains, next) {
2637         if (chain->proto == proto) {
2638             return chain;
2639         }
2640     }
2641 
2642     chain = g_malloc(sizeof(*chain));
2643     chain->n = n;
2644     chain->proto = proto;
2645     if (proto == (uint16_t)ETH_P_IP) {
2646         chain->max_payload = VIRTIO_NET_MAX_IP4_PAYLOAD;
2647         chain->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
2648     } else {
2649         chain->max_payload = VIRTIO_NET_MAX_IP6_PAYLOAD;
2650         chain->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
2651     }
2652     chain->drain_timer = timer_new_ns(QEMU_CLOCK_HOST,
2653                                       virtio_net_rsc_purge, chain);
2654     memset(&chain->stat, 0, sizeof(chain->stat));
2655 
2656     QTAILQ_INIT(&chain->buffers);
2657     QTAILQ_INSERT_TAIL(&n->rsc_chains, chain, next);
2658 
2659     return chain;
2660 }
2661 
2662 static ssize_t virtio_net_rsc_receive(NetClientState *nc,
2663                                       const uint8_t *buf,
2664                                       size_t size)
2665 {
2666     uint16_t proto;
2667     VirtioNetRscChain *chain;
2668     struct eth_header *eth;
2669     VirtIONet *n;
2670 
2671     n = qemu_get_nic_opaque(nc);
2672     if (size < (n->host_hdr_len + sizeof(struct eth_header))) {
2673         return virtio_net_do_receive(nc, buf, size);
2674     }
2675 
2676     eth = (struct eth_header *)(buf + n->guest_hdr_len);
2677     proto = htons(eth->h_proto);
2678 
2679     chain = virtio_net_rsc_lookup_chain(n, nc, proto);
2680     if (chain) {
2681         chain->stat.received++;
2682         if (proto == (uint16_t)ETH_P_IP && n->rsc4_enabled) {
2683             return virtio_net_rsc_receive4(chain, nc, buf, size);
2684         } else if (proto == (uint16_t)ETH_P_IPV6 && n->rsc6_enabled) {
2685             return virtio_net_rsc_receive6(chain, nc, buf, size);
2686         }
2687     }
2688     return virtio_net_do_receive(nc, buf, size);
2689 }
2690 
2691 static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf,
2692                                   size_t size)
2693 {
2694     VirtIONet *n = qemu_get_nic_opaque(nc);
2695     if ((n->rsc4_enabled || n->rsc6_enabled)) {
2696         return virtio_net_rsc_receive(nc, buf, size);
2697     } else {
2698         return virtio_net_do_receive(nc, buf, size);
2699     }
2700 }
2701 
2702 static int32_t virtio_net_flush_tx(VirtIONetQueue *q);
2703 
2704 static void virtio_net_tx_complete(NetClientState *nc, ssize_t len)
2705 {
2706     VirtIONet *n = qemu_get_nic_opaque(nc);
2707     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
2708     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2709     int ret;
2710 
2711     virtqueue_push(q->tx_vq, q->async_tx.elem, 0);
2712     virtio_notify(vdev, q->tx_vq);
2713 
2714     g_free(q->async_tx.elem);
2715     q->async_tx.elem = NULL;
2716 
2717     virtio_queue_set_notification(q->tx_vq, 1);
2718     ret = virtio_net_flush_tx(q);
2719     if (ret >= n->tx_burst) {
2720         /*
2721          * the flush has been stopped by tx_burst
2722          * we will not receive notification for the
2723          * remainining part, so re-schedule
2724          */
2725         virtio_queue_set_notification(q->tx_vq, 0);
2726         if (q->tx_bh) {
2727             qemu_bh_schedule(q->tx_bh);
2728         } else {
2729             timer_mod(q->tx_timer,
2730                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2731         }
2732         q->tx_waiting = 1;
2733     }
2734 }
2735 
2736 /* TX */
2737 static int32_t virtio_net_flush_tx(VirtIONetQueue *q)
2738 {
2739     VirtIONet *n = q->n;
2740     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2741     VirtQueueElement *elem;
2742     int32_t num_packets = 0;
2743     int queue_index = vq2q(virtio_get_queue_index(q->tx_vq));
2744     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
2745         return num_packets;
2746     }
2747 
2748     if (q->async_tx.elem) {
2749         virtio_queue_set_notification(q->tx_vq, 0);
2750         return num_packets;
2751     }
2752 
2753     for (;;) {
2754         ssize_t ret;
2755         unsigned int out_num;
2756         struct iovec sg[VIRTQUEUE_MAX_SIZE], sg2[VIRTQUEUE_MAX_SIZE + 1], *out_sg;
2757         struct virtio_net_hdr_v1_hash vhdr;
2758 
2759         elem = virtqueue_pop(q->tx_vq, sizeof(VirtQueueElement));
2760         if (!elem) {
2761             break;
2762         }
2763 
2764         out_num = elem->out_num;
2765         out_sg = elem->out_sg;
2766         if (out_num < 1) {
2767             virtio_error(vdev, "virtio-net header not in first element");
2768             virtqueue_detach_element(q->tx_vq, elem, 0);
2769             g_free(elem);
2770             return -EINVAL;
2771         }
2772 
2773         if (n->has_vnet_hdr) {
2774             if (iov_to_buf(out_sg, out_num, 0, &vhdr, n->guest_hdr_len) <
2775                 n->guest_hdr_len) {
2776                 virtio_error(vdev, "virtio-net header incorrect");
2777                 virtqueue_detach_element(q->tx_vq, elem, 0);
2778                 g_free(elem);
2779                 return -EINVAL;
2780             }
2781             if (n->needs_vnet_hdr_swap) {
2782                 virtio_net_hdr_swap(vdev, (void *) &vhdr);
2783                 sg2[0].iov_base = &vhdr;
2784                 sg2[0].iov_len = n->guest_hdr_len;
2785                 out_num = iov_copy(&sg2[1], ARRAY_SIZE(sg2) - 1,
2786                                    out_sg, out_num,
2787                                    n->guest_hdr_len, -1);
2788                 if (out_num == VIRTQUEUE_MAX_SIZE) {
2789                     goto drop;
2790                 }
2791                 out_num += 1;
2792                 out_sg = sg2;
2793             }
2794         }
2795         /*
2796          * If host wants to see the guest header as is, we can
2797          * pass it on unchanged. Otherwise, copy just the parts
2798          * that host is interested in.
2799          */
2800         assert(n->host_hdr_len <= n->guest_hdr_len);
2801         if (n->host_hdr_len != n->guest_hdr_len) {
2802             unsigned sg_num = iov_copy(sg, ARRAY_SIZE(sg),
2803                                        out_sg, out_num,
2804                                        0, n->host_hdr_len);
2805             sg_num += iov_copy(sg + sg_num, ARRAY_SIZE(sg) - sg_num,
2806                              out_sg, out_num,
2807                              n->guest_hdr_len, -1);
2808             out_num = sg_num;
2809             out_sg = sg;
2810         }
2811 
2812         ret = qemu_sendv_packet_async(qemu_get_subqueue(n->nic, queue_index),
2813                                       out_sg, out_num, virtio_net_tx_complete);
2814         if (ret == 0) {
2815             virtio_queue_set_notification(q->tx_vq, 0);
2816             q->async_tx.elem = elem;
2817             return -EBUSY;
2818         }
2819 
2820 drop:
2821         virtqueue_push(q->tx_vq, elem, 0);
2822         virtio_notify(vdev, q->tx_vq);
2823         g_free(elem);
2824 
2825         if (++num_packets >= n->tx_burst) {
2826             break;
2827         }
2828     }
2829     return num_packets;
2830 }
2831 
2832 static void virtio_net_tx_timer(void *opaque);
2833 
2834 static void virtio_net_handle_tx_timer(VirtIODevice *vdev, VirtQueue *vq)
2835 {
2836     VirtIONet *n = VIRTIO_NET(vdev);
2837     VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
2838 
2839     if (unlikely((n->status & VIRTIO_NET_S_LINK_UP) == 0)) {
2840         virtio_net_drop_tx_queue_data(vdev, vq);
2841         return;
2842     }
2843 
2844     /* This happens when device was stopped but VCPU wasn't. */
2845     if (!vdev->vm_running) {
2846         q->tx_waiting = 1;
2847         return;
2848     }
2849 
2850     if (q->tx_waiting) {
2851         /* We already have queued packets, immediately flush */
2852         timer_del(q->tx_timer);
2853         virtio_net_tx_timer(q);
2854     } else {
2855         /* re-arm timer to flush it (and more) on next tick */
2856         timer_mod(q->tx_timer,
2857                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2858         q->tx_waiting = 1;
2859         virtio_queue_set_notification(vq, 0);
2860     }
2861 }
2862 
2863 static void virtio_net_handle_tx_bh(VirtIODevice *vdev, VirtQueue *vq)
2864 {
2865     VirtIONet *n = VIRTIO_NET(vdev);
2866     VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
2867 
2868     if (unlikely(n->vhost_started)) {
2869         return;
2870     }
2871 
2872     if (unlikely((n->status & VIRTIO_NET_S_LINK_UP) == 0)) {
2873         virtio_net_drop_tx_queue_data(vdev, vq);
2874         return;
2875     }
2876 
2877     if (unlikely(q->tx_waiting)) {
2878         return;
2879     }
2880     q->tx_waiting = 1;
2881     /* This happens when device was stopped but VCPU wasn't. */
2882     if (!vdev->vm_running) {
2883         return;
2884     }
2885     virtio_queue_set_notification(vq, 0);
2886     qemu_bh_schedule(q->tx_bh);
2887 }
2888 
2889 static void virtio_net_tx_timer(void *opaque)
2890 {
2891     VirtIONetQueue *q = opaque;
2892     VirtIONet *n = q->n;
2893     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2894     int ret;
2895 
2896     /* This happens when device was stopped but BH wasn't. */
2897     if (!vdev->vm_running) {
2898         /* Make sure tx waiting is set, so we'll run when restarted. */
2899         assert(q->tx_waiting);
2900         return;
2901     }
2902 
2903     q->tx_waiting = 0;
2904 
2905     /* Just in case the driver is not ready on more */
2906     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
2907         return;
2908     }
2909 
2910     ret = virtio_net_flush_tx(q);
2911     if (ret == -EBUSY || ret == -EINVAL) {
2912         return;
2913     }
2914     /*
2915      * If we flush a full burst of packets, assume there are
2916      * more coming and immediately rearm
2917      */
2918     if (ret >= n->tx_burst) {
2919         q->tx_waiting = 1;
2920         timer_mod(q->tx_timer,
2921                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2922         return;
2923     }
2924     /*
2925      * If less than a full burst, re-enable notification and flush
2926      * anything that may have come in while we weren't looking.  If
2927      * we find something, assume the guest is still active and rearm
2928      */
2929     virtio_queue_set_notification(q->tx_vq, 1);
2930     ret = virtio_net_flush_tx(q);
2931     if (ret > 0) {
2932         virtio_queue_set_notification(q->tx_vq, 0);
2933         q->tx_waiting = 1;
2934         timer_mod(q->tx_timer,
2935                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2936     }
2937 }
2938 
2939 static void virtio_net_tx_bh(void *opaque)
2940 {
2941     VirtIONetQueue *q = opaque;
2942     VirtIONet *n = q->n;
2943     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2944     int32_t ret;
2945 
2946     /* This happens when device was stopped but BH wasn't. */
2947     if (!vdev->vm_running) {
2948         /* Make sure tx waiting is set, so we'll run when restarted. */
2949         assert(q->tx_waiting);
2950         return;
2951     }
2952 
2953     q->tx_waiting = 0;
2954 
2955     /* Just in case the driver is not ready on more */
2956     if (unlikely(!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))) {
2957         return;
2958     }
2959 
2960     ret = virtio_net_flush_tx(q);
2961     if (ret == -EBUSY || ret == -EINVAL) {
2962         return; /* Notification re-enable handled by tx_complete or device
2963                  * broken */
2964     }
2965 
2966     /* If we flush a full burst of packets, assume there are
2967      * more coming and immediately reschedule */
2968     if (ret >= n->tx_burst) {
2969         qemu_bh_schedule(q->tx_bh);
2970         q->tx_waiting = 1;
2971         return;
2972     }
2973 
2974     /* If less than a full burst, re-enable notification and flush
2975      * anything that may have come in while we weren't looking.  If
2976      * we find something, assume the guest is still active and reschedule */
2977     virtio_queue_set_notification(q->tx_vq, 1);
2978     ret = virtio_net_flush_tx(q);
2979     if (ret == -EINVAL) {
2980         return;
2981     } else if (ret > 0) {
2982         virtio_queue_set_notification(q->tx_vq, 0);
2983         qemu_bh_schedule(q->tx_bh);
2984         q->tx_waiting = 1;
2985     }
2986 }
2987 
2988 static void virtio_net_add_queue(VirtIONet *n, int index)
2989 {
2990     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2991 
2992     n->vqs[index].rx_vq = virtio_add_queue(vdev, n->net_conf.rx_queue_size,
2993                                            virtio_net_handle_rx);
2994 
2995     if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) {
2996         n->vqs[index].tx_vq =
2997             virtio_add_queue(vdev, n->net_conf.tx_queue_size,
2998                              virtio_net_handle_tx_timer);
2999         n->vqs[index].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
3000                                               virtio_net_tx_timer,
3001                                               &n->vqs[index]);
3002     } else {
3003         n->vqs[index].tx_vq =
3004             virtio_add_queue(vdev, n->net_conf.tx_queue_size,
3005                              virtio_net_handle_tx_bh);
3006         n->vqs[index].tx_bh = qemu_bh_new_guarded(virtio_net_tx_bh, &n->vqs[index],
3007                                                   &DEVICE(vdev)->mem_reentrancy_guard);
3008     }
3009 
3010     n->vqs[index].tx_waiting = 0;
3011     n->vqs[index].n = n;
3012 }
3013 
3014 static void virtio_net_del_queue(VirtIONet *n, int index)
3015 {
3016     VirtIODevice *vdev = VIRTIO_DEVICE(n);
3017     VirtIONetQueue *q = &n->vqs[index];
3018     NetClientState *nc = qemu_get_subqueue(n->nic, index);
3019 
3020     qemu_purge_queued_packets(nc);
3021 
3022     virtio_del_queue(vdev, index * 2);
3023     if (q->tx_timer) {
3024         timer_free(q->tx_timer);
3025         q->tx_timer = NULL;
3026     } else {
3027         qemu_bh_delete(q->tx_bh);
3028         q->tx_bh = NULL;
3029     }
3030     q->tx_waiting = 0;
3031     virtio_del_queue(vdev, index * 2 + 1);
3032 }
3033 
3034 static void virtio_net_change_num_queue_pairs(VirtIONet *n, int new_max_queue_pairs)
3035 {
3036     VirtIODevice *vdev = VIRTIO_DEVICE(n);
3037     int old_num_queues = virtio_get_num_queues(vdev);
3038     int new_num_queues = new_max_queue_pairs * 2 + 1;
3039     int i;
3040 
3041     assert(old_num_queues >= 3);
3042     assert(old_num_queues % 2 == 1);
3043 
3044     if (old_num_queues == new_num_queues) {
3045         return;
3046     }
3047 
3048     /*
3049      * We always need to remove and add ctrl vq if
3050      * old_num_queues != new_num_queues. Remove ctrl_vq first,
3051      * and then we only enter one of the following two loops.
3052      */
3053     virtio_del_queue(vdev, old_num_queues - 1);
3054 
3055     for (i = new_num_queues - 1; i < old_num_queues - 1; i += 2) {
3056         /* new_num_queues < old_num_queues */
3057         virtio_net_del_queue(n, i / 2);
3058     }
3059 
3060     for (i = old_num_queues - 1; i < new_num_queues - 1; i += 2) {
3061         /* new_num_queues > old_num_queues */
3062         virtio_net_add_queue(n, i / 2);
3063     }
3064 
3065     /* add ctrl_vq last */
3066     n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
3067 }
3068 
3069 static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue)
3070 {
3071     int max = multiqueue ? n->max_queue_pairs : 1;
3072 
3073     n->multiqueue = multiqueue;
3074     virtio_net_change_num_queue_pairs(n, max);
3075 
3076     virtio_net_set_queue_pairs(n);
3077 }
3078 
3079 static int virtio_net_post_load_device(void *opaque, int version_id)
3080 {
3081     VirtIONet *n = opaque;
3082     VirtIODevice *vdev = VIRTIO_DEVICE(n);
3083     int i, link_down;
3084 
3085     trace_virtio_net_post_load_device();
3086     virtio_net_set_mrg_rx_bufs(n, n->mergeable_rx_bufs,
3087                                virtio_vdev_has_feature(vdev,
3088                                                        VIRTIO_F_VERSION_1),
3089                                virtio_vdev_has_feature(vdev,
3090                                                        VIRTIO_NET_F_HASH_REPORT));
3091 
3092     /* MAC_TABLE_ENTRIES may be different from the saved image */
3093     if (n->mac_table.in_use > MAC_TABLE_ENTRIES) {
3094         n->mac_table.in_use = 0;
3095     }
3096 
3097     if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {
3098         n->curr_guest_offloads = virtio_net_supported_guest_offloads(n);
3099     }
3100 
3101     /*
3102      * curr_guest_offloads will be later overwritten by the
3103      * virtio_set_features_nocheck call done from the virtio_load.
3104      * Here we make sure it is preserved and restored accordingly
3105      * in the virtio_net_post_load_virtio callback.
3106      */
3107     n->saved_guest_offloads = n->curr_guest_offloads;
3108 
3109     virtio_net_set_queue_pairs(n);
3110 
3111     /* Find the first multicast entry in the saved MAC filter */
3112     for (i = 0; i < n->mac_table.in_use; i++) {
3113         if (n->mac_table.macs[i * ETH_ALEN] & 1) {
3114             break;
3115         }
3116     }
3117     n->mac_table.first_multi = i;
3118 
3119     /* nc.link_down can't be migrated, so infer link_down according
3120      * to link status bit in n->status */
3121     link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0;
3122     for (i = 0; i < n->max_queue_pairs; i++) {
3123         qemu_get_subqueue(n->nic, i)->link_down = link_down;
3124     }
3125 
3126     if (virtio_vdev_has_feature(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE) &&
3127         virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
3128         qemu_announce_timer_reset(&n->announce_timer, migrate_announce_params(),
3129                                   QEMU_CLOCK_VIRTUAL,
3130                                   virtio_net_announce_timer, n);
3131         if (n->announce_timer.round) {
3132             timer_mod(n->announce_timer.tm,
3133                       qemu_clock_get_ms(n->announce_timer.type));
3134         } else {
3135             qemu_announce_timer_del(&n->announce_timer, false);
3136         }
3137     }
3138 
3139     if (n->rss_data.enabled) {
3140         n->rss_data.enabled_software_rss = n->rss_data.populate_hash;
3141         if (!n->rss_data.populate_hash) {
3142             if (!virtio_net_attach_epbf_rss(n)) {
3143                 if (get_vhost_net(qemu_get_queue(n->nic)->peer)) {
3144                     warn_report("Can't post-load eBPF RSS for vhost");
3145                 } else {
3146                     warn_report("Can't post-load eBPF RSS - "
3147                                 "fallback to software RSS");
3148                     n->rss_data.enabled_software_rss = true;
3149                 }
3150             }
3151         }
3152 
3153         trace_virtio_net_rss_enable(n->rss_data.hash_types,
3154                                     n->rss_data.indirections_len,
3155                                     sizeof(n->rss_data.key));
3156     } else {
3157         trace_virtio_net_rss_disable();
3158     }
3159     return 0;
3160 }
3161 
3162 static int virtio_net_post_load_virtio(VirtIODevice *vdev)
3163 {
3164     VirtIONet *n = VIRTIO_NET(vdev);
3165     /*
3166      * The actual needed state is now in saved_guest_offloads,
3167      * see virtio_net_post_load_device for detail.
3168      * Restore it back and apply the desired offloads.
3169      */
3170     n->curr_guest_offloads = n->saved_guest_offloads;
3171     if (peer_has_vnet_hdr(n)) {
3172         virtio_net_apply_guest_offloads(n);
3173     }
3174 
3175     return 0;
3176 }
3177 
3178 /* tx_waiting field of a VirtIONetQueue */
3179 static const VMStateDescription vmstate_virtio_net_queue_tx_waiting = {
3180     .name = "virtio-net-queue-tx_waiting",
3181     .fields = (const VMStateField[]) {
3182         VMSTATE_UINT32(tx_waiting, VirtIONetQueue),
3183         VMSTATE_END_OF_LIST()
3184    },
3185 };
3186 
3187 static bool max_queue_pairs_gt_1(void *opaque, int version_id)
3188 {
3189     return VIRTIO_NET(opaque)->max_queue_pairs > 1;
3190 }
3191 
3192 static bool has_ctrl_guest_offloads(void *opaque, int version_id)
3193 {
3194     return virtio_vdev_has_feature(VIRTIO_DEVICE(opaque),
3195                                    VIRTIO_NET_F_CTRL_GUEST_OFFLOADS);
3196 }
3197 
3198 static bool mac_table_fits(void *opaque, int version_id)
3199 {
3200     return VIRTIO_NET(opaque)->mac_table.in_use <= MAC_TABLE_ENTRIES;
3201 }
3202 
3203 static bool mac_table_doesnt_fit(void *opaque, int version_id)
3204 {
3205     return !mac_table_fits(opaque, version_id);
3206 }
3207 
3208 /* This temporary type is shared by all the WITH_TMP methods
3209  * although only some fields are used by each.
3210  */
3211 struct VirtIONetMigTmp {
3212     VirtIONet      *parent;
3213     VirtIONetQueue *vqs_1;
3214     uint16_t        curr_queue_pairs_1;
3215     uint8_t         has_ufo;
3216     uint32_t        has_vnet_hdr;
3217 };
3218 
3219 /* The 2nd and subsequent tx_waiting flags are loaded later than
3220  * the 1st entry in the queue_pairs and only if there's more than one
3221  * entry.  We use the tmp mechanism to calculate a temporary
3222  * pointer and count and also validate the count.
3223  */
3224 
3225 static int virtio_net_tx_waiting_pre_save(void *opaque)
3226 {
3227     struct VirtIONetMigTmp *tmp = opaque;
3228 
3229     tmp->vqs_1 = tmp->parent->vqs + 1;
3230     tmp->curr_queue_pairs_1 = tmp->parent->curr_queue_pairs - 1;
3231     if (tmp->parent->curr_queue_pairs == 0) {
3232         tmp->curr_queue_pairs_1 = 0;
3233     }
3234 
3235     return 0;
3236 }
3237 
3238 static int virtio_net_tx_waiting_pre_load(void *opaque)
3239 {
3240     struct VirtIONetMigTmp *tmp = opaque;
3241 
3242     /* Reuse the pointer setup from save */
3243     virtio_net_tx_waiting_pre_save(opaque);
3244 
3245     if (tmp->parent->curr_queue_pairs > tmp->parent->max_queue_pairs) {
3246         error_report("virtio-net: curr_queue_pairs %x > max_queue_pairs %x",
3247             tmp->parent->curr_queue_pairs, tmp->parent->max_queue_pairs);
3248 
3249         return -EINVAL;
3250     }
3251 
3252     return 0; /* all good */
3253 }
3254 
3255 static const VMStateDescription vmstate_virtio_net_tx_waiting = {
3256     .name      = "virtio-net-tx_waiting",
3257     .pre_load  = virtio_net_tx_waiting_pre_load,
3258     .pre_save  = virtio_net_tx_waiting_pre_save,
3259     .fields    = (const VMStateField[]) {
3260         VMSTATE_STRUCT_VARRAY_POINTER_UINT16(vqs_1, struct VirtIONetMigTmp,
3261                                      curr_queue_pairs_1,
3262                                      vmstate_virtio_net_queue_tx_waiting,
3263                                      struct VirtIONetQueue),
3264         VMSTATE_END_OF_LIST()
3265     },
3266 };
3267 
3268 /* the 'has_ufo' flag is just tested; if the incoming stream has the
3269  * flag set we need to check that we have it
3270  */
3271 static int virtio_net_ufo_post_load(void *opaque, int version_id)
3272 {
3273     struct VirtIONetMigTmp *tmp = opaque;
3274 
3275     if (tmp->has_ufo && !peer_has_ufo(tmp->parent)) {
3276         error_report("virtio-net: saved image requires TUN_F_UFO support");
3277         return -EINVAL;
3278     }
3279 
3280     return 0;
3281 }
3282 
3283 static int virtio_net_ufo_pre_save(void *opaque)
3284 {
3285     struct VirtIONetMigTmp *tmp = opaque;
3286 
3287     tmp->has_ufo = tmp->parent->has_ufo;
3288 
3289     return 0;
3290 }
3291 
3292 static const VMStateDescription vmstate_virtio_net_has_ufo = {
3293     .name      = "virtio-net-ufo",
3294     .post_load = virtio_net_ufo_post_load,
3295     .pre_save  = virtio_net_ufo_pre_save,
3296     .fields    = (const VMStateField[]) {
3297         VMSTATE_UINT8(has_ufo, struct VirtIONetMigTmp),
3298         VMSTATE_END_OF_LIST()
3299     },
3300 };
3301 
3302 /* the 'has_vnet_hdr' flag is just tested; if the incoming stream has the
3303  * flag set we need to check that we have it
3304  */
3305 static int virtio_net_vnet_post_load(void *opaque, int version_id)
3306 {
3307     struct VirtIONetMigTmp *tmp = opaque;
3308 
3309     if (tmp->has_vnet_hdr && !peer_has_vnet_hdr(tmp->parent)) {
3310         error_report("virtio-net: saved image requires vnet_hdr=on");
3311         return -EINVAL;
3312     }
3313 
3314     return 0;
3315 }
3316 
3317 static int virtio_net_vnet_pre_save(void *opaque)
3318 {
3319     struct VirtIONetMigTmp *tmp = opaque;
3320 
3321     tmp->has_vnet_hdr = tmp->parent->has_vnet_hdr;
3322 
3323     return 0;
3324 }
3325 
3326 static const VMStateDescription vmstate_virtio_net_has_vnet = {
3327     .name      = "virtio-net-vnet",
3328     .post_load = virtio_net_vnet_post_load,
3329     .pre_save  = virtio_net_vnet_pre_save,
3330     .fields    = (const VMStateField[]) {
3331         VMSTATE_UINT32(has_vnet_hdr, struct VirtIONetMigTmp),
3332         VMSTATE_END_OF_LIST()
3333     },
3334 };
3335 
3336 static bool virtio_net_rss_needed(void *opaque)
3337 {
3338     return VIRTIO_NET(opaque)->rss_data.enabled;
3339 }
3340 
3341 static const VMStateDescription vmstate_virtio_net_rss = {
3342     .name      = "virtio-net-device/rss",
3343     .version_id = 1,
3344     .minimum_version_id = 1,
3345     .needed = virtio_net_rss_needed,
3346     .fields = (const VMStateField[]) {
3347         VMSTATE_BOOL(rss_data.enabled, VirtIONet),
3348         VMSTATE_BOOL(rss_data.redirect, VirtIONet),
3349         VMSTATE_BOOL(rss_data.populate_hash, VirtIONet),
3350         VMSTATE_UINT32(rss_data.hash_types, VirtIONet),
3351         VMSTATE_UINT16(rss_data.indirections_len, VirtIONet),
3352         VMSTATE_UINT16(rss_data.default_queue, VirtIONet),
3353         VMSTATE_UINT8_ARRAY(rss_data.key, VirtIONet,
3354                             VIRTIO_NET_RSS_MAX_KEY_SIZE),
3355         VMSTATE_VARRAY_UINT16_ALLOC(rss_data.indirections_table, VirtIONet,
3356                                     rss_data.indirections_len, 0,
3357                                     vmstate_info_uint16, uint16_t),
3358         VMSTATE_END_OF_LIST()
3359     },
3360 };
3361 
3362 static const VMStateDescription vmstate_virtio_net_device = {
3363     .name = "virtio-net-device",
3364     .version_id = VIRTIO_NET_VM_VERSION,
3365     .minimum_version_id = VIRTIO_NET_VM_VERSION,
3366     .post_load = virtio_net_post_load_device,
3367     .fields = (const VMStateField[]) {
3368         VMSTATE_UINT8_ARRAY(mac, VirtIONet, ETH_ALEN),
3369         VMSTATE_STRUCT_POINTER(vqs, VirtIONet,
3370                                vmstate_virtio_net_queue_tx_waiting,
3371                                VirtIONetQueue),
3372         VMSTATE_UINT32(mergeable_rx_bufs, VirtIONet),
3373         VMSTATE_UINT16(status, VirtIONet),
3374         VMSTATE_UINT8(promisc, VirtIONet),
3375         VMSTATE_UINT8(allmulti, VirtIONet),
3376         VMSTATE_UINT32(mac_table.in_use, VirtIONet),
3377 
3378         /* Guarded pair: If it fits we load it, else we throw it away
3379          * - can happen if source has a larger MAC table.; post-load
3380          *  sets flags in this case.
3381          */
3382         VMSTATE_VBUFFER_MULTIPLY(mac_table.macs, VirtIONet,
3383                                 0, mac_table_fits, mac_table.in_use,
3384                                  ETH_ALEN),
3385         VMSTATE_UNUSED_VARRAY_UINT32(VirtIONet, mac_table_doesnt_fit, 0,
3386                                      mac_table.in_use, ETH_ALEN),
3387 
3388         /* Note: This is an array of uint32's that's always been saved as a
3389          * buffer; hold onto your endiannesses; it's actually used as a bitmap
3390          * but based on the uint.
3391          */
3392         VMSTATE_BUFFER_POINTER_UNSAFE(vlans, VirtIONet, 0, MAX_VLAN >> 3),
3393         VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
3394                          vmstate_virtio_net_has_vnet),
3395         VMSTATE_UINT8(mac_table.multi_overflow, VirtIONet),
3396         VMSTATE_UINT8(mac_table.uni_overflow, VirtIONet),
3397         VMSTATE_UINT8(alluni, VirtIONet),
3398         VMSTATE_UINT8(nomulti, VirtIONet),
3399         VMSTATE_UINT8(nouni, VirtIONet),
3400         VMSTATE_UINT8(nobcast, VirtIONet),
3401         VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
3402                          vmstate_virtio_net_has_ufo),
3403         VMSTATE_SINGLE_TEST(max_queue_pairs, VirtIONet, max_queue_pairs_gt_1, 0,
3404                             vmstate_info_uint16_equal, uint16_t),
3405         VMSTATE_UINT16_TEST(curr_queue_pairs, VirtIONet, max_queue_pairs_gt_1),
3406         VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
3407                          vmstate_virtio_net_tx_waiting),
3408         VMSTATE_UINT64_TEST(curr_guest_offloads, VirtIONet,
3409                             has_ctrl_guest_offloads),
3410         VMSTATE_END_OF_LIST()
3411     },
3412     .subsections = (const VMStateDescription * const []) {
3413         &vmstate_virtio_net_rss,
3414         NULL
3415     }
3416 };
3417 
3418 static NetClientInfo net_virtio_info = {
3419     .type = NET_CLIENT_DRIVER_NIC,
3420     .size = sizeof(NICState),
3421     .can_receive = virtio_net_can_receive,
3422     .receive = virtio_net_receive,
3423     .link_status_changed = virtio_net_set_link_status,
3424     .query_rx_filter = virtio_net_query_rxfilter,
3425     .announce = virtio_net_announce,
3426 };
3427 
3428 static bool virtio_net_guest_notifier_pending(VirtIODevice *vdev, int idx)
3429 {
3430     VirtIONet *n = VIRTIO_NET(vdev);
3431     NetClientState *nc;
3432     assert(n->vhost_started);
3433     if (!n->multiqueue && idx == 2) {
3434         /* Must guard against invalid features and bogus queue index
3435          * from being set by malicious guest, or penetrated through
3436          * buggy migration stream.
3437          */
3438         if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
3439             qemu_log_mask(LOG_GUEST_ERROR,
3440                           "%s: bogus vq index ignored\n", __func__);
3441             return false;
3442         }
3443         nc = qemu_get_subqueue(n->nic, n->max_queue_pairs);
3444     } else {
3445         nc = qemu_get_subqueue(n->nic, vq2q(idx));
3446     }
3447     /*
3448      * Add the check for configure interrupt, Use VIRTIO_CONFIG_IRQ_IDX -1
3449      * as the macro of configure interrupt's IDX, If this driver does not
3450      * support, the function will return false
3451      */
3452 
3453     if (idx == VIRTIO_CONFIG_IRQ_IDX) {
3454         return vhost_net_config_pending(get_vhost_net(nc->peer));
3455     }
3456     return vhost_net_virtqueue_pending(get_vhost_net(nc->peer), idx);
3457 }
3458 
3459 static void virtio_net_guest_notifier_mask(VirtIODevice *vdev, int idx,
3460                                            bool mask)
3461 {
3462     VirtIONet *n = VIRTIO_NET(vdev);
3463     NetClientState *nc;
3464     assert(n->vhost_started);
3465     if (!n->multiqueue && idx == 2) {
3466         /* Must guard against invalid features and bogus queue index
3467          * from being set by malicious guest, or penetrated through
3468          * buggy migration stream.
3469          */
3470         if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
3471             qemu_log_mask(LOG_GUEST_ERROR,
3472                           "%s: bogus vq index ignored\n", __func__);
3473             return;
3474         }
3475         nc = qemu_get_subqueue(n->nic, n->max_queue_pairs);
3476     } else {
3477         nc = qemu_get_subqueue(n->nic, vq2q(idx));
3478     }
3479     /*
3480      *Add the check for configure interrupt, Use VIRTIO_CONFIG_IRQ_IDX -1
3481      * as the macro of configure interrupt's IDX, If this driver does not
3482      * support, the function will return
3483      */
3484 
3485     if (idx == VIRTIO_CONFIG_IRQ_IDX) {
3486         vhost_net_config_mask(get_vhost_net(nc->peer), vdev, mask);
3487         return;
3488     }
3489     vhost_net_virtqueue_mask(get_vhost_net(nc->peer), vdev, idx, mask);
3490 }
3491 
3492 static void virtio_net_set_config_size(VirtIONet *n, uint64_t host_features)
3493 {
3494     virtio_add_feature(&host_features, VIRTIO_NET_F_MAC);
3495 
3496     n->config_size = virtio_get_config_size(&cfg_size_params, host_features);
3497 }
3498 
3499 void virtio_net_set_netclient_name(VirtIONet *n, const char *name,
3500                                    const char *type)
3501 {
3502     /*
3503      * The name can be NULL, the netclient name will be type.x.
3504      */
3505     assert(type != NULL);
3506 
3507     g_free(n->netclient_name);
3508     g_free(n->netclient_type);
3509     n->netclient_name = g_strdup(name);
3510     n->netclient_type = g_strdup(type);
3511 }
3512 
3513 static bool failover_unplug_primary(VirtIONet *n, DeviceState *dev)
3514 {
3515     HotplugHandler *hotplug_ctrl;
3516     PCIDevice *pci_dev;
3517     Error *err = NULL;
3518 
3519     hotplug_ctrl = qdev_get_hotplug_handler(dev);
3520     if (hotplug_ctrl) {
3521         pci_dev = PCI_DEVICE(dev);
3522         pci_dev->partially_hotplugged = true;
3523         hotplug_handler_unplug_request(hotplug_ctrl, dev, &err);
3524         if (err) {
3525             error_report_err(err);
3526             return false;
3527         }
3528     } else {
3529         return false;
3530     }
3531     return true;
3532 }
3533 
3534 static bool failover_replug_primary(VirtIONet *n, DeviceState *dev,
3535                                     Error **errp)
3536 {
3537     Error *err = NULL;
3538     HotplugHandler *hotplug_ctrl;
3539     PCIDevice *pdev = PCI_DEVICE(dev);
3540     BusState *primary_bus;
3541 
3542     if (!pdev->partially_hotplugged) {
3543         return true;
3544     }
3545     primary_bus = dev->parent_bus;
3546     if (!primary_bus) {
3547         error_setg(errp, "virtio_net: couldn't find primary bus");
3548         return false;
3549     }
3550     qdev_set_parent_bus(dev, primary_bus, &error_abort);
3551     qatomic_set(&n->failover_primary_hidden, false);
3552     hotplug_ctrl = qdev_get_hotplug_handler(dev);
3553     if (hotplug_ctrl) {
3554         hotplug_handler_pre_plug(hotplug_ctrl, dev, &err);
3555         if (err) {
3556             goto out;
3557         }
3558         hotplug_handler_plug(hotplug_ctrl, dev, &err);
3559     }
3560     pdev->partially_hotplugged = false;
3561 
3562 out:
3563     error_propagate(errp, err);
3564     return !err;
3565 }
3566 
3567 static void virtio_net_handle_migration_primary(VirtIONet *n, MigrationEvent *e)
3568 {
3569     bool should_be_hidden;
3570     Error *err = NULL;
3571     DeviceState *dev = failover_find_primary_device(n);
3572 
3573     if (!dev) {
3574         return;
3575     }
3576 
3577     should_be_hidden = qatomic_read(&n->failover_primary_hidden);
3578 
3579     if (e->type == MIG_EVENT_PRECOPY_SETUP && !should_be_hidden) {
3580         if (failover_unplug_primary(n, dev)) {
3581             vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
3582             qapi_event_send_unplug_primary(dev->id);
3583             qatomic_set(&n->failover_primary_hidden, true);
3584         } else {
3585             warn_report("couldn't unplug primary device");
3586         }
3587     } else if (e->type == MIG_EVENT_PRECOPY_FAILED) {
3588         /* We already unplugged the device let's plug it back */
3589         if (!failover_replug_primary(n, dev, &err)) {
3590             if (err) {
3591                 error_report_err(err);
3592             }
3593         }
3594     }
3595 }
3596 
3597 static int virtio_net_migration_state_notifier(NotifierWithReturn *notifier,
3598                                                MigrationEvent *e, Error **errp)
3599 {
3600     VirtIONet *n = container_of(notifier, VirtIONet, migration_state);
3601     virtio_net_handle_migration_primary(n, e);
3602     return 0;
3603 }
3604 
3605 static bool failover_hide_primary_device(DeviceListener *listener,
3606                                          const QDict *device_opts,
3607                                          bool from_json,
3608                                          Error **errp)
3609 {
3610     VirtIONet *n = container_of(listener, VirtIONet, primary_listener);
3611     const char *standby_id;
3612 
3613     if (!device_opts) {
3614         return false;
3615     }
3616 
3617     if (!qdict_haskey(device_opts, "failover_pair_id")) {
3618         return false;
3619     }
3620 
3621     if (!qdict_haskey(device_opts, "id")) {
3622         error_setg(errp, "Device with failover_pair_id needs to have id");
3623         return false;
3624     }
3625 
3626     standby_id = qdict_get_str(device_opts, "failover_pair_id");
3627     if (g_strcmp0(standby_id, n->netclient_name) != 0) {
3628         return false;
3629     }
3630 
3631     /*
3632      * The hide helper can be called several times for a given device.
3633      * Check there is only one primary for a virtio-net device but
3634      * don't duplicate the qdict several times if it's called for the same
3635      * device.
3636      */
3637     if (n->primary_opts) {
3638         const char *old, *new;
3639         /* devices with failover_pair_id always have an id */
3640         old = qdict_get_str(n->primary_opts, "id");
3641         new = qdict_get_str(device_opts, "id");
3642         if (strcmp(old, new) != 0) {
3643             error_setg(errp, "Cannot attach more than one primary device to "
3644                        "'%s': '%s' and '%s'", n->netclient_name, old, new);
3645             return false;
3646         }
3647     } else {
3648         n->primary_opts = qdict_clone_shallow(device_opts);
3649         n->primary_opts_from_json = from_json;
3650     }
3651 
3652     /* failover_primary_hidden is set during feature negotiation */
3653     return qatomic_read(&n->failover_primary_hidden);
3654 }
3655 
3656 static void virtio_net_device_realize(DeviceState *dev, Error **errp)
3657 {
3658     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3659     VirtIONet *n = VIRTIO_NET(dev);
3660     NetClientState *nc;
3661     int i;
3662 
3663     if (n->net_conf.mtu) {
3664         n->host_features |= (1ULL << VIRTIO_NET_F_MTU);
3665     }
3666 
3667     if (n->net_conf.duplex_str) {
3668         if (strncmp(n->net_conf.duplex_str, "half", 5) == 0) {
3669             n->net_conf.duplex = DUPLEX_HALF;
3670         } else if (strncmp(n->net_conf.duplex_str, "full", 5) == 0) {
3671             n->net_conf.duplex = DUPLEX_FULL;
3672         } else {
3673             error_setg(errp, "'duplex' must be 'half' or 'full'");
3674             return;
3675         }
3676         n->host_features |= (1ULL << VIRTIO_NET_F_SPEED_DUPLEX);
3677     } else {
3678         n->net_conf.duplex = DUPLEX_UNKNOWN;
3679     }
3680 
3681     if (n->net_conf.speed < SPEED_UNKNOWN) {
3682         error_setg(errp, "'speed' must be between 0 and INT_MAX");
3683         return;
3684     }
3685     if (n->net_conf.speed >= 0) {
3686         n->host_features |= (1ULL << VIRTIO_NET_F_SPEED_DUPLEX);
3687     }
3688 
3689     if (n->failover) {
3690         n->primary_listener.hide_device = failover_hide_primary_device;
3691         qatomic_set(&n->failover_primary_hidden, true);
3692         device_listener_register(&n->primary_listener);
3693         migration_add_notifier(&n->migration_state,
3694                                virtio_net_migration_state_notifier);
3695         n->host_features |= (1ULL << VIRTIO_NET_F_STANDBY);
3696     }
3697 
3698     virtio_net_set_config_size(n, n->host_features);
3699     virtio_init(vdev, VIRTIO_ID_NET, n->config_size);
3700 
3701     /*
3702      * We set a lower limit on RX queue size to what it always was.
3703      * Guests that want a smaller ring can always resize it without
3704      * help from us (using virtio 1 and up).
3705      */
3706     if (n->net_conf.rx_queue_size < VIRTIO_NET_RX_QUEUE_MIN_SIZE ||
3707         n->net_conf.rx_queue_size > VIRTQUEUE_MAX_SIZE ||
3708         !is_power_of_2(n->net_conf.rx_queue_size)) {
3709         error_setg(errp, "Invalid rx_queue_size (= %" PRIu16 "), "
3710                    "must be a power of 2 between %d and %d.",
3711                    n->net_conf.rx_queue_size, VIRTIO_NET_RX_QUEUE_MIN_SIZE,
3712                    VIRTQUEUE_MAX_SIZE);
3713         virtio_cleanup(vdev);
3714         return;
3715     }
3716 
3717     if (n->net_conf.tx_queue_size < VIRTIO_NET_TX_QUEUE_MIN_SIZE ||
3718         n->net_conf.tx_queue_size > virtio_net_max_tx_queue_size(n) ||
3719         !is_power_of_2(n->net_conf.tx_queue_size)) {
3720         error_setg(errp, "Invalid tx_queue_size (= %" PRIu16 "), "
3721                    "must be a power of 2 between %d and %d",
3722                    n->net_conf.tx_queue_size, VIRTIO_NET_TX_QUEUE_MIN_SIZE,
3723                    virtio_net_max_tx_queue_size(n));
3724         virtio_cleanup(vdev);
3725         return;
3726     }
3727 
3728     n->max_ncs = MAX(n->nic_conf.peers.queues, 1);
3729 
3730     /*
3731      * Figure out the datapath queue pairs since the backend could
3732      * provide control queue via peers as well.
3733      */
3734     if (n->nic_conf.peers.queues) {
3735         for (i = 0; i < n->max_ncs; i++) {
3736             if (n->nic_conf.peers.ncs[i]->is_datapath) {
3737                 ++n->max_queue_pairs;
3738             }
3739         }
3740     }
3741     n->max_queue_pairs = MAX(n->max_queue_pairs, 1);
3742 
3743     if (n->max_queue_pairs * 2 + 1 > VIRTIO_QUEUE_MAX) {
3744         error_setg(errp, "Invalid number of queue pairs (= %" PRIu32 "), "
3745                    "must be a positive integer less than %d.",
3746                    n->max_queue_pairs, (VIRTIO_QUEUE_MAX - 1) / 2);
3747         virtio_cleanup(vdev);
3748         return;
3749     }
3750     n->vqs = g_new0(VirtIONetQueue, n->max_queue_pairs);
3751     n->curr_queue_pairs = 1;
3752     n->tx_timeout = n->net_conf.txtimer;
3753 
3754     if (n->net_conf.tx && strcmp(n->net_conf.tx, "timer")
3755                        && strcmp(n->net_conf.tx, "bh")) {
3756         warn_report("virtio-net: "
3757                     "Unknown option tx=%s, valid options: \"timer\" \"bh\"",
3758                     n->net_conf.tx);
3759         error_printf("Defaulting to \"bh\"");
3760     }
3761 
3762     n->net_conf.tx_queue_size = MIN(virtio_net_max_tx_queue_size(n),
3763                                     n->net_conf.tx_queue_size);
3764 
3765     for (i = 0; i < n->max_queue_pairs; i++) {
3766         virtio_net_add_queue(n, i);
3767     }
3768 
3769     n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
3770     qemu_macaddr_default_if_unset(&n->nic_conf.macaddr);
3771     memcpy(&n->mac[0], &n->nic_conf.macaddr, sizeof(n->mac));
3772     n->status = VIRTIO_NET_S_LINK_UP;
3773     qemu_announce_timer_reset(&n->announce_timer, migrate_announce_params(),
3774                               QEMU_CLOCK_VIRTUAL,
3775                               virtio_net_announce_timer, n);
3776     n->announce_timer.round = 0;
3777 
3778     if (n->netclient_type) {
3779         /*
3780          * Happen when virtio_net_set_netclient_name has been called.
3781          */
3782         n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
3783                               n->netclient_type, n->netclient_name,
3784                               &dev->mem_reentrancy_guard, n);
3785     } else {
3786         n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
3787                               object_get_typename(OBJECT(dev)), dev->id,
3788                               &dev->mem_reentrancy_guard, n);
3789     }
3790 
3791     for (i = 0; i < n->max_queue_pairs; i++) {
3792         n->nic->ncs[i].do_not_pad = true;
3793     }
3794 
3795     peer_test_vnet_hdr(n);
3796     if (peer_has_vnet_hdr(n)) {
3797         for (i = 0; i < n->max_queue_pairs; i++) {
3798             qemu_using_vnet_hdr(qemu_get_subqueue(n->nic, i)->peer, true);
3799         }
3800         n->host_hdr_len = sizeof(struct virtio_net_hdr);
3801     } else {
3802         n->host_hdr_len = 0;
3803     }
3804 
3805     qemu_format_nic_info_str(qemu_get_queue(n->nic), n->nic_conf.macaddr.a);
3806 
3807     n->vqs[0].tx_waiting = 0;
3808     n->tx_burst = n->net_conf.txburst;
3809     virtio_net_set_mrg_rx_bufs(n, 0, 0, 0);
3810     n->promisc = 1; /* for compatibility */
3811 
3812     n->mac_table.macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);
3813 
3814     n->vlans = g_malloc0(MAX_VLAN >> 3);
3815 
3816     nc = qemu_get_queue(n->nic);
3817     nc->rxfilter_notify_enabled = 1;
3818 
3819    if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_VDPA) {
3820         struct virtio_net_config netcfg = {};
3821         memcpy(&netcfg.mac, &n->nic_conf.macaddr, ETH_ALEN);
3822         vhost_net_set_config(get_vhost_net(nc->peer),
3823             (uint8_t *)&netcfg, 0, ETH_ALEN, VHOST_SET_CONFIG_TYPE_FRONTEND);
3824     }
3825     QTAILQ_INIT(&n->rsc_chains);
3826     n->qdev = dev;
3827 
3828     net_rx_pkt_init(&n->rx_pkt);
3829 
3830     if (virtio_has_feature(n->host_features, VIRTIO_NET_F_RSS)) {
3831         virtio_net_load_ebpf(n, errp);
3832     }
3833 }
3834 
3835 static void virtio_net_device_unrealize(DeviceState *dev)
3836 {
3837     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3838     VirtIONet *n = VIRTIO_NET(dev);
3839     int i, max_queue_pairs;
3840 
3841     if (virtio_has_feature(n->host_features, VIRTIO_NET_F_RSS)) {
3842         virtio_net_unload_ebpf(n);
3843     }
3844 
3845     /* This will stop vhost backend if appropriate. */
3846     virtio_net_set_status(vdev, 0);
3847 
3848     g_free(n->netclient_name);
3849     n->netclient_name = NULL;
3850     g_free(n->netclient_type);
3851     n->netclient_type = NULL;
3852 
3853     g_free(n->mac_table.macs);
3854     g_free(n->vlans);
3855 
3856     if (n->failover) {
3857         qobject_unref(n->primary_opts);
3858         device_listener_unregister(&n->primary_listener);
3859         migration_remove_notifier(&n->migration_state);
3860     } else {
3861         assert(n->primary_opts == NULL);
3862     }
3863 
3864     max_queue_pairs = n->multiqueue ? n->max_queue_pairs : 1;
3865     for (i = 0; i < max_queue_pairs; i++) {
3866         virtio_net_del_queue(n, i);
3867     }
3868     /* delete also control vq */
3869     virtio_del_queue(vdev, max_queue_pairs * 2);
3870     qemu_announce_timer_del(&n->announce_timer, false);
3871     g_free(n->vqs);
3872     qemu_del_nic(n->nic);
3873     virtio_net_rsc_cleanup(n);
3874     g_free(n->rss_data.indirections_table);
3875     net_rx_pkt_uninit(n->rx_pkt);
3876     virtio_cleanup(vdev);
3877 }
3878 
3879 static void virtio_net_instance_init(Object *obj)
3880 {
3881     VirtIONet *n = VIRTIO_NET(obj);
3882 
3883     /*
3884      * The default config_size is sizeof(struct virtio_net_config).
3885      * Can be overridden with virtio_net_set_config_size.
3886      */
3887     n->config_size = sizeof(struct virtio_net_config);
3888     device_add_bootindex_property(obj, &n->nic_conf.bootindex,
3889                                   "bootindex", "/ethernet-phy@0",
3890                                   DEVICE(n));
3891 
3892     ebpf_rss_init(&n->ebpf_rss);
3893 }
3894 
3895 static int virtio_net_pre_save(void *opaque)
3896 {
3897     VirtIONet *n = opaque;
3898 
3899     /* At this point, backend must be stopped, otherwise
3900      * it might keep writing to memory. */
3901     assert(!n->vhost_started);
3902 
3903     return 0;
3904 }
3905 
3906 static bool primary_unplug_pending(void *opaque)
3907 {
3908     DeviceState *dev = opaque;
3909     DeviceState *primary;
3910     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3911     VirtIONet *n = VIRTIO_NET(vdev);
3912 
3913     if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3914         return false;
3915     }
3916     primary = failover_find_primary_device(n);
3917     return primary ? primary->pending_deleted_event : false;
3918 }
3919 
3920 static bool dev_unplug_pending(void *opaque)
3921 {
3922     DeviceState *dev = opaque;
3923     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3924 
3925     return vdc->primary_unplug_pending(dev);
3926 }
3927 
3928 static struct vhost_dev *virtio_net_get_vhost(VirtIODevice *vdev)
3929 {
3930     VirtIONet *n = VIRTIO_NET(vdev);
3931     NetClientState *nc = qemu_get_queue(n->nic);
3932     struct vhost_net *net = get_vhost_net(nc->peer);
3933     return &net->dev;
3934 }
3935 
3936 static const VMStateDescription vmstate_virtio_net = {
3937     .name = "virtio-net",
3938     .minimum_version_id = VIRTIO_NET_VM_VERSION,
3939     .version_id = VIRTIO_NET_VM_VERSION,
3940     .fields = (const VMStateField[]) {
3941         VMSTATE_VIRTIO_DEVICE,
3942         VMSTATE_END_OF_LIST()
3943     },
3944     .pre_save = virtio_net_pre_save,
3945     .dev_unplug_pending = dev_unplug_pending,
3946 };
3947 
3948 static Property virtio_net_properties[] = {
3949     DEFINE_PROP_BIT64("csum", VirtIONet, host_features,
3950                     VIRTIO_NET_F_CSUM, true),
3951     DEFINE_PROP_BIT64("guest_csum", VirtIONet, host_features,
3952                     VIRTIO_NET_F_GUEST_CSUM, true),
3953     DEFINE_PROP_BIT64("gso", VirtIONet, host_features, VIRTIO_NET_F_GSO, true),
3954     DEFINE_PROP_BIT64("guest_tso4", VirtIONet, host_features,
3955                     VIRTIO_NET_F_GUEST_TSO4, true),
3956     DEFINE_PROP_BIT64("guest_tso6", VirtIONet, host_features,
3957                     VIRTIO_NET_F_GUEST_TSO6, true),
3958     DEFINE_PROP_BIT64("guest_ecn", VirtIONet, host_features,
3959                     VIRTIO_NET_F_GUEST_ECN, true),
3960     DEFINE_PROP_BIT64("guest_ufo", VirtIONet, host_features,
3961                     VIRTIO_NET_F_GUEST_UFO, true),
3962     DEFINE_PROP_BIT64("guest_announce", VirtIONet, host_features,
3963                     VIRTIO_NET_F_GUEST_ANNOUNCE, true),
3964     DEFINE_PROP_BIT64("host_tso4", VirtIONet, host_features,
3965                     VIRTIO_NET_F_HOST_TSO4, true),
3966     DEFINE_PROP_BIT64("host_tso6", VirtIONet, host_features,
3967                     VIRTIO_NET_F_HOST_TSO6, true),
3968     DEFINE_PROP_BIT64("host_ecn", VirtIONet, host_features,
3969                     VIRTIO_NET_F_HOST_ECN, true),
3970     DEFINE_PROP_BIT64("host_ufo", VirtIONet, host_features,
3971                     VIRTIO_NET_F_HOST_UFO, true),
3972     DEFINE_PROP_BIT64("mrg_rxbuf", VirtIONet, host_features,
3973                     VIRTIO_NET_F_MRG_RXBUF, true),
3974     DEFINE_PROP_BIT64("status", VirtIONet, host_features,
3975                     VIRTIO_NET_F_STATUS, true),
3976     DEFINE_PROP_BIT64("ctrl_vq", VirtIONet, host_features,
3977                     VIRTIO_NET_F_CTRL_VQ, true),
3978     DEFINE_PROP_BIT64("ctrl_rx", VirtIONet, host_features,
3979                     VIRTIO_NET_F_CTRL_RX, true),
3980     DEFINE_PROP_BIT64("ctrl_vlan", VirtIONet, host_features,
3981                     VIRTIO_NET_F_CTRL_VLAN, true),
3982     DEFINE_PROP_BIT64("ctrl_rx_extra", VirtIONet, host_features,
3983                     VIRTIO_NET_F_CTRL_RX_EXTRA, true),
3984     DEFINE_PROP_BIT64("ctrl_mac_addr", VirtIONet, host_features,
3985                     VIRTIO_NET_F_CTRL_MAC_ADDR, true),
3986     DEFINE_PROP_BIT64("ctrl_guest_offloads", VirtIONet, host_features,
3987                     VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, true),
3988     DEFINE_PROP_BIT64("mq", VirtIONet, host_features, VIRTIO_NET_F_MQ, false),
3989     DEFINE_PROP_BIT64("rss", VirtIONet, host_features,
3990                     VIRTIO_NET_F_RSS, false),
3991     DEFINE_PROP_BIT64("hash", VirtIONet, host_features,
3992                     VIRTIO_NET_F_HASH_REPORT, false),
3993     DEFINE_PROP_ARRAY("ebpf-rss-fds", VirtIONet, nr_ebpf_rss_fds,
3994                       ebpf_rss_fds, qdev_prop_string, char*),
3995     DEFINE_PROP_BIT64("guest_rsc_ext", VirtIONet, host_features,
3996                     VIRTIO_NET_F_RSC_EXT, false),
3997     DEFINE_PROP_UINT32("rsc_interval", VirtIONet, rsc_timeout,
3998                        VIRTIO_NET_RSC_DEFAULT_INTERVAL),
3999     DEFINE_NIC_PROPERTIES(VirtIONet, nic_conf),
4000     DEFINE_PROP_UINT32("x-txtimer", VirtIONet, net_conf.txtimer,
4001                        TX_TIMER_INTERVAL),
4002     DEFINE_PROP_INT32("x-txburst", VirtIONet, net_conf.txburst, TX_BURST),
4003     DEFINE_PROP_STRING("tx", VirtIONet, net_conf.tx),
4004     DEFINE_PROP_UINT16("rx_queue_size", VirtIONet, net_conf.rx_queue_size,
4005                        VIRTIO_NET_RX_QUEUE_DEFAULT_SIZE),
4006     DEFINE_PROP_UINT16("tx_queue_size", VirtIONet, net_conf.tx_queue_size,
4007                        VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE),
4008     DEFINE_PROP_UINT16("host_mtu", VirtIONet, net_conf.mtu, 0),
4009     DEFINE_PROP_BOOL("x-mtu-bypass-backend", VirtIONet, mtu_bypass_backend,
4010                      true),
4011     DEFINE_PROP_INT32("speed", VirtIONet, net_conf.speed, SPEED_UNKNOWN),
4012     DEFINE_PROP_STRING("duplex", VirtIONet, net_conf.duplex_str),
4013     DEFINE_PROP_BOOL("failover", VirtIONet, failover, false),
4014     DEFINE_PROP_BIT64("guest_uso4", VirtIONet, host_features,
4015                       VIRTIO_NET_F_GUEST_USO4, true),
4016     DEFINE_PROP_BIT64("guest_uso6", VirtIONet, host_features,
4017                       VIRTIO_NET_F_GUEST_USO6, true),
4018     DEFINE_PROP_BIT64("host_uso", VirtIONet, host_features,
4019                       VIRTIO_NET_F_HOST_USO, true),
4020     DEFINE_PROP_END_OF_LIST(),
4021 };
4022 
4023 static void virtio_net_class_init(ObjectClass *klass, void *data)
4024 {
4025     DeviceClass *dc = DEVICE_CLASS(klass);
4026     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
4027 
4028     device_class_set_props(dc, virtio_net_properties);
4029     dc->vmsd = &vmstate_virtio_net;
4030     set_bit(DEVICE_CATEGORY_NETWORK, dc->categories);
4031     vdc->realize = virtio_net_device_realize;
4032     vdc->unrealize = virtio_net_device_unrealize;
4033     vdc->get_config = virtio_net_get_config;
4034     vdc->set_config = virtio_net_set_config;
4035     vdc->get_features = virtio_net_get_features;
4036     vdc->set_features = virtio_net_set_features;
4037     vdc->bad_features = virtio_net_bad_features;
4038     vdc->reset = virtio_net_reset;
4039     vdc->queue_reset = virtio_net_queue_reset;
4040     vdc->queue_enable = virtio_net_queue_enable;
4041     vdc->set_status = virtio_net_set_status;
4042     vdc->guest_notifier_mask = virtio_net_guest_notifier_mask;
4043     vdc->guest_notifier_pending = virtio_net_guest_notifier_pending;
4044     vdc->legacy_features |= (0x1 << VIRTIO_NET_F_GSO);
4045     vdc->post_load = virtio_net_post_load_virtio;
4046     vdc->vmsd = &vmstate_virtio_net_device;
4047     vdc->primary_unplug_pending = primary_unplug_pending;
4048     vdc->get_vhost = virtio_net_get_vhost;
4049     vdc->toggle_device_iotlb = vhost_toggle_device_iotlb;
4050 }
4051 
4052 static const TypeInfo virtio_net_info = {
4053     .name = TYPE_VIRTIO_NET,
4054     .parent = TYPE_VIRTIO_DEVICE,
4055     .instance_size = sizeof(VirtIONet),
4056     .instance_init = virtio_net_instance_init,
4057     .class_init = virtio_net_class_init,
4058 };
4059 
4060 static void virtio_register_types(void)
4061 {
4062     type_register_static(&virtio_net_info);
4063 }
4064 
4065 type_init(virtio_register_types)
4066