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