xref: /openbmc/qemu/net/net.c (revision d044b7c3)
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 
25 #include "qemu/osdep.h"
26 
27 #include "net/net.h"
28 #include "clients.h"
29 #include "hub.h"
30 #include "hw/qdev-properties.h"
31 #include "net/slirp.h"
32 #include "net/eth.h"
33 #include "util.h"
34 
35 #include "monitor/monitor.h"
36 #include "qemu/help_option.h"
37 #include "qapi/qapi-commands-net.h"
38 #include "qapi/qapi-visit-net.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qmp/qerror.h"
41 #include "qemu/error-report.h"
42 #include "qemu/sockets.h"
43 #include "qemu/cutils.h"
44 #include "qemu/config-file.h"
45 #include "qemu/ctype.h"
46 #include "qemu/id.h"
47 #include "qemu/iov.h"
48 #include "qemu/qemu-print.h"
49 #include "qemu/main-loop.h"
50 #include "qemu/option.h"
51 #include "qemu/keyval.h"
52 #include "qapi/error.h"
53 #include "qapi/opts-visitor.h"
54 #include "sysemu/runstate.h"
55 #include "net/colo-compare.h"
56 #include "net/filter.h"
57 #include "qapi/string-output-visitor.h"
58 #include "qapi/qobject-input-visitor.h"
59 
60 /* Net bridge is currently not supported for W32. */
61 #if !defined(_WIN32)
62 # define CONFIG_NET_BRIDGE
63 #endif
64 
65 static VMChangeStateEntry *net_change_state_entry;
66 NetClientStateList net_clients;
67 
68 typedef struct NetdevQueueEntry {
69     Netdev *nd;
70     Location loc;
71     QSIMPLEQ_ENTRY(NetdevQueueEntry) entry;
72 } NetdevQueueEntry;
73 
74 typedef QSIMPLEQ_HEAD(, NetdevQueueEntry) NetdevQueue;
75 
76 static NetdevQueue nd_queue = QSIMPLEQ_HEAD_INITIALIZER(nd_queue);
77 
78 /***********************************************************/
79 /* network device redirectors */
80 
81 int convert_host_port(struct sockaddr_in *saddr, const char *host,
82                       const char *port, Error **errp)
83 {
84     struct hostent *he;
85     const char *r;
86     long p;
87 
88     memset(saddr, 0, sizeof(*saddr));
89 
90     saddr->sin_family = AF_INET;
91     if (host[0] == '\0') {
92         saddr->sin_addr.s_addr = 0;
93     } else {
94         if (qemu_isdigit(host[0])) {
95             if (!inet_aton(host, &saddr->sin_addr)) {
96                 error_setg(errp, "host address '%s' is not a valid "
97                            "IPv4 address", host);
98                 return -1;
99             }
100         } else {
101             he = gethostbyname(host);
102             if (he == NULL) {
103                 error_setg(errp, "can't resolve host address '%s'", host);
104                 return -1;
105             }
106             saddr->sin_addr = *(struct in_addr *)he->h_addr;
107         }
108     }
109     if (qemu_strtol(port, &r, 0, &p) != 0) {
110         error_setg(errp, "port number '%s' is invalid", port);
111         return -1;
112     }
113     saddr->sin_port = htons(p);
114     return 0;
115 }
116 
117 int parse_host_port(struct sockaddr_in *saddr, const char *str,
118                     Error **errp)
119 {
120     gchar **substrings;
121     int ret;
122 
123     substrings = g_strsplit(str, ":", 2);
124     if (!substrings || !substrings[0] || !substrings[1]) {
125         error_setg(errp, "host address '%s' doesn't contain ':' "
126                    "separating host from port", str);
127         ret = -1;
128         goto out;
129     }
130 
131     ret = convert_host_port(saddr, substrings[0], substrings[1], errp);
132 
133 out:
134     g_strfreev(substrings);
135     return ret;
136 }
137 
138 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
139 {
140     return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
141                            macaddr[0], macaddr[1], macaddr[2],
142                            macaddr[3], macaddr[4], macaddr[5]);
143 }
144 
145 void qemu_set_info_str(NetClientState *nc, const char *fmt, ...)
146 {
147     va_list ap;
148 
149     va_start(ap, fmt);
150     vsnprintf(nc->info_str, sizeof(nc->info_str), fmt, ap);
151     va_end(ap);
152 }
153 
154 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
155 {
156     qemu_set_info_str(nc, "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
157                       nc->model, macaddr[0], macaddr[1], macaddr[2],
158                       macaddr[3], macaddr[4], macaddr[5]);
159 }
160 
161 static int mac_table[256] = {0};
162 
163 static void qemu_macaddr_set_used(MACAddr *macaddr)
164 {
165     int index;
166 
167     for (index = 0x56; index < 0xFF; index++) {
168         if (macaddr->a[5] == index) {
169             mac_table[index]++;
170         }
171     }
172 }
173 
174 static void qemu_macaddr_set_free(MACAddr *macaddr)
175 {
176     int index;
177     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
178 
179     if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
180         return;
181     }
182     for (index = 0x56; index < 0xFF; index++) {
183         if (macaddr->a[5] == index) {
184             mac_table[index]--;
185         }
186     }
187 }
188 
189 static int qemu_macaddr_get_free(void)
190 {
191     int index;
192 
193     for (index = 0x56; index < 0xFF; index++) {
194         if (mac_table[index] == 0) {
195             return index;
196         }
197     }
198 
199     return -1;
200 }
201 
202 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
203 {
204     static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
205     static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
206 
207     if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
208         if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
209             return;
210         } else {
211             qemu_macaddr_set_used(macaddr);
212             return;
213         }
214     }
215 
216     macaddr->a[0] = 0x52;
217     macaddr->a[1] = 0x54;
218     macaddr->a[2] = 0x00;
219     macaddr->a[3] = 0x12;
220     macaddr->a[4] = 0x34;
221     macaddr->a[5] = qemu_macaddr_get_free();
222     qemu_macaddr_set_used(macaddr);
223 }
224 
225 /**
226  * Generate a name for net client
227  *
228  * Only net clients created with the legacy -net option and NICs need this.
229  */
230 static char *assign_name(NetClientState *nc1, const char *model)
231 {
232     NetClientState *nc;
233     int id = 0;
234 
235     QTAILQ_FOREACH(nc, &net_clients, next) {
236         if (nc == nc1) {
237             continue;
238         }
239         if (strcmp(nc->model, model) == 0) {
240             id++;
241         }
242     }
243 
244     return g_strdup_printf("%s.%d", model, id);
245 }
246 
247 static void qemu_net_client_destructor(NetClientState *nc)
248 {
249     g_free(nc);
250 }
251 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
252                                        unsigned flags,
253                                        const struct iovec *iov,
254                                        int iovcnt,
255                                        void *opaque);
256 
257 static void qemu_net_client_setup(NetClientState *nc,
258                                   NetClientInfo *info,
259                                   NetClientState *peer,
260                                   const char *model,
261                                   const char *name,
262                                   NetClientDestructor *destructor,
263                                   bool is_datapath)
264 {
265     nc->info = info;
266     nc->model = g_strdup(model);
267     if (name) {
268         nc->name = g_strdup(name);
269     } else {
270         nc->name = assign_name(nc, model);
271     }
272 
273     if (peer) {
274         assert(!peer->peer);
275         nc->peer = peer;
276         peer->peer = nc;
277     }
278     QTAILQ_INSERT_TAIL(&net_clients, nc, next);
279 
280     nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
281     nc->destructor = destructor;
282     nc->is_datapath = is_datapath;
283     QTAILQ_INIT(&nc->filters);
284 }
285 
286 NetClientState *qemu_new_net_client(NetClientInfo *info,
287                                     NetClientState *peer,
288                                     const char *model,
289                                     const char *name)
290 {
291     NetClientState *nc;
292 
293     assert(info->size >= sizeof(NetClientState));
294 
295     nc = g_malloc0(info->size);
296     qemu_net_client_setup(nc, info, peer, model, name,
297                           qemu_net_client_destructor, true);
298 
299     return nc;
300 }
301 
302 NetClientState *qemu_new_net_control_client(NetClientInfo *info,
303                                             NetClientState *peer,
304                                             const char *model,
305                                             const char *name)
306 {
307     NetClientState *nc;
308 
309     assert(info->size >= sizeof(NetClientState));
310 
311     nc = g_malloc0(info->size);
312     qemu_net_client_setup(nc, info, peer, model, name,
313                           qemu_net_client_destructor, false);
314 
315     return nc;
316 }
317 
318 NICState *qemu_new_nic(NetClientInfo *info,
319                        NICConf *conf,
320                        const char *model,
321                        const char *name,
322                        void *opaque)
323 {
324     NetClientState **peers = conf->peers.ncs;
325     NICState *nic;
326     int i, queues = MAX(1, conf->peers.queues);
327 
328     assert(info->type == NET_CLIENT_DRIVER_NIC);
329     assert(info->size >= sizeof(NICState));
330 
331     nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
332     nic->ncs = (void *)nic + info->size;
333     nic->conf = conf;
334     nic->opaque = opaque;
335 
336     for (i = 0; i < queues; i++) {
337         qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
338                               NULL, true);
339         nic->ncs[i].queue_index = i;
340     }
341 
342     return nic;
343 }
344 
345 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
346 {
347     return nic->ncs + queue_index;
348 }
349 
350 NetClientState *qemu_get_queue(NICState *nic)
351 {
352     return qemu_get_subqueue(nic, 0);
353 }
354 
355 NICState *qemu_get_nic(NetClientState *nc)
356 {
357     NetClientState *nc0 = nc - nc->queue_index;
358 
359     return (NICState *)((void *)nc0 - nc->info->size);
360 }
361 
362 void *qemu_get_nic_opaque(NetClientState *nc)
363 {
364     NICState *nic = qemu_get_nic(nc);
365 
366     return nic->opaque;
367 }
368 
369 NetClientState *qemu_get_peer(NetClientState *nc, int queue_index)
370 {
371     assert(nc != NULL);
372     NetClientState *ncs = nc + queue_index;
373     return ncs->peer;
374 }
375 
376 static void qemu_cleanup_net_client(NetClientState *nc)
377 {
378     QTAILQ_REMOVE(&net_clients, nc, next);
379 
380     if (nc->info->cleanup) {
381         nc->info->cleanup(nc);
382     }
383 }
384 
385 static void qemu_free_net_client(NetClientState *nc)
386 {
387     if (nc->incoming_queue) {
388         qemu_del_net_queue(nc->incoming_queue);
389     }
390     if (nc->peer) {
391         nc->peer->peer = NULL;
392     }
393     g_free(nc->name);
394     g_free(nc->model);
395     if (nc->destructor) {
396         nc->destructor(nc);
397     }
398 }
399 
400 void qemu_del_net_client(NetClientState *nc)
401 {
402     NetClientState *ncs[MAX_QUEUE_NUM];
403     int queues, i;
404     NetFilterState *nf, *next;
405 
406     assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
407 
408     /* If the NetClientState belongs to a multiqueue backend, we will change all
409      * other NetClientStates also.
410      */
411     queues = qemu_find_net_clients_except(nc->name, ncs,
412                                           NET_CLIENT_DRIVER_NIC,
413                                           MAX_QUEUE_NUM);
414     assert(queues != 0);
415 
416     QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
417         object_unparent(OBJECT(nf));
418     }
419 
420     /* If there is a peer NIC, delete and cleanup client, but do not free. */
421     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
422         NICState *nic = qemu_get_nic(nc->peer);
423         if (nic->peer_deleted) {
424             return;
425         }
426         nic->peer_deleted = true;
427 
428         for (i = 0; i < queues; i++) {
429             ncs[i]->peer->link_down = true;
430         }
431 
432         if (nc->peer->info->link_status_changed) {
433             nc->peer->info->link_status_changed(nc->peer);
434         }
435 
436         for (i = 0; i < queues; i++) {
437             qemu_cleanup_net_client(ncs[i]);
438         }
439 
440         return;
441     }
442 
443     for (i = 0; i < queues; i++) {
444         qemu_cleanup_net_client(ncs[i]);
445         qemu_free_net_client(ncs[i]);
446     }
447 }
448 
449 void qemu_del_nic(NICState *nic)
450 {
451     int i, queues = MAX(nic->conf->peers.queues, 1);
452 
453     qemu_macaddr_set_free(&nic->conf->macaddr);
454 
455     for (i = 0; i < queues; i++) {
456         NetClientState *nc = qemu_get_subqueue(nic, i);
457         /* If this is a peer NIC and peer has already been deleted, free it now. */
458         if (nic->peer_deleted) {
459             qemu_free_net_client(nc->peer);
460         } else if (nc->peer) {
461             /* if there are RX packets pending, complete them */
462             qemu_purge_queued_packets(nc->peer);
463         }
464     }
465 
466     for (i = queues - 1; i >= 0; i--) {
467         NetClientState *nc = qemu_get_subqueue(nic, i);
468 
469         qemu_cleanup_net_client(nc);
470         qemu_free_net_client(nc);
471     }
472 
473     g_free(nic);
474 }
475 
476 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
477 {
478     NetClientState *nc;
479 
480     QTAILQ_FOREACH(nc, &net_clients, next) {
481         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
482             if (nc->queue_index == 0) {
483                 func(qemu_get_nic(nc), opaque);
484             }
485         }
486     }
487 }
488 
489 bool qemu_has_ufo(NetClientState *nc)
490 {
491     if (!nc || !nc->info->has_ufo) {
492         return false;
493     }
494 
495     return nc->info->has_ufo(nc);
496 }
497 
498 bool qemu_has_vnet_hdr(NetClientState *nc)
499 {
500     if (!nc || !nc->info->has_vnet_hdr) {
501         return false;
502     }
503 
504     return nc->info->has_vnet_hdr(nc);
505 }
506 
507 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
508 {
509     if (!nc || !nc->info->has_vnet_hdr_len) {
510         return false;
511     }
512 
513     return nc->info->has_vnet_hdr_len(nc, len);
514 }
515 
516 bool qemu_get_using_vnet_hdr(NetClientState *nc)
517 {
518     if (!nc || !nc->info->get_using_vnet_hdr) {
519         return false;
520     }
521 
522     return nc->info->get_using_vnet_hdr(nc);
523 }
524 
525 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
526 {
527     if (!nc || !nc->info->using_vnet_hdr) {
528         return;
529     }
530 
531     nc->info->using_vnet_hdr(nc, enable);
532 }
533 
534 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
535                           int ecn, int ufo)
536 {
537     if (!nc || !nc->info->set_offload) {
538         return;
539     }
540 
541     nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
542 }
543 
544 int qemu_get_vnet_hdr_len(NetClientState *nc)
545 {
546     if (!nc || !nc->info->get_vnet_hdr_len) {
547         return 0;
548     }
549 
550     return nc->info->get_vnet_hdr_len(nc);
551 }
552 
553 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
554 {
555     if (!nc || !nc->info->set_vnet_hdr_len) {
556         return;
557     }
558 
559     nc->vnet_hdr_len = len;
560     nc->info->set_vnet_hdr_len(nc, len);
561 }
562 
563 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
564 {
565 #if HOST_BIG_ENDIAN
566     if (!nc || !nc->info->set_vnet_le) {
567         return -ENOSYS;
568     }
569 
570     return nc->info->set_vnet_le(nc, is_le);
571 #else
572     return 0;
573 #endif
574 }
575 
576 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
577 {
578 #if HOST_BIG_ENDIAN
579     return 0;
580 #else
581     if (!nc || !nc->info->set_vnet_be) {
582         return -ENOSYS;
583     }
584 
585     return nc->info->set_vnet_be(nc, is_be);
586 #endif
587 }
588 
589 int qemu_can_receive_packet(NetClientState *nc)
590 {
591     if (nc->receive_disabled) {
592         return 0;
593     } else if (nc->info->can_receive &&
594                !nc->info->can_receive(nc)) {
595         return 0;
596     }
597     return 1;
598 }
599 
600 int qemu_can_send_packet(NetClientState *sender)
601 {
602     int vm_running = runstate_is_running();
603 
604     if (!vm_running) {
605         return 0;
606     }
607 
608     if (!sender->peer) {
609         return 1;
610     }
611 
612     return qemu_can_receive_packet(sender->peer);
613 }
614 
615 static ssize_t filter_receive_iov(NetClientState *nc,
616                                   NetFilterDirection direction,
617                                   NetClientState *sender,
618                                   unsigned flags,
619                                   const struct iovec *iov,
620                                   int iovcnt,
621                                   NetPacketSent *sent_cb)
622 {
623     ssize_t ret = 0;
624     NetFilterState *nf = NULL;
625 
626     if (direction == NET_FILTER_DIRECTION_TX) {
627         QTAILQ_FOREACH(nf, &nc->filters, next) {
628             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
629                                          iovcnt, sent_cb);
630             if (ret) {
631                 return ret;
632             }
633         }
634     } else {
635         QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
636             ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
637                                          iovcnt, sent_cb);
638             if (ret) {
639                 return ret;
640             }
641         }
642     }
643 
644     return ret;
645 }
646 
647 static ssize_t filter_receive(NetClientState *nc,
648                               NetFilterDirection direction,
649                               NetClientState *sender,
650                               unsigned flags,
651                               const uint8_t *data,
652                               size_t size,
653                               NetPacketSent *sent_cb)
654 {
655     struct iovec iov = {
656         .iov_base = (void *)data,
657         .iov_len = size
658     };
659 
660     return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
661 }
662 
663 void qemu_purge_queued_packets(NetClientState *nc)
664 {
665     if (!nc->peer) {
666         return;
667     }
668 
669     qemu_net_queue_purge(nc->peer->incoming_queue, nc);
670 }
671 
672 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
673 {
674     nc->receive_disabled = 0;
675 
676     if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
677         if (net_hub_flush(nc->peer)) {
678             qemu_notify_event();
679         }
680     }
681     if (qemu_net_queue_flush(nc->incoming_queue)) {
682         /* We emptied the queue successfully, signal to the IO thread to repoll
683          * the file descriptor (for tap, for example).
684          */
685         qemu_notify_event();
686     } else if (purge) {
687         /* Unable to empty the queue, purge remaining packets */
688         qemu_net_queue_purge(nc->incoming_queue, nc->peer);
689     }
690 }
691 
692 void qemu_flush_queued_packets(NetClientState *nc)
693 {
694     qemu_flush_or_purge_queued_packets(nc, false);
695 }
696 
697 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
698                                                  unsigned flags,
699                                                  const uint8_t *buf, int size,
700                                                  NetPacketSent *sent_cb)
701 {
702     NetQueue *queue;
703     int ret;
704 
705 #ifdef DEBUG_NET
706     printf("qemu_send_packet_async:\n");
707     qemu_hexdump(stdout, "net", buf, size);
708 #endif
709 
710     if (sender->link_down || !sender->peer) {
711         return size;
712     }
713 
714     /* Let filters handle the packet first */
715     ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
716                          sender, flags, buf, size, sent_cb);
717     if (ret) {
718         return ret;
719     }
720 
721     ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
722                          sender, flags, buf, size, sent_cb);
723     if (ret) {
724         return ret;
725     }
726 
727     queue = sender->peer->incoming_queue;
728 
729     return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
730 }
731 
732 ssize_t qemu_send_packet_async(NetClientState *sender,
733                                const uint8_t *buf, int size,
734                                NetPacketSent *sent_cb)
735 {
736     return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
737                                              buf, size, sent_cb);
738 }
739 
740 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
741 {
742     return qemu_send_packet_async(nc, buf, size, NULL);
743 }
744 
745 ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
746 {
747     if (!qemu_can_receive_packet(nc)) {
748         return 0;
749     }
750 
751     return qemu_net_queue_receive(nc->incoming_queue, buf, size);
752 }
753 
754 ssize_t qemu_receive_packet_iov(NetClientState *nc, const struct iovec *iov,
755                                 int iovcnt)
756 {
757     if (!qemu_can_receive_packet(nc)) {
758         return 0;
759     }
760 
761     return qemu_net_queue_receive_iov(nc->incoming_queue, iov, iovcnt);
762 }
763 
764 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
765 {
766     return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
767                                              buf, size, NULL);
768 }
769 
770 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
771                                int iovcnt, unsigned flags)
772 {
773     uint8_t *buf = NULL;
774     uint8_t *buffer;
775     size_t offset;
776     ssize_t ret;
777 
778     if (iovcnt == 1) {
779         buffer = iov[0].iov_base;
780         offset = iov[0].iov_len;
781     } else {
782         offset = iov_size(iov, iovcnt);
783         if (offset > NET_BUFSIZE) {
784             return -1;
785         }
786         buf = g_malloc(offset);
787         buffer = buf;
788         offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
789     }
790 
791     if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
792         ret = nc->info->receive_raw(nc, buffer, offset);
793     } else {
794         ret = nc->info->receive(nc, buffer, offset);
795     }
796 
797     g_free(buf);
798     return ret;
799 }
800 
801 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
802                                        unsigned flags,
803                                        const struct iovec *iov,
804                                        int iovcnt,
805                                        void *opaque)
806 {
807     NetClientState *nc = opaque;
808     int ret;
809 
810 
811     if (nc->link_down) {
812         return iov_size(iov, iovcnt);
813     }
814 
815     if (nc->receive_disabled) {
816         return 0;
817     }
818 
819     if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
820         ret = nc->info->receive_iov(nc, iov, iovcnt);
821     } else {
822         ret = nc_sendv_compat(nc, iov, iovcnt, flags);
823     }
824 
825     if (ret == 0) {
826         nc->receive_disabled = 1;
827     }
828 
829     return ret;
830 }
831 
832 ssize_t qemu_sendv_packet_async(NetClientState *sender,
833                                 const struct iovec *iov, int iovcnt,
834                                 NetPacketSent *sent_cb)
835 {
836     NetQueue *queue;
837     size_t size = iov_size(iov, iovcnt);
838     int ret;
839 
840     if (size > NET_BUFSIZE) {
841         return size;
842     }
843 
844     if (sender->link_down || !sender->peer) {
845         return size;
846     }
847 
848     /* Let filters handle the packet first */
849     ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
850                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
851     if (ret) {
852         return ret;
853     }
854 
855     ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
856                              QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
857     if (ret) {
858         return ret;
859     }
860 
861     queue = sender->peer->incoming_queue;
862 
863     return qemu_net_queue_send_iov(queue, sender,
864                                    QEMU_NET_PACKET_FLAG_NONE,
865                                    iov, iovcnt, sent_cb);
866 }
867 
868 ssize_t
869 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
870 {
871     return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
872 }
873 
874 NetClientState *qemu_find_netdev(const char *id)
875 {
876     NetClientState *nc;
877 
878     QTAILQ_FOREACH(nc, &net_clients, next) {
879         if (nc->info->type == NET_CLIENT_DRIVER_NIC)
880             continue;
881         if (!strcmp(nc->name, id)) {
882             return nc;
883         }
884     }
885 
886     return NULL;
887 }
888 
889 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
890                                  NetClientDriver type, int max)
891 {
892     NetClientState *nc;
893     int ret = 0;
894 
895     QTAILQ_FOREACH(nc, &net_clients, next) {
896         if (nc->info->type == type) {
897             continue;
898         }
899         if (!id || !strcmp(nc->name, id)) {
900             if (ret < max) {
901                 ncs[ret] = nc;
902             }
903             ret++;
904         }
905     }
906 
907     return ret;
908 }
909 
910 static int nic_get_free_idx(void)
911 {
912     int index;
913 
914     for (index = 0; index < MAX_NICS; index++)
915         if (!nd_table[index].used)
916             return index;
917     return -1;
918 }
919 
920 GPtrArray *qemu_get_nic_models(const char *device_type)
921 {
922     GPtrArray *nic_models = g_ptr_array_new();
923     GSList *list = object_class_get_list_sorted(device_type, false);
924 
925     while (list) {
926         DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, list->data,
927                                              TYPE_DEVICE);
928         GSList *next;
929         if (test_bit(DEVICE_CATEGORY_NETWORK, dc->categories) &&
930             dc->user_creatable) {
931             const char *name = object_class_get_name(list->data);
932             /*
933              * A network device might also be something else than a NIC, see
934              * e.g. the "rocker" device. Thus we have to look for the "netdev"
935              * property, too. Unfortunately, some devices like virtio-net only
936              * create this property during instance_init, so we have to create
937              * a temporary instance here to be able to check it.
938              */
939             Object *obj = object_new_with_class(OBJECT_CLASS(dc));
940             if (object_property_find(obj, "netdev")) {
941                 g_ptr_array_add(nic_models, (gpointer)name);
942             }
943             object_unref(obj);
944         }
945         next = list->next;
946         g_slist_free_1(list);
947         list = next;
948     }
949     g_ptr_array_add(nic_models, NULL);
950 
951     return nic_models;
952 }
953 
954 int qemu_show_nic_models(const char *arg, const char *const *models)
955 {
956     int i;
957 
958     if (!arg || !is_help_option(arg)) {
959         return 0;
960     }
961 
962     printf("Available NIC models:\n");
963     for (i = 0 ; models[i]; i++) {
964         printf("%s\n", models[i]);
965     }
966     return 1;
967 }
968 
969 void qemu_check_nic_model(NICInfo *nd, const char *model)
970 {
971     const char *models[2];
972 
973     models[0] = model;
974     models[1] = NULL;
975 
976     if (qemu_show_nic_models(nd->model, models))
977         exit(0);
978     if (qemu_find_nic_model(nd, models, model) < 0)
979         exit(1);
980 }
981 
982 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
983                         const char *default_model)
984 {
985     int i;
986 
987     if (!nd->model)
988         nd->model = g_strdup(default_model);
989 
990     for (i = 0 ; models[i]; i++) {
991         if (strcmp(nd->model, models[i]) == 0)
992             return i;
993     }
994 
995     error_report("Unsupported NIC model: %s", nd->model);
996     return -1;
997 }
998 
999 static int net_init_nic(const Netdev *netdev, const char *name,
1000                         NetClientState *peer, Error **errp)
1001 {
1002     int idx;
1003     NICInfo *nd;
1004     const NetLegacyNicOptions *nic;
1005 
1006     assert(netdev->type == NET_CLIENT_DRIVER_NIC);
1007     nic = &netdev->u.nic;
1008 
1009     idx = nic_get_free_idx();
1010     if (idx == -1 || nb_nics >= MAX_NICS) {
1011         error_setg(errp, "too many NICs");
1012         return -1;
1013     }
1014 
1015     nd = &nd_table[idx];
1016 
1017     memset(nd, 0, sizeof(*nd));
1018 
1019     if (nic->netdev) {
1020         nd->netdev = qemu_find_netdev(nic->netdev);
1021         if (!nd->netdev) {
1022             error_setg(errp, "netdev '%s' not found", nic->netdev);
1023             return -1;
1024         }
1025     } else {
1026         assert(peer);
1027         nd->netdev = peer;
1028     }
1029     nd->name = g_strdup(name);
1030     if (nic->model) {
1031         nd->model = g_strdup(nic->model);
1032     }
1033     if (nic->addr) {
1034         nd->devaddr = g_strdup(nic->addr);
1035     }
1036 
1037     if (nic->macaddr &&
1038         net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
1039         error_setg(errp, "invalid syntax for ethernet address");
1040         return -1;
1041     }
1042     if (nic->macaddr &&
1043         is_multicast_ether_addr(nd->macaddr.a)) {
1044         error_setg(errp,
1045                    "NIC cannot have multicast MAC address (odd 1st byte)");
1046         return -1;
1047     }
1048     qemu_macaddr_default_if_unset(&nd->macaddr);
1049 
1050     if (nic->has_vectors) {
1051         if (nic->vectors > 0x7ffffff) {
1052             error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
1053             return -1;
1054         }
1055         nd->nvectors = nic->vectors;
1056     } else {
1057         nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
1058     }
1059 
1060     nd->used = 1;
1061     nb_nics++;
1062 
1063     return idx;
1064 }
1065 
1066 
1067 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
1068     const Netdev *netdev,
1069     const char *name,
1070     NetClientState *peer, Error **errp) = {
1071         [NET_CLIENT_DRIVER_NIC]       = net_init_nic,
1072 #ifdef CONFIG_SLIRP
1073         [NET_CLIENT_DRIVER_USER]      = net_init_slirp,
1074 #endif
1075         [NET_CLIENT_DRIVER_TAP]       = net_init_tap,
1076         [NET_CLIENT_DRIVER_SOCKET]    = net_init_socket,
1077         [NET_CLIENT_DRIVER_STREAM]    = net_init_stream,
1078         [NET_CLIENT_DRIVER_DGRAM]     = net_init_dgram,
1079 #ifdef CONFIG_VDE
1080         [NET_CLIENT_DRIVER_VDE]       = net_init_vde,
1081 #endif
1082 #ifdef CONFIG_NETMAP
1083         [NET_CLIENT_DRIVER_NETMAP]    = net_init_netmap,
1084 #endif
1085 #ifdef CONFIG_NET_BRIDGE
1086         [NET_CLIENT_DRIVER_BRIDGE]    = net_init_bridge,
1087 #endif
1088         [NET_CLIENT_DRIVER_HUBPORT]   = net_init_hubport,
1089 #ifdef CONFIG_VHOST_NET_USER
1090         [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
1091 #endif
1092 #ifdef CONFIG_VHOST_NET_VDPA
1093         [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
1094 #endif
1095 #ifdef CONFIG_L2TPV3
1096         [NET_CLIENT_DRIVER_L2TPV3]    = net_init_l2tpv3,
1097 #endif
1098 #ifdef CONFIG_VMNET
1099         [NET_CLIENT_DRIVER_VMNET_HOST] = net_init_vmnet_host,
1100         [NET_CLIENT_DRIVER_VMNET_SHARED] = net_init_vmnet_shared,
1101         [NET_CLIENT_DRIVER_VMNET_BRIDGED] = net_init_vmnet_bridged,
1102 #endif /* CONFIG_VMNET */
1103 };
1104 
1105 
1106 static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
1107 {
1108     NetClientState *peer = NULL;
1109     NetClientState *nc;
1110 
1111     if (is_netdev) {
1112         if (netdev->type == NET_CLIENT_DRIVER_NIC ||
1113             !net_client_init_fun[netdev->type]) {
1114             error_setg(errp, "network backend '%s' is not compiled into this binary",
1115                        NetClientDriver_str(netdev->type));
1116             return -1;
1117         }
1118     } else {
1119         if (netdev->type == NET_CLIENT_DRIVER_NONE) {
1120             return 0; /* nothing to do */
1121         }
1122         if (netdev->type == NET_CLIENT_DRIVER_HUBPORT) {
1123             error_setg(errp, "network backend '%s' is only supported with -netdev/-nic",
1124                        NetClientDriver_str(netdev->type));
1125             return -1;
1126         }
1127 
1128         if (!net_client_init_fun[netdev->type]) {
1129             error_setg(errp, "network backend '%s' is not compiled into this binary",
1130                        NetClientDriver_str(netdev->type));
1131             return -1;
1132         }
1133 
1134         /* Do not add to a hub if it's a nic with a netdev= parameter. */
1135         if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1136             !netdev->u.nic.netdev) {
1137             peer = net_hub_add_port(0, NULL, NULL);
1138         }
1139     }
1140 
1141     nc = qemu_find_netdev(netdev->id);
1142     if (nc) {
1143         error_setg(errp, "Duplicate ID '%s'", netdev->id);
1144         return -1;
1145     }
1146 
1147     if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
1148         /* FIXME drop when all init functions store an Error */
1149         if (errp && !*errp) {
1150             error_setg(errp, "Device '%s' could not be initialized",
1151                        NetClientDriver_str(netdev->type));
1152         }
1153         return -1;
1154     }
1155 
1156     if (is_netdev) {
1157         nc = qemu_find_netdev(netdev->id);
1158         assert(nc);
1159         nc->is_netdev = true;
1160     }
1161 
1162     return 0;
1163 }
1164 
1165 void show_netdevs(void)
1166 {
1167     int idx;
1168     const char *available_netdevs[] = {
1169         "socket",
1170         "stream",
1171         "dgram",
1172         "hubport",
1173         "tap",
1174 #ifdef CONFIG_SLIRP
1175         "user",
1176 #endif
1177 #ifdef CONFIG_L2TPV3
1178         "l2tpv3",
1179 #endif
1180 #ifdef CONFIG_VDE
1181         "vde",
1182 #endif
1183 #ifdef CONFIG_NET_BRIDGE
1184         "bridge",
1185 #endif
1186 #ifdef CONFIG_NETMAP
1187         "netmap",
1188 #endif
1189 #ifdef CONFIG_POSIX
1190         "vhost-user",
1191 #endif
1192 #ifdef CONFIG_VHOST_VDPA
1193         "vhost-vdpa",
1194 #endif
1195 #ifdef CONFIG_VMNET
1196         "vmnet-host",
1197         "vmnet-shared",
1198         "vmnet-bridged",
1199 #endif
1200     };
1201 
1202     qemu_printf("Available netdev backend types:\n");
1203     for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1204         qemu_printf("%s\n", available_netdevs[idx]);
1205     }
1206 }
1207 
1208 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1209 {
1210     gchar **substrings = NULL;
1211     Netdev *object = NULL;
1212     int ret = -1;
1213     Visitor *v = opts_visitor_new(opts);
1214 
1215     /* Parse convenience option format ip6-net=fec0::0[/64] */
1216     const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1217 
1218     if (ip6_net) {
1219         char *prefix_addr;
1220         unsigned long prefix_len = 64; /* Default 64bit prefix length. */
1221 
1222         substrings = g_strsplit(ip6_net, "/", 2);
1223         if (!substrings || !substrings[0]) {
1224             error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
1225                        "a valid IPv6 prefix");
1226             goto out;
1227         }
1228 
1229         prefix_addr = substrings[0];
1230 
1231         /* Handle user-specified prefix length. */
1232         if (substrings[1] &&
1233             qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
1234         {
1235             error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1236                        "ipv6-prefixlen", "a number");
1237             goto out;
1238         }
1239 
1240         qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
1241         qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
1242                             &error_abort);
1243         qemu_opt_unset(opts, "ipv6-net");
1244     }
1245 
1246     /* Create an ID for -net if the user did not specify one */
1247     if (!is_netdev && !qemu_opts_id(opts)) {
1248         qemu_opts_set_id(opts, id_generate(ID_NET));
1249     }
1250 
1251     if (visit_type_Netdev(v, NULL, &object, errp)) {
1252         ret = net_client_init1(object, is_netdev, errp);
1253     }
1254 
1255     qapi_free_Netdev(object);
1256 
1257 out:
1258     g_strfreev(substrings);
1259     visit_free(v);
1260     return ret;
1261 }
1262 
1263 void netdev_add(QemuOpts *opts, Error **errp)
1264 {
1265     net_client_init(opts, true, errp);
1266 }
1267 
1268 void qmp_netdev_add(Netdev *netdev, Error **errp)
1269 {
1270     if (!id_wellformed(netdev->id)) {
1271         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
1272         return;
1273     }
1274 
1275     net_client_init1(netdev, true, errp);
1276 }
1277 
1278 void qmp_netdev_del(const char *id, Error **errp)
1279 {
1280     NetClientState *nc;
1281     QemuOpts *opts;
1282 
1283     nc = qemu_find_netdev(id);
1284     if (!nc) {
1285         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1286                   "Device '%s' not found", id);
1287         return;
1288     }
1289 
1290     if (!nc->is_netdev) {
1291         error_setg(errp, "Device '%s' is not a netdev", id);
1292         return;
1293     }
1294 
1295     qemu_del_net_client(nc);
1296 
1297     /*
1298      * Wart: we need to delete the QemuOpts associated with netdevs
1299      * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
1300      * HMP netdev_add.
1301      */
1302     opts = qemu_opts_find(qemu_find_opts("netdev"), id);
1303     if (opts) {
1304         qemu_opts_del(opts);
1305     }
1306 }
1307 
1308 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1309 {
1310     char *str;
1311     ObjectProperty *prop;
1312     ObjectPropertyIterator iter;
1313     Visitor *v;
1314 
1315     /* generate info str */
1316     object_property_iter_init(&iter, OBJECT(nf));
1317     while ((prop = object_property_iter_next(&iter))) {
1318         if (!strcmp(prop->name, "type")) {
1319             continue;
1320         }
1321         v = string_output_visitor_new(false, &str);
1322         object_property_get(OBJECT(nf), prop->name, v, NULL);
1323         visit_complete(v, &str);
1324         visit_free(v);
1325         monitor_printf(mon, ",%s=%s", prop->name, str);
1326         g_free(str);
1327     }
1328     monitor_printf(mon, "\n");
1329 }
1330 
1331 void print_net_client(Monitor *mon, NetClientState *nc)
1332 {
1333     NetFilterState *nf;
1334 
1335     monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1336                    nc->queue_index,
1337                    NetClientDriver_str(nc->info->type),
1338                    nc->info_str);
1339     if (!QTAILQ_EMPTY(&nc->filters)) {
1340         monitor_printf(mon, "filters:\n");
1341     }
1342     QTAILQ_FOREACH(nf, &nc->filters, next) {
1343         monitor_printf(mon, "  - %s: type=%s",
1344                        object_get_canonical_path_component(OBJECT(nf)),
1345                        object_get_typename(OBJECT(nf)));
1346         netfilter_print_info(mon, nf);
1347     }
1348 }
1349 
1350 RxFilterInfoList *qmp_query_rx_filter(const char *name, Error **errp)
1351 {
1352     NetClientState *nc;
1353     RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
1354 
1355     QTAILQ_FOREACH(nc, &net_clients, next) {
1356         RxFilterInfo *info;
1357 
1358         if (name && strcmp(nc->name, name) != 0) {
1359             continue;
1360         }
1361 
1362         /* only query rx-filter information of NIC */
1363         if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1364             if (name) {
1365                 error_setg(errp, "net client(%s) isn't a NIC", name);
1366                 assert(!filter_list);
1367                 return NULL;
1368             }
1369             continue;
1370         }
1371 
1372         /* only query information on queue 0 since the info is per nic,
1373          * not per queue
1374          */
1375         if (nc->queue_index != 0)
1376             continue;
1377 
1378         if (nc->info->query_rx_filter) {
1379             info = nc->info->query_rx_filter(nc);
1380             QAPI_LIST_APPEND(tail, info);
1381         } else if (name) {
1382             error_setg(errp, "net client(%s) doesn't support"
1383                        " rx-filter querying", name);
1384             assert(!filter_list);
1385             return NULL;
1386         }
1387 
1388         if (name) {
1389             break;
1390         }
1391     }
1392 
1393     if (filter_list == NULL && name) {
1394         error_setg(errp, "invalid net client name: %s", name);
1395     }
1396 
1397     return filter_list;
1398 }
1399 
1400 void colo_notify_filters_event(int event, Error **errp)
1401 {
1402     NetClientState *nc;
1403     NetFilterState *nf;
1404     NetFilterClass *nfc = NULL;
1405     Error *local_err = NULL;
1406 
1407     QTAILQ_FOREACH(nc, &net_clients, next) {
1408         QTAILQ_FOREACH(nf, &nc->filters, next) {
1409             nfc = NETFILTER_GET_CLASS(OBJECT(nf));
1410             nfc->handle_event(nf, event, &local_err);
1411             if (local_err) {
1412                 error_propagate(errp, local_err);
1413                 return;
1414             }
1415         }
1416     }
1417 }
1418 
1419 void qmp_set_link(const char *name, bool up, Error **errp)
1420 {
1421     NetClientState *ncs[MAX_QUEUE_NUM];
1422     NetClientState *nc;
1423     int queues, i;
1424 
1425     queues = qemu_find_net_clients_except(name, ncs,
1426                                           NET_CLIENT_DRIVER__MAX,
1427                                           MAX_QUEUE_NUM);
1428 
1429     if (queues == 0) {
1430         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1431                   "Device '%s' not found", name);
1432         return;
1433     }
1434     nc = ncs[0];
1435 
1436     for (i = 0; i < queues; i++) {
1437         ncs[i]->link_down = !up;
1438     }
1439 
1440     if (nc->info->link_status_changed) {
1441         nc->info->link_status_changed(nc);
1442     }
1443 
1444     if (nc->peer) {
1445         /* Change peer link only if the peer is NIC and then notify peer.
1446          * If the peer is a HUBPORT or a backend, we do not change the
1447          * link status.
1448          *
1449          * This behavior is compatible with qemu hubs where there could be
1450          * multiple clients that can still communicate with each other in
1451          * disconnected mode. For now maintain this compatibility.
1452          */
1453         if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1454             for (i = 0; i < queues; i++) {
1455                 ncs[i]->peer->link_down = !up;
1456             }
1457         }
1458         if (nc->peer->info->link_status_changed) {
1459             nc->peer->info->link_status_changed(nc->peer);
1460         }
1461     }
1462 }
1463 
1464 static void net_vm_change_state_handler(void *opaque, bool running,
1465                                         RunState state)
1466 {
1467     NetClientState *nc;
1468     NetClientState *tmp;
1469 
1470     QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1471         if (running) {
1472             /* Flush queued packets and wake up backends. */
1473             if (nc->peer && qemu_can_send_packet(nc)) {
1474                 qemu_flush_queued_packets(nc->peer);
1475             }
1476         } else {
1477             /* Complete all queued packets, to guarantee we don't modify
1478              * state later when VM is not running.
1479              */
1480             qemu_flush_or_purge_queued_packets(nc, true);
1481         }
1482     }
1483 }
1484 
1485 void net_cleanup(void)
1486 {
1487     NetClientState *nc;
1488 
1489     /*cleanup colo compare module for COLO*/
1490     colo_compare_cleanup();
1491 
1492     /* We may del multiple entries during qemu_del_net_client(),
1493      * so QTAILQ_FOREACH_SAFE() is also not safe here.
1494      */
1495     while (!QTAILQ_EMPTY(&net_clients)) {
1496         nc = QTAILQ_FIRST(&net_clients);
1497         if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1498             qemu_del_nic(qemu_get_nic(nc));
1499         } else {
1500             qemu_del_net_client(nc);
1501         }
1502     }
1503 
1504     qemu_del_vm_change_state_handler(net_change_state_entry);
1505 }
1506 
1507 void net_check_clients(void)
1508 {
1509     NetClientState *nc;
1510     int i;
1511 
1512     net_hub_check_clients();
1513 
1514     QTAILQ_FOREACH(nc, &net_clients, next) {
1515         if (!nc->peer) {
1516             warn_report("%s %s has no peer",
1517                         nc->info->type == NET_CLIENT_DRIVER_NIC
1518                         ? "nic" : "netdev",
1519                         nc->name);
1520         }
1521     }
1522 
1523     /* Check that all NICs requested via -net nic actually got created.
1524      * NICs created via -device don't need to be checked here because
1525      * they are always instantiated.
1526      */
1527     for (i = 0; i < MAX_NICS; i++) {
1528         NICInfo *nd = &nd_table[i];
1529         if (nd->used && !nd->instantiated) {
1530             warn_report("requested NIC (%s, model %s) "
1531                         "was not created (not supported by this machine?)",
1532                         nd->name ? nd->name : "anonymous",
1533                         nd->model ? nd->model : "unspecified");
1534         }
1535     }
1536 }
1537 
1538 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1539 {
1540     return net_client_init(opts, false, errp);
1541 }
1542 
1543 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1544 {
1545     const char *type = qemu_opt_get(opts, "type");
1546 
1547     if (type && is_help_option(type)) {
1548         show_netdevs();
1549         exit(0);
1550     }
1551     return net_client_init(opts, true, errp);
1552 }
1553 
1554 /* For the convenience "--nic" parameter */
1555 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1556 {
1557     char *mac, *nd_id;
1558     int idx, ret;
1559     NICInfo *ni;
1560     const char *type;
1561 
1562     type = qemu_opt_get(opts, "type");
1563     if (type) {
1564         if (g_str_equal(type, "none")) {
1565             return 0;    /* Nothing to do, default_net is cleared in vl.c */
1566         }
1567         if (is_help_option(type)) {
1568             GPtrArray *nic_models = qemu_get_nic_models(TYPE_DEVICE);
1569             show_netdevs();
1570             printf("\n");
1571             qemu_show_nic_models(type, (const char **)nic_models->pdata);
1572             g_ptr_array_free(nic_models, true);
1573             exit(0);
1574         }
1575     }
1576 
1577     idx = nic_get_free_idx();
1578     if (idx == -1 || nb_nics >= MAX_NICS) {
1579         error_setg(errp, "no more on-board/default NIC slots available");
1580         return -1;
1581     }
1582 
1583     if (!type) {
1584         qemu_opt_set(opts, "type", "user", &error_abort);
1585     }
1586 
1587     ni = &nd_table[idx];
1588     memset(ni, 0, sizeof(*ni));
1589     ni->model = qemu_opt_get_del(opts, "model");
1590 
1591     /* Create an ID if the user did not specify one */
1592     nd_id = g_strdup(qemu_opts_id(opts));
1593     if (!nd_id) {
1594         nd_id = id_generate(ID_NET);
1595         qemu_opts_set_id(opts, nd_id);
1596     }
1597 
1598     /* Handle MAC address */
1599     mac = qemu_opt_get_del(opts, "mac");
1600     if (mac) {
1601         ret = net_parse_macaddr(ni->macaddr.a, mac);
1602         g_free(mac);
1603         if (ret) {
1604             error_setg(errp, "invalid syntax for ethernet address");
1605             goto out;
1606         }
1607         if (is_multicast_ether_addr(ni->macaddr.a)) {
1608             error_setg(errp, "NIC cannot have multicast MAC address");
1609             ret = -1;
1610             goto out;
1611         }
1612     }
1613     qemu_macaddr_default_if_unset(&ni->macaddr);
1614 
1615     ret = net_client_init(opts, true, errp);
1616     if (ret == 0) {
1617         ni->netdev = qemu_find_netdev(nd_id);
1618         ni->used = true;
1619         nb_nics++;
1620     }
1621 
1622 out:
1623     g_free(nd_id);
1624     return ret;
1625 }
1626 
1627 static void netdev_init_modern(void)
1628 {
1629     while (!QSIMPLEQ_EMPTY(&nd_queue)) {
1630         NetdevQueueEntry *nd = QSIMPLEQ_FIRST(&nd_queue);
1631 
1632         QSIMPLEQ_REMOVE_HEAD(&nd_queue, entry);
1633         loc_push_restore(&nd->loc);
1634         net_client_init1(nd->nd, true, &error_fatal);
1635         loc_pop(&nd->loc);
1636         qapi_free_Netdev(nd->nd);
1637         g_free(nd);
1638     }
1639 }
1640 
1641 void net_init_clients(void)
1642 {
1643     net_change_state_entry =
1644         qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1645 
1646     QTAILQ_INIT(&net_clients);
1647 
1648     netdev_init_modern();
1649 
1650     qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL,
1651                       &error_fatal);
1652 
1653     qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL,
1654                       &error_fatal);
1655 
1656     qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL,
1657                       &error_fatal);
1658 }
1659 
1660 /*
1661  * Does this -netdev argument use modern rather than traditional syntax?
1662  * Modern syntax is to be parsed with netdev_parse_modern().
1663  * Traditional syntax is to be parsed with net_client_parse().
1664  */
1665 bool netdev_is_modern(const char *optarg)
1666 {
1667     QemuOpts *opts;
1668     bool is_modern;
1669     const char *type;
1670     static QemuOptsList dummy_opts = {
1671         .name = "netdev",
1672         .implied_opt_name = "type",
1673         .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head),
1674         .desc = { { } },
1675     };
1676 
1677     if (optarg[0] == '{') {
1678         /* This is JSON, which means it's modern syntax */
1679         return true;
1680     }
1681 
1682     opts = qemu_opts_create(&dummy_opts, NULL, false, &error_abort);
1683     qemu_opts_do_parse(opts, optarg, dummy_opts.implied_opt_name,
1684                        &error_abort);
1685     type = qemu_opt_get(opts, "type");
1686     is_modern = !g_strcmp0(type, "stream") || !g_strcmp0(type, "dgram");
1687 
1688     qemu_opts_reset(&dummy_opts);
1689 
1690     return is_modern;
1691 }
1692 
1693 /*
1694  * netdev_parse_modern() uses modern, more expressive syntax than
1695  * net_client_parse(), but supports only the -netdev option.
1696  * netdev_parse_modern() appends to @nd_queue, whereas net_client_parse()
1697  * appends to @qemu_netdev_opts.
1698  */
1699 void netdev_parse_modern(const char *optarg)
1700 {
1701     Visitor *v;
1702     NetdevQueueEntry *nd;
1703 
1704     v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1705     nd = g_new(NetdevQueueEntry, 1);
1706     visit_type_Netdev(v, NULL, &nd->nd, &error_fatal);
1707     visit_free(v);
1708     loc_save(&nd->loc);
1709 
1710     QSIMPLEQ_INSERT_TAIL(&nd_queue, nd, entry);
1711 }
1712 
1713 void net_client_parse(QemuOptsList *opts_list, const char *optarg)
1714 {
1715     if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1716         exit(1);
1717     }
1718 }
1719 
1720 /* From FreeBSD */
1721 /* XXX: optimize */
1722 uint32_t net_crc32(const uint8_t *p, int len)
1723 {
1724     uint32_t crc;
1725     int carry, i, j;
1726     uint8_t b;
1727 
1728     crc = 0xffffffff;
1729     for (i = 0; i < len; i++) {
1730         b = *p++;
1731         for (j = 0; j < 8; j++) {
1732             carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1733             crc <<= 1;
1734             b >>= 1;
1735             if (carry) {
1736                 crc = ((crc ^ POLYNOMIAL_BE) | carry);
1737             }
1738         }
1739     }
1740 
1741     return crc;
1742 }
1743 
1744 uint32_t net_crc32_le(const uint8_t *p, int len)
1745 {
1746     uint32_t crc;
1747     int carry, i, j;
1748     uint8_t b;
1749 
1750     crc = 0xffffffff;
1751     for (i = 0; i < len; i++) {
1752         b = *p++;
1753         for (j = 0; j < 8; j++) {
1754             carry = (crc & 0x1) ^ (b & 0x01);
1755             crc >>= 1;
1756             b >>= 1;
1757             if (carry) {
1758                 crc ^= POLYNOMIAL_LE;
1759             }
1760         }
1761     }
1762 
1763     return crc;
1764 }
1765 
1766 QemuOptsList qemu_netdev_opts = {
1767     .name = "netdev",
1768     .implied_opt_name = "type",
1769     .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1770     .desc = {
1771         /*
1772          * no elements => accept any params
1773          * validation will happen later
1774          */
1775         { /* end of list */ }
1776     },
1777 };
1778 
1779 QemuOptsList qemu_nic_opts = {
1780     .name = "nic",
1781     .implied_opt_name = "type",
1782     .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1783     .desc = {
1784         /*
1785          * no elements => accept any params
1786          * validation will happen later
1787          */
1788         { /* end of list */ }
1789     },
1790 };
1791 
1792 QemuOptsList qemu_net_opts = {
1793     .name = "net",
1794     .implied_opt_name = "type",
1795     .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1796     .desc = {
1797         /*
1798          * no elements => accept any params
1799          * validation will happen later
1800          */
1801         { /* end of list */ }
1802     },
1803 };
1804 
1805 void net_socket_rs_init(SocketReadState *rs,
1806                         SocketReadStateFinalize *finalize,
1807                         bool vnet_hdr)
1808 {
1809     rs->state = 0;
1810     rs->vnet_hdr = vnet_hdr;
1811     rs->index = 0;
1812     rs->packet_len = 0;
1813     rs->vnet_hdr_len = 0;
1814     memset(rs->buf, 0, sizeof(rs->buf));
1815     rs->finalize = finalize;
1816 }
1817 
1818 /*
1819  * Returns
1820  * 0: success
1821  * -1: error occurs
1822  */
1823 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1824 {
1825     unsigned int l;
1826 
1827     while (size > 0) {
1828         /* Reassemble a packet from the network.
1829          * 0 = getting length.
1830          * 1 = getting vnet header length.
1831          * 2 = getting data.
1832          */
1833         switch (rs->state) {
1834         case 0:
1835             l = 4 - rs->index;
1836             if (l > size) {
1837                 l = size;
1838             }
1839             memcpy(rs->buf + rs->index, buf, l);
1840             buf += l;
1841             size -= l;
1842             rs->index += l;
1843             if (rs->index == 4) {
1844                 /* got length */
1845                 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1846                 rs->index = 0;
1847                 if (rs->vnet_hdr) {
1848                     rs->state = 1;
1849                 } else {
1850                     rs->state = 2;
1851                     rs->vnet_hdr_len = 0;
1852                 }
1853             }
1854             break;
1855         case 1:
1856             l = 4 - rs->index;
1857             if (l > size) {
1858                 l = size;
1859             }
1860             memcpy(rs->buf + rs->index, buf, l);
1861             buf += l;
1862             size -= l;
1863             rs->index += l;
1864             if (rs->index == 4) {
1865                 /* got vnet header length */
1866                 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1867                 rs->index = 0;
1868                 rs->state = 2;
1869             }
1870             break;
1871         case 2:
1872             l = rs->packet_len - rs->index;
1873             if (l > size) {
1874                 l = size;
1875             }
1876             if (rs->index + l <= sizeof(rs->buf)) {
1877                 memcpy(rs->buf + rs->index, buf, l);
1878             } else {
1879                 fprintf(stderr, "serious error: oversized packet received,"
1880                     "connection terminated.\n");
1881                 rs->index = rs->state = 0;
1882                 return -1;
1883             }
1884 
1885             rs->index += l;
1886             buf += l;
1887             size -= l;
1888             if (rs->index >= rs->packet_len) {
1889                 rs->index = 0;
1890                 rs->state = 0;
1891                 assert(rs->finalize);
1892                 rs->finalize(rs);
1893             }
1894             break;
1895         }
1896     }
1897 
1898     assert(size == 0);
1899     return 0;
1900 }
1901