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