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