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