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