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