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