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