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