xref: /qemu/net/net.c (revision 6402cbbb)
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->vnet_hdr_len = len;
496     nc->info->set_vnet_hdr_len(nc, len);
497 }
498 
499 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
500 {
501 #ifdef HOST_WORDS_BIGENDIAN
502     if (!nc || !nc->info->set_vnet_le) {
503         return -ENOSYS;
504     }
505 
506     return nc->info->set_vnet_le(nc, is_le);
507 #else
508     return 0;
509 #endif
510 }
511 
512 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
513 {
514 #ifdef HOST_WORDS_BIGENDIAN
515     return 0;
516 #else
517     if (!nc || !nc->info->set_vnet_be) {
518         return -ENOSYS;
519     }
520 
521     return nc->info->set_vnet_be(nc, is_be);
522 #endif
523 }
524 
525 int qemu_can_send_packet(NetClientState *sender)
526 {
527     int vm_running = runstate_is_running();
528 
529     if (!vm_running) {
530         return 0;
531     }
532 
533     if (!sender->peer) {
534         return 1;
535     }
536 
537     if (sender->peer->receive_disabled) {
538         return 0;
539     } else if (sender->peer->info->can_receive &&
540                !sender->peer->info->can_receive(sender->peer)) {
541         return 0;
542     }
543     return 1;
544 }
545 
546 static ssize_t filter_receive_iov(NetClientState *nc,
547                                   NetFilterDirection direction,
548                                   NetClientState *sender,
549                                   unsigned flags,
550                                   const struct iovec *iov,
551                                   int iovcnt,
552                                   NetPacketSent *sent_cb)
553 {
554     ssize_t ret = 0;
555     NetFilterState *nf = NULL;
556 
557     if (direction == NET_FILTER_DIRECTION_TX) {
558         QTAILQ_FOREACH(nf, &nc->filters, next) {
559             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
560                                          iovcnt, sent_cb);
561             if (ret) {
562                 return ret;
563             }
564         }
565     } else {
566         QTAILQ_FOREACH_REVERSE(nf, &nc->filters, NetFilterHead, next) {
567             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
568                                          iovcnt, sent_cb);
569             if (ret) {
570                 return ret;
571             }
572         }
573     }
574 
575     return ret;
576 }
577 
578 static ssize_t filter_receive(NetClientState *nc,
579                               NetFilterDirection direction,
580                               NetClientState *sender,
581                               unsigned flags,
582                               const uint8_t *data,
583                               size_t size,
584                               NetPacketSent *sent_cb)
585 {
586     struct iovec iov = {
587         .iov_base = (void *)data,
588         .iov_len = size
589     };
590 
591     return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
592 }
593 
594 void qemu_purge_queued_packets(NetClientState *nc)
595 {
596     if (!nc->peer) {
597         return;
598     }
599 
600     qemu_net_queue_purge(nc->peer->incoming_queue, nc);
601 }
602 
603 static
604 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
605 {
606     nc->receive_disabled = 0;
607 
608     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
609         if (net_hub_flush(nc->peer)) {
610             qemu_notify_event();
611         }
612     }
613     if (qemu_net_queue_flush(nc->incoming_queue)) {
614         /* We emptied the queue successfully, signal to the IO thread to repoll
615          * the file descriptor (for tap, for example).
616          */
617         qemu_notify_event();
618     } else if (purge) {
619         /* Unable to empty the queue, purge remaining packets */
620         qemu_net_queue_purge(nc->incoming_queue, nc);
621     }
622 }
623 
624 void qemu_flush_queued_packets(NetClientState *nc)
625 {
626     qemu_flush_or_purge_queued_packets(nc, false);
627 }
628 
629 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
630                                                  unsigned flags,
631                                                  const uint8_t *buf, int size,
632                                                  NetPacketSent *sent_cb)
633 {
634     NetQueue *queue;
635     int ret;
636 
637 #ifdef DEBUG_NET
638     printf("qemu_send_packet_async:\n");
639     qemu_hexdump((const char *)buf, stdout, "net", size);
640 #endif
641 
642     if (sender->link_down || !sender->peer) {
643         return size;
644     }
645 
646     /* Let filters handle the packet first */
647     ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
648                          sender, flags, buf, size, sent_cb);
649     if (ret) {
650         return ret;
651     }
652 
653     ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
654                          sender, flags, buf, size, sent_cb);
655     if (ret) {
656         return ret;
657     }
658 
659     queue = sender->peer->incoming_queue;
660 
661     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
662 }
663 
664 ssize_t qemu_send_packet_async(NetClientState *sender,
665                                const uint8_t *buf, int size,
666                                NetPacketSent *sent_cb)
667 {
668     return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
669                                              buf, size, sent_cb);
670 }
671 
672 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
673 {
674     qemu_send_packet_async(nc, buf, size, NULL);
675 }
676 
677 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
678 {
679     return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
680                                              buf, size, NULL);
681 }
682 
683 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
684                                int iovcnt, unsigned flags)
685 {
686     uint8_t *buf = NULL;
687     uint8_t *buffer;
688     size_t offset;
689     ssize_t ret;
690 
691     if (iovcnt == 1) {
692         buffer = iov[0].iov_base;
693         offset = iov[0].iov_len;
694     } else {
695         offset = iov_size(iov, iovcnt);
696         if (offset > NET_BUFSIZE) {
697             return -1;
698         }
699         buf = g_malloc(offset);
700         buffer = buf;
701         offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
702     }
703 
704     if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
705         ret = nc->info->receive_raw(nc, buffer, offset);
706     } else {
707         ret = nc->info->receive(nc, buffer, offset);
708     }
709 
710     g_free(buf);
711     return ret;
712 }
713 
714 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
715                                 unsigned flags,
716                                 const struct iovec *iov,
717                                 int iovcnt,
718                                 void *opaque)
719 {
720     NetClientState *nc = opaque;
721     int ret;
722 
723     if (nc->link_down) {
724         return iov_size(iov, iovcnt);
725     }
726 
727     if (nc->receive_disabled) {
728         return 0;
729     }
730 
731     if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
732         ret = nc->info->receive_iov(nc, iov, iovcnt);
733     } else {
734         ret = nc_sendv_compat(nc, iov, iovcnt, flags);
735     }
736 
737     if (ret == 0) {
738         nc->receive_disabled = 1;
739     }
740 
741     return ret;
742 }
743 
744 ssize_t qemu_sendv_packet_async(NetClientState *sender,
745                                 const struct iovec *iov, int iovcnt,
746                                 NetPacketSent *sent_cb)
747 {
748     NetQueue *queue;
749     int ret;
750 
751     if (sender->link_down || !sender->peer) {
752         return iov_size(iov, iovcnt);
753     }
754 
755     /* Let filters handle the packet first */
756     ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
757                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
758     if (ret) {
759         return ret;
760     }
761 
762     ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
763                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
764     if (ret) {
765         return ret;
766     }
767 
768     queue = sender->peer->incoming_queue;
769 
770     return qemu_net_queue_send_iov(queue, sender,
771                                    QEMU_NET_PACKET_FLAG_NONE,
772                                    iov, iovcnt, sent_cb);
773 }
774 
775 ssize_t
776 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
777 {
778     return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
779 }
780 
781 NetClientState *qemu_find_netdev(const char *id)
782 {
783     NetClientState *nc;
784 
785     QTAILQ_FOREACH(nc, &net_clients, next) {
786         if (nc->info->type == NET_CLIENT_DRIVER_NIC)
787             continue;
788         if (!strcmp(nc->name, id)) {
789             return nc;
790         }
791     }
792 
793     return NULL;
794 }
795 
796 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
797                                  NetClientDriver type, int max)
798 {
799     NetClientState *nc;
800     int ret = 0;
801 
802     QTAILQ_FOREACH(nc, &net_clients, next) {
803         if (nc->info->type == type) {
804             continue;
805         }
806         if (!id || !strcmp(nc->name, id)) {
807             if (ret < max) {
808                 ncs[ret] = nc;
809             }
810             ret++;
811         }
812     }
813 
814     return ret;
815 }
816 
817 static int nic_get_free_idx(void)
818 {
819     int index;
820 
821     for (index = 0; index < MAX_NICS; index++)
822         if (!nd_table[index].used)
823             return index;
824     return -1;
825 }
826 
827 int qemu_show_nic_models(const char *arg, const char *const *models)
828 {
829     int i;
830 
831     if (!arg || !is_help_option(arg)) {
832         return 0;
833     }
834 
835     fprintf(stderr, "qemu: Supported NIC models: ");
836     for (i = 0 ; models[i]; i++)
837         fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
838     return 1;
839 }
840 
841 void qemu_check_nic_model(NICInfo *nd, const char *model)
842 {
843     const char *models[2];
844 
845     models[0] = model;
846     models[1] = NULL;
847 
848     if (qemu_show_nic_models(nd->model, models))
849         exit(0);
850     if (qemu_find_nic_model(nd, models, model) < 0)
851         exit(1);
852 }
853 
854 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
855                         const char *default_model)
856 {
857     int i;
858 
859     if (!nd->model)
860         nd->model = g_strdup(default_model);
861 
862     for (i = 0 ; models[i]; i++) {
863         if (strcmp(nd->model, models[i]) == 0)
864             return i;
865     }
866 
867     error_report("Unsupported NIC model: %s", nd->model);
868     return -1;
869 }
870 
871 static int net_init_nic(const Netdev *netdev, const char *name,
872                         NetClientState *peer, Error **errp)
873 {
874     int idx;
875     NICInfo *nd;
876     const NetLegacyNicOptions *nic;
877 
878     assert(netdev->type == NET_CLIENT_DRIVER_NIC);
879     nic = &netdev->u.nic;
880 
881     idx = nic_get_free_idx();
882     if (idx == -1 || nb_nics >= MAX_NICS) {
883         error_setg(errp, "too many NICs");
884         return -1;
885     }
886 
887     nd = &nd_table[idx];
888 
889     memset(nd, 0, sizeof(*nd));
890 
891     if (nic->has_netdev) {
892         nd->netdev = qemu_find_netdev(nic->netdev);
893         if (!nd->netdev) {
894             error_setg(errp, "netdev '%s' not found", nic->netdev);
895             return -1;
896         }
897     } else {
898         assert(peer);
899         nd->netdev = peer;
900     }
901     nd->name = g_strdup(name);
902     if (nic->has_model) {
903         nd->model = g_strdup(nic->model);
904     }
905     if (nic->has_addr) {
906         nd->devaddr = g_strdup(nic->addr);
907     }
908 
909     if (nic->has_macaddr &&
910         net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
911         error_setg(errp, "invalid syntax for ethernet address");
912         return -1;
913     }
914     if (nic->has_macaddr &&
915         is_multicast_ether_addr(nd->macaddr.a)) {
916         error_setg(errp,
917                    "NIC cannot have multicast MAC address (odd 1st byte)");
918         return -1;
919     }
920     qemu_macaddr_default_if_unset(&nd->macaddr);
921 
922     if (nic->has_vectors) {
923         if (nic->vectors > 0x7ffffff) {
924             error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
925             return -1;
926         }
927         nd->nvectors = nic->vectors;
928     } else {
929         nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
930     }
931 
932     nd->used = 1;
933     nb_nics++;
934 
935     return idx;
936 }
937 
938 
939 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
940     const Netdev *netdev,
941     const char *name,
942     NetClientState *peer, Error **errp) = {
943         [NET_CLIENT_DRIVER_NIC]       = net_init_nic,
944 #ifdef CONFIG_SLIRP
945         [NET_CLIENT_DRIVER_USER]      = net_init_slirp,
946 #endif
947         [NET_CLIENT_DRIVER_TAP]       = net_init_tap,
948         [NET_CLIENT_DRIVER_SOCKET]    = net_init_socket,
949 #ifdef CONFIG_VDE
950         [NET_CLIENT_DRIVER_VDE]       = net_init_vde,
951 #endif
952 #ifdef CONFIG_NETMAP
953         [NET_CLIENT_DRIVER_NETMAP]    = net_init_netmap,
954 #endif
955         [NET_CLIENT_DRIVER_DUMP]      = net_init_dump,
956 #ifdef CONFIG_NET_BRIDGE
957         [NET_CLIENT_DRIVER_BRIDGE]    = net_init_bridge,
958 #endif
959         [NET_CLIENT_DRIVER_HUBPORT]   = net_init_hubport,
960 #ifdef CONFIG_VHOST_NET_USED
961         [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
962 #endif
963 #ifdef CONFIG_L2TPV3
964         [NET_CLIENT_DRIVER_L2TPV3]    = net_init_l2tpv3,
965 #endif
966 };
967 
968 
969 static int net_client_init1(const void *object, bool is_netdev, Error **errp)
970 {
971     Netdev legacy = {0};
972     const Netdev *netdev;
973     const char *name;
974     NetClientState *peer = NULL;
975     static bool vlan_warned;
976 
977     if (is_netdev) {
978         netdev = object;
979         name = netdev->id;
980 
981         if (netdev->type == NET_CLIENT_DRIVER_DUMP ||
982             netdev->type == NET_CLIENT_DRIVER_NIC ||
983             !net_client_init_fun[netdev->type]) {
984             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
985                        "a netdev backend type");
986             return -1;
987         }
988     } else {
989         const NetLegacy *net = object;
990         const NetLegacyOptions *opts = net->opts;
991         legacy.id = net->id;
992         netdev = &legacy;
993         /* missing optional values have been initialized to "all bits zero" */
994         name = net->has_id ? net->id : net->name;
995 
996         /* Map the old options to the new flat type */
997         switch (opts->type) {
998         case NET_LEGACY_OPTIONS_TYPE_NONE:
999             return 0; /* nothing to do */
1000         case NET_LEGACY_OPTIONS_TYPE_NIC:
1001             legacy.type = NET_CLIENT_DRIVER_NIC;
1002             legacy.u.nic = opts->u.nic;
1003             break;
1004         case NET_LEGACY_OPTIONS_TYPE_USER:
1005             legacy.type = NET_CLIENT_DRIVER_USER;
1006             legacy.u.user = opts->u.user;
1007             break;
1008         case NET_LEGACY_OPTIONS_TYPE_TAP:
1009             legacy.type = NET_CLIENT_DRIVER_TAP;
1010             legacy.u.tap = opts->u.tap;
1011             break;
1012         case NET_LEGACY_OPTIONS_TYPE_L2TPV3:
1013             legacy.type = NET_CLIENT_DRIVER_L2TPV3;
1014             legacy.u.l2tpv3 = opts->u.l2tpv3;
1015             break;
1016         case NET_LEGACY_OPTIONS_TYPE_SOCKET:
1017             legacy.type = NET_CLIENT_DRIVER_SOCKET;
1018             legacy.u.socket = opts->u.socket;
1019             break;
1020         case NET_LEGACY_OPTIONS_TYPE_VDE:
1021             legacy.type = NET_CLIENT_DRIVER_VDE;
1022             legacy.u.vde = opts->u.vde;
1023             break;
1024         case NET_LEGACY_OPTIONS_TYPE_DUMP:
1025             legacy.type = NET_CLIENT_DRIVER_DUMP;
1026             legacy.u.dump = opts->u.dump;
1027             break;
1028         case NET_LEGACY_OPTIONS_TYPE_BRIDGE:
1029             legacy.type = NET_CLIENT_DRIVER_BRIDGE;
1030             legacy.u.bridge = opts->u.bridge;
1031             break;
1032         case NET_LEGACY_OPTIONS_TYPE_NETMAP:
1033             legacy.type = NET_CLIENT_DRIVER_NETMAP;
1034             legacy.u.netmap = opts->u.netmap;
1035             break;
1036         case NET_LEGACY_OPTIONS_TYPE_VHOST_USER:
1037             legacy.type = NET_CLIENT_DRIVER_VHOST_USER;
1038             legacy.u.vhost_user = opts->u.vhost_user;
1039             break;
1040         default:
1041             abort();
1042         }
1043 
1044         if (!net_client_init_fun[netdev->type]) {
1045             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1046                        "a net backend type (maybe it is not compiled "
1047                        "into this binary)");
1048             return -1;
1049         }
1050 
1051         /* Do not add to a vlan if it's a nic with a netdev= parameter. */
1052         if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1053             !opts->u.nic.has_netdev) {
1054             peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
1055         }
1056 
1057         if (net->has_vlan && !vlan_warned) {
1058             error_report("'vlan' is deprecated. Please use 'netdev' instead.");
1059             vlan_warned = true;
1060         }
1061     }
1062 
1063     if (net_client_init_fun[netdev->type](netdev, name, peer, errp) < 0) {
1064         /* FIXME drop when all init functions store an Error */
1065         if (errp && !*errp) {
1066             error_setg(errp, QERR_DEVICE_INIT_FAILED,
1067                        NetClientDriver_lookup[netdev->type]);
1068         }
1069         return -1;
1070     }
1071     return 0;
1072 }
1073 
1074 
1075 int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1076 {
1077     void *object = NULL;
1078     Error *err = NULL;
1079     int ret = -1;
1080     Visitor *v = opts_visitor_new(opts);
1081 
1082     {
1083         /* Parse convenience option format ip6-net=fec0::0[/64] */
1084         const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1085 
1086         if (ip6_net) {
1087             char buf[strlen(ip6_net) + 1];
1088 
1089             if (get_str_sep(buf, sizeof(buf), &ip6_net, '/') < 0) {
1090                 /* Default 64bit prefix length.  */
1091                 qemu_opt_set(opts, "ipv6-prefix", ip6_net, &error_abort);
1092                 qemu_opt_set_number(opts, "ipv6-prefixlen", 64, &error_abort);
1093             } else {
1094                 /* User-specified prefix length.  */
1095                 unsigned long len;
1096                 int err;
1097 
1098                 qemu_opt_set(opts, "ipv6-prefix", buf, &error_abort);
1099                 err = qemu_strtoul(ip6_net, NULL, 10, &len);
1100 
1101                 if (err) {
1102                     error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1103                               "ipv6-prefix", "a number");
1104                 } else {
1105                     qemu_opt_set_number(opts, "ipv6-prefixlen", len,
1106                                         &error_abort);
1107                 }
1108             }
1109             qemu_opt_unset(opts, "ipv6-net");
1110         }
1111     }
1112 
1113     if (is_netdev) {
1114         visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1115     } else {
1116         visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1117     }
1118 
1119     if (!err) {
1120         ret = net_client_init1(object, is_netdev, &err);
1121     }
1122 
1123     if (is_netdev) {
1124         qapi_free_Netdev(object);
1125     } else {
1126         qapi_free_NetLegacy(object);
1127     }
1128 
1129     error_propagate(errp, err);
1130     visit_free(v);
1131     return ret;
1132 }
1133 
1134 
1135 static int net_host_check_device(const char *device)
1136 {
1137     int i;
1138     for (i = 0; host_net_devices[i]; i++) {
1139         if (!strncmp(host_net_devices[i], device,
1140                      strlen(host_net_devices[i]))) {
1141             return 1;
1142         }
1143     }
1144 
1145     return 0;
1146 }
1147 
1148 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1149 {
1150     const char *device = qdict_get_str(qdict, "device");
1151     const char *opts_str = qdict_get_try_str(qdict, "opts");
1152     Error *local_err = NULL;
1153     QemuOpts *opts;
1154     static bool warned;
1155 
1156     if (!warned && !qtest_enabled()) {
1157         error_report("host_net_add is deprecated, use netdev_add instead");
1158         warned = true;
1159     }
1160 
1161     if (!net_host_check_device(device)) {
1162         monitor_printf(mon, "invalid host network device %s\n", device);
1163         return;
1164     }
1165 
1166     opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1167                                    opts_str ? opts_str : "", false);
1168     if (!opts) {
1169         return;
1170     }
1171 
1172     qemu_opt_set(opts, "type", device, &error_abort);
1173 
1174     net_client_init(opts, false, &local_err);
1175     if (local_err) {
1176         error_report_err(local_err);
1177         monitor_printf(mon, "adding host network device %s failed\n", device);
1178     }
1179 }
1180 
1181 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1182 {
1183     NetClientState *nc;
1184     int vlan_id = qdict_get_int(qdict, "vlan_id");
1185     const char *device = qdict_get_str(qdict, "device");
1186     static bool warned;
1187 
1188     if (!warned && !qtest_enabled()) {
1189         error_report("host_net_remove is deprecated, use netdev_del instead");
1190         warned = true;
1191     }
1192 
1193     nc = net_hub_find_client_by_name(vlan_id, device);
1194     if (!nc) {
1195         error_report("Host network device '%s' on hub '%d' not found",
1196                      device, vlan_id);
1197         return;
1198     }
1199     if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1200         error_report("invalid host network device '%s'", device);
1201         return;
1202     }
1203 
1204     qemu_del_net_client(nc->peer);
1205     qemu_del_net_client(nc);
1206     qemu_opts_del(qemu_opts_find(qemu_find_opts("net"), device));
1207 }
1208 
1209 void netdev_add(QemuOpts *opts, Error **errp)
1210 {
1211     net_client_init(opts, true, errp);
1212 }
1213 
1214 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1215 {
1216     Error *local_err = NULL;
1217     QemuOptsList *opts_list;
1218     QemuOpts *opts;
1219 
1220     opts_list = qemu_find_opts_err("netdev", &local_err);
1221     if (local_err) {
1222         goto out;
1223     }
1224 
1225     opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1226     if (local_err) {
1227         goto out;
1228     }
1229 
1230     netdev_add(opts, &local_err);
1231     if (local_err) {
1232         qemu_opts_del(opts);
1233         goto out;
1234     }
1235 
1236 out:
1237     error_propagate(errp, local_err);
1238 }
1239 
1240 void qmp_netdev_del(const char *id, Error **errp)
1241 {
1242     NetClientState *nc;
1243     QemuOpts *opts;
1244 
1245     nc = qemu_find_netdev(id);
1246     if (!nc) {
1247         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1248                   "Device '%s' not found", id);
1249         return;
1250     }
1251 
1252     opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1253     if (!opts) {
1254         error_setg(errp, "Device '%s' is not a netdev", id);
1255         return;
1256     }
1257 
1258     qemu_del_net_client(nc);
1259     qemu_opts_del(opts);
1260 }
1261 
1262 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1263 {
1264     char *str;
1265     ObjectProperty *prop;
1266     ObjectPropertyIterator iter;
1267     Visitor *v;
1268 
1269     /* generate info str */
1270     object_property_iter_init(&iter, OBJECT(nf));
1271     while ((prop = object_property_iter_next(&iter))) {
1272         if (!strcmp(prop->name, "type")) {
1273             continue;
1274         }
1275         v = string_output_visitor_new(false, &str);
1276         object_property_get(OBJECT(nf), v, prop->name, NULL);
1277         visit_complete(v, &str);
1278         visit_free(v);
1279         monitor_printf(mon, ",%s=%s", prop->name, str);
1280         g_free(str);
1281     }
1282     monitor_printf(mon, "\n");
1283 }
1284 
1285 void print_net_client(Monitor *mon, NetClientState *nc)
1286 {
1287     NetFilterState *nf;
1288 
1289     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1290                    nc->queue_index,
1291                    NetClientDriver_lookup[nc->info->type],
1292                    nc->info_str);
1293     if (!QTAILQ_EMPTY(&nc->filters)) {
1294         monitor_printf(mon, "filters:\n");
1295     }
1296     QTAILQ_FOREACH(nf, &nc->filters, next) {
1297         char *path = object_get_canonical_path_component(OBJECT(nf));
1298 
1299         monitor_printf(mon, "  - %s: type=%s", path,
1300                        object_get_typename(OBJECT(nf)));
1301         netfilter_print_info(mon, nf);
1302         g_free(path);
1303     }
1304 }
1305 
1306 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1307                                       Error **errp)
1308 {
1309     NetClientState *nc;
1310     RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1311 
1312     QTAILQ_FOREACH(nc, &net_clients, next) {
1313         RxFilterInfoList *entry;
1314         RxFilterInfo *info;
1315 
1316         if (has_name && strcmp(nc->name, name) != 0) {
1317             continue;
1318         }
1319 
1320         /* only query rx-filter information of NIC */
1321         if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1322             if (has_name) {
1323                 error_setg(errp, "net client(%s) isn't a NIC", name);
1324                 return NULL;
1325             }
1326             continue;
1327         }
1328 
1329         /* only query information on queue 0 since the info is per nic,
1330          * not per queue
1331          */
1332         if (nc->queue_index != 0)
1333             continue;
1334 
1335         if (nc->info->query_rx_filter) {
1336             info = nc->info->query_rx_filter(nc);
1337             entry = g_malloc0(sizeof(*entry));
1338             entry->value = info;
1339 
1340             if (!filter_list) {
1341                 filter_list = entry;
1342             } else {
1343                 last_entry->next = entry;
1344             }
1345             last_entry = entry;
1346         } else if (has_name) {
1347             error_setg(errp, "net client(%s) doesn't support"
1348                        " rx-filter querying", name);
1349             return NULL;
1350         }
1351 
1352         if (has_name) {
1353             break;
1354         }
1355     }
1356 
1357     if (filter_list == NULL && has_name) {
1358         error_setg(errp, "invalid net client name: %s", name);
1359     }
1360 
1361     return filter_list;
1362 }
1363 
1364 void hmp_info_network(Monitor *mon, const QDict *qdict)
1365 {
1366     NetClientState *nc, *peer;
1367     NetClientDriver type;
1368 
1369     net_hub_info(mon);
1370 
1371     QTAILQ_FOREACH(nc, &net_clients, next) {
1372         peer = nc->peer;
1373         type = nc->info->type;
1374 
1375         /* Skip if already printed in hub info */
1376         if (net_hub_id_for_client(nc, NULL) == 0) {
1377             continue;
1378         }
1379 
1380         if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1381             print_net_client(mon, nc);
1382         } /* else it's a netdev connected to a NIC, printed with the NIC */
1383         if (peer && type == NET_CLIENT_DRIVER_NIC) {
1384             monitor_printf(mon, " \\ ");
1385             print_net_client(mon, peer);
1386         }
1387     }
1388 }
1389 
1390 void qmp_set_link(const char *name, bool up, Error **errp)
1391 {
1392     NetClientState *ncs[MAX_QUEUE_NUM];
1393     NetClientState *nc;
1394     int queues, i;
1395 
1396     queues = qemu_find_net_clients_except(name, ncs,
1397                                           NET_CLIENT_DRIVER__MAX,
1398                                           MAX_QUEUE_NUM);
1399 
1400     if (queues == 0) {
1401         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1402                   "Device '%s' not found", name);
1403         return;
1404     }
1405     nc = ncs[0];
1406 
1407     for (i = 0; i < queues; i++) {
1408         ncs[i]->link_down = !up;
1409     }
1410 
1411     if (nc->info->link_status_changed) {
1412         nc->info->link_status_changed(nc);
1413     }
1414 
1415     if (nc->peer) {
1416         /* Change peer link only if the peer is NIC and then notify peer.
1417          * If the peer is a HUBPORT or a backend, we do not change the
1418          * link status.
1419          *
1420          * This behavior is compatible with qemu vlans where there could be
1421          * multiple clients that can still communicate with each other in
1422          * disconnected mode. For now maintain this compatibility.
1423          */
1424         if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1425             for (i = 0; i < queues; i++) {
1426                 ncs[i]->peer->link_down = !up;
1427             }
1428         }
1429         if (nc->peer->info->link_status_changed) {
1430             nc->peer->info->link_status_changed(nc->peer);
1431         }
1432     }
1433 }
1434 
1435 static void net_vm_change_state_handler(void *opaque, int running,
1436                                         RunState state)
1437 {
1438     NetClientState *nc;
1439     NetClientState *tmp;
1440 
1441     QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1442         if (running) {
1443             /* Flush queued packets and wake up backends. */
1444             if (nc->peer && qemu_can_send_packet(nc)) {
1445                 qemu_flush_queued_packets(nc->peer);
1446             }
1447         } else {
1448             /* Complete all queued packets, to guarantee we don't modify
1449              * state later when VM is not running.
1450              */
1451             qemu_flush_or_purge_queued_packets(nc, true);
1452         }
1453     }
1454 }
1455 
1456 void net_cleanup(void)
1457 {
1458     NetClientState *nc;
1459 
1460     /* We may del multiple entries during qemu_del_net_client(),
1461      * so QTAILQ_FOREACH_SAFE() is also not safe here.
1462      */
1463     while (!QTAILQ_EMPTY(&net_clients)) {
1464         nc = QTAILQ_FIRST(&net_clients);
1465         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1466             qemu_del_nic(qemu_get_nic(nc));
1467         } else {
1468             qemu_del_net_client(nc);
1469         }
1470     }
1471 
1472     qemu_del_vm_change_state_handler(net_change_state_entry);
1473 }
1474 
1475 void net_check_clients(void)
1476 {
1477     NetClientState *nc;
1478     int i;
1479 
1480     net_hub_check_clients();
1481 
1482     QTAILQ_FOREACH(nc, &net_clients, next) {
1483         if (!nc->peer) {
1484             fprintf(stderr, "Warning: %s %s has no peer\n",
1485                     nc->info->type == NET_CLIENT_DRIVER_NIC ?
1486                     "nic" : "netdev", nc->name);
1487         }
1488     }
1489 
1490     /* Check that all NICs requested via -net nic actually got created.
1491      * NICs created via -device don't need to be checked here because
1492      * they are always instantiated.
1493      */
1494     for (i = 0; i < MAX_NICS; i++) {
1495         NICInfo *nd = &nd_table[i];
1496         if (nd->used && !nd->instantiated) {
1497             fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1498                     "was not created (not supported by this machine?)\n",
1499                     nd->name ? nd->name : "anonymous",
1500                     nd->model ? nd->model : "unspecified");
1501         }
1502     }
1503 }
1504 
1505 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1506 {
1507     Error *local_err = NULL;
1508 
1509     net_client_init(opts, false, &local_err);
1510     if (local_err) {
1511         error_report_err(local_err);
1512         return -1;
1513     }
1514 
1515     return 0;
1516 }
1517 
1518 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1519 {
1520     Error *local_err = NULL;
1521     int ret;
1522 
1523     ret = net_client_init(opts, true, &local_err);
1524     if (local_err) {
1525         error_report_err(local_err);
1526         return -1;
1527     }
1528 
1529     return ret;
1530 }
1531 
1532 int net_init_clients(void)
1533 {
1534     QemuOptsList *net = qemu_find_opts("net");
1535 
1536     net_change_state_entry =
1537         qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1538 
1539     QTAILQ_INIT(&net_clients);
1540 
1541     if (qemu_opts_foreach(qemu_find_opts("netdev"),
1542                           net_init_netdev, NULL, NULL)) {
1543         return -1;
1544     }
1545 
1546     if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1547         return -1;
1548     }
1549 
1550     return 0;
1551 }
1552 
1553 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1554 {
1555 #if defined(CONFIG_SLIRP)
1556     int ret;
1557     if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1558         return ret;
1559     }
1560 #endif
1561 
1562     if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1563         return -1;
1564     }
1565 
1566     return 0;
1567 }
1568 
1569 /* From FreeBSD */
1570 /* XXX: optimize */
1571 unsigned compute_mcast_idx(const uint8_t *ep)
1572 {
1573     uint32_t crc;
1574     int carry, i, j;
1575     uint8_t b;
1576 
1577     crc = 0xffffffff;
1578     for (i = 0; i < 6; i++) {
1579         b = *ep++;
1580         for (j = 0; j < 8; j++) {
1581             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1582             crc <<= 1;
1583             b >>= 1;
1584             if (carry) {
1585                 crc = ((crc ^ POLYNOMIAL) | carry);
1586             }
1587         }
1588     }
1589     return crc >> 26;
1590 }
1591 
1592 QemuOptsList qemu_netdev_opts = {
1593     .name = "netdev",
1594     .implied_opt_name = "type",
1595     .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1596     .desc = {
1597         /*
1598          * no elements => accept any params
1599          * validation will happen later
1600          */
1601         { /* end of list */ }
1602     },
1603 };
1604 
1605 QemuOptsList qemu_net_opts = {
1606     .name = "net",
1607     .implied_opt_name = "type",
1608     .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1609     .desc = {
1610         /*
1611          * no elements => accept any params
1612          * validation will happen later
1613          */
1614         { /* end of list */ }
1615     },
1616 };
1617 
1618 void net_socket_rs_init(SocketReadState *rs,
1619                         SocketReadStateFinalize *finalize,
1620                         bool vnet_hdr)
1621 {
1622     rs->state = 0;
1623     rs->vnet_hdr = vnet_hdr;
1624     rs->index = 0;
1625     rs->packet_len = 0;
1626     rs->vnet_hdr_len = 0;
1627     memset(rs->buf, 0, sizeof(rs->buf));
1628     rs->finalize = finalize;
1629 }
1630 
1631 /*
1632  * Returns
1633  * 0: success
1634  * -1: error occurs
1635  */
1636 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1637 {
1638     unsigned int l;
1639 
1640     while (size > 0) {
1641         /* Reassemble a packet from the network.
1642          * 0 = getting length.
1643          * 1 = getting vnet header length.
1644          * 2 = getting data.
1645          */
1646         switch (rs->state) {
1647         case 0:
1648             l = 4 - rs->index;
1649             if (l > size) {
1650                 l = size;
1651             }
1652             memcpy(rs->buf + rs->index, buf, l);
1653             buf += l;
1654             size -= l;
1655             rs->index += l;
1656             if (rs->index == 4) {
1657                 /* got length */
1658                 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1659                 rs->index = 0;
1660                 if (rs->vnet_hdr) {
1661                     rs->state = 1;
1662                 } else {
1663                     rs->state = 2;
1664                     rs->vnet_hdr_len = 0;
1665                 }
1666             }
1667             break;
1668         case 1:
1669             l = 4 - rs->index;
1670             if (l > size) {
1671                 l = size;
1672             }
1673             memcpy(rs->buf + rs->index, buf, l);
1674             buf += l;
1675             size -= l;
1676             rs->index += l;
1677             if (rs->index == 4) {
1678                 /* got vnet header length */
1679                 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1680                 rs->index = 0;
1681                 rs->state = 2;
1682             }
1683             break;
1684         case 2:
1685             l = rs->packet_len - rs->index;
1686             if (l > size) {
1687                 l = size;
1688             }
1689             if (rs->index + l <= sizeof(rs->buf)) {
1690                 memcpy(rs->buf + rs->index, buf, l);
1691             } else {
1692                 fprintf(stderr, "serious error: oversized packet received,"
1693                     "connection terminated.\n");
1694                 rs->index = rs->state = 0;
1695                 return -1;
1696             }
1697 
1698             rs->index += l;
1699             buf += l;
1700             size -= l;
1701             if (rs->index >= rs->packet_len) {
1702                 rs->index = 0;
1703                 rs->state = 0;
1704                 assert(rs->finalize);
1705                 rs->finalize(rs);
1706             }
1707             break;
1708         }
1709     }
1710 
1711     assert(size == 0);
1712     return 0;
1713 }
1714