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