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