xref: /openbmc/qemu/hw/net/virtio-net.c (revision 07a32d6b)
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/iov.h"
15 #include "hw/virtio/virtio.h"
16 #include "net/net.h"
17 #include "net/checksum.h"
18 #include "net/tap.h"
19 #include "qemu/error-report.h"
20 #include "qemu/timer.h"
21 #include "hw/virtio/virtio-net.h"
22 #include "net/vhost_net.h"
23 #include "hw/virtio/virtio-bus.h"
24 #include "qapi/qmp/qjson.h"
25 #include "monitor/monitor.h"
26 
27 #define VIRTIO_NET_VM_VERSION    11
28 
29 #define MAC_TABLE_ENTRIES    64
30 #define MAX_VLAN    (1 << 12)   /* Per 802.1Q definition */
31 
32 /*
33  * Calculate the number of bytes up to and including the given 'field' of
34  * 'container'.
35  */
36 #define endof(container, field) \
37     (offsetof(container, field) + sizeof(((container *)0)->field))
38 
39 typedef struct VirtIOFeature {
40     uint32_t flags;
41     size_t end;
42 } VirtIOFeature;
43 
44 static VirtIOFeature feature_sizes[] = {
45     {.flags = 1 << VIRTIO_NET_F_MAC,
46      .end = endof(struct virtio_net_config, mac)},
47     {.flags = 1 << VIRTIO_NET_F_STATUS,
48      .end = endof(struct virtio_net_config, status)},
49     {.flags = 1 << VIRTIO_NET_F_MQ,
50      .end = endof(struct virtio_net_config, max_virtqueue_pairs)},
51     {}
52 };
53 
54 static VirtIONetQueue *virtio_net_get_subqueue(NetClientState *nc)
55 {
56     VirtIONet *n = qemu_get_nic_opaque(nc);
57 
58     return &n->vqs[nc->queue_index];
59 }
60 
61 static int vq2q(int queue_index)
62 {
63     return queue_index / 2;
64 }
65 
66 /* TODO
67  * - we could suppress RX interrupt if we were so inclined.
68  */
69 
70 static void virtio_net_get_config(VirtIODevice *vdev, uint8_t *config)
71 {
72     VirtIONet *n = VIRTIO_NET(vdev);
73     struct virtio_net_config netcfg;
74 
75     stw_p(&netcfg.status, n->status);
76     stw_p(&netcfg.max_virtqueue_pairs, n->max_queues);
77     memcpy(netcfg.mac, n->mac, ETH_ALEN);
78     memcpy(config, &netcfg, n->config_size);
79 }
80 
81 static void virtio_net_set_config(VirtIODevice *vdev, const uint8_t *config)
82 {
83     VirtIONet *n = VIRTIO_NET(vdev);
84     struct virtio_net_config netcfg = {};
85 
86     memcpy(&netcfg, config, n->config_size);
87 
88     if (!(vdev->guest_features >> VIRTIO_NET_F_CTRL_MAC_ADDR & 1) &&
89         memcmp(netcfg.mac, n->mac, ETH_ALEN)) {
90         memcpy(n->mac, netcfg.mac, ETH_ALEN);
91         qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
92     }
93 }
94 
95 static bool virtio_net_started(VirtIONet *n, uint8_t status)
96 {
97     VirtIODevice *vdev = VIRTIO_DEVICE(n);
98     return (status & VIRTIO_CONFIG_S_DRIVER_OK) &&
99         (n->status & VIRTIO_NET_S_LINK_UP) && vdev->vm_running;
100 }
101 
102 static void virtio_net_announce_timer(void *opaque)
103 {
104     VirtIONet *n = opaque;
105     VirtIODevice *vdev = VIRTIO_DEVICE(n);
106 
107     n->announce_counter--;
108     n->status |= VIRTIO_NET_S_ANNOUNCE;
109     virtio_notify_config(vdev);
110 }
111 
112 static void virtio_net_vhost_status(VirtIONet *n, uint8_t status)
113 {
114     VirtIODevice *vdev = VIRTIO_DEVICE(n);
115     NetClientState *nc = qemu_get_queue(n->nic);
116     int queues = n->multiqueue ? n->max_queues : 1;
117 
118     if (!get_vhost_net(nc->peer)) {
119         return;
120     }
121 
122     if (!!n->vhost_started ==
123         (virtio_net_started(n, status) && !nc->peer->link_down)) {
124         return;
125     }
126     if (!n->vhost_started) {
127         int r;
128         if (!vhost_net_query(get_vhost_net(nc->peer), vdev)) {
129             return;
130         }
131         n->vhost_started = 1;
132         r = vhost_net_start(vdev, n->nic->ncs, queues);
133         if (r < 0) {
134             error_report("unable to start vhost net: %d: "
135                          "falling back on userspace virtio", -r);
136             n->vhost_started = 0;
137         }
138     } else {
139         vhost_net_stop(vdev, n->nic->ncs, queues);
140         n->vhost_started = 0;
141     }
142 }
143 
144 static void virtio_net_set_status(struct VirtIODevice *vdev, uint8_t status)
145 {
146     VirtIONet *n = VIRTIO_NET(vdev);
147     VirtIONetQueue *q;
148     int i;
149     uint8_t queue_status;
150 
151     virtio_net_vhost_status(n, status);
152 
153     for (i = 0; i < n->max_queues; i++) {
154         q = &n->vqs[i];
155 
156         if ((!n->multiqueue && i != 0) || i >= n->curr_queues) {
157             queue_status = 0;
158         } else {
159             queue_status = status;
160         }
161 
162         if (!q->tx_waiting) {
163             continue;
164         }
165 
166         if (virtio_net_started(n, queue_status) && !n->vhost_started) {
167             if (q->tx_timer) {
168                 timer_mod(q->tx_timer,
169                                qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
170             } else {
171                 qemu_bh_schedule(q->tx_bh);
172             }
173         } else {
174             if (q->tx_timer) {
175                 timer_del(q->tx_timer);
176             } else {
177                 qemu_bh_cancel(q->tx_bh);
178             }
179         }
180     }
181 }
182 
183 static void virtio_net_set_link_status(NetClientState *nc)
184 {
185     VirtIONet *n = qemu_get_nic_opaque(nc);
186     VirtIODevice *vdev = VIRTIO_DEVICE(n);
187     uint16_t old_status = n->status;
188 
189     if (nc->link_down)
190         n->status &= ~VIRTIO_NET_S_LINK_UP;
191     else
192         n->status |= VIRTIO_NET_S_LINK_UP;
193 
194     if (n->status != old_status)
195         virtio_notify_config(vdev);
196 
197     virtio_net_set_status(vdev, vdev->status);
198 }
199 
200 static void rxfilter_notify(NetClientState *nc)
201 {
202     QObject *event_data;
203     VirtIONet *n = qemu_get_nic_opaque(nc);
204 
205     if (nc->rxfilter_notify_enabled) {
206         gchar *path = object_get_canonical_path(OBJECT(n->qdev));
207         if (n->netclient_name) {
208             event_data = qobject_from_jsonf("{ 'name': %s, 'path': %s }",
209                                     n->netclient_name, path);
210         } else {
211             event_data = qobject_from_jsonf("{ 'path': %s }", path);
212         }
213         monitor_protocol_event(QEVENT_NIC_RX_FILTER_CHANGED, event_data);
214         qobject_decref(event_data);
215         g_free(path);
216 
217         /* disable event notification to avoid events flooding */
218         nc->rxfilter_notify_enabled = 0;
219     }
220 }
221 
222 static char *mac_strdup_printf(const uint8_t *mac)
223 {
224     return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x", mac[0],
225                             mac[1], mac[2], mac[3], mac[4], mac[5]);
226 }
227 
228 static intList *get_vlan_table(VirtIONet *n)
229 {
230     intList *list, *entry;
231     int i, j;
232 
233     list = NULL;
234     for (i = 0; i < MAX_VLAN >> 5; i++) {
235         for (j = 0; n->vlans[i] && j <= 0x1f; j++) {
236             if (n->vlans[i] & (1U << j)) {
237                 entry = g_malloc0(sizeof(*entry));
238                 entry->value = (i << 5) + j;
239                 entry->next = list;
240                 list = entry;
241             }
242         }
243     }
244 
245     return list;
246 }
247 
248 static RxFilterInfo *virtio_net_query_rxfilter(NetClientState *nc)
249 {
250     VirtIONet *n = qemu_get_nic_opaque(nc);
251     VirtIODevice *vdev = VIRTIO_DEVICE(n);
252     RxFilterInfo *info;
253     strList *str_list, *entry;
254     int i;
255 
256     info = g_malloc0(sizeof(*info));
257     info->name = g_strdup(nc->name);
258     info->promiscuous = n->promisc;
259 
260     if (n->nouni) {
261         info->unicast = RX_STATE_NONE;
262     } else if (n->alluni) {
263         info->unicast = RX_STATE_ALL;
264     } else {
265         info->unicast = RX_STATE_NORMAL;
266     }
267 
268     if (n->nomulti) {
269         info->multicast = RX_STATE_NONE;
270     } else if (n->allmulti) {
271         info->multicast = RX_STATE_ALL;
272     } else {
273         info->multicast = RX_STATE_NORMAL;
274     }
275 
276     info->broadcast_allowed = n->nobcast;
277     info->multicast_overflow = n->mac_table.multi_overflow;
278     info->unicast_overflow = n->mac_table.uni_overflow;
279 
280     info->main_mac = mac_strdup_printf(n->mac);
281 
282     str_list = NULL;
283     for (i = 0; i < n->mac_table.first_multi; i++) {
284         entry = g_malloc0(sizeof(*entry));
285         entry->value = mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN);
286         entry->next = str_list;
287         str_list = entry;
288     }
289     info->unicast_table = str_list;
290 
291     str_list = NULL;
292     for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {
293         entry = g_malloc0(sizeof(*entry));
294         entry->value = mac_strdup_printf(n->mac_table.macs + i * ETH_ALEN);
295         entry->next = str_list;
296         str_list = entry;
297     }
298     info->multicast_table = str_list;
299     info->vlan_table = get_vlan_table(n);
300 
301     if (!((1 << VIRTIO_NET_F_CTRL_VLAN) & vdev->guest_features)) {
302         info->vlan = RX_STATE_ALL;
303     } else if (!info->vlan_table) {
304         info->vlan = RX_STATE_NONE;
305     } else {
306         info->vlan = RX_STATE_NORMAL;
307     }
308 
309     /* enable event notification after query */
310     nc->rxfilter_notify_enabled = 1;
311 
312     return info;
313 }
314 
315 static void virtio_net_reset(VirtIODevice *vdev)
316 {
317     VirtIONet *n = VIRTIO_NET(vdev);
318 
319     /* Reset back to compatibility mode */
320     n->promisc = 1;
321     n->allmulti = 0;
322     n->alluni = 0;
323     n->nomulti = 0;
324     n->nouni = 0;
325     n->nobcast = 0;
326     /* multiqueue is disabled by default */
327     n->curr_queues = 1;
328     timer_del(n->announce_timer);
329     n->announce_counter = 0;
330     n->status &= ~VIRTIO_NET_S_ANNOUNCE;
331 
332     /* Flush any MAC and VLAN filter table state */
333     n->mac_table.in_use = 0;
334     n->mac_table.first_multi = 0;
335     n->mac_table.multi_overflow = 0;
336     n->mac_table.uni_overflow = 0;
337     memset(n->mac_table.macs, 0, MAC_TABLE_ENTRIES * ETH_ALEN);
338     memcpy(&n->mac[0], &n->nic->conf->macaddr, sizeof(n->mac));
339     qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
340     memset(n->vlans, 0, MAX_VLAN >> 3);
341 }
342 
343 static void peer_test_vnet_hdr(VirtIONet *n)
344 {
345     NetClientState *nc = qemu_get_queue(n->nic);
346     if (!nc->peer) {
347         return;
348     }
349 
350     n->has_vnet_hdr = qemu_has_vnet_hdr(nc->peer);
351 }
352 
353 static int peer_has_vnet_hdr(VirtIONet *n)
354 {
355     return n->has_vnet_hdr;
356 }
357 
358 static int peer_has_ufo(VirtIONet *n)
359 {
360     if (!peer_has_vnet_hdr(n))
361         return 0;
362 
363     n->has_ufo = qemu_has_ufo(qemu_get_queue(n->nic)->peer);
364 
365     return n->has_ufo;
366 }
367 
368 static void virtio_net_set_mrg_rx_bufs(VirtIONet *n, int mergeable_rx_bufs)
369 {
370     int i;
371     NetClientState *nc;
372 
373     n->mergeable_rx_bufs = mergeable_rx_bufs;
374 
375     n->guest_hdr_len = n->mergeable_rx_bufs ?
376         sizeof(struct virtio_net_hdr_mrg_rxbuf) : sizeof(struct virtio_net_hdr);
377 
378     for (i = 0; i < n->max_queues; i++) {
379         nc = qemu_get_subqueue(n->nic, i);
380 
381         if (peer_has_vnet_hdr(n) &&
382             qemu_has_vnet_hdr_len(nc->peer, n->guest_hdr_len)) {
383             qemu_set_vnet_hdr_len(nc->peer, n->guest_hdr_len);
384             n->host_hdr_len = n->guest_hdr_len;
385         }
386     }
387 }
388 
389 static int peer_attach(VirtIONet *n, int index)
390 {
391     NetClientState *nc = qemu_get_subqueue(n->nic, index);
392 
393     if (!nc->peer) {
394         return 0;
395     }
396 
397     if (nc->peer->info->type != NET_CLIENT_OPTIONS_KIND_TAP) {
398         return 0;
399     }
400 
401     return tap_enable(nc->peer);
402 }
403 
404 static int peer_detach(VirtIONet *n, int index)
405 {
406     NetClientState *nc = qemu_get_subqueue(n->nic, index);
407 
408     if (!nc->peer) {
409         return 0;
410     }
411 
412     if (nc->peer->info->type !=  NET_CLIENT_OPTIONS_KIND_TAP) {
413         return 0;
414     }
415 
416     return tap_disable(nc->peer);
417 }
418 
419 static void virtio_net_set_queues(VirtIONet *n)
420 {
421     int i;
422     int r;
423 
424     for (i = 0; i < n->max_queues; i++) {
425         if (i < n->curr_queues) {
426             r = peer_attach(n, i);
427             assert(!r);
428         } else {
429             r = peer_detach(n, i);
430             assert(!r);
431         }
432     }
433 }
434 
435 static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue);
436 
437 static uint32_t virtio_net_get_features(VirtIODevice *vdev, uint32_t features)
438 {
439     VirtIONet *n = VIRTIO_NET(vdev);
440     NetClientState *nc = qemu_get_queue(n->nic);
441 
442     features |= (1 << VIRTIO_NET_F_MAC);
443 
444     if (!peer_has_vnet_hdr(n)) {
445         features &= ~(0x1 << VIRTIO_NET_F_CSUM);
446         features &= ~(0x1 << VIRTIO_NET_F_HOST_TSO4);
447         features &= ~(0x1 << VIRTIO_NET_F_HOST_TSO6);
448         features &= ~(0x1 << VIRTIO_NET_F_HOST_ECN);
449 
450         features &= ~(0x1 << VIRTIO_NET_F_GUEST_CSUM);
451         features &= ~(0x1 << VIRTIO_NET_F_GUEST_TSO4);
452         features &= ~(0x1 << VIRTIO_NET_F_GUEST_TSO6);
453         features &= ~(0x1 << VIRTIO_NET_F_GUEST_ECN);
454     }
455 
456     if (!peer_has_vnet_hdr(n) || !peer_has_ufo(n)) {
457         features &= ~(0x1 << VIRTIO_NET_F_GUEST_UFO);
458         features &= ~(0x1 << VIRTIO_NET_F_HOST_UFO);
459     }
460 
461     if (!get_vhost_net(nc->peer)) {
462         return features;
463     }
464     return vhost_net_get_features(get_vhost_net(nc->peer), features);
465 }
466 
467 static uint32_t virtio_net_bad_features(VirtIODevice *vdev)
468 {
469     uint32_t features = 0;
470 
471     /* Linux kernel 2.6.25.  It understood MAC (as everyone must),
472      * but also these: */
473     features |= (1 << VIRTIO_NET_F_MAC);
474     features |= (1 << VIRTIO_NET_F_CSUM);
475     features |= (1 << VIRTIO_NET_F_HOST_TSO4);
476     features |= (1 << VIRTIO_NET_F_HOST_TSO6);
477     features |= (1 << VIRTIO_NET_F_HOST_ECN);
478 
479     return features;
480 }
481 
482 static void virtio_net_apply_guest_offloads(VirtIONet *n)
483 {
484     qemu_set_offload(qemu_get_queue(n->nic)->peer,
485             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_CSUM)),
486             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO4)),
487             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_TSO6)),
488             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_ECN)),
489             !!(n->curr_guest_offloads & (1ULL << VIRTIO_NET_F_GUEST_UFO)));
490 }
491 
492 static uint64_t virtio_net_guest_offloads_by_features(uint32_t features)
493 {
494     static const uint64_t guest_offloads_mask =
495         (1ULL << VIRTIO_NET_F_GUEST_CSUM) |
496         (1ULL << VIRTIO_NET_F_GUEST_TSO4) |
497         (1ULL << VIRTIO_NET_F_GUEST_TSO6) |
498         (1ULL << VIRTIO_NET_F_GUEST_ECN)  |
499         (1ULL << VIRTIO_NET_F_GUEST_UFO);
500 
501     return guest_offloads_mask & features;
502 }
503 
504 static inline uint64_t virtio_net_supported_guest_offloads(VirtIONet *n)
505 {
506     VirtIODevice *vdev = VIRTIO_DEVICE(n);
507     return virtio_net_guest_offloads_by_features(vdev->guest_features);
508 }
509 
510 static void virtio_net_set_features(VirtIODevice *vdev, uint32_t features)
511 {
512     VirtIONet *n = VIRTIO_NET(vdev);
513     int i;
514 
515     virtio_net_set_multiqueue(n, !!(features & (1 << VIRTIO_NET_F_MQ)));
516 
517     virtio_net_set_mrg_rx_bufs(n, !!(features & (1 << VIRTIO_NET_F_MRG_RXBUF)));
518 
519     if (n->has_vnet_hdr) {
520         n->curr_guest_offloads =
521             virtio_net_guest_offloads_by_features(features);
522         virtio_net_apply_guest_offloads(n);
523     }
524 
525     for (i = 0;  i < n->max_queues; i++) {
526         NetClientState *nc = qemu_get_subqueue(n->nic, i);
527 
528         if (!get_vhost_net(nc->peer)) {
529             continue;
530         }
531         vhost_net_ack_features(get_vhost_net(nc->peer), features);
532     }
533 
534     if ((1 << VIRTIO_NET_F_CTRL_VLAN) & features) {
535         memset(n->vlans, 0, MAX_VLAN >> 3);
536     } else {
537         memset(n->vlans, 0xff, MAX_VLAN >> 3);
538     }
539 }
540 
541 static int virtio_net_handle_rx_mode(VirtIONet *n, uint8_t cmd,
542                                      struct iovec *iov, unsigned int iov_cnt)
543 {
544     uint8_t on;
545     size_t s;
546     NetClientState *nc = qemu_get_queue(n->nic);
547 
548     s = iov_to_buf(iov, iov_cnt, 0, &on, sizeof(on));
549     if (s != sizeof(on)) {
550         return VIRTIO_NET_ERR;
551     }
552 
553     if (cmd == VIRTIO_NET_CTRL_RX_PROMISC) {
554         n->promisc = on;
555     } else if (cmd == VIRTIO_NET_CTRL_RX_ALLMULTI) {
556         n->allmulti = on;
557     } else if (cmd == VIRTIO_NET_CTRL_RX_ALLUNI) {
558         n->alluni = on;
559     } else if (cmd == VIRTIO_NET_CTRL_RX_NOMULTI) {
560         n->nomulti = on;
561     } else if (cmd == VIRTIO_NET_CTRL_RX_NOUNI) {
562         n->nouni = on;
563     } else if (cmd == VIRTIO_NET_CTRL_RX_NOBCAST) {
564         n->nobcast = on;
565     } else {
566         return VIRTIO_NET_ERR;
567     }
568 
569     rxfilter_notify(nc);
570 
571     return VIRTIO_NET_OK;
572 }
573 
574 static int virtio_net_handle_offloads(VirtIONet *n, uint8_t cmd,
575                                      struct iovec *iov, unsigned int iov_cnt)
576 {
577     VirtIODevice *vdev = VIRTIO_DEVICE(n);
578     uint64_t offloads;
579     size_t s;
580 
581     if (!((1 << VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) & vdev->guest_features)) {
582         return VIRTIO_NET_ERR;
583     }
584 
585     s = iov_to_buf(iov, iov_cnt, 0, &offloads, sizeof(offloads));
586     if (s != sizeof(offloads)) {
587         return VIRTIO_NET_ERR;
588     }
589 
590     if (cmd == VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET) {
591         uint64_t supported_offloads;
592 
593         if (!n->has_vnet_hdr) {
594             return VIRTIO_NET_ERR;
595         }
596 
597         supported_offloads = virtio_net_supported_guest_offloads(n);
598         if (offloads & ~supported_offloads) {
599             return VIRTIO_NET_ERR;
600         }
601 
602         n->curr_guest_offloads = offloads;
603         virtio_net_apply_guest_offloads(n);
604 
605         return VIRTIO_NET_OK;
606     } else {
607         return VIRTIO_NET_ERR;
608     }
609 }
610 
611 static int virtio_net_handle_mac(VirtIONet *n, uint8_t cmd,
612                                  struct iovec *iov, unsigned int iov_cnt)
613 {
614     struct virtio_net_ctrl_mac mac_data;
615     size_t s;
616     NetClientState *nc = qemu_get_queue(n->nic);
617 
618     if (cmd == VIRTIO_NET_CTRL_MAC_ADDR_SET) {
619         if (iov_size(iov, iov_cnt) != sizeof(n->mac)) {
620             return VIRTIO_NET_ERR;
621         }
622         s = iov_to_buf(iov, iov_cnt, 0, &n->mac, sizeof(n->mac));
623         assert(s == sizeof(n->mac));
624         qemu_format_nic_info_str(qemu_get_queue(n->nic), n->mac);
625         rxfilter_notify(nc);
626 
627         return VIRTIO_NET_OK;
628     }
629 
630     if (cmd != VIRTIO_NET_CTRL_MAC_TABLE_SET) {
631         return VIRTIO_NET_ERR;
632     }
633 
634     int in_use = 0;
635     int first_multi = 0;
636     uint8_t uni_overflow = 0;
637     uint8_t multi_overflow = 0;
638     uint8_t *macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);
639 
640     s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,
641                    sizeof(mac_data.entries));
642     mac_data.entries = ldl_p(&mac_data.entries);
643     if (s != sizeof(mac_data.entries)) {
644         goto error;
645     }
646     iov_discard_front(&iov, &iov_cnt, s);
647 
648     if (mac_data.entries * ETH_ALEN > iov_size(iov, iov_cnt)) {
649         goto error;
650     }
651 
652     if (mac_data.entries <= MAC_TABLE_ENTRIES) {
653         s = iov_to_buf(iov, iov_cnt, 0, macs,
654                        mac_data.entries * ETH_ALEN);
655         if (s != mac_data.entries * ETH_ALEN) {
656             goto error;
657         }
658         in_use += mac_data.entries;
659     } else {
660         uni_overflow = 1;
661     }
662 
663     iov_discard_front(&iov, &iov_cnt, mac_data.entries * ETH_ALEN);
664 
665     first_multi = in_use;
666 
667     s = iov_to_buf(iov, iov_cnt, 0, &mac_data.entries,
668                    sizeof(mac_data.entries));
669     mac_data.entries = ldl_p(&mac_data.entries);
670     if (s != sizeof(mac_data.entries)) {
671         goto error;
672     }
673 
674     iov_discard_front(&iov, &iov_cnt, s);
675 
676     if (mac_data.entries * ETH_ALEN != iov_size(iov, iov_cnt)) {
677         goto error;
678     }
679 
680     if (mac_data.entries <= MAC_TABLE_ENTRIES - in_use) {
681         s = iov_to_buf(iov, iov_cnt, 0, &macs[in_use * ETH_ALEN],
682                        mac_data.entries * ETH_ALEN);
683         if (s != mac_data.entries * ETH_ALEN) {
684             goto error;
685         }
686         in_use += mac_data.entries;
687     } else {
688         multi_overflow = 1;
689     }
690 
691     n->mac_table.in_use = in_use;
692     n->mac_table.first_multi = first_multi;
693     n->mac_table.uni_overflow = uni_overflow;
694     n->mac_table.multi_overflow = multi_overflow;
695     memcpy(n->mac_table.macs, macs, MAC_TABLE_ENTRIES * ETH_ALEN);
696     g_free(macs);
697     rxfilter_notify(nc);
698 
699     return VIRTIO_NET_OK;
700 
701 error:
702     g_free(macs);
703     return VIRTIO_NET_ERR;
704 }
705 
706 static int virtio_net_handle_vlan_table(VirtIONet *n, uint8_t cmd,
707                                         struct iovec *iov, unsigned int iov_cnt)
708 {
709     uint16_t vid;
710     size_t s;
711     NetClientState *nc = qemu_get_queue(n->nic);
712 
713     s = iov_to_buf(iov, iov_cnt, 0, &vid, sizeof(vid));
714     vid = lduw_p(&vid);
715     if (s != sizeof(vid)) {
716         return VIRTIO_NET_ERR;
717     }
718 
719     if (vid >= MAX_VLAN)
720         return VIRTIO_NET_ERR;
721 
722     if (cmd == VIRTIO_NET_CTRL_VLAN_ADD)
723         n->vlans[vid >> 5] |= (1U << (vid & 0x1f));
724     else if (cmd == VIRTIO_NET_CTRL_VLAN_DEL)
725         n->vlans[vid >> 5] &= ~(1U << (vid & 0x1f));
726     else
727         return VIRTIO_NET_ERR;
728 
729     rxfilter_notify(nc);
730 
731     return VIRTIO_NET_OK;
732 }
733 
734 static int virtio_net_handle_announce(VirtIONet *n, uint8_t cmd,
735                                       struct iovec *iov, unsigned int iov_cnt)
736 {
737     if (cmd == VIRTIO_NET_CTRL_ANNOUNCE_ACK &&
738         n->status & VIRTIO_NET_S_ANNOUNCE) {
739         n->status &= ~VIRTIO_NET_S_ANNOUNCE;
740         if (n->announce_counter) {
741             timer_mod(n->announce_timer,
742                       qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
743                       self_announce_delay(n->announce_counter));
744         }
745         return VIRTIO_NET_OK;
746     } else {
747         return VIRTIO_NET_ERR;
748     }
749 }
750 
751 static int virtio_net_handle_mq(VirtIONet *n, uint8_t cmd,
752                                 struct iovec *iov, unsigned int iov_cnt)
753 {
754     VirtIODevice *vdev = VIRTIO_DEVICE(n);
755     struct virtio_net_ctrl_mq mq;
756     size_t s;
757     uint16_t queues;
758 
759     s = iov_to_buf(iov, iov_cnt, 0, &mq, sizeof(mq));
760     if (s != sizeof(mq)) {
761         return VIRTIO_NET_ERR;
762     }
763 
764     if (cmd != VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET) {
765         return VIRTIO_NET_ERR;
766     }
767 
768     queues = lduw_p(&mq.virtqueue_pairs);
769 
770     if (queues < VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MIN ||
771         queues > VIRTIO_NET_CTRL_MQ_VQ_PAIRS_MAX ||
772         queues > n->max_queues ||
773         !n->multiqueue) {
774         return VIRTIO_NET_ERR;
775     }
776 
777     n->curr_queues = queues;
778     /* stop the backend before changing the number of queues to avoid handling a
779      * disabled queue */
780     virtio_net_set_status(vdev, vdev->status);
781     virtio_net_set_queues(n);
782 
783     return VIRTIO_NET_OK;
784 }
785 static void virtio_net_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)
786 {
787     VirtIONet *n = VIRTIO_NET(vdev);
788     struct virtio_net_ctrl_hdr ctrl;
789     virtio_net_ctrl_ack status = VIRTIO_NET_ERR;
790     VirtQueueElement elem;
791     size_t s;
792     struct iovec *iov;
793     unsigned int iov_cnt;
794 
795     while (virtqueue_pop(vq, &elem)) {
796         if (iov_size(elem.in_sg, elem.in_num) < sizeof(status) ||
797             iov_size(elem.out_sg, elem.out_num) < sizeof(ctrl)) {
798             error_report("virtio-net ctrl missing headers");
799             exit(1);
800         }
801 
802         iov = elem.out_sg;
803         iov_cnt = elem.out_num;
804         s = iov_to_buf(iov, iov_cnt, 0, &ctrl, sizeof(ctrl));
805         iov_discard_front(&iov, &iov_cnt, sizeof(ctrl));
806         if (s != sizeof(ctrl)) {
807             status = VIRTIO_NET_ERR;
808         } else if (ctrl.class == VIRTIO_NET_CTRL_RX) {
809             status = virtio_net_handle_rx_mode(n, ctrl.cmd, iov, iov_cnt);
810         } else if (ctrl.class == VIRTIO_NET_CTRL_MAC) {
811             status = virtio_net_handle_mac(n, ctrl.cmd, iov, iov_cnt);
812         } else if (ctrl.class == VIRTIO_NET_CTRL_VLAN) {
813             status = virtio_net_handle_vlan_table(n, ctrl.cmd, iov, iov_cnt);
814         } else if (ctrl.class == VIRTIO_NET_CTRL_ANNOUNCE) {
815             status = virtio_net_handle_announce(n, ctrl.cmd, iov, iov_cnt);
816         } else if (ctrl.class == VIRTIO_NET_CTRL_MQ) {
817             status = virtio_net_handle_mq(n, ctrl.cmd, iov, iov_cnt);
818         } else if (ctrl.class == VIRTIO_NET_CTRL_GUEST_OFFLOADS) {
819             status = virtio_net_handle_offloads(n, ctrl.cmd, iov, iov_cnt);
820         }
821 
822         s = iov_from_buf(elem.in_sg, elem.in_num, 0, &status, sizeof(status));
823         assert(s == sizeof(status));
824 
825         virtqueue_push(vq, &elem, sizeof(status));
826         virtio_notify(vdev, vq);
827     }
828 }
829 
830 /* RX */
831 
832 static void virtio_net_handle_rx(VirtIODevice *vdev, VirtQueue *vq)
833 {
834     VirtIONet *n = VIRTIO_NET(vdev);
835     int queue_index = vq2q(virtio_get_queue_index(vq));
836 
837     qemu_flush_queued_packets(qemu_get_subqueue(n->nic, queue_index));
838 }
839 
840 static int virtio_net_can_receive(NetClientState *nc)
841 {
842     VirtIONet *n = qemu_get_nic_opaque(nc);
843     VirtIODevice *vdev = VIRTIO_DEVICE(n);
844     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
845 
846     if (!vdev->vm_running) {
847         return 0;
848     }
849 
850     if (nc->queue_index >= n->curr_queues) {
851         return 0;
852     }
853 
854     if (!virtio_queue_ready(q->rx_vq) ||
855         !(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
856         return 0;
857     }
858 
859     return 1;
860 }
861 
862 static int virtio_net_has_buffers(VirtIONetQueue *q, int bufsize)
863 {
864     VirtIONet *n = q->n;
865     if (virtio_queue_empty(q->rx_vq) ||
866         (n->mergeable_rx_bufs &&
867          !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
868         virtio_queue_set_notification(q->rx_vq, 1);
869 
870         /* To avoid a race condition where the guest has made some buffers
871          * available after the above check but before notification was
872          * enabled, check for available buffers again.
873          */
874         if (virtio_queue_empty(q->rx_vq) ||
875             (n->mergeable_rx_bufs &&
876              !virtqueue_avail_bytes(q->rx_vq, bufsize, 0))) {
877             return 0;
878         }
879     }
880 
881     virtio_queue_set_notification(q->rx_vq, 0);
882     return 1;
883 }
884 
885 /* dhclient uses AF_PACKET but doesn't pass auxdata to the kernel so
886  * it never finds out that the packets don't have valid checksums.  This
887  * causes dhclient to get upset.  Fedora's carried a patch for ages to
888  * fix this with Xen but it hasn't appeared in an upstream release of
889  * dhclient yet.
890  *
891  * To avoid breaking existing guests, we catch udp packets and add
892  * checksums.  This is terrible but it's better than hacking the guest
893  * kernels.
894  *
895  * N.B. if we introduce a zero-copy API, this operation is no longer free so
896  * we should provide a mechanism to disable it to avoid polluting the host
897  * cache.
898  */
899 static void work_around_broken_dhclient(struct virtio_net_hdr *hdr,
900                                         uint8_t *buf, size_t size)
901 {
902     if ((hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && /* missing csum */
903         (size > 27 && size < 1500) && /* normal sized MTU */
904         (buf[12] == 0x08 && buf[13] == 0x00) && /* ethertype == IPv4 */
905         (buf[23] == 17) && /* ip.protocol == UDP */
906         (buf[34] == 0 && buf[35] == 67)) { /* udp.srcport == bootps */
907         net_checksum_calculate(buf, size);
908         hdr->flags &= ~VIRTIO_NET_HDR_F_NEEDS_CSUM;
909     }
910 }
911 
912 static void receive_header(VirtIONet *n, const struct iovec *iov, int iov_cnt,
913                            const void *buf, size_t size)
914 {
915     if (n->has_vnet_hdr) {
916         /* FIXME this cast is evil */
917         void *wbuf = (void *)buf;
918         work_around_broken_dhclient(wbuf, wbuf + n->host_hdr_len,
919                                     size - n->host_hdr_len);
920         iov_from_buf(iov, iov_cnt, 0, buf, sizeof(struct virtio_net_hdr));
921     } else {
922         struct virtio_net_hdr hdr = {
923             .flags = 0,
924             .gso_type = VIRTIO_NET_HDR_GSO_NONE
925         };
926         iov_from_buf(iov, iov_cnt, 0, &hdr, sizeof hdr);
927     }
928 }
929 
930 static int receive_filter(VirtIONet *n, const uint8_t *buf, int size)
931 {
932     static const uint8_t bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
933     static const uint8_t vlan[] = {0x81, 0x00};
934     uint8_t *ptr = (uint8_t *)buf;
935     int i;
936 
937     if (n->promisc)
938         return 1;
939 
940     ptr += n->host_hdr_len;
941 
942     if (!memcmp(&ptr[12], vlan, sizeof(vlan))) {
943         int vid = be16_to_cpup((uint16_t *)(ptr + 14)) & 0xfff;
944         if (!(n->vlans[vid >> 5] & (1U << (vid & 0x1f))))
945             return 0;
946     }
947 
948     if (ptr[0] & 1) { // multicast
949         if (!memcmp(ptr, bcast, sizeof(bcast))) {
950             return !n->nobcast;
951         } else if (n->nomulti) {
952             return 0;
953         } else if (n->allmulti || n->mac_table.multi_overflow) {
954             return 1;
955         }
956 
957         for (i = n->mac_table.first_multi; i < n->mac_table.in_use; i++) {
958             if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
959                 return 1;
960             }
961         }
962     } else { // unicast
963         if (n->nouni) {
964             return 0;
965         } else if (n->alluni || n->mac_table.uni_overflow) {
966             return 1;
967         } else if (!memcmp(ptr, n->mac, ETH_ALEN)) {
968             return 1;
969         }
970 
971         for (i = 0; i < n->mac_table.first_multi; i++) {
972             if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN)) {
973                 return 1;
974             }
975         }
976     }
977 
978     return 0;
979 }
980 
981 static ssize_t virtio_net_receive(NetClientState *nc, const uint8_t *buf, size_t size)
982 {
983     VirtIONet *n = qemu_get_nic_opaque(nc);
984     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
985     VirtIODevice *vdev = VIRTIO_DEVICE(n);
986     struct iovec mhdr_sg[VIRTQUEUE_MAX_SIZE];
987     struct virtio_net_hdr_mrg_rxbuf mhdr;
988     unsigned mhdr_cnt = 0;
989     size_t offset, i, guest_offset;
990 
991     if (!virtio_net_can_receive(nc)) {
992         return -1;
993     }
994 
995     /* hdr_len refers to the header we supply to the guest */
996     if (!virtio_net_has_buffers(q, size + n->guest_hdr_len - n->host_hdr_len)) {
997         return 0;
998     }
999 
1000     if (!receive_filter(n, buf, size))
1001         return size;
1002 
1003     offset = i = 0;
1004 
1005     while (offset < size) {
1006         VirtQueueElement elem;
1007         int len, total;
1008         const struct iovec *sg = elem.in_sg;
1009 
1010         total = 0;
1011 
1012         if (virtqueue_pop(q->rx_vq, &elem) == 0) {
1013             if (i == 0)
1014                 return -1;
1015             error_report("virtio-net unexpected empty queue: "
1016                     "i %zd mergeable %d offset %zd, size %zd, "
1017                     "guest hdr len %zd, host hdr len %zd guest features 0x%x",
1018                     i, n->mergeable_rx_bufs, offset, size,
1019                     n->guest_hdr_len, n->host_hdr_len, vdev->guest_features);
1020             exit(1);
1021         }
1022 
1023         if (elem.in_num < 1) {
1024             error_report("virtio-net receive queue contains no in buffers");
1025             exit(1);
1026         }
1027 
1028         if (i == 0) {
1029             assert(offset == 0);
1030             if (n->mergeable_rx_bufs) {
1031                 mhdr_cnt = iov_copy(mhdr_sg, ARRAY_SIZE(mhdr_sg),
1032                                     sg, elem.in_num,
1033                                     offsetof(typeof(mhdr), num_buffers),
1034                                     sizeof(mhdr.num_buffers));
1035             }
1036 
1037             receive_header(n, sg, elem.in_num, buf, size);
1038             offset = n->host_hdr_len;
1039             total += n->guest_hdr_len;
1040             guest_offset = n->guest_hdr_len;
1041         } else {
1042             guest_offset = 0;
1043         }
1044 
1045         /* copy in packet.  ugh */
1046         len = iov_from_buf(sg, elem.in_num, guest_offset,
1047                            buf + offset, size - offset);
1048         total += len;
1049         offset += len;
1050         /* If buffers can't be merged, at this point we
1051          * must have consumed the complete packet.
1052          * Otherwise, drop it. */
1053         if (!n->mergeable_rx_bufs && offset < size) {
1054 #if 0
1055             error_report("virtio-net truncated non-mergeable packet: "
1056                          "i %zd mergeable %d offset %zd, size %zd, "
1057                          "guest hdr len %zd, host hdr len %zd",
1058                          i, n->mergeable_rx_bufs,
1059                          offset, size, n->guest_hdr_len, n->host_hdr_len);
1060 #endif
1061             return size;
1062         }
1063 
1064         /* signal other side */
1065         virtqueue_fill(q->rx_vq, &elem, total, i++);
1066     }
1067 
1068     if (mhdr_cnt) {
1069         stw_p(&mhdr.num_buffers, i);
1070         iov_from_buf(mhdr_sg, mhdr_cnt,
1071                      0,
1072                      &mhdr.num_buffers, sizeof mhdr.num_buffers);
1073     }
1074 
1075     virtqueue_flush(q->rx_vq, i);
1076     virtio_notify(vdev, q->rx_vq);
1077 
1078     return size;
1079 }
1080 
1081 static int32_t virtio_net_flush_tx(VirtIONetQueue *q);
1082 
1083 static void virtio_net_tx_complete(NetClientState *nc, ssize_t len)
1084 {
1085     VirtIONet *n = qemu_get_nic_opaque(nc);
1086     VirtIONetQueue *q = virtio_net_get_subqueue(nc);
1087     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1088 
1089     virtqueue_push(q->tx_vq, &q->async_tx.elem, 0);
1090     virtio_notify(vdev, q->tx_vq);
1091 
1092     q->async_tx.elem.out_num = q->async_tx.len = 0;
1093 
1094     virtio_queue_set_notification(q->tx_vq, 1);
1095     virtio_net_flush_tx(q);
1096 }
1097 
1098 /* TX */
1099 static int32_t virtio_net_flush_tx(VirtIONetQueue *q)
1100 {
1101     VirtIONet *n = q->n;
1102     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1103     VirtQueueElement elem;
1104     int32_t num_packets = 0;
1105     int queue_index = vq2q(virtio_get_queue_index(q->tx_vq));
1106     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1107         return num_packets;
1108     }
1109 
1110     assert(vdev->vm_running);
1111 
1112     if (q->async_tx.elem.out_num) {
1113         virtio_queue_set_notification(q->tx_vq, 0);
1114         return num_packets;
1115     }
1116 
1117     while (virtqueue_pop(q->tx_vq, &elem)) {
1118         ssize_t ret, len;
1119         unsigned int out_num = elem.out_num;
1120         struct iovec *out_sg = &elem.out_sg[0];
1121         struct iovec sg[VIRTQUEUE_MAX_SIZE];
1122 
1123         if (out_num < 1) {
1124             error_report("virtio-net header not in first element");
1125             exit(1);
1126         }
1127 
1128         /*
1129          * If host wants to see the guest header as is, we can
1130          * pass it on unchanged. Otherwise, copy just the parts
1131          * that host is interested in.
1132          */
1133         assert(n->host_hdr_len <= n->guest_hdr_len);
1134         if (n->host_hdr_len != n->guest_hdr_len) {
1135             unsigned sg_num = iov_copy(sg, ARRAY_SIZE(sg),
1136                                        out_sg, out_num,
1137                                        0, n->host_hdr_len);
1138             sg_num += iov_copy(sg + sg_num, ARRAY_SIZE(sg) - sg_num,
1139                              out_sg, out_num,
1140                              n->guest_hdr_len, -1);
1141             out_num = sg_num;
1142             out_sg = sg;
1143         }
1144 
1145         len = n->guest_hdr_len;
1146 
1147         ret = qemu_sendv_packet_async(qemu_get_subqueue(n->nic, queue_index),
1148                                       out_sg, out_num, virtio_net_tx_complete);
1149         if (ret == 0) {
1150             virtio_queue_set_notification(q->tx_vq, 0);
1151             q->async_tx.elem = elem;
1152             q->async_tx.len  = len;
1153             return -EBUSY;
1154         }
1155 
1156         len += ret;
1157 
1158         virtqueue_push(q->tx_vq, &elem, 0);
1159         virtio_notify(vdev, q->tx_vq);
1160 
1161         if (++num_packets >= n->tx_burst) {
1162             break;
1163         }
1164     }
1165     return num_packets;
1166 }
1167 
1168 static void virtio_net_handle_tx_timer(VirtIODevice *vdev, VirtQueue *vq)
1169 {
1170     VirtIONet *n = VIRTIO_NET(vdev);
1171     VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
1172 
1173     /* This happens when device was stopped but VCPU wasn't. */
1174     if (!vdev->vm_running) {
1175         q->tx_waiting = 1;
1176         return;
1177     }
1178 
1179     if (q->tx_waiting) {
1180         virtio_queue_set_notification(vq, 1);
1181         timer_del(q->tx_timer);
1182         q->tx_waiting = 0;
1183         virtio_net_flush_tx(q);
1184     } else {
1185         timer_mod(q->tx_timer,
1186                        qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + n->tx_timeout);
1187         q->tx_waiting = 1;
1188         virtio_queue_set_notification(vq, 0);
1189     }
1190 }
1191 
1192 static void virtio_net_handle_tx_bh(VirtIODevice *vdev, VirtQueue *vq)
1193 {
1194     VirtIONet *n = VIRTIO_NET(vdev);
1195     VirtIONetQueue *q = &n->vqs[vq2q(virtio_get_queue_index(vq))];
1196 
1197     if (unlikely(q->tx_waiting)) {
1198         return;
1199     }
1200     q->tx_waiting = 1;
1201     /* This happens when device was stopped but VCPU wasn't. */
1202     if (!vdev->vm_running) {
1203         return;
1204     }
1205     virtio_queue_set_notification(vq, 0);
1206     qemu_bh_schedule(q->tx_bh);
1207 }
1208 
1209 static void virtio_net_tx_timer(void *opaque)
1210 {
1211     VirtIONetQueue *q = opaque;
1212     VirtIONet *n = q->n;
1213     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1214     assert(vdev->vm_running);
1215 
1216     q->tx_waiting = 0;
1217 
1218     /* Just in case the driver is not ready on more */
1219     if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {
1220         return;
1221     }
1222 
1223     virtio_queue_set_notification(q->tx_vq, 1);
1224     virtio_net_flush_tx(q);
1225 }
1226 
1227 static void virtio_net_tx_bh(void *opaque)
1228 {
1229     VirtIONetQueue *q = opaque;
1230     VirtIONet *n = q->n;
1231     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1232     int32_t ret;
1233 
1234     assert(vdev->vm_running);
1235 
1236     q->tx_waiting = 0;
1237 
1238     /* Just in case the driver is not ready on more */
1239     if (unlikely(!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))) {
1240         return;
1241     }
1242 
1243     ret = virtio_net_flush_tx(q);
1244     if (ret == -EBUSY) {
1245         return; /* Notification re-enable handled by tx_complete */
1246     }
1247 
1248     /* If we flush a full burst of packets, assume there are
1249      * more coming and immediately reschedule */
1250     if (ret >= n->tx_burst) {
1251         qemu_bh_schedule(q->tx_bh);
1252         q->tx_waiting = 1;
1253         return;
1254     }
1255 
1256     /* If less than a full burst, re-enable notification and flush
1257      * anything that may have come in while we weren't looking.  If
1258      * we find something, assume the guest is still active and reschedule */
1259     virtio_queue_set_notification(q->tx_vq, 1);
1260     if (virtio_net_flush_tx(q) > 0) {
1261         virtio_queue_set_notification(q->tx_vq, 0);
1262         qemu_bh_schedule(q->tx_bh);
1263         q->tx_waiting = 1;
1264     }
1265 }
1266 
1267 static void virtio_net_set_multiqueue(VirtIONet *n, int multiqueue)
1268 {
1269     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1270     int i, max = multiqueue ? n->max_queues : 1;
1271 
1272     n->multiqueue = multiqueue;
1273 
1274     for (i = 2; i <= n->max_queues * 2 + 1; i++) {
1275         virtio_del_queue(vdev, i);
1276     }
1277 
1278     for (i = 1; i < max; i++) {
1279         n->vqs[i].rx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_rx);
1280         if (n->vqs[i].tx_timer) {
1281             n->vqs[i].tx_vq =
1282                 virtio_add_queue(vdev, 256, virtio_net_handle_tx_timer);
1283             n->vqs[i].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,
1284                                                    virtio_net_tx_timer,
1285                                                    &n->vqs[i]);
1286         } else {
1287             n->vqs[i].tx_vq =
1288                 virtio_add_queue(vdev, 256, virtio_net_handle_tx_bh);
1289             n->vqs[i].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[i]);
1290         }
1291 
1292         n->vqs[i].tx_waiting = 0;
1293         n->vqs[i].n = n;
1294     }
1295 
1296     /* Note: Minux Guests (version 3.2.1) use ctrl vq but don't ack
1297      * VIRTIO_NET_F_CTRL_VQ. Create ctrl vq unconditionally to avoid
1298      * breaking them.
1299      */
1300     n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
1301 
1302     virtio_net_set_queues(n);
1303 }
1304 
1305 static void virtio_net_save(QEMUFile *f, void *opaque)
1306 {
1307     int i;
1308     VirtIONet *n = opaque;
1309     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1310 
1311     /* At this point, backend must be stopped, otherwise
1312      * it might keep writing to memory. */
1313     assert(!n->vhost_started);
1314     virtio_save(vdev, f);
1315 
1316     qemu_put_buffer(f, n->mac, ETH_ALEN);
1317     qemu_put_be32(f, n->vqs[0].tx_waiting);
1318     qemu_put_be32(f, n->mergeable_rx_bufs);
1319     qemu_put_be16(f, n->status);
1320     qemu_put_byte(f, n->promisc);
1321     qemu_put_byte(f, n->allmulti);
1322     qemu_put_be32(f, n->mac_table.in_use);
1323     qemu_put_buffer(f, n->mac_table.macs, n->mac_table.in_use * ETH_ALEN);
1324     qemu_put_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3);
1325     qemu_put_be32(f, n->has_vnet_hdr);
1326     qemu_put_byte(f, n->mac_table.multi_overflow);
1327     qemu_put_byte(f, n->mac_table.uni_overflow);
1328     qemu_put_byte(f, n->alluni);
1329     qemu_put_byte(f, n->nomulti);
1330     qemu_put_byte(f, n->nouni);
1331     qemu_put_byte(f, n->nobcast);
1332     qemu_put_byte(f, n->has_ufo);
1333     if (n->max_queues > 1) {
1334         qemu_put_be16(f, n->max_queues);
1335         qemu_put_be16(f, n->curr_queues);
1336         for (i = 1; i < n->curr_queues; i++) {
1337             qemu_put_be32(f, n->vqs[i].tx_waiting);
1338         }
1339     }
1340 
1341     if ((1 << VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) & vdev->guest_features) {
1342         qemu_put_be64(f, n->curr_guest_offloads);
1343     }
1344 }
1345 
1346 static int virtio_net_load(QEMUFile *f, void *opaque, int version_id)
1347 {
1348     VirtIONet *n = opaque;
1349     VirtIODevice *vdev = VIRTIO_DEVICE(n);
1350     int ret, i, link_down;
1351 
1352     if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION)
1353         return -EINVAL;
1354 
1355     ret = virtio_load(vdev, f);
1356     if (ret) {
1357         return ret;
1358     }
1359 
1360     qemu_get_buffer(f, n->mac, ETH_ALEN);
1361     n->vqs[0].tx_waiting = qemu_get_be32(f);
1362 
1363     virtio_net_set_mrg_rx_bufs(n, qemu_get_be32(f));
1364 
1365     if (version_id >= 3)
1366         n->status = qemu_get_be16(f);
1367 
1368     if (version_id >= 4) {
1369         if (version_id < 8) {
1370             n->promisc = qemu_get_be32(f);
1371             n->allmulti = qemu_get_be32(f);
1372         } else {
1373             n->promisc = qemu_get_byte(f);
1374             n->allmulti = qemu_get_byte(f);
1375         }
1376     }
1377 
1378     if (version_id >= 5) {
1379         n->mac_table.in_use = qemu_get_be32(f);
1380         /* MAC_TABLE_ENTRIES may be different from the saved image */
1381         if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) {
1382             qemu_get_buffer(f, n->mac_table.macs,
1383                             n->mac_table.in_use * ETH_ALEN);
1384         } else {
1385             int64_t i;
1386 
1387             /* Overflow detected - can happen if source has a larger MAC table.
1388              * We simply set overflow flag so there's no need to maintain the
1389              * table of addresses, discard them all.
1390              * Note: 64 bit math to avoid integer overflow.
1391              */
1392             for (i = 0; i < (int64_t)n->mac_table.in_use * ETH_ALEN; ++i) {
1393                 qemu_get_byte(f);
1394             }
1395             n->mac_table.multi_overflow = n->mac_table.uni_overflow = 1;
1396             n->mac_table.in_use = 0;
1397         }
1398     }
1399 
1400     if (version_id >= 6)
1401         qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3);
1402 
1403     if (version_id >= 7) {
1404         if (qemu_get_be32(f) && !peer_has_vnet_hdr(n)) {
1405             error_report("virtio-net: saved image requires vnet_hdr=on");
1406             return -1;
1407         }
1408     }
1409 
1410     if (version_id >= 9) {
1411         n->mac_table.multi_overflow = qemu_get_byte(f);
1412         n->mac_table.uni_overflow = qemu_get_byte(f);
1413     }
1414 
1415     if (version_id >= 10) {
1416         n->alluni = qemu_get_byte(f);
1417         n->nomulti = qemu_get_byte(f);
1418         n->nouni = qemu_get_byte(f);
1419         n->nobcast = qemu_get_byte(f);
1420     }
1421 
1422     if (version_id >= 11) {
1423         if (qemu_get_byte(f) && !peer_has_ufo(n)) {
1424             error_report("virtio-net: saved image requires TUN_F_UFO support");
1425             return -1;
1426         }
1427     }
1428 
1429     if (n->max_queues > 1) {
1430         if (n->max_queues != qemu_get_be16(f)) {
1431             error_report("virtio-net: different max_queues ");
1432             return -1;
1433         }
1434 
1435         n->curr_queues = qemu_get_be16(f);
1436         if (n->curr_queues > n->max_queues) {
1437             error_report("virtio-net: curr_queues %x > max_queues %x",
1438                          n->curr_queues, n->max_queues);
1439             return -1;
1440         }
1441         for (i = 1; i < n->curr_queues; i++) {
1442             n->vqs[i].tx_waiting = qemu_get_be32(f);
1443         }
1444     }
1445 
1446     if ((1 << VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) & vdev->guest_features) {
1447         n->curr_guest_offloads = qemu_get_be64(f);
1448     } else {
1449         n->curr_guest_offloads = virtio_net_supported_guest_offloads(n);
1450     }
1451 
1452     if (peer_has_vnet_hdr(n)) {
1453         virtio_net_apply_guest_offloads(n);
1454     }
1455 
1456     virtio_net_set_queues(n);
1457 
1458     /* Find the first multicast entry in the saved MAC filter */
1459     for (i = 0; i < n->mac_table.in_use; i++) {
1460         if (n->mac_table.macs[i * ETH_ALEN] & 1) {
1461             break;
1462         }
1463     }
1464     n->mac_table.first_multi = i;
1465 
1466     /* nc.link_down can't be migrated, so infer link_down according
1467      * to link status bit in n->status */
1468     link_down = (n->status & VIRTIO_NET_S_LINK_UP) == 0;
1469     for (i = 0; i < n->max_queues; i++) {
1470         qemu_get_subqueue(n->nic, i)->link_down = link_down;
1471     }
1472 
1473     if (vdev->guest_features & (0x1 << VIRTIO_NET_F_GUEST_ANNOUNCE) &&
1474         vdev->guest_features & (0x1 << VIRTIO_NET_F_CTRL_VQ)) {
1475         n->announce_counter = SELF_ANNOUNCE_ROUNDS;
1476         timer_mod(n->announce_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL));
1477     }
1478 
1479     return 0;
1480 }
1481 
1482 static void virtio_net_cleanup(NetClientState *nc)
1483 {
1484     VirtIONet *n = qemu_get_nic_opaque(nc);
1485 
1486     n->nic = NULL;
1487 }
1488 
1489 static NetClientInfo net_virtio_info = {
1490     .type = NET_CLIENT_OPTIONS_KIND_NIC,
1491     .size = sizeof(NICState),
1492     .can_receive = virtio_net_can_receive,
1493     .receive = virtio_net_receive,
1494     .cleanup = virtio_net_cleanup,
1495     .link_status_changed = virtio_net_set_link_status,
1496     .query_rx_filter = virtio_net_query_rxfilter,
1497 };
1498 
1499 static bool virtio_net_guest_notifier_pending(VirtIODevice *vdev, int idx)
1500 {
1501     VirtIONet *n = VIRTIO_NET(vdev);
1502     NetClientState *nc = qemu_get_subqueue(n->nic, vq2q(idx));
1503     assert(n->vhost_started);
1504     return vhost_net_virtqueue_pending(get_vhost_net(nc->peer), idx);
1505 }
1506 
1507 static void virtio_net_guest_notifier_mask(VirtIODevice *vdev, int idx,
1508                                            bool mask)
1509 {
1510     VirtIONet *n = VIRTIO_NET(vdev);
1511     NetClientState *nc = qemu_get_subqueue(n->nic, vq2q(idx));
1512     assert(n->vhost_started);
1513     vhost_net_virtqueue_mask(get_vhost_net(nc->peer),
1514                              vdev, idx, mask);
1515 }
1516 
1517 void virtio_net_set_config_size(VirtIONet *n, uint32_t host_features)
1518 {
1519     int i, config_size = 0;
1520     host_features |= (1 << VIRTIO_NET_F_MAC);
1521     for (i = 0; feature_sizes[i].flags != 0; i++) {
1522         if (host_features & feature_sizes[i].flags) {
1523             config_size = MAX(feature_sizes[i].end, config_size);
1524         }
1525     }
1526     n->config_size = config_size;
1527 }
1528 
1529 void virtio_net_set_netclient_name(VirtIONet *n, const char *name,
1530                                    const char *type)
1531 {
1532     /*
1533      * The name can be NULL, the netclient name will be type.x.
1534      */
1535     assert(type != NULL);
1536 
1537     g_free(n->netclient_name);
1538     g_free(n->netclient_type);
1539     n->netclient_name = g_strdup(name);
1540     n->netclient_type = g_strdup(type);
1541 }
1542 
1543 static void virtio_net_device_realize(DeviceState *dev, Error **errp)
1544 {
1545     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1546     VirtIONet *n = VIRTIO_NET(dev);
1547     NetClientState *nc;
1548     int i;
1549 
1550     virtio_init(vdev, "virtio-net", VIRTIO_ID_NET, n->config_size);
1551 
1552     n->max_queues = MAX(n->nic_conf.queues, 1);
1553     n->vqs = g_malloc0(sizeof(VirtIONetQueue) * n->max_queues);
1554     n->vqs[0].rx_vq = virtio_add_queue(vdev, 256, virtio_net_handle_rx);
1555     n->curr_queues = 1;
1556     n->vqs[0].n = n;
1557     n->tx_timeout = n->net_conf.txtimer;
1558 
1559     if (n->net_conf.tx && strcmp(n->net_conf.tx, "timer")
1560                        && strcmp(n->net_conf.tx, "bh")) {
1561         error_report("virtio-net: "
1562                      "Unknown option tx=%s, valid options: \"timer\" \"bh\"",
1563                      n->net_conf.tx);
1564         error_report("Defaulting to \"bh\"");
1565     }
1566 
1567     if (n->net_conf.tx && !strcmp(n->net_conf.tx, "timer")) {
1568         n->vqs[0].tx_vq = virtio_add_queue(vdev, 256,
1569                                            virtio_net_handle_tx_timer);
1570         n->vqs[0].tx_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, virtio_net_tx_timer,
1571                                                &n->vqs[0]);
1572     } else {
1573         n->vqs[0].tx_vq = virtio_add_queue(vdev, 256,
1574                                            virtio_net_handle_tx_bh);
1575         n->vqs[0].tx_bh = qemu_bh_new(virtio_net_tx_bh, &n->vqs[0]);
1576     }
1577     n->ctrl_vq = virtio_add_queue(vdev, 64, virtio_net_handle_ctrl);
1578     qemu_macaddr_default_if_unset(&n->nic_conf.macaddr);
1579     memcpy(&n->mac[0], &n->nic_conf.macaddr, sizeof(n->mac));
1580     n->status = VIRTIO_NET_S_LINK_UP;
1581     n->announce_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL,
1582                                      virtio_net_announce_timer, n);
1583 
1584     if (n->netclient_type) {
1585         /*
1586          * Happen when virtio_net_set_netclient_name has been called.
1587          */
1588         n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
1589                               n->netclient_type, n->netclient_name, n);
1590     } else {
1591         n->nic = qemu_new_nic(&net_virtio_info, &n->nic_conf,
1592                               object_get_typename(OBJECT(dev)), dev->id, n);
1593     }
1594 
1595     peer_test_vnet_hdr(n);
1596     if (peer_has_vnet_hdr(n)) {
1597         for (i = 0; i < n->max_queues; i++) {
1598             qemu_using_vnet_hdr(qemu_get_subqueue(n->nic, i)->peer, true);
1599         }
1600         n->host_hdr_len = sizeof(struct virtio_net_hdr);
1601     } else {
1602         n->host_hdr_len = 0;
1603     }
1604 
1605     qemu_format_nic_info_str(qemu_get_queue(n->nic), n->nic_conf.macaddr.a);
1606 
1607     n->vqs[0].tx_waiting = 0;
1608     n->tx_burst = n->net_conf.txburst;
1609     virtio_net_set_mrg_rx_bufs(n, 0);
1610     n->promisc = 1; /* for compatibility */
1611 
1612     n->mac_table.macs = g_malloc0(MAC_TABLE_ENTRIES * ETH_ALEN);
1613 
1614     n->vlans = g_malloc0(MAX_VLAN >> 3);
1615 
1616     nc = qemu_get_queue(n->nic);
1617     nc->rxfilter_notify_enabled = 1;
1618 
1619     n->qdev = dev;
1620     register_savevm(dev, "virtio-net", -1, VIRTIO_NET_VM_VERSION,
1621                     virtio_net_save, virtio_net_load, n);
1622 
1623     add_boot_device_path(n->nic_conf.bootindex, dev, "/ethernet-phy@0");
1624 }
1625 
1626 static void virtio_net_device_unrealize(DeviceState *dev, Error **errp)
1627 {
1628     VirtIODevice *vdev = VIRTIO_DEVICE(dev);
1629     VirtIONet *n = VIRTIO_NET(dev);
1630     int i;
1631 
1632     /* This will stop vhost backend if appropriate. */
1633     virtio_net_set_status(vdev, 0);
1634 
1635     unregister_savevm(dev, "virtio-net", n);
1636 
1637     g_free(n->netclient_name);
1638     n->netclient_name = NULL;
1639     g_free(n->netclient_type);
1640     n->netclient_type = NULL;
1641 
1642     g_free(n->mac_table.macs);
1643     g_free(n->vlans);
1644 
1645     for (i = 0; i < n->max_queues; i++) {
1646         VirtIONetQueue *q = &n->vqs[i];
1647         NetClientState *nc = qemu_get_subqueue(n->nic, i);
1648 
1649         qemu_purge_queued_packets(nc);
1650 
1651         if (q->tx_timer) {
1652             timer_del(q->tx_timer);
1653             timer_free(q->tx_timer);
1654         } else if (q->tx_bh) {
1655             qemu_bh_delete(q->tx_bh);
1656         }
1657     }
1658 
1659     timer_del(n->announce_timer);
1660     timer_free(n->announce_timer);
1661     g_free(n->vqs);
1662     qemu_del_nic(n->nic);
1663     virtio_cleanup(vdev);
1664 }
1665 
1666 static void virtio_net_instance_init(Object *obj)
1667 {
1668     VirtIONet *n = VIRTIO_NET(obj);
1669 
1670     /*
1671      * The default config_size is sizeof(struct virtio_net_config).
1672      * Can be overriden with virtio_net_set_config_size.
1673      */
1674     n->config_size = sizeof(struct virtio_net_config);
1675 }
1676 
1677 static Property virtio_net_properties[] = {
1678     DEFINE_NIC_PROPERTIES(VirtIONet, nic_conf),
1679     DEFINE_PROP_UINT32("x-txtimer", VirtIONet, net_conf.txtimer,
1680                                                TX_TIMER_INTERVAL),
1681     DEFINE_PROP_INT32("x-txburst", VirtIONet, net_conf.txburst, TX_BURST),
1682     DEFINE_PROP_STRING("tx", VirtIONet, net_conf.tx),
1683     DEFINE_PROP_END_OF_LIST(),
1684 };
1685 
1686 static void virtio_net_class_init(ObjectClass *klass, void *data)
1687 {
1688     DeviceClass *dc = DEVICE_CLASS(klass);
1689     VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
1690 
1691     dc->props = virtio_net_properties;
1692     set_bit(DEVICE_CATEGORY_NETWORK, dc->categories);
1693     vdc->realize = virtio_net_device_realize;
1694     vdc->unrealize = virtio_net_device_unrealize;
1695     vdc->get_config = virtio_net_get_config;
1696     vdc->set_config = virtio_net_set_config;
1697     vdc->get_features = virtio_net_get_features;
1698     vdc->set_features = virtio_net_set_features;
1699     vdc->bad_features = virtio_net_bad_features;
1700     vdc->reset = virtio_net_reset;
1701     vdc->set_status = virtio_net_set_status;
1702     vdc->guest_notifier_mask = virtio_net_guest_notifier_mask;
1703     vdc->guest_notifier_pending = virtio_net_guest_notifier_pending;
1704 }
1705 
1706 static const TypeInfo virtio_net_info = {
1707     .name = TYPE_VIRTIO_NET,
1708     .parent = TYPE_VIRTIO_DEVICE,
1709     .instance_size = sizeof(VirtIONet),
1710     .instance_init = virtio_net_instance_init,
1711     .class_init = virtio_net_class_init,
1712 };
1713 
1714 static void virtio_register_types(void)
1715 {
1716     type_register_static(&virtio_net_info);
1717 }
1718 
1719 type_init(virtio_register_types)
1720