xref: /qemu/net/net.c (revision bfa3ab61)
1 /*
2  * QEMU System Emulator
3  *
4  * Copyright (c) 2003-2008 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "config-host.h"
25 
26 #include "net/net.h"
27 #include "clients.h"
28 #include "hub.h"
29 #include "net/slirp.h"
30 #include "net/eth.h"
31 #include "util.h"
32 
33 #include "monitor/monitor.h"
34 #include "qemu-common.h"
35 #include "qapi/qmp/qerror.h"
36 #include "qemu/error-report.h"
37 #include "qemu/sockets.h"
38 #include "qemu/config-file.h"
39 #include "qmp-commands.h"
40 #include "hw/qdev.h"
41 #include "qemu/iov.h"
42 #include "qemu/main-loop.h"
43 #include "qapi-visit.h"
44 #include "qapi/opts-visitor.h"
45 #include "qapi/dealloc-visitor.h"
46 #include "sysemu/sysemu.h"
47 
48 /* Net bridge is currently not supported for W32. */
49 #if !defined(_WIN32)
50 # define CONFIG_NET_BRIDGE
51 #endif
52 
53 static VMChangeStateEntry *net_change_state_entry;
54 static QTAILQ_HEAD(, NetClientState) net_clients;
55 
56 const char *host_net_devices[] = {
57     "tap",
58     "socket",
59     "dump",
60 #ifdef CONFIG_NET_BRIDGE
61     "bridge",
62 #endif
63 #ifdef CONFIG_SLIRP
64     "user",
65 #endif
66 #ifdef CONFIG_VDE
67     "vde",
68 #endif
69     "vhost-user",
70     NULL,
71 };
72 
73 int default_net = 1;
74 
75 /***********************************************************/
76 /* network device redirectors */
77 
78 #if defined(DEBUG_NET)
79 static void hex_dump(FILE *f, const uint8_t *buf, int size)
80 {
81     int len, i, j, c;
82 
83     for(i=0;i<size;i+=16) {
84         len = size - i;
85         if (len > 16)
86             len = 16;
87         fprintf(f, "%08x ", i);
88         for(j=0;j<16;j++) {
89             if (j < len)
90                 fprintf(f, " %02x", buf[i+j]);
91             else
92                 fprintf(f, "   ");
93         }
94         fprintf(f, " ");
95         for(j=0;j<len;j++) {
96             c = buf[i+j];
97             if (c < ' ' || c > '~')
98                 c = '.';
99             fprintf(f, "%c", c);
100         }
101         fprintf(f, "\n");
102     }
103 }
104 #endif
105 
106 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
107 {
108     const char *p, *p1;
109     int len;
110     p = *pp;
111     p1 = strchr(p, sep);
112     if (!p1)
113         return -1;
114     len = p1 - p;
115     p1++;
116     if (buf_size > 0) {
117         if (len > buf_size - 1)
118             len = buf_size - 1;
119         memcpy(buf, p, len);
120         buf[len] = '\0';
121     }
122     *pp = p1;
123     return 0;
124 }
125 
126 int parse_host_port(struct sockaddr_in *saddr, const char *str)
127 {
128     char buf[512];
129     struct hostent *he;
130     const char *p, *r;
131     int port;
132 
133     p = str;
134     if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
135         return -1;
136     saddr->sin_family = AF_INET;
137     if (buf[0] == '\0') {
138         saddr->sin_addr.s_addr = 0;
139     } else {
140         if (qemu_isdigit(buf[0])) {
141             if (!inet_aton(buf, &saddr->sin_addr))
142                 return -1;
143         } else {
144             if ((he = gethostbyname(buf)) == NULL)
145                 return - 1;
146             saddr->sin_addr = *(struct in_addr *)he->h_addr;
147         }
148     }
149     port = strtol(p, (char **)&r, 0);
150     if (r == p)
151         return -1;
152     saddr->sin_port = htons(port);
153     return 0;
154 }
155 
156 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
157 {
158     return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
159                            macaddr[0], macaddr[1], macaddr[2],
160                            macaddr[3], macaddr[4], macaddr[5]);
161 }
162 
163 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
164 {
165     snprintf(nc->info_str, sizeof(nc->info_str),
166              "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
167              nc->model,
168              macaddr[0], macaddr[1], macaddr[2],
169              macaddr[3], macaddr[4], macaddr[5]);
170 }
171 
172 static int mac_table[256] = {0};
173 
174 static void qemu_macaddr_set_used(MACAddr *macaddr)
175 {
176     int index;
177 
178     for (index = 0x56; index < 0xFF; index++) {
179         if (macaddr->a[5] == index) {
180             mac_table[index]++;
181         }
182     }
183 }
184 
185 static void qemu_macaddr_set_free(MACAddr *macaddr)
186 {
187     int index;
188     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
189 
190     if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
191         return;
192     }
193     for (index = 0x56; index < 0xFF; index++) {
194         if (macaddr->a[5] == index) {
195             mac_table[index]--;
196         }
197     }
198 }
199 
200 static int qemu_macaddr_get_free(void)
201 {
202     int index;
203 
204     for (index = 0x56; index < 0xFF; index++) {
205         if (mac_table[index] == 0) {
206             return index;
207         }
208     }
209 
210     return -1;
211 }
212 
213 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
214 {
215     static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
216     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
217 
218     if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
219         if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
220             return;
221         } else {
222             qemu_macaddr_set_used(macaddr);
223             return;
224         }
225     }
226 
227     macaddr->a[0] = 0x52;
228     macaddr->a[1] = 0x54;
229     macaddr->a[2] = 0x00;
230     macaddr->a[3] = 0x12;
231     macaddr->a[4] = 0x34;
232     macaddr->a[5] = qemu_macaddr_get_free();
233     qemu_macaddr_set_used(macaddr);
234 }
235 
236 /**
237  * Generate a name for net client
238  *
239  * Only net clients created with the legacy -net option and NICs need this.
240  */
241 static char *assign_name(NetClientState *nc1, const char *model)
242 {
243     NetClientState *nc;
244     int id = 0;
245 
246     QTAILQ_FOREACH(nc, &net_clients, next) {
247         if (nc == nc1) {
248             continue;
249         }
250         if (strcmp(nc->model, model) == 0) {
251             id++;
252         }
253     }
254 
255     return g_strdup_printf("%s.%d", model, id);
256 }
257 
258 static void qemu_net_client_destructor(NetClientState *nc)
259 {
260     g_free(nc);
261 }
262 
263 static void qemu_net_client_setup(NetClientState *nc,
264                                   NetClientInfo *info,
265                                   NetClientState *peer,
266                                   const char *model,
267                                   const char *name,
268                                   NetClientDestructor *destructor)
269 {
270     nc->info = info;
271     nc->model = g_strdup(model);
272     if (name) {
273         nc->name = g_strdup(name);
274     } else {
275         nc->name = assign_name(nc, model);
276     }
277 
278     if (peer) {
279         assert(!peer->peer);
280         nc->peer = peer;
281         peer->peer = nc;
282     }
283     QTAILQ_INSERT_TAIL(&net_clients, nc, next);
284 
285     nc->incoming_queue = qemu_new_net_queue(nc);
286     nc->destructor = destructor;
287 }
288 
289 NetClientState *qemu_new_net_client(NetClientInfo *info,
290                                     NetClientState *peer,
291                                     const char *model,
292                                     const char *name)
293 {
294     NetClientState *nc;
295 
296     assert(info->size >= sizeof(NetClientState));
297 
298     nc = g_malloc0(info->size);
299     qemu_net_client_setup(nc, info, peer, model, name,
300                           qemu_net_client_destructor);
301 
302     return nc;
303 }
304 
305 NICState *qemu_new_nic(NetClientInfo *info,
306                        NICConf *conf,
307                        const char *model,
308                        const char *name,
309                        void *opaque)
310 {
311     NetClientState **peers = conf->peers.ncs;
312     NICState *nic;
313     int i, queues = MAX(1, conf->peers.queues);
314 
315     assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
316     assert(info->size >= sizeof(NICState));
317 
318     nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
319     nic->ncs = (void *)nic + info->size;
320     nic->conf = conf;
321     nic->opaque = opaque;
322 
323     for (i = 0; i < queues; i++) {
324         qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
325                               NULL);
326         nic->ncs[i].queue_index = i;
327     }
328 
329     return nic;
330 }
331 
332 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
333 {
334     return nic->ncs + queue_index;
335 }
336 
337 NetClientState *qemu_get_queue(NICState *nic)
338 {
339     return qemu_get_subqueue(nic, 0);
340 }
341 
342 NICState *qemu_get_nic(NetClientState *nc)
343 {
344     NetClientState *nc0 = nc - nc->queue_index;
345 
346     return (NICState *)((void *)nc0 - nc->info->size);
347 }
348 
349 void *qemu_get_nic_opaque(NetClientState *nc)
350 {
351     NICState *nic = qemu_get_nic(nc);
352 
353     return nic->opaque;
354 }
355 
356 static void qemu_cleanup_net_client(NetClientState *nc)
357 {
358     QTAILQ_REMOVE(&net_clients, nc, next);
359 
360     if (nc->info->cleanup) {
361         nc->info->cleanup(nc);
362     }
363 }
364 
365 static void qemu_free_net_client(NetClientState *nc)
366 {
367     if (nc->incoming_queue) {
368         qemu_del_net_queue(nc->incoming_queue);
369     }
370     if (nc->peer) {
371         nc->peer->peer = NULL;
372     }
373     g_free(nc->name);
374     g_free(nc->model);
375     if (nc->destructor) {
376         nc->destructor(nc);
377     }
378 }
379 
380 void qemu_del_net_client(NetClientState *nc)
381 {
382     NetClientState *ncs[MAX_QUEUE_NUM];
383     int queues, i;
384 
385     assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
386 
387     /* If the NetClientState belongs to a multiqueue backend, we will change all
388      * other NetClientStates also.
389      */
390     queues = qemu_find_net_clients_except(nc->name, ncs,
391                                           NET_CLIENT_OPTIONS_KIND_NIC,
392                                           MAX_QUEUE_NUM);
393     assert(queues != 0);
394 
395     /* If there is a peer NIC, delete and cleanup client, but do not free. */
396     if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
397         NICState *nic = qemu_get_nic(nc->peer);
398         if (nic->peer_deleted) {
399             return;
400         }
401         nic->peer_deleted = true;
402 
403         for (i = 0; i < queues; i++) {
404             ncs[i]->peer->link_down = true;
405         }
406 
407         if (nc->peer->info->link_status_changed) {
408             nc->peer->info->link_status_changed(nc->peer);
409         }
410 
411         for (i = 0; i < queues; i++) {
412             qemu_cleanup_net_client(ncs[i]);
413         }
414 
415         return;
416     }
417 
418     for (i = 0; i < queues; i++) {
419         qemu_cleanup_net_client(ncs[i]);
420         qemu_free_net_client(ncs[i]);
421     }
422 }
423 
424 void qemu_del_nic(NICState *nic)
425 {
426     int i, queues = MAX(nic->conf->peers.queues, 1);
427 
428     qemu_macaddr_set_free(&nic->conf->macaddr);
429 
430     /* If this is a peer NIC and peer has already been deleted, free it now. */
431     if (nic->peer_deleted) {
432         for (i = 0; i < queues; i++) {
433             qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
434         }
435     }
436 
437     for (i = queues - 1; i >= 0; i--) {
438         NetClientState *nc = qemu_get_subqueue(nic, i);
439 
440         qemu_cleanup_net_client(nc);
441         qemu_free_net_client(nc);
442     }
443 
444     g_free(nic);
445 }
446 
447 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
448 {
449     NetClientState *nc;
450 
451     QTAILQ_FOREACH(nc, &net_clients, next) {
452         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
453             if (nc->queue_index == 0) {
454                 func(qemu_get_nic(nc), opaque);
455             }
456         }
457     }
458 }
459 
460 bool qemu_has_ufo(NetClientState *nc)
461 {
462     if (!nc || !nc->info->has_ufo) {
463         return false;
464     }
465 
466     return nc->info->has_ufo(nc);
467 }
468 
469 bool qemu_has_vnet_hdr(NetClientState *nc)
470 {
471     if (!nc || !nc->info->has_vnet_hdr) {
472         return false;
473     }
474 
475     return nc->info->has_vnet_hdr(nc);
476 }
477 
478 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
479 {
480     if (!nc || !nc->info->has_vnet_hdr_len) {
481         return false;
482     }
483 
484     return nc->info->has_vnet_hdr_len(nc, len);
485 }
486 
487 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
488 {
489     if (!nc || !nc->info->using_vnet_hdr) {
490         return;
491     }
492 
493     nc->info->using_vnet_hdr(nc, enable);
494 }
495 
496 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
497                           int ecn, int ufo)
498 {
499     if (!nc || !nc->info->set_offload) {
500         return;
501     }
502 
503     nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
504 }
505 
506 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
507 {
508     if (!nc || !nc->info->set_vnet_hdr_len) {
509         return;
510     }
511 
512     nc->info->set_vnet_hdr_len(nc, len);
513 }
514 
515 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
516 {
517     if (!nc || !nc->info->set_vnet_le) {
518         return -ENOSYS;
519     }
520 
521     return nc->info->set_vnet_le(nc, is_le);
522 }
523 
524 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
525 {
526     if (!nc || !nc->info->set_vnet_be) {
527         return -ENOSYS;
528     }
529 
530     return nc->info->set_vnet_be(nc, is_be);
531 }
532 
533 int qemu_can_send_packet(NetClientState *sender)
534 {
535     int vm_running = runstate_is_running();
536 
537     if (!vm_running) {
538         return 0;
539     }
540 
541     if (!sender->peer) {
542         return 1;
543     }
544 
545     if (sender->peer->receive_disabled) {
546         return 0;
547     } else if (sender->peer->info->can_receive &&
548                !sender->peer->info->can_receive(sender->peer)) {
549         return 0;
550     }
551     return 1;
552 }
553 
554 ssize_t qemu_deliver_packet(NetClientState *sender,
555                             unsigned flags,
556                             const uint8_t *data,
557                             size_t size,
558                             void *opaque)
559 {
560     NetClientState *nc = opaque;
561     ssize_t ret;
562 
563     if (nc->link_down) {
564         return size;
565     }
566 
567     if (nc->receive_disabled) {
568         return 0;
569     }
570 
571     if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
572         ret = nc->info->receive_raw(nc, data, size);
573     } else {
574         ret = nc->info->receive(nc, data, size);
575     }
576 
577     if (ret == 0) {
578         nc->receive_disabled = 1;
579     }
580 
581     return ret;
582 }
583 
584 void qemu_purge_queued_packets(NetClientState *nc)
585 {
586     if (!nc->peer) {
587         return;
588     }
589 
590     qemu_net_queue_purge(nc->peer->incoming_queue, nc);
591 }
592 
593 static
594 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
595 {
596     nc->receive_disabled = 0;
597 
598     if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
599         if (net_hub_flush(nc->peer)) {
600             qemu_notify_event();
601         }
602     }
603     if (qemu_net_queue_flush(nc->incoming_queue)) {
604         /* We emptied the queue successfully, signal to the IO thread to repoll
605          * the file descriptor (for tap, for example).
606          */
607         qemu_notify_event();
608     } else if (purge) {
609         /* Unable to empty the queue, purge remaining packets */
610         qemu_net_queue_purge(nc->incoming_queue, nc);
611     }
612 }
613 
614 void qemu_flush_queued_packets(NetClientState *nc)
615 {
616     qemu_flush_or_purge_queued_packets(nc, false);
617 }
618 
619 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
620                                                  unsigned flags,
621                                                  const uint8_t *buf, int size,
622                                                  NetPacketSent *sent_cb)
623 {
624     NetQueue *queue;
625 
626 #ifdef DEBUG_NET
627     printf("qemu_send_packet_async:\n");
628     hex_dump(stdout, buf, size);
629 #endif
630 
631     if (sender->link_down || !sender->peer) {
632         return size;
633     }
634 
635     queue = sender->peer->incoming_queue;
636 
637     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
638 }
639 
640 ssize_t qemu_send_packet_async(NetClientState *sender,
641                                const uint8_t *buf, int size,
642                                NetPacketSent *sent_cb)
643 {
644     return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
645                                              buf, size, sent_cb);
646 }
647 
648 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
649 {
650     qemu_send_packet_async(nc, buf, size, NULL);
651 }
652 
653 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
654 {
655     return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
656                                              buf, size, NULL);
657 }
658 
659 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
660                                int iovcnt)
661 {
662     uint8_t buffer[NET_BUFSIZE];
663     size_t offset;
664 
665     offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
666 
667     return nc->info->receive(nc, buffer, offset);
668 }
669 
670 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
671                                 unsigned flags,
672                                 const struct iovec *iov,
673                                 int iovcnt,
674                                 void *opaque)
675 {
676     NetClientState *nc = opaque;
677     int ret;
678 
679     if (nc->link_down) {
680         return iov_size(iov, iovcnt);
681     }
682 
683     if (nc->receive_disabled) {
684         return 0;
685     }
686 
687     if (nc->info->receive_iov) {
688         ret = nc->info->receive_iov(nc, iov, iovcnt);
689     } else {
690         ret = nc_sendv_compat(nc, iov, iovcnt);
691     }
692 
693     if (ret == 0) {
694         nc->receive_disabled = 1;
695     }
696 
697     return ret;
698 }
699 
700 ssize_t qemu_sendv_packet_async(NetClientState *sender,
701                                 const struct iovec *iov, int iovcnt,
702                                 NetPacketSent *sent_cb)
703 {
704     NetQueue *queue;
705 
706     if (sender->link_down || !sender->peer) {
707         return iov_size(iov, iovcnt);
708     }
709 
710     queue = sender->peer->incoming_queue;
711 
712     return qemu_net_queue_send_iov(queue, sender,
713                                    QEMU_NET_PACKET_FLAG_NONE,
714                                    iov, iovcnt, sent_cb);
715 }
716 
717 ssize_t
718 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
719 {
720     return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
721 }
722 
723 NetClientState *qemu_find_netdev(const char *id)
724 {
725     NetClientState *nc;
726 
727     QTAILQ_FOREACH(nc, &net_clients, next) {
728         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
729             continue;
730         if (!strcmp(nc->name, id)) {
731             return nc;
732         }
733     }
734 
735     return NULL;
736 }
737 
738 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
739                                  NetClientOptionsKind type, int max)
740 {
741     NetClientState *nc;
742     int ret = 0;
743 
744     QTAILQ_FOREACH(nc, &net_clients, next) {
745         if (nc->info->type == type) {
746             continue;
747         }
748         if (!id || !strcmp(nc->name, id)) {
749             if (ret < max) {
750                 ncs[ret] = nc;
751             }
752             ret++;
753         }
754     }
755 
756     return ret;
757 }
758 
759 static int nic_get_free_idx(void)
760 {
761     int index;
762 
763     for (index = 0; index < MAX_NICS; index++)
764         if (!nd_table[index].used)
765             return index;
766     return -1;
767 }
768 
769 int qemu_show_nic_models(const char *arg, const char *const *models)
770 {
771     int i;
772 
773     if (!arg || !is_help_option(arg)) {
774         return 0;
775     }
776 
777     fprintf(stderr, "qemu: Supported NIC models: ");
778     for (i = 0 ; models[i]; i++)
779         fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
780     return 1;
781 }
782 
783 void qemu_check_nic_model(NICInfo *nd, const char *model)
784 {
785     const char *models[2];
786 
787     models[0] = model;
788     models[1] = NULL;
789 
790     if (qemu_show_nic_models(nd->model, models))
791         exit(0);
792     if (qemu_find_nic_model(nd, models, model) < 0)
793         exit(1);
794 }
795 
796 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
797                         const char *default_model)
798 {
799     int i;
800 
801     if (!nd->model)
802         nd->model = g_strdup(default_model);
803 
804     for (i = 0 ; models[i]; i++) {
805         if (strcmp(nd->model, models[i]) == 0)
806             return i;
807     }
808 
809     error_report("Unsupported NIC model: %s", nd->model);
810     return -1;
811 }
812 
813 static int net_init_nic(const NetClientOptions *opts, const char *name,
814                         NetClientState *peer, Error **errp)
815 {
816     int idx;
817     NICInfo *nd;
818     const NetLegacyNicOptions *nic;
819 
820     assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);
821     nic = opts->nic;
822 
823     idx = nic_get_free_idx();
824     if (idx == -1 || nb_nics >= MAX_NICS) {
825         error_setg(errp, "too many NICs");
826         return -1;
827     }
828 
829     nd = &nd_table[idx];
830 
831     memset(nd, 0, sizeof(*nd));
832 
833     if (nic->has_netdev) {
834         nd->netdev = qemu_find_netdev(nic->netdev);
835         if (!nd->netdev) {
836             error_setg(errp, "netdev '%s' not found", nic->netdev);
837             return -1;
838         }
839     } else {
840         assert(peer);
841         nd->netdev = peer;
842     }
843     nd->name = g_strdup(name);
844     if (nic->has_model) {
845         nd->model = g_strdup(nic->model);
846     }
847     if (nic->has_addr) {
848         nd->devaddr = g_strdup(nic->addr);
849     }
850 
851     if (nic->has_macaddr &&
852         net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
853         error_setg(errp, "invalid syntax for ethernet address");
854         return -1;
855     }
856     if (nic->has_macaddr &&
857         is_multicast_ether_addr(nd->macaddr.a)) {
858         error_setg(errp,
859                    "NIC cannot have multicast MAC address (odd 1st byte)");
860         return -1;
861     }
862     qemu_macaddr_default_if_unset(&nd->macaddr);
863 
864     if (nic->has_vectors) {
865         if (nic->vectors > 0x7ffffff) {
866             error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
867             return -1;
868         }
869         nd->nvectors = nic->vectors;
870     } else {
871         nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
872     }
873 
874     nd->used = 1;
875     nb_nics++;
876 
877     return idx;
878 }
879 
880 
881 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
882     const NetClientOptions *opts,
883     const char *name,
884     NetClientState *peer, Error **errp) = {
885         [NET_CLIENT_OPTIONS_KIND_NIC]       = net_init_nic,
886 #ifdef CONFIG_SLIRP
887         [NET_CLIENT_OPTIONS_KIND_USER]      = net_init_slirp,
888 #endif
889         [NET_CLIENT_OPTIONS_KIND_TAP]       = net_init_tap,
890         [NET_CLIENT_OPTIONS_KIND_SOCKET]    = net_init_socket,
891 #ifdef CONFIG_VDE
892         [NET_CLIENT_OPTIONS_KIND_VDE]       = net_init_vde,
893 #endif
894 #ifdef CONFIG_NETMAP
895         [NET_CLIENT_OPTIONS_KIND_NETMAP]    = net_init_netmap,
896 #endif
897         [NET_CLIENT_OPTIONS_KIND_DUMP]      = net_init_dump,
898 #ifdef CONFIG_NET_BRIDGE
899         [NET_CLIENT_OPTIONS_KIND_BRIDGE]    = net_init_bridge,
900 #endif
901         [NET_CLIENT_OPTIONS_KIND_HUBPORT]   = net_init_hubport,
902 #ifdef CONFIG_VHOST_NET_USED
903         [NET_CLIENT_OPTIONS_KIND_VHOST_USER] = net_init_vhost_user,
904 #endif
905 #ifdef CONFIG_L2TPV3
906         [NET_CLIENT_OPTIONS_KIND_L2TPV3]    = net_init_l2tpv3,
907 #endif
908 };
909 
910 
911 static int net_client_init1(const void *object, int is_netdev, Error **errp)
912 {
913     union {
914         const Netdev    *netdev;
915         const NetLegacy *net;
916     } u;
917     const NetClientOptions *opts;
918     const char *name;
919 
920     if (is_netdev) {
921         u.netdev = object;
922         opts = u.netdev->opts;
923         name = u.netdev->id;
924 
925         switch (opts->kind) {
926 #ifdef CONFIG_SLIRP
927         case NET_CLIENT_OPTIONS_KIND_USER:
928 #endif
929         case NET_CLIENT_OPTIONS_KIND_TAP:
930         case NET_CLIENT_OPTIONS_KIND_SOCKET:
931 #ifdef CONFIG_VDE
932         case NET_CLIENT_OPTIONS_KIND_VDE:
933 #endif
934 #ifdef CONFIG_NETMAP
935         case NET_CLIENT_OPTIONS_KIND_NETMAP:
936 #endif
937 #ifdef CONFIG_NET_BRIDGE
938         case NET_CLIENT_OPTIONS_KIND_BRIDGE:
939 #endif
940         case NET_CLIENT_OPTIONS_KIND_HUBPORT:
941 #ifdef CONFIG_VHOST_NET_USED
942         case NET_CLIENT_OPTIONS_KIND_VHOST_USER:
943 #endif
944 #ifdef CONFIG_L2TPV3
945         case NET_CLIENT_OPTIONS_KIND_L2TPV3:
946 #endif
947             break;
948 
949         default:
950             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
951                        "a netdev backend type");
952             return -1;
953         }
954     } else {
955         u.net = object;
956         opts = u.net->opts;
957         if (opts->kind == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
958             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
959                        "a net type");
960             return -1;
961         }
962         /* missing optional values have been initialized to "all bits zero" */
963         name = u.net->has_id ? u.net->id : u.net->name;
964     }
965 
966     if (net_client_init_fun[opts->kind]) {
967         NetClientState *peer = NULL;
968 
969         /* Do not add to a vlan if it's a -netdev or a nic with a netdev=
970          * parameter. */
971         if (!is_netdev &&
972             (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
973              !opts->nic->has_netdev)) {
974             peer = net_hub_add_port(u.net->has_vlan ? u.net->vlan : 0, NULL);
975         }
976 
977         if (net_client_init_fun[opts->kind](opts, name, peer, errp) < 0) {
978             /* FIXME drop when all init functions store an Error */
979             if (errp && !*errp) {
980                 error_setg(errp, QERR_DEVICE_INIT_FAILED,
981                            NetClientOptionsKind_lookup[opts->kind]);
982             }
983             return -1;
984         }
985     }
986     return 0;
987 }
988 
989 
990 static void net_visit(Visitor *v, int is_netdev, void **object, Error **errp)
991 {
992     if (is_netdev) {
993         visit_type_Netdev(v, (Netdev **)object, NULL, errp);
994     } else {
995         visit_type_NetLegacy(v, (NetLegacy **)object, NULL, errp);
996     }
997 }
998 
999 
1000 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
1001 {
1002     void *object = NULL;
1003     Error *err = NULL;
1004     int ret = -1;
1005 
1006     {
1007         OptsVisitor *ov = opts_visitor_new(opts);
1008 
1009         net_visit(opts_get_visitor(ov), is_netdev, &object, &err);
1010         opts_visitor_cleanup(ov);
1011     }
1012 
1013     if (!err) {
1014         ret = net_client_init1(object, is_netdev, &err);
1015     }
1016 
1017     if (object) {
1018         QapiDeallocVisitor *dv = qapi_dealloc_visitor_new();
1019 
1020         net_visit(qapi_dealloc_get_visitor(dv), is_netdev, &object, NULL);
1021         qapi_dealloc_visitor_cleanup(dv);
1022     }
1023 
1024     error_propagate(errp, err);
1025     return ret;
1026 }
1027 
1028 
1029 static int net_host_check_device(const char *device)
1030 {
1031     int i;
1032     for (i = 0; host_net_devices[i]; i++) {
1033         if (!strncmp(host_net_devices[i], device,
1034                      strlen(host_net_devices[i]))) {
1035             return 1;
1036         }
1037     }
1038 
1039     return 0;
1040 }
1041 
1042 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1043 {
1044     const char *device = qdict_get_str(qdict, "device");
1045     const char *opts_str = qdict_get_try_str(qdict, "opts");
1046     Error *local_err = NULL;
1047     QemuOpts *opts;
1048 
1049     if (!net_host_check_device(device)) {
1050         monitor_printf(mon, "invalid host network device %s\n", device);
1051         return;
1052     }
1053 
1054     opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1055                                    opts_str ? opts_str : "", false);
1056     if (!opts) {
1057         return;
1058     }
1059 
1060     qemu_opt_set(opts, "type", device, &error_abort);
1061 
1062     net_client_init(opts, 0, &local_err);
1063     if (local_err) {
1064         error_report_err(local_err);
1065         monitor_printf(mon, "adding host network device %s failed\n", device);
1066     }
1067 }
1068 
1069 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1070 {
1071     NetClientState *nc;
1072     int vlan_id = qdict_get_int(qdict, "vlan_id");
1073     const char *device = qdict_get_str(qdict, "device");
1074 
1075     nc = net_hub_find_client_by_name(vlan_id, device);
1076     if (!nc) {
1077         error_report("Host network device '%s' on hub '%d' not found",
1078                      device, vlan_id);
1079         return;
1080     }
1081     if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1082         error_report("invalid host network device '%s'", device);
1083         return;
1084     }
1085 
1086     qemu_del_net_client(nc->peer);
1087     qemu_del_net_client(nc);
1088 }
1089 
1090 void netdev_add(QemuOpts *opts, Error **errp)
1091 {
1092     net_client_init(opts, 1, errp);
1093 }
1094 
1095 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1096 {
1097     Error *local_err = NULL;
1098     QemuOptsList *opts_list;
1099     QemuOpts *opts;
1100 
1101     opts_list = qemu_find_opts_err("netdev", &local_err);
1102     if (local_err) {
1103         goto out;
1104     }
1105 
1106     opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1107     if (local_err) {
1108         goto out;
1109     }
1110 
1111     netdev_add(opts, &local_err);
1112     if (local_err) {
1113         qemu_opts_del(opts);
1114         goto out;
1115     }
1116 
1117 out:
1118     error_propagate(errp, local_err);
1119 }
1120 
1121 void qmp_netdev_del(const char *id, Error **errp)
1122 {
1123     NetClientState *nc;
1124     QemuOpts *opts;
1125 
1126     nc = qemu_find_netdev(id);
1127     if (!nc) {
1128         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1129                   "Device '%s' not found", id);
1130         return;
1131     }
1132 
1133     opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1134     if (!opts) {
1135         error_setg(errp, "Device '%s' is not a netdev", id);
1136         return;
1137     }
1138 
1139     qemu_del_net_client(nc);
1140     qemu_opts_del(opts);
1141 }
1142 
1143 void print_net_client(Monitor *mon, NetClientState *nc)
1144 {
1145     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1146                    nc->queue_index,
1147                    NetClientOptionsKind_lookup[nc->info->type],
1148                    nc->info_str);
1149 }
1150 
1151 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1152                                       Error **errp)
1153 {
1154     NetClientState *nc;
1155     RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1156 
1157     QTAILQ_FOREACH(nc, &net_clients, next) {
1158         RxFilterInfoList *entry;
1159         RxFilterInfo *info;
1160 
1161         if (has_name && strcmp(nc->name, name) != 0) {
1162             continue;
1163         }
1164 
1165         /* only query rx-filter information of NIC */
1166         if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1167             if (has_name) {
1168                 error_setg(errp, "net client(%s) isn't a NIC", name);
1169                 return NULL;
1170             }
1171             continue;
1172         }
1173 
1174         if (nc->info->query_rx_filter) {
1175             info = nc->info->query_rx_filter(nc);
1176             entry = g_malloc0(sizeof(*entry));
1177             entry->value = info;
1178 
1179             if (!filter_list) {
1180                 filter_list = entry;
1181             } else {
1182                 last_entry->next = entry;
1183             }
1184             last_entry = entry;
1185         } else if (has_name) {
1186             error_setg(errp, "net client(%s) doesn't support"
1187                        " rx-filter querying", name);
1188             return NULL;
1189         }
1190 
1191         if (has_name) {
1192             break;
1193         }
1194     }
1195 
1196     if (filter_list == NULL && has_name) {
1197         error_setg(errp, "invalid net client name: %s", name);
1198     }
1199 
1200     return filter_list;
1201 }
1202 
1203 void hmp_info_network(Monitor *mon, const QDict *qdict)
1204 {
1205     NetClientState *nc, *peer;
1206     NetClientOptionsKind type;
1207 
1208     net_hub_info(mon);
1209 
1210     QTAILQ_FOREACH(nc, &net_clients, next) {
1211         peer = nc->peer;
1212         type = nc->info->type;
1213 
1214         /* Skip if already printed in hub info */
1215         if (net_hub_id_for_client(nc, NULL) == 0) {
1216             continue;
1217         }
1218 
1219         if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1220             print_net_client(mon, nc);
1221         } /* else it's a netdev connected to a NIC, printed with the NIC */
1222         if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1223             monitor_printf(mon, " \\ ");
1224             print_net_client(mon, peer);
1225         }
1226     }
1227 }
1228 
1229 void qmp_set_link(const char *name, bool up, Error **errp)
1230 {
1231     NetClientState *ncs[MAX_QUEUE_NUM];
1232     NetClientState *nc;
1233     int queues, i;
1234 
1235     queues = qemu_find_net_clients_except(name, ncs,
1236                                           NET_CLIENT_OPTIONS_KIND_MAX,
1237                                           MAX_QUEUE_NUM);
1238 
1239     if (queues == 0) {
1240         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1241                   "Device '%s' not found", name);
1242         return;
1243     }
1244     nc = ncs[0];
1245 
1246     for (i = 0; i < queues; i++) {
1247         ncs[i]->link_down = !up;
1248     }
1249 
1250     if (nc->info->link_status_changed) {
1251         nc->info->link_status_changed(nc);
1252     }
1253 
1254     if (nc->peer) {
1255         /* Change peer link only if the peer is NIC and then notify peer.
1256          * If the peer is a HUBPORT or a backend, we do not change the
1257          * link status.
1258          *
1259          * This behavior is compatible with qemu vlans where there could be
1260          * multiple clients that can still communicate with each other in
1261          * disconnected mode. For now maintain this compatibility.
1262          */
1263         if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1264             for (i = 0; i < queues; i++) {
1265                 ncs[i]->peer->link_down = !up;
1266             }
1267         }
1268         if (nc->peer->info->link_status_changed) {
1269             nc->peer->info->link_status_changed(nc->peer);
1270         }
1271     }
1272 }
1273 
1274 static void net_vm_change_state_handler(void *opaque, int running,
1275                                         RunState state)
1276 {
1277     /* Complete all queued packets, to guarantee we don't modify
1278      * state later when VM is not running.
1279      */
1280     if (!running) {
1281         NetClientState *nc;
1282         NetClientState *tmp;
1283 
1284         QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1285             qemu_flush_or_purge_queued_packets(nc, true);
1286         }
1287     }
1288 }
1289 
1290 void net_cleanup(void)
1291 {
1292     NetClientState *nc;
1293 
1294     /* We may del multiple entries during qemu_del_net_client(),
1295      * so QTAILQ_FOREACH_SAFE() is also not safe here.
1296      */
1297     while (!QTAILQ_EMPTY(&net_clients)) {
1298         nc = QTAILQ_FIRST(&net_clients);
1299         if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1300             qemu_del_nic(qemu_get_nic(nc));
1301         } else {
1302             qemu_del_net_client(nc);
1303         }
1304     }
1305 
1306     qemu_del_vm_change_state_handler(net_change_state_entry);
1307 }
1308 
1309 void net_check_clients(void)
1310 {
1311     NetClientState *nc;
1312     int i;
1313 
1314     /* Don't warn about the default network setup that you get if
1315      * no command line -net or -netdev options are specified. There
1316      * are two cases that we would otherwise complain about:
1317      * (1) board doesn't support a NIC but the implicit "-net nic"
1318      * requested one
1319      * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1320      * sets up a nic that isn't connected to anything.
1321      */
1322     if (default_net) {
1323         return;
1324     }
1325 
1326     net_hub_check_clients();
1327 
1328     QTAILQ_FOREACH(nc, &net_clients, next) {
1329         if (!nc->peer) {
1330             fprintf(stderr, "Warning: %s %s has no peer\n",
1331                     nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1332                     "nic" : "netdev", nc->name);
1333         }
1334     }
1335 
1336     /* Check that all NICs requested via -net nic actually got created.
1337      * NICs created via -device don't need to be checked here because
1338      * they are always instantiated.
1339      */
1340     for (i = 0; i < MAX_NICS; i++) {
1341         NICInfo *nd = &nd_table[i];
1342         if (nd->used && !nd->instantiated) {
1343             fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1344                     "was not created (not supported by this machine?)\n",
1345                     nd->name ? nd->name : "anonymous",
1346                     nd->model ? nd->model : "unspecified");
1347         }
1348     }
1349 }
1350 
1351 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1352 {
1353     Error *local_err = NULL;
1354 
1355     net_client_init(opts, 0, &local_err);
1356     if (local_err) {
1357         error_report_err(local_err);
1358         return -1;
1359     }
1360 
1361     return 0;
1362 }
1363 
1364 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1365 {
1366     Error *local_err = NULL;
1367     int ret;
1368 
1369     ret = net_client_init(opts, 1, &local_err);
1370     if (local_err) {
1371         error_report_err(local_err);
1372         return -1;
1373     }
1374 
1375     return ret;
1376 }
1377 
1378 int net_init_clients(void)
1379 {
1380     QemuOptsList *net = qemu_find_opts("net");
1381 
1382     if (default_net) {
1383         /* if no clients, we use a default config */
1384         qemu_opts_set(net, NULL, "type", "nic", &error_abort);
1385 #ifdef CONFIG_SLIRP
1386         qemu_opts_set(net, NULL, "type", "user", &error_abort);
1387 #endif
1388     }
1389 
1390     net_change_state_entry =
1391         qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1392 
1393     QTAILQ_INIT(&net_clients);
1394 
1395     if (qemu_opts_foreach(qemu_find_opts("netdev"),
1396                           net_init_netdev, NULL, NULL)) {
1397         return -1;
1398     }
1399 
1400     if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1401         return -1;
1402     }
1403 
1404     return 0;
1405 }
1406 
1407 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1408 {
1409 #if defined(CONFIG_SLIRP)
1410     int ret;
1411     if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1412         return ret;
1413     }
1414 #endif
1415 
1416     if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1417         return -1;
1418     }
1419 
1420     default_net = 0;
1421     return 0;
1422 }
1423 
1424 /* From FreeBSD */
1425 /* XXX: optimize */
1426 unsigned compute_mcast_idx(const uint8_t *ep)
1427 {
1428     uint32_t crc;
1429     int carry, i, j;
1430     uint8_t b;
1431 
1432     crc = 0xffffffff;
1433     for (i = 0; i < 6; i++) {
1434         b = *ep++;
1435         for (j = 0; j < 8; j++) {
1436             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1437             crc <<= 1;
1438             b >>= 1;
1439             if (carry) {
1440                 crc = ((crc ^ POLYNOMIAL) | carry);
1441             }
1442         }
1443     }
1444     return crc >> 26;
1445 }
1446 
1447 QemuOptsList qemu_netdev_opts = {
1448     .name = "netdev",
1449     .implied_opt_name = "type",
1450     .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1451     .desc = {
1452         /*
1453          * no elements => accept any params
1454          * validation will happen later
1455          */
1456         { /* end of list */ }
1457     },
1458 };
1459 
1460 QemuOptsList qemu_net_opts = {
1461     .name = "net",
1462     .implied_opt_name = "type",
1463     .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1464     .desc = {
1465         /*
1466          * no elements => accept any params
1467          * validation will happen later
1468          */
1469         { /* end of list */ }
1470     },
1471 };
1472