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