xref: /openbmc/qemu/hw/net/virtio-net.c (revision f1595ceb9aad36a6c1da95bcb77ab9509b38822d)
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     VirtIONet *n = q->n;
1645     if (virtio_queue_empty(q->rx_vq) ||
1646         (n->mergeable_rx_bufs &&
1647          !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
1648         virtio_queue_set_notification(q->rx_vq, 1);
1649 
1650         /* To avoid a race condition where the guest has made some buffers
1651          * available after the above check but before notification was
1652          * enabled, check for available buffers again.
1653          */
1654         if (virtio_queue_empty(q->rx_vq) ||
1655             (n->mergeable_rx_bufs &&
1656              !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
1657             return 0;
1658         }
1659     }
1660 
1661     virtio_queue_set_notification(q->rx_vq, 0);
1662     return 1;
1663 }
1664 
1665 static void virtio_net_hdr_swap(VirtIODevice *vdev, struct virtio_net_hdr *hdr)
1666 {
1667     virtio_tswap16s(vdev, &hdr->hdr_len);
1668     virtio_tswap16s(vdev, &hdr->gso_size);
1669     virtio_tswap16s(vdev, &hdr->csum_start);
1670     virtio_tswap16s(vdev, &hdr->csum_offset);
1671 }
1672 
1673 /* dhclient uses AF_PACKET but doesn't pass auxdata to the kernel so
1674  * it never finds out that the packets don't have valid checksums.  This
1675  * causes dhclient to get upset.  Fedora's carried a patch for ages to
1676  * fix this with Xen but it hasn't appeared in an upstream release of
1677  * dhclient yet.
1678  *
1679  * To avoid breaking existing guests, we catch udp packets and add
1680  * checksums.  This is terrible but it's better than hacking the guest
1681  * kernels.
1682  *
1683  * N.B. if we introduce a zero-copy API, this operation is no longer free so
1684  * we should provide a mechanism to disable it to avoid polluting the host
1685  * cache.
1686  */
1687 static void work_around_broken_dhclient(struct virtio_net_hdr *hdr,
1688                                         uint8_t *buf, size_t size)
1689 {
1690     if ((hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && /* missing csum */
1691         (size > 27 && size < 1500) && /* normal sized MTU */
1692         (buf[12] == 0x08 && buf[13] == 0x00) && /* ethertype == IPv4 */
1693         (buf[23] == 17) && /* ip.protocol == UDP */
1694         (buf[34] == 0 && buf[35] == 67)) { /* udp.srcport == bootps */
1695         net_checksum_calculate(buf, size, CSUM_UDP);
1696         hdr->flags &= ~VIRTIO_NET_HDR_F_NEEDS_CSUM;
1697     }
1698 }
1699 
1700 static void receive_header(VirtIONet *n, const struct iovec *iov, int iov_cnt,
1701                            const void *buf, size_t size)
1702 {
1703     if (n->has_vnet_hdr) {
1704         /* FIXME this cast is evil */
1705         void *wbuf = (void *)buf;
1706         work_around_broken_dhclient(wbuf, wbuf + n->host_hdr_len,
1707                                     size - n->host_hdr_len);
1708 
1709         if (n->needs_vnet_hdr_swap) {
1710             virtio_net_hdr_swap(VIRTIO_DEVICE(n), wbuf);
1711         }
1712         iov_from_buf(iov, iov_cnt, 0, buf, sizeof(struct virtio_net_hdr));
1713     } else {
1714         struct virtio_net_hdr hdr = {
1715             .flags = 0,
1716             .gso_type = VIRTIO_NET_HDR_GSO_NONE
1717         };
1718         iov_from_buf(iov, iov_cnt, 0, &hdr, sizeof hdr);
1719     }
1720 }
1721 
1722 static int receive_filter(VirtIONet *n, const uint8_t *buf, int size)
1723 {
1724     static const uint8_t bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
1725     static const uint8_t vlan[] = {0x81, 0x00};
1726     uint8_t *ptr = (uint8_t *)buf;
1727     int i;
1728 
1729     if (n->promisc)
1730         return 1;
1731 
1732     ptr += n->host_hdr_len;
1733 
1734     if (!memcmp(&ptr[12], vlan, sizeof(vlan))) {
1735         int vid = lduw_be_p(ptr + 14) & 0xfff;
1736         if (!(n->vlans[vid >> 5] & (1U << (vid & 0x1f))))
1737             return 0;
1738     }
1739 
1740     if (ptr[0] & 1) { // multicast
1741         if (!memcmp(ptr, bcast, sizeof(bcast))) {
1742             return !n->nobcast;
1743         } else if (n->nomulti) {
1744             return 0;
1745         } else if (n->allmulti || n->mac_table.multi_overflow) {
1746             return 1;
1747         }
1748 
1749         for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {
1750             if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
1751                 return 1;
1752             }
1753         }
1754     } else { // unicast
1755         if (n->nouni) {
1756             return 0;
1757         } else if (n->alluni || n->mac_table.uni_overflow) {
1758             return 1;
1759         } else if (!memcmp(ptr, n->mac, ETH_ALEN)) {
1760             return 1;
1761         }
1762 
1763         for (i = 0; i < n->mac_table.first_multi; i++) {
1764             if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
1765                 return 1;
1766             }
1767         }
1768     }
1769 
1770     return 0;
1771 }
1772 
1773 static uint8_t virtio_net_get_hash_type(bool hasip4,
1774                                         bool hasip6,
1775                                         EthL4HdrProto l4hdr_proto,
1776                                         uint32_t types)
1777 {
1778     if (hasip4) {
1779         switch (l4hdr_proto) {
1780         case ETH_L4_HDR_PROTO_TCP:
1781             if (types & VIRTIO_NET_RSS_HASH_TYPE_TCPv4) {
1782                 return NetPktRssIpV4Tcp;
1783             }
1784             break;
1785 
1786         case ETH_L4_HDR_PROTO_UDP:
1787             if (types & VIRTIO_NET_RSS_HASH_TYPE_UDPv4) {
1788                 return NetPktRssIpV4Udp;
1789             }
1790             break;
1791 
1792         default:
1793             break;
1794         }
1795 
1796         if (types & VIRTIO_NET_RSS_HASH_TYPE_IPv4) {
1797             return NetPktRssIpV4;
1798         }
1799     } else if (hasip6) {
1800         switch (l4hdr_proto) {
1801         case ETH_L4_HDR_PROTO_TCP:
1802             if (types & VIRTIO_NET_RSS_HASH_TYPE_TCP_EX) {
1803                 return NetPktRssIpV6TcpEx;
1804             }
1805             if (types & VIRTIO_NET_RSS_HASH_TYPE_TCPv6) {
1806                 return NetPktRssIpV6Tcp;
1807             }
1808             break;
1809 
1810         case ETH_L4_HDR_PROTO_UDP:
1811             if (types & VIRTIO_NET_RSS_HASH_TYPE_UDP_EX) {
1812                 return NetPktRssIpV6UdpEx;
1813             }
1814             if (types & VIRTIO_NET_RSS_HASH_TYPE_UDPv6) {
1815                 return NetPktRssIpV6Udp;
1816             }
1817             break;
1818 
1819         default:
1820             break;
1821         }
1822 
1823         if (types & VIRTIO_NET_RSS_HASH_TYPE_IP_EX) {
1824             return NetPktRssIpV6Ex;
1825         }
1826         if (types & VIRTIO_NET_RSS_HASH_TYPE_IPv6) {
1827             return NetPktRssIpV6;
1828         }
1829     }
1830     return 0xff;
1831 }
1832 
1833 static int virtio_net_process_rss(NetClientState *nc, const uint8_t *buf,
1834                                   size_t size,
1835                                   struct virtio_net_hdr_v1_hash *hdr)
1836 {
1837     VirtIONet *n = qemu_get_nic_opaque(nc);
1838     unsigned int index = nc->queue_index, new_index = index;
1839     struct NetRxPkt *pkt = n->rx_pkt;
1840     uint8_t net_hash_type;
1841     uint32_t hash;
1842     bool hasip4, hasip6;
1843     EthL4HdrProto l4hdr_proto;
1844     static const uint8_t reports[NetPktRssIpV6UdpEx + 1] = {
1845         VIRTIO_NET_HASH_REPORT_IPv4,
1846         VIRTIO_NET_HASH_REPORT_TCPv4,
1847         VIRTIO_NET_HASH_REPORT_TCPv6,
1848         VIRTIO_NET_HASH_REPORT_IPv6,
1849         VIRTIO_NET_HASH_REPORT_IPv6_EX,
1850         VIRTIO_NET_HASH_REPORT_TCPv6_EX,
1851         VIRTIO_NET_HASH_REPORT_UDPv4,
1852         VIRTIO_NET_HASH_REPORT_UDPv6,
1853         VIRTIO_NET_HASH_REPORT_UDPv6_EX
1854     };
1855     struct iovec iov = {
1856         .iov_base = (void *)buf,
1857         .iov_len = size
1858     };
1859 
1860     net_rx_pkt_set_protocols(pkt, &iov, 1, n->host_hdr_len);
1861     net_rx_pkt_get_protocols(pkt, &hasip4, &hasip6, &l4hdr_proto);
1862     net_hash_type = virtio_net_get_hash_type(hasip4, hasip6, l4hdr_proto,
1863                                              n->rss_data.hash_types);
1864     if (net_hash_type > NetPktRssIpV6UdpEx) {
1865         if (n->rss_data.populate_hash) {
1866             hdr->hash_value = VIRTIO_NET_HASH_REPORT_NONE;
1867             hdr->hash_report = 0;
1868         }
1869         return n->rss_data.redirect ? n->rss_data.default_queue : -1;
1870     }
1871 
1872     hash = net_rx_pkt_calc_rss_hash(pkt, net_hash_type, n->rss_data.key);
1873 
1874     if (n->rss_data.populate_hash) {
1875         hdr->hash_value = hash;
1876         hdr->hash_report = reports[net_hash_type];
1877     }
1878 
1879     if (n->rss_data.redirect) {
1880         new_index = hash & (n->rss_data.indirections_len - 1);
1881         new_index = n->rss_data.indirections_table[new_index];
1882     }
1883 
1884     return (index == new_index) ? -1 : new_index;
1885 }
1886 
1887 static ssize_t virtio_net_receive_rcu(NetClientState *nc, const uint8_t *buf,
1888                                       size_t size, bool no_rss)
1889 {
1890     VirtIONet *n = qemu_get_nic_opaque(nc);
1891     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
1892     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1893     VirtQueueElement *elems[VIRTQUEUE_MAX_SIZE];
1894     size_t lens[VIRTQUEUE_MAX_SIZE];
1895     struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];
1896     struct virtio_net_hdr_v1_hash extra_hdr;
1897     unsigned mhdr_cnt = 0;
1898     size_t offset, i, guest_offset, j;
1899     ssize_t err;
1900 
1901     if (!virtio_net_can_receive(nc)) {
1902         return -1;
1903     }
1904 
1905     if (!no_rss && n->rss_data.enabled && n->rss_data.enabled_software_rss) {
1906         int index = virtio_net_process_rss(nc, buf, size, &extra_hdr);
1907         if (index >= 0) {
1908             NetClientState *nc2 =
1909                 qemu_get_subqueue(n->nic, index % n->curr_queue_pairs);
1910             return virtio_net_receive_rcu(nc2, buf, size, true);
1911         }
1912     }
1913 
1914     /* hdr_len refers to the header we supply to the guest */
1915     if (!virtio_net_has_buffers(q, size + n->guest_hdr_len - n->host_hdr_len)) {
1916         return 0;
1917     }
1918 
1919     if (!receive_filter(n, buf, size))
1920         return size;
1921 
1922     offset = i = 0;
1923 
1924     while (offset < size) {
1925         VirtQueueElement *elem;
1926         int len, total;
1927         const struct iovec *sg;
1928 
1929         total = 0;
1930 
1931         if (i == VIRTQUEUE_MAX_SIZE) {
1932             virtio_error(vdev, "virtio-net unexpected long buffer chain");
1933             err = size;
1934             goto err;
1935         }
1936 
1937         elem = virtqueue_pop(q->rx_vq, sizeof(VirtQueueElement));
1938         if (!elem) {
1939             if (i) {
1940                 virtio_error(vdev, "virtio-net unexpected empty queue: "
1941                              "i %zd mergeable %d offset %zd, size %zd, "
1942                              "guest hdr len %zd, host hdr len %zd "
1943                              "guest features 0x%" PRIx64,
1944                              i, n->mergeable_rx_bufs, offset, size,
1945                              n->guest_hdr_len, n->host_hdr_len,
1946                              vdev->guest_features);
1947             }
1948             err = -1;
1949             goto err;
1950         }
1951 
1952         if (elem->in_num < 1) {
1953             virtio_error(vdev,
1954                          "virtio-net receive queue contains no in buffers");
1955             virtqueue_detach_element(q->rx_vq, elem, 0);
1956             g_free(elem);
1957             err = -1;
1958             goto err;
1959         }
1960 
1961         sg = elem->in_sg;
1962         if (i == 0) {
1963             assert(offset == 0);
1964             if (n->mergeable_rx_bufs) {
1965                 mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),
1966                                     sg, elem->in_num,
1967                                     offsetof(typeof(extra_hdr), hdr.num_buffers),
1968                                     sizeof(extra_hdr.hdr.num_buffers));
1969             }
1970 
1971             receive_header(n, sg, elem->in_num, buf, size);
1972             if (n->rss_data.populate_hash) {
1973                 offset = offsetof(typeof(extra_hdr), hash_value);
1974                 iov_from_buf(sg, elem->in_num, offset,
1975                              (char *)&extra_hdr + offset,
1976                              sizeof(extra_hdr.hash_value) +
1977                              sizeof(extra_hdr.hash_report));
1978             }
1979             offset = n->host_hdr_len;
1980             total += n->guest_hdr_len;
1981             guest_offset = n->guest_hdr_len;
1982         } else {
1983             guest_offset = 0;
1984         }
1985 
1986         /* copy in packet.  ugh */
1987         len = iov_from_buf(sg, elem->in_num, guest_offset,
1988                            buf + offset, size - offset);
1989         total += len;
1990         offset += len;
1991         /* If buffers can't be merged, at this point we
1992          * must have consumed the complete packet.
1993          * Otherwise, drop it. */
1994         if (!n->mergeable_rx_bufs && offset < size) {
1995             virtqueue_unpop(q->rx_vq, elem, total);
1996             g_free(elem);
1997             err = size;
1998             goto err;
1999         }
2000 
2001         elems[i] = elem;
2002         lens[i] = total;
2003         i++;
2004     }
2005 
2006     if (mhdr_cnt) {
2007         virtio_stw_p(vdev, &extra_hdr.hdr.num_buffers, i);
2008         iov_from_buf(mhdr_sg, mhdr_cnt,
2009                      0,
2010                      &extra_hdr.hdr.num_buffers,
2011                      sizeof extra_hdr.hdr.num_buffers);
2012     }
2013 
2014     for (j = 0; j < i; j++) {
2015         /* signal other side */
2016         virtqueue_fill(q->rx_vq, elems[j], lens[j], j);
2017         g_free(elems[j]);
2018     }
2019 
2020     virtqueue_flush(q->rx_vq, i);
2021     virtio_notify(vdev, q->rx_vq);
2022 
2023     return size;
2024 
2025 err:
2026     for (j = 0; j < i; j++) {
2027         virtqueue_detach_element(q->rx_vq, elems[j], lens[j]);
2028         g_free(elems[j]);
2029     }
2030 
2031     return err;
2032 }
2033 
2034 static ssize_t virtio_net_do_receive(NetClientState *nc, const uint8_t *buf,
2035                                   size_t size)
2036 {
2037     RCU_READ_LOCK_GUARD();
2038 
2039     return virtio_net_receive_rcu(nc, buf, size, false);
2040 }
2041 
2042 static void virtio_net_rsc_extract_unit4(VirtioNetRscChain *chain,
2043                                          const uint8_t *buf,
2044                                          VirtioNetRscUnit *unit)
2045 {
2046     uint16_t ip_hdrlen;
2047     struct ip_header *ip;
2048 
2049     ip = (struct ip_header *)(buf + chain->n->guest_hdr_len
2050                               + sizeof(struct eth_header));
2051     unit->ip = (void *)ip;
2052     ip_hdrlen = (ip->ip_ver_len & 0xF) << 2;
2053     unit->ip_plen = &ip->ip_len;
2054     unit->tcp = (struct tcp_header *)(((uint8_t *)unit->ip) + ip_hdrlen);
2055     unit->tcp_hdrlen = (htons(unit->tcp->th_offset_flags) & 0xF000) >> 10;
2056     unit->payload = htons(*unit->ip_plen) - ip_hdrlen - unit->tcp_hdrlen;
2057 }
2058 
2059 static void virtio_net_rsc_extract_unit6(VirtioNetRscChain *chain,
2060                                          const uint8_t *buf,
2061                                          VirtioNetRscUnit *unit)
2062 {
2063     struct ip6_header *ip6;
2064 
2065     ip6 = (struct ip6_header *)(buf + chain->n->guest_hdr_len
2066                                  + sizeof(struct eth_header));
2067     unit->ip = ip6;
2068     unit->ip_plen = &(ip6->ip6_ctlun.ip6_un1.ip6_un1_plen);
2069     unit->tcp = (struct tcp_header *)(((uint8_t *)unit->ip)
2070                                         + sizeof(struct ip6_header));
2071     unit->tcp_hdrlen = (htons(unit->tcp->th_offset_flags) & 0xF000) >> 10;
2072 
2073     /* There is a difference between payload length in ipv4 and v6,
2074        ip header is excluded in ipv6 */
2075     unit->payload = htons(*unit->ip_plen) - unit->tcp_hdrlen;
2076 }
2077 
2078 static size_t virtio_net_rsc_drain_seg(VirtioNetRscChain *chain,
2079                                        VirtioNetRscSeg *seg)
2080 {
2081     int ret;
2082     struct virtio_net_hdr_v1 *h;
2083 
2084     h = (struct virtio_net_hdr_v1 *)seg->buf;
2085     h->flags = 0;
2086     h->gso_type = VIRTIO_NET_HDR_GSO_NONE;
2087 
2088     if (seg->is_coalesced) {
2089         h->rsc.segments = seg->packets;
2090         h->rsc.dup_acks = seg->dup_ack;
2091         h->flags = VIRTIO_NET_HDR_F_RSC_INFO;
2092         if (chain->proto == ETH_P_IP) {
2093             h->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
2094         } else {
2095             h->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
2096         }
2097     }
2098 
2099     ret = virtio_net_do_receive(seg->nc, seg->buf, seg->size);
2100     QTAILQ_REMOVE(&chain->buffers, seg, next);
2101     g_free(seg->buf);
2102     g_free(seg);
2103 
2104     return ret;
2105 }
2106 
2107 static void virtio_net_rsc_purge(void *opq)
2108 {
2109     VirtioNetRscSeg *seg, *rn;
2110     VirtioNetRscChain *chain = (VirtioNetRscChain *)opq;
2111 
2112     QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, rn) {
2113         if (virtio_net_rsc_drain_seg(chain, seg) == 0) {
2114             chain->stat.purge_failed++;
2115             continue;
2116         }
2117     }
2118 
2119     chain->stat.timer++;
2120     if (!QTAILQ_EMPTY(&chain->buffers)) {
2121         timer_mod(chain->drain_timer,
2122               qemu_clock_get_ns(QEMU_CLOCK_HOST) + chain->n->rsc_timeout);
2123     }
2124 }
2125 
2126 static void virtio_net_rsc_cleanup(VirtIONet *n)
2127 {
2128     VirtioNetRscChain *chain, *rn_chain;
2129     VirtioNetRscSeg *seg, *rn_seg;
2130 
2131     QTAILQ_FOREACH_SAFE(chain, &n->rsc_chains, next, rn_chain) {
2132         QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, rn_seg) {
2133             QTAILQ_REMOVE(&chain->buffers, seg, next);
2134             g_free(seg->buf);
2135             g_free(seg);
2136         }
2137 
2138         timer_free(chain->drain_timer);
2139         QTAILQ_REMOVE(&n->rsc_chains, chain, next);
2140         g_free(chain);
2141     }
2142 }
2143 
2144 static void virtio_net_rsc_cache_buf(VirtioNetRscChain *chain,
2145                                      NetClientState *nc,
2146                                      const uint8_t *buf, size_t size)
2147 {
2148     uint16_t hdr_len;
2149     VirtioNetRscSeg *seg;
2150 
2151     hdr_len = chain->n->guest_hdr_len;
2152     seg = g_new(VirtioNetRscSeg, 1);
2153     seg->buf = g_malloc(hdr_len + sizeof(struct eth_header)
2154         + sizeof(struct ip6_header) + VIRTIO_NET_MAX_TCP_PAYLOAD);
2155     memcpy(seg->buf, buf, size);
2156     seg->size = size;
2157     seg->packets = 1;
2158     seg->dup_ack = 0;
2159     seg->is_coalesced = 0;
2160     seg->nc = nc;
2161 
2162     QTAILQ_INSERT_TAIL(&chain->buffers, seg, next);
2163     chain->stat.cache++;
2164 
2165     switch (chain->proto) {
2166     case ETH_P_IP:
2167         virtio_net_rsc_extract_unit4(chain, seg->buf, &seg->unit);
2168         break;
2169     case ETH_P_IPV6:
2170         virtio_net_rsc_extract_unit6(chain, seg->buf, &seg->unit);
2171         break;
2172     default:
2173         g_assert_not_reached();
2174     }
2175 }
2176 
2177 static int32_t virtio_net_rsc_handle_ack(VirtioNetRscChain *chain,
2178                                          VirtioNetRscSeg *seg,
2179                                          const uint8_t *buf,
2180                                          struct tcp_header *n_tcp,
2181                                          struct tcp_header *o_tcp)
2182 {
2183     uint32_t nack, oack;
2184     uint16_t nwin, owin;
2185 
2186     nack = htonl(n_tcp->th_ack);
2187     nwin = htons(n_tcp->th_win);
2188     oack = htonl(o_tcp->th_ack);
2189     owin = htons(o_tcp->th_win);
2190 
2191     if ((nack - oack) >= VIRTIO_NET_MAX_TCP_PAYLOAD) {
2192         chain->stat.ack_out_of_win++;
2193         return RSC_FINAL;
2194     } else if (nack == oack) {
2195         /* duplicated ack or window probe */
2196         if (nwin == owin) {
2197             /* duplicated ack, add dup ack count due to whql test up to 1 */
2198             chain->stat.dup_ack++;
2199             return RSC_FINAL;
2200         } else {
2201             /* Coalesce window update */
2202             o_tcp->th_win = n_tcp->th_win;
2203             chain->stat.win_update++;
2204             return RSC_COALESCE;
2205         }
2206     } else {
2207         /* pure ack, go to 'C', finalize*/
2208         chain->stat.pure_ack++;
2209         return RSC_FINAL;
2210     }
2211 }
2212 
2213 static int32_t virtio_net_rsc_coalesce_data(VirtioNetRscChain *chain,
2214                                             VirtioNetRscSeg *seg,
2215                                             const uint8_t *buf,
2216                                             VirtioNetRscUnit *n_unit)
2217 {
2218     void *data;
2219     uint16_t o_ip_len;
2220     uint32_t nseq, oseq;
2221     VirtioNetRscUnit *o_unit;
2222 
2223     o_unit = &seg->unit;
2224     o_ip_len = htons(*o_unit->ip_plen);
2225     nseq = htonl(n_unit->tcp->th_seq);
2226     oseq = htonl(o_unit->tcp->th_seq);
2227 
2228     /* out of order or retransmitted. */
2229     if ((nseq - oseq) > VIRTIO_NET_MAX_TCP_PAYLOAD) {
2230         chain->stat.data_out_of_win++;
2231         return RSC_FINAL;
2232     }
2233 
2234     data = ((uint8_t *)n_unit->tcp) + n_unit->tcp_hdrlen;
2235     if (nseq == oseq) {
2236         if ((o_unit->payload == 0) && n_unit->payload) {
2237             /* From no payload to payload, normal case, not a dup ack or etc */
2238             chain->stat.data_after_pure_ack++;
2239             goto coalesce;
2240         } else {
2241             return virtio_net_rsc_handle_ack(chain, seg, buf,
2242                                              n_unit->tcp, o_unit->tcp);
2243         }
2244     } else if ((nseq - oseq) != o_unit->payload) {
2245         /* Not a consistent packet, out of order */
2246         chain->stat.data_out_of_order++;
2247         return RSC_FINAL;
2248     } else {
2249 coalesce:
2250         if ((o_ip_len + n_unit->payload) > chain->max_payload) {
2251             chain->stat.over_size++;
2252             return RSC_FINAL;
2253         }
2254 
2255         /* Here comes the right data, the payload length in v4/v6 is different,
2256            so use the field value to update and record the new data len */
2257         o_unit->payload += n_unit->payload; /* update new data len */
2258 
2259         /* update field in ip header */
2260         *o_unit->ip_plen = htons(o_ip_len + n_unit->payload);
2261 
2262         /* Bring 'PUSH' big, the whql test guide says 'PUSH' can be coalesced
2263            for windows guest, while this may change the behavior for linux
2264            guest (only if it uses RSC feature). */
2265         o_unit->tcp->th_offset_flags = n_unit->tcp->th_offset_flags;
2266 
2267         o_unit->tcp->th_ack = n_unit->tcp->th_ack;
2268         o_unit->tcp->th_win = n_unit->tcp->th_win;
2269 
2270         memmove(seg->buf + seg->size, data, n_unit->payload);
2271         seg->size += n_unit->payload;
2272         seg->packets++;
2273         chain->stat.coalesced++;
2274         return RSC_COALESCE;
2275     }
2276 }
2277 
2278 static int32_t virtio_net_rsc_coalesce4(VirtioNetRscChain *chain,
2279                                         VirtioNetRscSeg *seg,
2280                                         const uint8_t *buf, size_t size,
2281                                         VirtioNetRscUnit *unit)
2282 {
2283     struct ip_header *ip1, *ip2;
2284 
2285     ip1 = (struct ip_header *)(unit->ip);
2286     ip2 = (struct ip_header *)(seg->unit.ip);
2287     if ((ip1->ip_src ^ ip2->ip_src) || (ip1->ip_dst ^ ip2->ip_dst)
2288         || (unit->tcp->th_sport ^ seg->unit.tcp->th_sport)
2289         || (unit->tcp->th_dport ^ seg->unit.tcp->th_dport)) {
2290         chain->stat.no_match++;
2291         return RSC_NO_MATCH;
2292     }
2293 
2294     return virtio_net_rsc_coalesce_data(chain, seg, buf, unit);
2295 }
2296 
2297 static int32_t virtio_net_rsc_coalesce6(VirtioNetRscChain *chain,
2298                                         VirtioNetRscSeg *seg,
2299                                         const uint8_t *buf, size_t size,
2300                                         VirtioNetRscUnit *unit)
2301 {
2302     struct ip6_header *ip1, *ip2;
2303 
2304     ip1 = (struct ip6_header *)(unit->ip);
2305     ip2 = (struct ip6_header *)(seg->unit.ip);
2306     if (memcmp(&ip1->ip6_src, &ip2->ip6_src, sizeof(struct in6_address))
2307         || memcmp(&ip1->ip6_dst, &ip2->ip6_dst, sizeof(struct in6_address))
2308         || (unit->tcp->th_sport ^ seg->unit.tcp->th_sport)
2309         || (unit->tcp->th_dport ^ seg->unit.tcp->th_dport)) {
2310             chain->stat.no_match++;
2311             return RSC_NO_MATCH;
2312     }
2313 
2314     return virtio_net_rsc_coalesce_data(chain, seg, buf, unit);
2315 }
2316 
2317 /* Packets with 'SYN' should bypass, other flag should be sent after drain
2318  * to prevent out of order */
2319 static int virtio_net_rsc_tcp_ctrl_check(VirtioNetRscChain *chain,
2320                                          struct tcp_header *tcp)
2321 {
2322     uint16_t tcp_hdr;
2323     uint16_t tcp_flag;
2324 
2325     tcp_flag = htons(tcp->th_offset_flags);
2326     tcp_hdr = (tcp_flag & VIRTIO_NET_TCP_HDR_LENGTH) >> 10;
2327     tcp_flag &= VIRTIO_NET_TCP_FLAG;
2328     if (tcp_flag & TH_SYN) {
2329         chain->stat.tcp_syn++;
2330         return RSC_BYPASS;
2331     }
2332 
2333     if (tcp_flag & (TH_FIN | TH_URG | TH_RST | TH_ECE | TH_CWR)) {
2334         chain->stat.tcp_ctrl_drain++;
2335         return RSC_FINAL;
2336     }
2337 
2338     if (tcp_hdr > sizeof(struct tcp_header)) {
2339         chain->stat.tcp_all_opt++;
2340         return RSC_FINAL;
2341     }
2342 
2343     return RSC_CANDIDATE;
2344 }
2345 
2346 static size_t virtio_net_rsc_do_coalesce(VirtioNetRscChain *chain,
2347                                          NetClientState *nc,
2348                                          const uint8_t *buf, size_t size,
2349                                          VirtioNetRscUnit *unit)
2350 {
2351     int ret;
2352     VirtioNetRscSeg *seg, *nseg;
2353 
2354     if (QTAILQ_EMPTY(&chain->buffers)) {
2355         chain->stat.empty_cache++;
2356         virtio_net_rsc_cache_buf(chain, nc, buf, size);
2357         timer_mod(chain->drain_timer,
2358               qemu_clock_get_ns(QEMU_CLOCK_HOST) + chain->n->rsc_timeout);
2359         return size;
2360     }
2361 
2362     QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, nseg) {
2363         if (chain->proto == ETH_P_IP) {
2364             ret = virtio_net_rsc_coalesce4(chain, seg, buf, size, unit);
2365         } else {
2366             ret = virtio_net_rsc_coalesce6(chain, seg, buf, size, unit);
2367         }
2368 
2369         if (ret == RSC_FINAL) {
2370             if (virtio_net_rsc_drain_seg(chain, seg) == 0) {
2371                 /* Send failed */
2372                 chain->stat.final_failed++;
2373                 return 0;
2374             }
2375 
2376             /* Send current packet */
2377             return virtio_net_do_receive(nc, buf, size);
2378         } else if (ret == RSC_NO_MATCH) {
2379             continue;
2380         } else {
2381             /* Coalesced, mark coalesced flag to tell calc cksum for ipv4 */
2382             seg->is_coalesced = 1;
2383             return size;
2384         }
2385     }
2386 
2387     chain->stat.no_match_cache++;
2388     virtio_net_rsc_cache_buf(chain, nc, buf, size);
2389     return size;
2390 }
2391 
2392 /* Drain a connection data, this is to avoid out of order segments */
2393 static size_t virtio_net_rsc_drain_flow(VirtioNetRscChain *chain,
2394                                         NetClientState *nc,
2395                                         const uint8_t *buf, size_t size,
2396                                         uint16_t ip_start, uint16_t ip_size,
2397                                         uint16_t tcp_port)
2398 {
2399     VirtioNetRscSeg *seg, *nseg;
2400     uint32_t ppair1, ppair2;
2401 
2402     ppair1 = *(uint32_t *)(buf + tcp_port);
2403     QTAILQ_FOREACH_SAFE(seg, &chain->buffers, next, nseg) {
2404         ppair2 = *(uint32_t *)(seg->buf + tcp_port);
2405         if (memcmp(buf + ip_start, seg->buf + ip_start, ip_size)
2406             || (ppair1 != ppair2)) {
2407             continue;
2408         }
2409         if (virtio_net_rsc_drain_seg(chain, seg) == 0) {
2410             chain->stat.drain_failed++;
2411         }
2412 
2413         break;
2414     }
2415 
2416     return virtio_net_do_receive(nc, buf, size);
2417 }
2418 
2419 static int32_t virtio_net_rsc_sanity_check4(VirtioNetRscChain *chain,
2420                                             struct ip_header *ip,
2421                                             const uint8_t *buf, size_t size)
2422 {
2423     uint16_t ip_len;
2424 
2425     /* Not an ipv4 packet */
2426     if (((ip->ip_ver_len & 0xF0) >> 4) != IP_HEADER_VERSION_4) {
2427         chain->stat.ip_option++;
2428         return RSC_BYPASS;
2429     }
2430 
2431     /* Don't handle packets with ip option */
2432     if ((ip->ip_ver_len & 0xF) != VIRTIO_NET_IP4_HEADER_LENGTH) {
2433         chain->stat.ip_option++;
2434         return RSC_BYPASS;
2435     }
2436 
2437     if (ip->ip_p != IPPROTO_TCP) {
2438         chain->stat.bypass_not_tcp++;
2439         return RSC_BYPASS;
2440     }
2441 
2442     /* Don't handle packets with ip fragment */
2443     if (!(htons(ip->ip_off) & IP_DF)) {
2444         chain->stat.ip_frag++;
2445         return RSC_BYPASS;
2446     }
2447 
2448     /* Don't handle packets with ecn flag */
2449     if (IPTOS_ECN(ip->ip_tos)) {
2450         chain->stat.ip_ecn++;
2451         return RSC_BYPASS;
2452     }
2453 
2454     ip_len = htons(ip->ip_len);
2455     if (ip_len < (sizeof(struct ip_header) + sizeof(struct tcp_header))
2456         || ip_len > (size - chain->n->guest_hdr_len -
2457                      sizeof(struct eth_header))) {
2458         chain->stat.ip_hacked++;
2459         return RSC_BYPASS;
2460     }
2461 
2462     return RSC_CANDIDATE;
2463 }
2464 
2465 static size_t virtio_net_rsc_receive4(VirtioNetRscChain *chain,
2466                                       NetClientState *nc,
2467                                       const uint8_t *buf, size_t size)
2468 {
2469     int32_t ret;
2470     uint16_t hdr_len;
2471     VirtioNetRscUnit unit;
2472 
2473     hdr_len = ((VirtIONet *)(chain->n))->guest_hdr_len;
2474 
2475     if (size < (hdr_len + sizeof(struct eth_header) + sizeof(struct ip_header)
2476         + sizeof(struct tcp_header))) {
2477         chain->stat.bypass_not_tcp++;
2478         return virtio_net_do_receive(nc, buf, size);
2479     }
2480 
2481     virtio_net_rsc_extract_unit4(chain, buf, &unit);
2482     if (virtio_net_rsc_sanity_check4(chain, unit.ip, buf, size)
2483         != RSC_CANDIDATE) {
2484         return virtio_net_do_receive(nc, buf, size);
2485     }
2486 
2487     ret = virtio_net_rsc_tcp_ctrl_check(chain, unit.tcp);
2488     if (ret == RSC_BYPASS) {
2489         return virtio_net_do_receive(nc, buf, size);
2490     } else if (ret == RSC_FINAL) {
2491         return virtio_net_rsc_drain_flow(chain, nc, buf, size,
2492                 ((hdr_len + sizeof(struct eth_header)) + 12),
2493                 VIRTIO_NET_IP4_ADDR_SIZE,
2494                 hdr_len + sizeof(struct eth_header) + sizeof(struct ip_header));
2495     }
2496 
2497     return virtio_net_rsc_do_coalesce(chain, nc, buf, size, &unit);
2498 }
2499 
2500 static int32_t virtio_net_rsc_sanity_check6(VirtioNetRscChain *chain,
2501                                             struct ip6_header *ip6,
2502                                             const uint8_t *buf, size_t size)
2503 {
2504     uint16_t ip_len;
2505 
2506     if (((ip6->ip6_ctlun.ip6_un1.ip6_un1_flow & 0xF0) >> 4)
2507         != IP_HEADER_VERSION_6) {
2508         return RSC_BYPASS;
2509     }
2510 
2511     /* Both option and protocol is checked in this */
2512     if (ip6->ip6_ctlun.ip6_un1.ip6_un1_nxt != IPPROTO_TCP) {
2513         chain->stat.bypass_not_tcp++;
2514         return RSC_BYPASS;
2515     }
2516 
2517     ip_len = htons(ip6->ip6_ctlun.ip6_un1.ip6_un1_plen);
2518     if (ip_len < sizeof(struct tcp_header) ||
2519         ip_len > (size - chain->n->guest_hdr_len - sizeof(struct eth_header)
2520                   - sizeof(struct ip6_header))) {
2521         chain->stat.ip_hacked++;
2522         return RSC_BYPASS;
2523     }
2524 
2525     /* Don't handle packets with ecn flag */
2526     if (IP6_ECN(ip6->ip6_ctlun.ip6_un3.ip6_un3_ecn)) {
2527         chain->stat.ip_ecn++;
2528         return RSC_BYPASS;
2529     }
2530 
2531     return RSC_CANDIDATE;
2532 }
2533 
2534 static size_t virtio_net_rsc_receive6(void *opq, NetClientState *nc,
2535                                       const uint8_t *buf, size_t size)
2536 {
2537     int32_t ret;
2538     uint16_t hdr_len;
2539     VirtioNetRscChain *chain;
2540     VirtioNetRscUnit unit;
2541 
2542     chain = opq;
2543     hdr_len = ((VirtIONet *)(chain->n))->guest_hdr_len;
2544 
2545     if (size < (hdr_len + sizeof(struct eth_header) + sizeof(struct ip6_header)
2546         + sizeof(tcp_header))) {
2547         return virtio_net_do_receive(nc, buf, size);
2548     }
2549 
2550     virtio_net_rsc_extract_unit6(chain, buf, &unit);
2551     if (RSC_CANDIDATE != virtio_net_rsc_sanity_check6(chain,
2552                                                  unit.ip, buf, size)) {
2553         return virtio_net_do_receive(nc, buf, size);
2554     }
2555 
2556     ret = virtio_net_rsc_tcp_ctrl_check(chain, unit.tcp);
2557     if (ret == RSC_BYPASS) {
2558         return virtio_net_do_receive(nc, buf, size);
2559     } else if (ret == RSC_FINAL) {
2560         return virtio_net_rsc_drain_flow(chain, nc, buf, size,
2561                 ((hdr_len + sizeof(struct eth_header)) + 8),
2562                 VIRTIO_NET_IP6_ADDR_SIZE,
2563                 hdr_len + sizeof(struct eth_header)
2564                 + sizeof(struct ip6_header));
2565     }
2566 
2567     return virtio_net_rsc_do_coalesce(chain, nc, buf, size, &unit);
2568 }
2569 
2570 static VirtioNetRscChain *virtio_net_rsc_lookup_chain(VirtIONet *n,
2571                                                       NetClientState *nc,
2572                                                       uint16_t proto)
2573 {
2574     VirtioNetRscChain *chain;
2575 
2576     if ((proto != (uint16_t)ETH_P_IP) && (proto != (uint16_t)ETH_P_IPV6)) {
2577         return NULL;
2578     }
2579 
2580     QTAILQ_FOREACH(chain, &n->rsc_chains, next) {
2581         if (chain->proto == proto) {
2582             return chain;
2583         }
2584     }
2585 
2586     chain = g_malloc(sizeof(*chain));
2587     chain->n = n;
2588     chain->proto = proto;
2589     if (proto == (uint16_t)ETH_P_IP) {
2590         chain->max_payload = VIRTIO_NET_MAX_IP4_PAYLOAD;
2591         chain->gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
2592     } else {
2593         chain->max_payload = VIRTIO_NET_MAX_IP6_PAYLOAD;
2594         chain->gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
2595     }
2596     chain->drain_timer = timer_new_ns(QEMU_CLOCK_HOST,
2597                                       virtio_net_rsc_purge, chain);
2598     memset(&chain->stat, 0, sizeof(chain->stat));
2599 
2600     QTAILQ_INIT(&chain->buffers);
2601     QTAILQ_INSERT_TAIL(&n->rsc_chains, chain, next);
2602 
2603     return chain;
2604 }
2605 
2606 static ssize_t virtio_net_rsc_receive(NetClientState *nc,
2607                                       const uint8_t *buf,
2608                                       size_t size)
2609 {
2610     uint16_t proto;
2611     VirtioNetRscChain *chain;
2612     struct eth_header *eth;
2613     VirtIONet *n;
2614 
2615     n = qemu_get_nic_opaque(nc);
2616     if (size < (n->host_hdr_len + sizeof(struct eth_header))) {
2617         return virtio_net_do_receive(nc, buf, size);
2618     }
2619 
2620     eth = (struct eth_header *)(buf + n->guest_hdr_len);
2621     proto = htons(eth->h_proto);
2622 
2623     chain = virtio_net_rsc_lookup_chain(n, nc, proto);
2624     if (chain) {
2625         chain->stat.received++;
2626         if (proto == (uint16_t)ETH_P_IP && n->rsc4_enabled) {
2627             return virtio_net_rsc_receive4(chain, nc, buf, size);
2628         } else if (proto == (uint16_t)ETH_P_IPV6 && n->rsc6_enabled) {
2629             return virtio_net_rsc_receive6(chain, nc, buf, size);
2630         }
2631     }
2632     return virtio_net_do_receive(nc, buf, size);
2633 }
2634 
2635 static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf,
2636                                   size_t size)
2637 {
2638     VirtIONet *n = qemu_get_nic_opaque(nc);
2639     if ((n->rsc4_enabled || n->rsc6_enabled)) {
2640         return virtio_net_rsc_receive(nc, buf, size);
2641     } else {
2642         return virtio_net_do_receive(nc, buf, size);
2643     }
2644 }
2645 
2646 static int32_t virtio_net_flush_tx(VirtIONetQueue *q);
2647 
2648 static void virtio_net_tx_complete(NetClientState *nc, ssize_t len)
2649 {
2650     VirtIONet *n = qemu_get_nic_opaque(nc);
2651     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
2652     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2653     int ret;
2654 
2655     virtqueue_push(q->tx_vq, q->async_tx.elem, 0);
2656     virtio_notify(vdev, q->tx_vq);
2657 
2658     g_free(q->async_tx.elem);
2659     q->async_tx.elem = NULL;
2660 
2661     virtio_queue_set_notification(q->tx_vq, 1);
2662     ret = virtio_net_flush_tx(q);
2663     if (ret >= n->tx_burst) {
2664         /*
2665          * the flush has been stopped by tx_burst
2666          * we will not receive notification for the
2667          * remainining part, so re-schedule
2668          */
2669         virtio_queue_set_notification(q->tx_vq, 0);
2670         if (q->tx_bh) {
2671             qemu_bh_schedule(q->tx_bh);
2672         } else {
2673             timer_mod(q->tx_timer,
2674                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2675         }
2676         q->tx_waiting = 1;
2677     }
2678 }
2679 
2680 /* TX */
2681 static int32_t virtio_net_flush_tx(VirtIONetQueue *q)
2682 {
2683     VirtIONet *n = q->n;
2684     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2685     VirtQueueElement *elem;
2686     int32_t num_packets = 0;
2687     int queue_index = vq2q(virtio_get_queue_index(q->tx_vq));
2688     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
2689         return num_packets;
2690     }
2691 
2692     if (q->async_tx.elem) {
2693         virtio_queue_set_notification(q->tx_vq, 0);
2694         return num_packets;
2695     }
2696 
2697     for (;;) {
2698         ssize_t ret;
2699         unsigned int out_num;
2700         struct iovec sg[VIRTQUEUE_MAX_SIZE], sg2[VIRTQUEUE_MAX_SIZE + 1], *out_sg;
2701         struct virtio_net_hdr vhdr;
2702 
2703         elem = virtqueue_pop(q->tx_vq, sizeof(VirtQueueElement));
2704         if (!elem) {
2705             break;
2706         }
2707 
2708         out_num = elem->out_num;
2709         out_sg = elem->out_sg;
2710         if (out_num < 1) {
2711             virtio_error(vdev, "virtio-net header not in first element");
2712             goto detach;
2713         }
2714 
2715         if (n->needs_vnet_hdr_swap) {
2716             if (iov_to_buf(out_sg, out_num, 0, &vhdr, sizeof(vhdr)) <
2717                 sizeof(vhdr)) {
2718                 virtio_error(vdev, "virtio-net header incorrect");
2719                 goto detach;
2720             }
2721             virtio_net_hdr_swap(vdev, &vhdr);
2722             sg2[0].iov_base = &vhdr;
2723             sg2[0].iov_len = sizeof(vhdr);
2724             out_num = iov_copy(&sg2[1], ARRAY_SIZE(sg2) - 1, out_sg, out_num,
2725                                sizeof(vhdr), -1);
2726             if (out_num == VIRTQUEUE_MAX_SIZE) {
2727                 goto drop;
2728             }
2729             out_num += 1;
2730             out_sg = sg2;
2731         }
2732         /*
2733          * If host wants to see the guest header as is, we can
2734          * pass it on unchanged. Otherwise, copy just the parts
2735          * that host is interested in.
2736          */
2737         assert(n->host_hdr_len <= n->guest_hdr_len);
2738         if (n->host_hdr_len != n->guest_hdr_len) {
2739             if (iov_size(out_sg, out_num) < n->guest_hdr_len) {
2740                 virtio_error(vdev, "virtio-net header is invalid");
2741                 goto detach;
2742             }
2743             unsigned sg_num = iov_copy(sg, ARRAY_SIZE(sg),
2744                                        out_sg, out_num,
2745                                        0, n->host_hdr_len);
2746             sg_num += iov_copy(sg + sg_num, ARRAY_SIZE(sg) - sg_num,
2747                              out_sg, out_num,
2748                              n->guest_hdr_len, -1);
2749             out_num = sg_num;
2750             out_sg = sg;
2751 
2752             if (out_num < 1) {
2753                 virtio_error(vdev, "virtio-net nothing to send");
2754                 goto detach;
2755             }
2756         }
2757 
2758         ret = qemu_sendv_packet_async(qemu_get_subqueue(n->nic, queue_index),
2759                                       out_sg, out_num, virtio_net_tx_complete);
2760         if (ret == 0) {
2761             virtio_queue_set_notification(q->tx_vq, 0);
2762             q->async_tx.elem = elem;
2763             return -EBUSY;
2764         }
2765 
2766 drop:
2767         virtqueue_push(q->tx_vq, elem, 0);
2768         virtio_notify(vdev, q->tx_vq);
2769         g_free(elem);
2770 
2771         if (++num_packets >= n->tx_burst) {
2772             break;
2773         }
2774     }
2775     return num_packets;
2776 
2777 detach:
2778     virtqueue_detach_element(q->tx_vq, elem, 0);
2779     g_free(elem);
2780     return -EINVAL;
2781 }
2782 
2783 static void virtio_net_tx_timer(void *opaque);
2784 
2785 static void virtio_net_handle_tx_timer(VirtIODevice *vdev, VirtQueue *vq)
2786 {
2787     VirtIONet *n = VIRTIO_NET(vdev);
2788     VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
2789 
2790     if (unlikely((n->status & VIRTIO_NET_S_LINK_UP) == 0)) {
2791         virtio_net_drop_tx_queue_data(vdev, vq);
2792         return;
2793     }
2794 
2795     /* This happens when device was stopped but VCPU wasn't. */
2796     if (!vdev->vm_running) {
2797         q->tx_waiting = 1;
2798         return;
2799     }
2800 
2801     if (q->tx_waiting) {
2802         /* We already have queued packets, immediately flush */
2803         timer_del(q->tx_timer);
2804         virtio_net_tx_timer(q);
2805     } else {
2806         /* re-arm timer to flush it (and more) on next tick */
2807         timer_mod(q->tx_timer,
2808                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2809         q->tx_waiting = 1;
2810         virtio_queue_set_notification(vq, 0);
2811     }
2812 }
2813 
2814 static void virtio_net_handle_tx_bh(VirtIODevice *vdev, VirtQueue *vq)
2815 {
2816     VirtIONet *n = VIRTIO_NET(vdev);
2817     VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
2818 
2819     if (unlikely(n->vhost_started)) {
2820         return;
2821     }
2822 
2823     if (unlikely((n->status & VIRTIO_NET_S_LINK_UP) == 0)) {
2824         virtio_net_drop_tx_queue_data(vdev, vq);
2825         return;
2826     }
2827 
2828     if (unlikely(q->tx_waiting)) {
2829         return;
2830     }
2831     q->tx_waiting = 1;
2832     /* This happens when device was stopped but VCPU wasn't. */
2833     if (!vdev->vm_running) {
2834         return;
2835     }
2836     virtio_queue_set_notification(vq, 0);
2837     qemu_bh_schedule(q->tx_bh);
2838 }
2839 
2840 static void virtio_net_tx_timer(void *opaque)
2841 {
2842     VirtIONetQueue *q = opaque;
2843     VirtIONet *n = q->n;
2844     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2845     int ret;
2846 
2847     /* This happens when device was stopped but BH wasn't. */
2848     if (!vdev->vm_running) {
2849         /* Make sure tx waiting is set, so we'll run when restarted. */
2850         assert(q->tx_waiting);
2851         return;
2852     }
2853 
2854     q->tx_waiting = 0;
2855 
2856     /* Just in case the driver is not ready on more */
2857     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
2858         return;
2859     }
2860 
2861     ret = virtio_net_flush_tx(q);
2862     if (ret == -EBUSY || ret == -EINVAL) {
2863         return;
2864     }
2865     /*
2866      * If we flush a full burst of packets, assume there are
2867      * more coming and immediately rearm
2868      */
2869     if (ret >= n->tx_burst) {
2870         q->tx_waiting = 1;
2871         timer_mod(q->tx_timer,
2872                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2873         return;
2874     }
2875     /*
2876      * If less than a full burst, re-enable notification and flush
2877      * anything that may have come in while we weren't looking.  If
2878      * we find something, assume the guest is still active and rearm
2879      */
2880     virtio_queue_set_notification(q->tx_vq, 1);
2881     ret = virtio_net_flush_tx(q);
2882     if (ret > 0) {
2883         virtio_queue_set_notification(q->tx_vq, 0);
2884         q->tx_waiting = 1;
2885         timer_mod(q->tx_timer,
2886                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
2887     }
2888 }
2889 
2890 static void virtio_net_tx_bh(void *opaque)
2891 {
2892     VirtIONetQueue *q = opaque;
2893     VirtIONet *n = q->n;
2894     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2895     int32_t ret;
2896 
2897     /* This happens when device was stopped but BH wasn't. */
2898     if (!vdev->vm_running) {
2899         /* Make sure tx waiting is set, so we'll run when restarted. */
2900         assert(q->tx_waiting);
2901         return;
2902     }
2903 
2904     q->tx_waiting = 0;
2905 
2906     /* Just in case the driver is not ready on more */
2907     if (unlikely(!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))) {
2908         return;
2909     }
2910 
2911     ret = virtio_net_flush_tx(q);
2912     if (ret == -EBUSY || ret == -EINVAL) {
2913         return; /* Notification re-enable handled by tx_complete or device
2914                  * broken */
2915     }
2916 
2917     /* If we flush a full burst of packets, assume there are
2918      * more coming and immediately reschedule */
2919     if (ret >= n->tx_burst) {
2920         qemu_bh_schedule(q->tx_bh);
2921         q->tx_waiting = 1;
2922         return;
2923     }
2924 
2925     /* If less than a full burst, re-enable notification and flush
2926      * anything that may have come in while we weren't looking.  If
2927      * we find something, assume the guest is still active and reschedule */
2928     virtio_queue_set_notification(q->tx_vq, 1);
2929     ret = virtio_net_flush_tx(q);
2930     if (ret == -EINVAL) {
2931         return;
2932     } else if (ret > 0) {
2933         virtio_queue_set_notification(q->tx_vq, 0);
2934         qemu_bh_schedule(q->tx_bh);
2935         q->tx_waiting = 1;
2936     }
2937 }
2938 
2939 static void virtio_net_add_queue(VirtIONet *n, int index)
2940 {
2941     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2942 
2943     n->vqs[index].rx_vq = virtio_add_queue(vdev, n->net_conf.rx_queue_size,
2944                                            virtio_net_handle_rx);
2945 
2946     if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) {
2947         n->vqs[index].tx_vq =
2948             virtio_add_queue(vdev, n->net_conf.tx_queue_size,
2949                              virtio_net_handle_tx_timer);
2950         n->vqs[index].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
2951                                               virtio_net_tx_timer,
2952                                               &n->vqs[index]);
2953     } else {
2954         n->vqs[index].tx_vq =
2955             virtio_add_queue(vdev, n->net_conf.tx_queue_size,
2956                              virtio_net_handle_tx_bh);
2957         n->vqs[index].tx_bh = qemu_bh_new_guarded(virtio_net_tx_bh, &n->vqs[index],
2958                                                   &DEVICE(vdev)->mem_reentrancy_guard);
2959     }
2960 
2961     n->vqs[index].tx_waiting = 0;
2962     n->vqs[index].n = n;
2963 }
2964 
2965 static void virtio_net_del_queue(VirtIONet *n, int index)
2966 {
2967     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2968     VirtIONetQueue *q = &n->vqs[index];
2969     NetClientState *nc = qemu_get_subqueue(n->nic, index);
2970 
2971     qemu_purge_queued_packets(nc);
2972 
2973     virtio_del_queue(vdev, index * 2);
2974     if (q->tx_timer) {
2975         timer_free(q->tx_timer);
2976         q->tx_timer = NULL;
2977     } else {
2978         qemu_bh_delete(q->tx_bh);
2979         q->tx_bh = NULL;
2980     }
2981     q->tx_waiting = 0;
2982     virtio_del_queue(vdev, index * 2 + 1);
2983 }
2984 
2985 static void virtio_net_change_num_queue_pairs(VirtIONet *n, int new_max_queue_pairs)
2986 {
2987     VirtIODevice *vdev = VIRTIO_DEVICE(n);
2988     int old_num_queues = virtio_get_num_queues(vdev);
2989     int new_num_queues = new_max_queue_pairs * 2 + 1;
2990     int i;
2991 
2992     assert(old_num_queues >= 3);
2993     assert(old_num_queues % 2 == 1);
2994 
2995     if (old_num_queues == new_num_queues) {
2996         return;
2997     }
2998 
2999     /*
3000      * We always need to remove and add ctrl vq if
3001      * old_num_queues != new_num_queues. Remove ctrl_vq first,
3002      * and then we only enter one of the following two loops.
3003      */
3004     virtio_del_queue(vdev, old_num_queues - 1);
3005 
3006     for (i = new_num_queues - 1; i < old_num_queues - 1; i += 2) {
3007         /* new_num_queues < old_num_queues */
3008         virtio_net_del_queue(n, i / 2);
3009     }
3010 
3011     for (i = old_num_queues - 1; i < new_num_queues - 1; i += 2) {
3012         /* new_num_queues > old_num_queues */
3013         virtio_net_add_queue(n, i / 2);
3014     }
3015 
3016     /* add ctrl_vq last */
3017     n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
3018 }
3019 
3020 static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue)
3021 {
3022     int max = multiqueue ? n->max_queue_pairs : 1;
3023 
3024     n->multiqueue = multiqueue;
3025     virtio_net_change_num_queue_pairs(n, max);
3026 
3027     virtio_net_set_queue_pairs(n);
3028 }
3029 
3030 static int virtio_net_post_load_device(void *opaque, int version_id)
3031 {
3032     VirtIONet *n = opaque;
3033     VirtIODevice *vdev = VIRTIO_DEVICE(n);
3034     int i, link_down;
3035 
3036     trace_virtio_net_post_load_device();
3037     virtio_net_set_mrg_rx_bufs(n, n->mergeable_rx_bufs,
3038                                virtio_vdev_has_feature(vdev,
3039                                                        VIRTIO_F_VERSION_1),
3040                                virtio_vdev_has_feature(vdev,
3041                                                        VIRTIO_NET_F_HASH_REPORT));
3042 
3043     /* MAC_TABLE_ENTRIES may be different from the saved image */
3044     if (n->mac_table.in_use > MAC_TABLE_ENTRIES) {
3045         n->mac_table.in_use = 0;
3046     }
3047 
3048     if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_GUEST_OFFLOADS)) {
3049         n->curr_guest_offloads = virtio_net_supported_guest_offloads(n);
3050     }
3051 
3052     /*
3053      * curr_guest_offloads will be later overwritten by the
3054      * virtio_set_features_nocheck call done from the virtio_load.
3055      * Here we make sure it is preserved and restored accordingly
3056      * in the virtio_net_post_load_virtio callback.
3057      */
3058     n->saved_guest_offloads = n->curr_guest_offloads;
3059 
3060     virtio_net_set_queue_pairs(n);
3061 
3062     /* Find the first multicast entry in the saved MAC filter */
3063     for (i = 0; i < n->mac_table.in_use; i++) {
3064         if (n->mac_table.macs[i * ETH_ALEN] & 1) {
3065             break;
3066         }
3067     }
3068     n->mac_table.first_multi = i;
3069 
3070     /* nc.link_down can't be migrated, so infer link_down according
3071      * to link status bit in n->status */
3072     link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0;
3073     for (i = 0; i < n->max_queue_pairs; i++) {
3074         qemu_get_subqueue(n->nic, i)->link_down = link_down;
3075     }
3076 
3077     if (virtio_vdev_has_feature(vdev, VIRTIO_NET_F_GUEST_ANNOUNCE) &&
3078         virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
3079         qemu_announce_timer_reset(&n->announce_timer, migrate_announce_params(),
3080                                   QEMU_CLOCK_VIRTUAL,
3081                                   virtio_net_announce_timer, n);
3082         if (n->announce_timer.round) {
3083             timer_mod(n->announce_timer.tm,
3084                       qemu_clock_get_ms(n->announce_timer.type));
3085         } else {
3086             qemu_announce_timer_del(&n->announce_timer, false);
3087         }
3088     }
3089 
3090     virtio_net_commit_rss_config(n);
3091     return 0;
3092 }
3093 
3094 static int virtio_net_post_load_virtio(VirtIODevice *vdev)
3095 {
3096     VirtIONet *n = VIRTIO_NET(vdev);
3097     /*
3098      * The actual needed state is now in saved_guest_offloads,
3099      * see virtio_net_post_load_device for detail.
3100      * Restore it back and apply the desired offloads.
3101      */
3102     n->curr_guest_offloads = n->saved_guest_offloads;
3103     if (peer_has_vnet_hdr(n)) {
3104         virtio_net_apply_guest_offloads(n);
3105     }
3106 
3107     return 0;
3108 }
3109 
3110 /* tx_waiting field of a VirtIONetQueue */
3111 static const VMStateDescription vmstate_virtio_net_queue_tx_waiting = {
3112     .name = "virtio-net-queue-tx_waiting",
3113     .fields = (const VMStateField[]) {
3114         VMSTATE_UINT32(tx_waiting, VirtIONetQueue),
3115         VMSTATE_END_OF_LIST()
3116    },
3117 };
3118 
3119 static bool max_queue_pairs_gt_1(void *opaque, int version_id)
3120 {
3121     return VIRTIO_NET(opaque)->max_queue_pairs > 1;
3122 }
3123 
3124 static bool has_ctrl_guest_offloads(void *opaque, int version_id)
3125 {
3126     return virtio_vdev_has_feature(VIRTIO_DEVICE(opaque),
3127                                    VIRTIO_NET_F_CTRL_GUEST_OFFLOADS);
3128 }
3129 
3130 static bool mac_table_fits(void *opaque, int version_id)
3131 {
3132     return VIRTIO_NET(opaque)->mac_table.in_use <= MAC_TABLE_ENTRIES;
3133 }
3134 
3135 static bool mac_table_doesnt_fit(void *opaque, int version_id)
3136 {
3137     return !mac_table_fits(opaque, version_id);
3138 }
3139 
3140 /* This temporary type is shared by all the WITH_TMP methods
3141  * although only some fields are used by each.
3142  */
3143 struct VirtIONetMigTmp {
3144     VirtIONet      *parent;
3145     VirtIONetQueue *vqs_1;
3146     uint16_t        curr_queue_pairs_1;
3147     uint8_t         has_ufo;
3148     uint32_t        has_vnet_hdr;
3149 };
3150 
3151 /* The 2nd and subsequent tx_waiting flags are loaded later than
3152  * the 1st entry in the queue_pairs and only if there's more than one
3153  * entry.  We use the tmp mechanism to calculate a temporary
3154  * pointer and count and also validate the count.
3155  */
3156 
3157 static int virtio_net_tx_waiting_pre_save(void *opaque)
3158 {
3159     struct VirtIONetMigTmp *tmp = opaque;
3160 
3161     tmp->vqs_1 = tmp->parent->vqs + 1;
3162     tmp->curr_queue_pairs_1 = tmp->parent->curr_queue_pairs - 1;
3163     if (tmp->parent->curr_queue_pairs == 0) {
3164         tmp->curr_queue_pairs_1 = 0;
3165     }
3166 
3167     return 0;
3168 }
3169 
3170 static int virtio_net_tx_waiting_pre_load(void *opaque)
3171 {
3172     struct VirtIONetMigTmp *tmp = opaque;
3173 
3174     /* Reuse the pointer setup from save */
3175     virtio_net_tx_waiting_pre_save(opaque);
3176 
3177     if (tmp->parent->curr_queue_pairs > tmp->parent->max_queue_pairs) {
3178         error_report("virtio-net: curr_queue_pairs %x > max_queue_pairs %x",
3179             tmp->parent->curr_queue_pairs, tmp->parent->max_queue_pairs);
3180 
3181         return -EINVAL;
3182     }
3183 
3184     return 0; /* all good */
3185 }
3186 
3187 static const VMStateDescription vmstate_virtio_net_tx_waiting = {
3188     .name      = "virtio-net-tx_waiting",
3189     .pre_load  = virtio_net_tx_waiting_pre_load,
3190     .pre_save  = virtio_net_tx_waiting_pre_save,
3191     .fields    = (const VMStateField[]) {
3192         VMSTATE_STRUCT_VARRAY_POINTER_UINT16(vqs_1, struct VirtIONetMigTmp,
3193                                      curr_queue_pairs_1,
3194                                      vmstate_virtio_net_queue_tx_waiting,
3195                                      struct VirtIONetQueue),
3196         VMSTATE_END_OF_LIST()
3197     },
3198 };
3199 
3200 /* the 'has_ufo' flag is just tested; if the incoming stream has the
3201  * flag set we need to check that we have it
3202  */
3203 static int virtio_net_ufo_post_load(void *opaque, int version_id)
3204 {
3205     struct VirtIONetMigTmp *tmp = opaque;
3206 
3207     if (tmp->has_ufo && !peer_has_ufo(tmp->parent)) {
3208         error_report("virtio-net: saved image requires TUN_F_UFO support");
3209         return -EINVAL;
3210     }
3211 
3212     return 0;
3213 }
3214 
3215 static int virtio_net_ufo_pre_save(void *opaque)
3216 {
3217     struct VirtIONetMigTmp *tmp = opaque;
3218 
3219     tmp->has_ufo = tmp->parent->has_ufo;
3220 
3221     return 0;
3222 }
3223 
3224 static const VMStateDescription vmstate_virtio_net_has_ufo = {
3225     .name      = "virtio-net-ufo",
3226     .post_load = virtio_net_ufo_post_load,
3227     .pre_save  = virtio_net_ufo_pre_save,
3228     .fields    = (const VMStateField[]) {
3229         VMSTATE_UINT8(has_ufo, struct VirtIONetMigTmp),
3230         VMSTATE_END_OF_LIST()
3231     },
3232 };
3233 
3234 /* the 'has_vnet_hdr' flag is just tested; if the incoming stream has the
3235  * flag set we need to check that we have it
3236  */
3237 static int virtio_net_vnet_post_load(void *opaque, int version_id)
3238 {
3239     struct VirtIONetMigTmp *tmp = opaque;
3240 
3241     if (tmp->has_vnet_hdr && !peer_has_vnet_hdr(tmp->parent)) {
3242         error_report("virtio-net: saved image requires vnet_hdr=on");
3243         return -EINVAL;
3244     }
3245 
3246     return 0;
3247 }
3248 
3249 static int virtio_net_vnet_pre_save(void *opaque)
3250 {
3251     struct VirtIONetMigTmp *tmp = opaque;
3252 
3253     tmp->has_vnet_hdr = tmp->parent->has_vnet_hdr;
3254 
3255     return 0;
3256 }
3257 
3258 static const VMStateDescription vmstate_virtio_net_has_vnet = {
3259     .name      = "virtio-net-vnet",
3260     .post_load = virtio_net_vnet_post_load,
3261     .pre_save  = virtio_net_vnet_pre_save,
3262     .fields    = (const VMStateField[]) {
3263         VMSTATE_UINT32(has_vnet_hdr, struct VirtIONetMigTmp),
3264         VMSTATE_END_OF_LIST()
3265     },
3266 };
3267 
3268 static bool virtio_net_rss_needed(void *opaque)
3269 {
3270     return VIRTIO_NET(opaque)->rss_data.enabled;
3271 }
3272 
3273 static const VMStateDescription vmstate_virtio_net_rss = {
3274     .name      = "virtio-net-device/rss",
3275     .version_id = 1,
3276     .minimum_version_id = 1,
3277     .needed = virtio_net_rss_needed,
3278     .fields = (const VMStateField[]) {
3279         VMSTATE_BOOL(rss_data.enabled, VirtIONet),
3280         VMSTATE_BOOL(rss_data.redirect, VirtIONet),
3281         VMSTATE_BOOL(rss_data.populate_hash, VirtIONet),
3282         VMSTATE_UINT32(rss_data.hash_types, VirtIONet),
3283         VMSTATE_UINT16(rss_data.indirections_len, VirtIONet),
3284         VMSTATE_UINT16(rss_data.default_queue, VirtIONet),
3285         VMSTATE_UINT8_ARRAY(rss_data.key, VirtIONet,
3286                             VIRTIO_NET_RSS_MAX_KEY_SIZE),
3287         VMSTATE_VARRAY_UINT16_ALLOC(rss_data.indirections_table, VirtIONet,
3288                                     rss_data.indirections_len, 0,
3289                                     vmstate_info_uint16, uint16_t),
3290         VMSTATE_END_OF_LIST()
3291     },
3292 };
3293 
3294 static const VMStateDescription vmstate_virtio_net_device = {
3295     .name = "virtio-net-device",
3296     .version_id = VIRTIO_NET_VM_VERSION,
3297     .minimum_version_id = VIRTIO_NET_VM_VERSION,
3298     .post_load = virtio_net_post_load_device,
3299     .fields = (const VMStateField[]) {
3300         VMSTATE_UINT8_ARRAY(mac, VirtIONet, ETH_ALEN),
3301         VMSTATE_STRUCT_POINTER(vqs, VirtIONet,
3302                                vmstate_virtio_net_queue_tx_waiting,
3303                                VirtIONetQueue),
3304         VMSTATE_UINT32(mergeable_rx_bufs, VirtIONet),
3305         VMSTATE_UINT16(status, VirtIONet),
3306         VMSTATE_UINT8(promisc, VirtIONet),
3307         VMSTATE_UINT8(allmulti, VirtIONet),
3308         VMSTATE_UINT32(mac_table.in_use, VirtIONet),
3309 
3310         /* Guarded pair: If it fits we load it, else we throw it away
3311          * - can happen if source has a larger MAC table.; post-load
3312          *  sets flags in this case.
3313          */
3314         VMSTATE_VBUFFER_MULTIPLY(mac_table.macs, VirtIONet,
3315                                 0, mac_table_fits, mac_table.in_use,
3316                                  ETH_ALEN),
3317         VMSTATE_UNUSED_VARRAY_UINT32(VirtIONet, mac_table_doesnt_fit, 0,
3318                                      mac_table.in_use, ETH_ALEN),
3319 
3320         /* Note: This is an array of uint32's that's always been saved as a
3321          * buffer; hold onto your endiannesses; it's actually used as a bitmap
3322          * but based on the uint.
3323          */
3324         VMSTATE_BUFFER_POINTER_UNSAFE(vlans, VirtIONet, 0, MAX_VLAN >> 3),
3325         VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
3326                          vmstate_virtio_net_has_vnet),
3327         VMSTATE_UINT8(mac_table.multi_overflow, VirtIONet),
3328         VMSTATE_UINT8(mac_table.uni_overflow, VirtIONet),
3329         VMSTATE_UINT8(alluni, VirtIONet),
3330         VMSTATE_UINT8(nomulti, VirtIONet),
3331         VMSTATE_UINT8(nouni, VirtIONet),
3332         VMSTATE_UINT8(nobcast, VirtIONet),
3333         VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
3334                          vmstate_virtio_net_has_ufo),
3335         VMSTATE_SINGLE_TEST(max_queue_pairs, VirtIONet, max_queue_pairs_gt_1, 0,
3336                             vmstate_info_uint16_equal, uint16_t),
3337         VMSTATE_UINT16_TEST(curr_queue_pairs, VirtIONet, max_queue_pairs_gt_1),
3338         VMSTATE_WITH_TMP(VirtIONet, struct VirtIONetMigTmp,
3339                          vmstate_virtio_net_tx_waiting),
3340         VMSTATE_UINT64_TEST(curr_guest_offloads, VirtIONet,
3341                             has_ctrl_guest_offloads),
3342         VMSTATE_END_OF_LIST()
3343     },
3344     .subsections = (const VMStateDescription * const []) {
3345         &vmstate_virtio_net_rss,
3346         NULL
3347     }
3348 };
3349 
3350 static NetClientInfo net_virtio_info = {
3351     .type = NET_CLIENT_DRIVER_NIC,
3352     .size = sizeof(NICState),
3353     .can_receive = virtio_net_can_receive,
3354     .receive = virtio_net_receive,
3355     .link_status_changed = virtio_net_set_link_status,
3356     .query_rx_filter = virtio_net_query_rxfilter,
3357     .announce = virtio_net_announce,
3358 };
3359 
3360 static bool virtio_net_guest_notifier_pending(VirtIODevice *vdev, int idx)
3361 {
3362     VirtIONet *n = VIRTIO_NET(vdev);
3363     NetClientState *nc;
3364     assert(n->vhost_started);
3365     if (!n->multiqueue && idx == 2) {
3366         /* Must guard against invalid features and bogus queue index
3367          * from being set by malicious guest, or penetrated through
3368          * buggy migration stream.
3369          */
3370         if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
3371             qemu_log_mask(LOG_GUEST_ERROR,
3372                           "%s: bogus vq index ignored\n", __func__);
3373             return false;
3374         }
3375         nc = qemu_get_subqueue(n->nic, n->max_queue_pairs);
3376     } else {
3377         nc = qemu_get_subqueue(n->nic, vq2q(idx));
3378     }
3379     /*
3380      * Add the check for configure interrupt, Use VIRTIO_CONFIG_IRQ_IDX -1
3381      * as the macro of configure interrupt's IDX, If this driver does not
3382      * support, the function will return false
3383      */
3384 
3385     if (idx == VIRTIO_CONFIG_IRQ_IDX) {
3386         return vhost_net_config_pending(get_vhost_net(nc->peer));
3387     }
3388     return vhost_net_virtqueue_pending(get_vhost_net(nc->peer), idx);
3389 }
3390 
3391 static void virtio_net_guest_notifier_mask(VirtIODevice *vdev, int idx,
3392                                            bool mask)
3393 {
3394     VirtIONet *n = VIRTIO_NET(vdev);
3395     NetClientState *nc;
3396     assert(n->vhost_started);
3397     if (!n->multiqueue && idx == 2) {
3398         /* Must guard against invalid features and bogus queue index
3399          * from being set by malicious guest, or penetrated through
3400          * buggy migration stream.
3401          */
3402         if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_CTRL_VQ)) {
3403             qemu_log_mask(LOG_GUEST_ERROR,
3404                           "%s: bogus vq index ignored\n", __func__);
3405             return;
3406         }
3407         nc = qemu_get_subqueue(n->nic, n->max_queue_pairs);
3408     } else {
3409         nc = qemu_get_subqueue(n->nic, vq2q(idx));
3410     }
3411     /*
3412      *Add the check for configure interrupt, Use VIRTIO_CONFIG_IRQ_IDX -1
3413      * as the macro of configure interrupt's IDX, If this driver does not
3414      * support, the function will return
3415      */
3416 
3417     if (idx == VIRTIO_CONFIG_IRQ_IDX) {
3418         vhost_net_config_mask(get_vhost_net(nc->peer), vdev, mask);
3419         return;
3420     }
3421     vhost_net_virtqueue_mask(get_vhost_net(nc->peer), vdev, idx, mask);
3422 }
3423 
3424 static void virtio_net_set_config_size(VirtIONet *n, uint64_t host_features)
3425 {
3426     virtio_add_feature(&host_features, VIRTIO_NET_F_MAC);
3427 
3428     n->config_size = virtio_get_config_size(&cfg_size_params, host_features);
3429 }
3430 
3431 void virtio_net_set_netclient_name(VirtIONet *n, const char *name,
3432                                    const char *type)
3433 {
3434     /*
3435      * The name can be NULL, the netclient name will be type.x.
3436      */
3437     assert(type != NULL);
3438 
3439     g_free(n->netclient_name);
3440     g_free(n->netclient_type);
3441     n->netclient_name = g_strdup(name);
3442     n->netclient_type = g_strdup(type);
3443 }
3444 
3445 static bool failover_unplug_primary(VirtIONet *n, DeviceState *dev)
3446 {
3447     HotplugHandler *hotplug_ctrl;
3448     PCIDevice *pci_dev;
3449     Error *err = NULL;
3450 
3451     hotplug_ctrl = qdev_get_hotplug_handler(dev);
3452     if (hotplug_ctrl) {
3453         pci_dev = PCI_DEVICE(dev);
3454         pci_dev->partially_hotplugged = true;
3455         hotplug_handler_unplug_request(hotplug_ctrl, dev, &err);
3456         if (err) {
3457             error_report_err(err);
3458             return false;
3459         }
3460     } else {
3461         return false;
3462     }
3463     return true;
3464 }
3465 
3466 static bool failover_replug_primary(VirtIONet *n, DeviceState *dev,
3467                                     Error **errp)
3468 {
3469     Error *err = NULL;
3470     HotplugHandler *hotplug_ctrl;
3471     PCIDevice *pdev = PCI_DEVICE(dev);
3472     BusState *primary_bus;
3473 
3474     if (!pdev->partially_hotplugged) {
3475         return true;
3476     }
3477     primary_bus = dev->parent_bus;
3478     if (!primary_bus) {
3479         error_setg(errp, "virtio_net: couldn't find primary bus");
3480         return false;
3481     }
3482     qdev_set_parent_bus(dev, primary_bus, &error_abort);
3483     qatomic_set(&n->failover_primary_hidden, false);
3484     hotplug_ctrl = qdev_get_hotplug_handler(dev);
3485     if (hotplug_ctrl) {
3486         hotplug_handler_pre_plug(hotplug_ctrl, dev, &err);
3487         if (err) {
3488             goto out;
3489         }
3490         hotplug_handler_plug(hotplug_ctrl, dev, &err);
3491     }
3492     pdev->partially_hotplugged = false;
3493 
3494 out:
3495     error_propagate(errp, err);
3496     return !err;
3497 }
3498 
3499 static void virtio_net_handle_migration_primary(VirtIONet *n, MigrationEvent *e)
3500 {
3501     bool should_be_hidden;
3502     Error *err = NULL;
3503     DeviceState *dev = failover_find_primary_device(n);
3504 
3505     if (!dev) {
3506         return;
3507     }
3508 
3509     should_be_hidden = qatomic_read(&n->failover_primary_hidden);
3510 
3511     if (e->type == MIG_EVENT_PRECOPY_SETUP && !should_be_hidden) {
3512         if (failover_unplug_primary(n, dev)) {
3513             vmstate_unregister(VMSTATE_IF(dev), qdev_get_vmsd(dev), dev);
3514             qapi_event_send_unplug_primary(dev->id);
3515             qatomic_set(&n->failover_primary_hidden, true);
3516         } else {
3517             warn_report("couldn't unplug primary device");
3518         }
3519     } else if (e->type == MIG_EVENT_PRECOPY_FAILED) {
3520         /* We already unplugged the device let's plug it back */
3521         if (!failover_replug_primary(n, dev, &err)) {
3522             if (err) {
3523                 error_report_err(err);
3524             }
3525         }
3526     }
3527 }
3528 
3529 static int virtio_net_migration_state_notifier(NotifierWithReturn *notifier,
3530                                                MigrationEvent *e, Error **errp)
3531 {
3532     VirtIONet *n = container_of(notifier, VirtIONet, migration_state);
3533     virtio_net_handle_migration_primary(n, e);
3534     return 0;
3535 }
3536 
3537 static bool failover_hide_primary_device(DeviceListener *listener,
3538                                          const QDict *device_opts,
3539                                          bool from_json,
3540                                          Error **errp)
3541 {
3542     VirtIONet *n = container_of(listener, VirtIONet, primary_listener);
3543     const char *standby_id;
3544 
3545     if (!device_opts) {
3546         return false;
3547     }
3548 
3549     if (!qdict_haskey(device_opts, "failover_pair_id")) {
3550         return false;
3551     }
3552 
3553     if (!qdict_haskey(device_opts, "id")) {
3554         error_setg(errp, "Device with failover_pair_id needs to have id");
3555         return false;
3556     }
3557 
3558     standby_id = qdict_get_str(device_opts, "failover_pair_id");
3559     if (g_strcmp0(standby_id, n->netclient_name) != 0) {
3560         return false;
3561     }
3562 
3563     /*
3564      * The hide helper can be called several times for a given device.
3565      * Check there is only one primary for a virtio-net device but
3566      * don't duplicate the qdict several times if it's called for the same
3567      * device.
3568      */
3569     if (n->primary_opts) {
3570         const char *old, *new;
3571         /* devices with failover_pair_id always have an id */
3572         old = qdict_get_str(n->primary_opts, "id");
3573         new = qdict_get_str(device_opts, "id");
3574         if (strcmp(old, new) != 0) {
3575             error_setg(errp, "Cannot attach more than one primary device to "
3576                        "'%s': '%s' and '%s'", n->netclient_name, old, new);
3577             return false;
3578         }
3579     } else {
3580         n->primary_opts = qdict_clone_shallow(device_opts);
3581         n->primary_opts_from_json = from_json;
3582     }
3583 
3584     /* failover_primary_hidden is set during feature negotiation */
3585     return qatomic_read(&n->failover_primary_hidden);
3586 }
3587 
3588 static void virtio_net_device_realize(DeviceState *dev, Error **errp)
3589 {
3590     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3591     VirtIONet *n = VIRTIO_NET(dev);
3592     NetClientState *nc;
3593     int i;
3594 
3595     if (n->net_conf.mtu) {
3596         n->host_features |= (1ULL << VIRTIO_NET_F_MTU);
3597     }
3598 
3599     if (n->net_conf.duplex_str) {
3600         if (strncmp(n->net_conf.duplex_str, "half", 5) == 0) {
3601             n->net_conf.duplex = DUPLEX_HALF;
3602         } else if (strncmp(n->net_conf.duplex_str, "full", 5) == 0) {
3603             n->net_conf.duplex = DUPLEX_FULL;
3604         } else {
3605             error_setg(errp, "'duplex' must be 'half' or 'full'");
3606             return;
3607         }
3608         n->host_features |= (1ULL << VIRTIO_NET_F_SPEED_DUPLEX);
3609     } else {
3610         n->net_conf.duplex = DUPLEX_UNKNOWN;
3611     }
3612 
3613     if (n->net_conf.speed < SPEED_UNKNOWN) {
3614         error_setg(errp, "'speed' must be between 0 and INT_MAX");
3615         return;
3616     }
3617     if (n->net_conf.speed >= 0) {
3618         n->host_features |= (1ULL << VIRTIO_NET_F_SPEED_DUPLEX);
3619     }
3620 
3621     if (n->failover) {
3622         n->primary_listener.hide_device = failover_hide_primary_device;
3623         qatomic_set(&n->failover_primary_hidden, true);
3624         device_listener_register(&n->primary_listener);
3625         migration_add_notifier(&n->migration_state,
3626                                virtio_net_migration_state_notifier);
3627         n->host_features |= (1ULL << VIRTIO_NET_F_STANDBY);
3628     }
3629 
3630     virtio_net_set_config_size(n, n->host_features);
3631     virtio_init(vdev, VIRTIO_ID_NET, n->config_size);
3632 
3633     /*
3634      * We set a lower limit on RX queue size to what it always was.
3635      * Guests that want a smaller ring can always resize it without
3636      * help from us (using virtio 1 and up).
3637      */
3638     if (n->net_conf.rx_queue_size < VIRTIO_NET_RX_QUEUE_MIN_SIZE ||
3639         n->net_conf.rx_queue_size > VIRTQUEUE_MAX_SIZE ||
3640         !is_power_of_2(n->net_conf.rx_queue_size)) {
3641         error_setg(errp, "Invalid rx_queue_size (= %" PRIu16 "), "
3642                    "must be a power of 2 between %d and %d.",
3643                    n->net_conf.rx_queue_size, VIRTIO_NET_RX_QUEUE_MIN_SIZE,
3644                    VIRTQUEUE_MAX_SIZE);
3645         virtio_cleanup(vdev);
3646         return;
3647     }
3648 
3649     if (n->net_conf.tx_queue_size < VIRTIO_NET_TX_QUEUE_MIN_SIZE ||
3650         n->net_conf.tx_queue_size > virtio_net_max_tx_queue_size(n) ||
3651         !is_power_of_2(n->net_conf.tx_queue_size)) {
3652         error_setg(errp, "Invalid tx_queue_size (= %" PRIu16 "), "
3653                    "must be a power of 2 between %d and %d",
3654                    n->net_conf.tx_queue_size, VIRTIO_NET_TX_QUEUE_MIN_SIZE,
3655                    virtio_net_max_tx_queue_size(n));
3656         virtio_cleanup(vdev);
3657         return;
3658     }
3659 
3660     n->max_ncs = MAX(n->nic_conf.peers.queues, 1);
3661 
3662     /*
3663      * Figure out the datapath queue pairs since the backend could
3664      * provide control queue via peers as well.
3665      */
3666     if (n->nic_conf.peers.queues) {
3667         for (i = 0; i < n->max_ncs; i++) {
3668             if (n->nic_conf.peers.ncs[i]->is_datapath) {
3669                 ++n->max_queue_pairs;
3670             }
3671         }
3672     }
3673     n->max_queue_pairs = MAX(n->max_queue_pairs, 1);
3674 
3675     if (n->max_queue_pairs * 2 + 1 > VIRTIO_QUEUE_MAX) {
3676         error_setg(errp, "Invalid number of queue pairs (= %" PRIu32 "), "
3677                    "must be a positive integer less than %d.",
3678                    n->max_queue_pairs, (VIRTIO_QUEUE_MAX - 1) / 2);
3679         virtio_cleanup(vdev);
3680         return;
3681     }
3682     n->vqs = g_new0(VirtIONetQueue, n->max_queue_pairs);
3683     n->curr_queue_pairs = 1;
3684     n->tx_timeout = n->net_conf.txtimer;
3685 
3686     if (n->net_conf.tx && strcmp(n->net_conf.tx, "timer")
3687                        && strcmp(n->net_conf.tx, "bh")) {
3688         warn_report("virtio-net: "
3689                     "Unknown option tx=%s, valid options: \"timer\" \"bh\"",
3690                     n->net_conf.tx);
3691         error_printf("Defaulting to \"bh\"");
3692     }
3693 
3694     n->net_conf.tx_queue_size = MIN(virtio_net_max_tx_queue_size(n),
3695                                     n->net_conf.tx_queue_size);
3696 
3697     virtio_net_add_queue(n, 0);
3698 
3699     n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
3700     qemu_macaddr_default_if_unset(&n->nic_conf.macaddr);
3701     memcpy(&n->mac[0], &n->nic_conf.macaddr, sizeof(n->mac));
3702     n->status = VIRTIO_NET_S_LINK_UP;
3703     qemu_announce_timer_reset(&n->announce_timer, migrate_announce_params(),
3704                               QEMU_CLOCK_VIRTUAL,
3705                               virtio_net_announce_timer, n);
3706     n->announce_timer.round = 0;
3707 
3708     if (n->netclient_type) {
3709         /*
3710          * Happen when virtio_net_set_netclient_name has been called.
3711          */
3712         n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
3713                               n->netclient_type, n->netclient_name,
3714                               &dev->mem_reentrancy_guard, n);
3715     } else {
3716         n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
3717                               object_get_typename(OBJECT(dev)), dev->id,
3718                               &dev->mem_reentrancy_guard, n);
3719     }
3720 
3721     for (i = 0; i < n->max_queue_pairs; i++) {
3722         n->nic->ncs[i].do_not_pad = true;
3723     }
3724 
3725     peer_test_vnet_hdr(n);
3726     if (peer_has_vnet_hdr(n)) {
3727         n->host_hdr_len = sizeof(struct virtio_net_hdr);
3728     } else {
3729         n->host_hdr_len = 0;
3730     }
3731 
3732     qemu_format_nic_info_str(qemu_get_queue(n->nic), n->nic_conf.macaddr.a);
3733 
3734     n->vqs[0].tx_waiting = 0;
3735     n->tx_burst = n->net_conf.txburst;
3736     virtio_net_set_mrg_rx_bufs(n, 0, 0, 0);
3737     n->promisc = 1; /* for compatibility */
3738 
3739     n->mac_table.macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);
3740 
3741     n->vlans = g_malloc0(MAX_VLAN >> 3);
3742 
3743     nc = qemu_get_queue(n->nic);
3744     nc->rxfilter_notify_enabled = 1;
3745 
3746    if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_VHOST_VDPA) {
3747         struct virtio_net_config netcfg = {};
3748         memcpy(&netcfg.mac, &n->nic_conf.macaddr, ETH_ALEN);
3749         vhost_net_set_config(get_vhost_net(nc->peer),
3750             (uint8_t *)&netcfg, 0, ETH_ALEN, VHOST_SET_CONFIG_TYPE_FRONTEND);
3751     }
3752     QTAILQ_INIT(&n->rsc_chains);
3753     n->qdev = dev;
3754 
3755     net_rx_pkt_init(&n->rx_pkt);
3756 
3757     if (virtio_has_feature(n->host_features, VIRTIO_NET_F_RSS)) {
3758         virtio_net_load_ebpf(n);
3759     }
3760 }
3761 
3762 static void virtio_net_device_unrealize(DeviceState *dev)
3763 {
3764     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3765     VirtIONet *n = VIRTIO_NET(dev);
3766     int i, max_queue_pairs;
3767 
3768     if (virtio_has_feature(n->host_features, VIRTIO_NET_F_RSS)) {
3769         virtio_net_unload_ebpf(n);
3770     }
3771 
3772     /* This will stop vhost backend if appropriate. */
3773     virtio_net_set_status(vdev, 0);
3774 
3775     g_free(n->netclient_name);
3776     n->netclient_name = NULL;
3777     g_free(n->netclient_type);
3778     n->netclient_type = NULL;
3779 
3780     g_free(n->mac_table.macs);
3781     g_free(n->vlans);
3782 
3783     if (n->failover) {
3784         qobject_unref(n->primary_opts);
3785         device_listener_unregister(&n->primary_listener);
3786         migration_remove_notifier(&n->migration_state);
3787     } else {
3788         assert(n->primary_opts == NULL);
3789     }
3790 
3791     max_queue_pairs = n->multiqueue ? n->max_queue_pairs : 1;
3792     for (i = 0; i < max_queue_pairs; i++) {
3793         virtio_net_del_queue(n, i);
3794     }
3795     /* delete also control vq */
3796     virtio_del_queue(vdev, max_queue_pairs * 2);
3797     qemu_announce_timer_del(&n->announce_timer, false);
3798     g_free(n->vqs);
3799     qemu_del_nic(n->nic);
3800     virtio_net_rsc_cleanup(n);
3801     g_free(n->rss_data.indirections_table);
3802     net_rx_pkt_uninit(n->rx_pkt);
3803     virtio_cleanup(vdev);
3804 }
3805 
3806 static void virtio_net_reset(VirtIODevice *vdev)
3807 {
3808     VirtIONet *n = VIRTIO_NET(vdev);
3809     int i;
3810 
3811     /* Reset back to compatibility mode */
3812     n->promisc = 1;
3813     n->allmulti = 0;
3814     n->alluni = 0;
3815     n->nomulti = 0;
3816     n->nouni = 0;
3817     n->nobcast = 0;
3818     /* multiqueue is disabled by default */
3819     n->curr_queue_pairs = 1;
3820     timer_del(n->announce_timer.tm);
3821     n->announce_timer.round = 0;
3822     n->status &= ~VIRTIO_NET_S_ANNOUNCE;
3823 
3824     /* Flush any MAC and VLAN filter table state */
3825     n->mac_table.in_use = 0;
3826     n->mac_table.first_multi = 0;
3827     n->mac_table.multi_overflow = 0;
3828     n->mac_table.uni_overflow = 0;
3829     memset(n->mac_table.macs, 0, MAC_TABLE_ENTRIES * ETH_ALEN);
3830     memcpy(&n->mac[0], &n->nic->conf->macaddr, sizeof(n->mac));
3831     qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
3832     memset(n->vlans, 0, MAX_VLAN >> 3);
3833 
3834     /* Flush any async TX */
3835     for (i = 0;  i < n->max_queue_pairs; i++) {
3836         flush_or_purge_queued_packets(qemu_get_subqueue(n->nic, i));
3837     }
3838 
3839     virtio_net_disable_rss(n);
3840 }
3841 
3842 static void virtio_net_instance_init(Object *obj)
3843 {
3844     VirtIONet *n = VIRTIO_NET(obj);
3845 
3846     /*
3847      * The default config_size is sizeof(struct virtio_net_config).
3848      * Can be overridden with virtio_net_set_config_size.
3849      */
3850     n->config_size = sizeof(struct virtio_net_config);
3851     device_add_bootindex_property(obj, &n->nic_conf.bootindex,
3852                                   "bootindex", "/ethernet-phy@0",
3853                                   DEVICE(n));
3854 
3855     ebpf_rss_init(&n->ebpf_rss);
3856 }
3857 
3858 static int virtio_net_pre_save(void *opaque)
3859 {
3860     VirtIONet *n = opaque;
3861 
3862     /* At this point, backend must be stopped, otherwise
3863      * it might keep writing to memory. */
3864     assert(!n->vhost_started);
3865 
3866     return 0;
3867 }
3868 
3869 static bool primary_unplug_pending(void *opaque)
3870 {
3871     DeviceState *dev = opaque;
3872     DeviceState *primary;
3873     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
3874     VirtIONet *n = VIRTIO_NET(vdev);
3875 
3876     if (!virtio_vdev_has_feature(vdev, VIRTIO_NET_F_STANDBY)) {
3877         return false;
3878     }
3879     primary = failover_find_primary_device(n);
3880     return primary ? primary->pending_deleted_event : false;
3881 }
3882 
3883 static bool dev_unplug_pending(void *opaque)
3884 {
3885     DeviceState *dev = opaque;
3886     VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(dev);
3887 
3888     return vdc->primary_unplug_pending(dev);
3889 }
3890 
3891 static struct vhost_dev *virtio_net_get_vhost(VirtIODevice *vdev)
3892 {
3893     VirtIONet *n = VIRTIO_NET(vdev);
3894     NetClientState *nc = qemu_get_queue(n->nic);
3895     struct vhost_net *net = get_vhost_net(nc->peer);
3896     return &net->dev;
3897 }
3898 
3899 static const VMStateDescription vmstate_virtio_net = {
3900     .name = "virtio-net",
3901     .minimum_version_id = VIRTIO_NET_VM_VERSION,
3902     .version_id = VIRTIO_NET_VM_VERSION,
3903     .fields = (const VMStateField[]) {
3904         VMSTATE_VIRTIO_DEVICE,
3905         VMSTATE_END_OF_LIST()
3906     },
3907     .pre_save = virtio_net_pre_save,
3908     .dev_unplug_pending = dev_unplug_pending,
3909 };
3910 
3911 static Property virtio_net_properties[] = {
3912     DEFINE_PROP_BIT64("csum", VirtIONet, host_features,
3913                     VIRTIO_NET_F_CSUM, true),
3914     DEFINE_PROP_BIT64("guest_csum", VirtIONet, host_features,
3915                     VIRTIO_NET_F_GUEST_CSUM, true),
3916     DEFINE_PROP_BIT64("gso", VirtIONet, host_features, VIRTIO_NET_F_GSO, true),
3917     DEFINE_PROP_BIT64("guest_tso4", VirtIONet, host_features,
3918                     VIRTIO_NET_F_GUEST_TSO4, true),
3919     DEFINE_PROP_BIT64("guest_tso6", VirtIONet, host_features,
3920                     VIRTIO_NET_F_GUEST_TSO6, true),
3921     DEFINE_PROP_BIT64("guest_ecn", VirtIONet, host_features,
3922                     VIRTIO_NET_F_GUEST_ECN, true),
3923     DEFINE_PROP_BIT64("guest_ufo", VirtIONet, host_features,
3924                     VIRTIO_NET_F_GUEST_UFO, true),
3925     DEFINE_PROP_BIT64("guest_announce", VirtIONet, host_features,
3926                     VIRTIO_NET_F_GUEST_ANNOUNCE, true),
3927     DEFINE_PROP_BIT64("host_tso4", VirtIONet, host_features,
3928                     VIRTIO_NET_F_HOST_TSO4, true),
3929     DEFINE_PROP_BIT64("host_tso6", VirtIONet, host_features,
3930                     VIRTIO_NET_F_HOST_TSO6, true),
3931     DEFINE_PROP_BIT64("host_ecn", VirtIONet, host_features,
3932                     VIRTIO_NET_F_HOST_ECN, true),
3933     DEFINE_PROP_BIT64("host_ufo", VirtIONet, host_features,
3934                     VIRTIO_NET_F_HOST_UFO, true),
3935     DEFINE_PROP_BIT64("mrg_rxbuf", VirtIONet, host_features,
3936                     VIRTIO_NET_F_MRG_RXBUF, true),
3937     DEFINE_PROP_BIT64("status", VirtIONet, host_features,
3938                     VIRTIO_NET_F_STATUS, true),
3939     DEFINE_PROP_BIT64("ctrl_vq", VirtIONet, host_features,
3940                     VIRTIO_NET_F_CTRL_VQ, true),
3941     DEFINE_PROP_BIT64("ctrl_rx", VirtIONet, host_features,
3942                     VIRTIO_NET_F_CTRL_RX, true),
3943     DEFINE_PROP_BIT64("ctrl_vlan", VirtIONet, host_features,
3944                     VIRTIO_NET_F_CTRL_VLAN, true),
3945     DEFINE_PROP_BIT64("ctrl_rx_extra", VirtIONet, host_features,
3946                     VIRTIO_NET_F_CTRL_RX_EXTRA, true),
3947     DEFINE_PROP_BIT64("ctrl_mac_addr", VirtIONet, host_features,
3948                     VIRTIO_NET_F_CTRL_MAC_ADDR, true),
3949     DEFINE_PROP_BIT64("ctrl_guest_offloads", VirtIONet, host_features,
3950                     VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, true),
3951     DEFINE_PROP_BIT64("mq", VirtIONet, host_features, VIRTIO_NET_F_MQ, false),
3952     DEFINE_PROP_BIT64("rss", VirtIONet, host_features,
3953                     VIRTIO_NET_F_RSS, false),
3954     DEFINE_PROP_BIT64("hash", VirtIONet, host_features,
3955                     VIRTIO_NET_F_HASH_REPORT, false),
3956     DEFINE_PROP_ARRAY("ebpf-rss-fds", VirtIONet, nr_ebpf_rss_fds,
3957                       ebpf_rss_fds, qdev_prop_string, char*),
3958     DEFINE_PROP_BIT64("guest_rsc_ext", VirtIONet, host_features,
3959                     VIRTIO_NET_F_RSC_EXT, false),
3960     DEFINE_PROP_UINT32("rsc_interval", VirtIONet, rsc_timeout,
3961                        VIRTIO_NET_RSC_DEFAULT_INTERVAL),
3962     DEFINE_NIC_PROPERTIES(VirtIONet, nic_conf),
3963     DEFINE_PROP_UINT32("x-txtimer", VirtIONet, net_conf.txtimer,
3964                        TX_TIMER_INTERVAL),
3965     DEFINE_PROP_INT32("x-txburst", VirtIONet, net_conf.txburst, TX_BURST),
3966     DEFINE_PROP_STRING("tx", VirtIONet, net_conf.tx),
3967     DEFINE_PROP_UINT16("rx_queue_size", VirtIONet, net_conf.rx_queue_size,
3968                        VIRTIO_NET_RX_QUEUE_DEFAULT_SIZE),
3969     DEFINE_PROP_UINT16("tx_queue_size", VirtIONet, net_conf.tx_queue_size,
3970                        VIRTIO_NET_TX_QUEUE_DEFAULT_SIZE),
3971     DEFINE_PROP_UINT16("host_mtu", VirtIONet, net_conf.mtu, 0),
3972     DEFINE_PROP_BOOL("x-mtu-bypass-backend", VirtIONet, mtu_bypass_backend,
3973                      true),
3974     DEFINE_PROP_INT32("speed", VirtIONet, net_conf.speed, SPEED_UNKNOWN),
3975     DEFINE_PROP_STRING("duplex", VirtIONet, net_conf.duplex_str),
3976     DEFINE_PROP_BOOL("failover", VirtIONet, failover, false),
3977     DEFINE_PROP_BIT64("guest_uso4", VirtIONet, host_features,
3978                       VIRTIO_NET_F_GUEST_USO4, true),
3979     DEFINE_PROP_BIT64("guest_uso6", VirtIONet, host_features,
3980                       VIRTIO_NET_F_GUEST_USO6, true),
3981     DEFINE_PROP_BIT64("host_uso", VirtIONet, host_features,
3982                       VIRTIO_NET_F_HOST_USO, true),
3983     DEFINE_PROP_END_OF_LIST(),
3984 };
3985 
3986 static void virtio_net_class_init(ObjectClass *klass, void *data)
3987 {
3988     DeviceClass *dc = DEVICE_CLASS(klass);
3989     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
3990 
3991     device_class_set_props(dc, virtio_net_properties);
3992     dc->vmsd = &vmstate_virtio_net;
3993     set_bit(DEVICE_CATEGORY_NETWORK, dc->categories);
3994     vdc->realize = virtio_net_device_realize;
3995     vdc->unrealize = virtio_net_device_unrealize;
3996     vdc->get_config = virtio_net_get_config;
3997     vdc->set_config = virtio_net_set_config;
3998     vdc->get_features = virtio_net_get_features;
3999     vdc->set_features = virtio_net_set_features;
4000     vdc->bad_features = virtio_net_bad_features;
4001     vdc->reset = virtio_net_reset;
4002     vdc->queue_reset = virtio_net_queue_reset;
4003     vdc->queue_enable = virtio_net_queue_enable;
4004     vdc->set_status = virtio_net_set_status;
4005     vdc->guest_notifier_mask = virtio_net_guest_notifier_mask;
4006     vdc->guest_notifier_pending = virtio_net_guest_notifier_pending;
4007     vdc->legacy_features |= (0x1 << VIRTIO_NET_F_GSO);
4008     vdc->post_load = virtio_net_post_load_virtio;
4009     vdc->vmsd = &vmstate_virtio_net_device;
4010     vdc->primary_unplug_pending = primary_unplug_pending;
4011     vdc->get_vhost = virtio_net_get_vhost;
4012     vdc->toggle_device_iotlb = vhost_toggle_device_iotlb;
4013 }
4014 
4015 static const TypeInfo virtio_net_info = {
4016     .name = TYPE_VIRTIO_NET,
4017     .parent = TYPE_VIRTIO_DEVICE,
4018     .instance_size = sizeof(VirtIONet),
4019     .instance_init = virtio_net_instance_init,
4020     .class_init = virtio_net_class_init,
4021 };
4022 
4023 static void virtio_register_types(void)
4024 {
4025     type_register_static(&virtio_net_info);
4026 }
4027 
4028 type_init(virtio_register_types)
4029