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