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