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