hw/arm/virt-acpi-build: build SLIT when needed
[qemu/ar7.git] / net / net.c
blob6235aabed871be7eec71fec8a1ab431c874eedb4
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #include "qemu/osdep.h"
26 #include "net/net.h"
27 #include "clients.h"
28 #include "hub.h"
29 #include "net/slirp.h"
30 #include "net/eth.h"
31 #include "util.h"
33 #include "monitor/monitor.h"
34 #include "qemu-common.h"
35 #include "qemu/help_option.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qemu/error-report.h"
38 #include "qemu/sockets.h"
39 #include "qemu/cutils.h"
40 #include "qemu/config-file.h"
41 #include "qmp-commands.h"
42 #include "hw/qdev.h"
43 #include "qemu/iov.h"
44 #include "qemu/main-loop.h"
45 #include "qapi-visit.h"
46 #include "qapi/opts-visitor.h"
47 #include "sysemu/sysemu.h"
48 #include "sysemu/qtest.h"
49 #include "net/filter.h"
50 #include "qapi/string-output-visitor.h"
52 /* Net bridge is currently not supported for W32. */
53 #if !defined(_WIN32)
54 # define CONFIG_NET_BRIDGE
55 #endif
57 static VMChangeStateEntry *net_change_state_entry;
58 static QTAILQ_HEAD(, NetClientState) net_clients;
60 const char *host_net_devices[] = {
61 "tap",
62 "socket",
63 "dump",
64 #ifdef CONFIG_NET_BRIDGE
65 "bridge",
66 #endif
67 #ifdef CONFIG_NETMAP
68 "netmap",
69 #endif
70 #ifdef CONFIG_SLIRP
71 "user",
72 #endif
73 #ifdef CONFIG_VDE
74 "vde",
75 #endif
76 "vhost-user",
77 NULL,
80 /***********************************************************/
81 /* network device redirectors */
83 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
85 const char *p, *p1;
86 int len;
87 p = *pp;
88 p1 = strchr(p, sep);
89 if (!p1)
90 return -1;
91 len = p1 - p;
92 p1++;
93 if (buf_size > 0) {
94 if (len > buf_size - 1)
95 len = buf_size - 1;
96 memcpy(buf, p, len);
97 buf[len] = '\0';
99 *pp = p1;
100 return 0;
103 int parse_host_port(struct sockaddr_in *saddr, const char *str)
105 char buf[512];
106 struct hostent *he;
107 const char *p, *r;
108 int port;
110 p = str;
111 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
112 return -1;
113 saddr->sin_family = AF_INET;
114 if (buf[0] == '\0') {
115 saddr->sin_addr.s_addr = 0;
116 } else {
117 if (qemu_isdigit(buf[0])) {
118 if (!inet_aton(buf, &saddr->sin_addr))
119 return -1;
120 } else {
121 if ((he = gethostbyname(buf)) == NULL)
122 return - 1;
123 saddr->sin_addr = *(struct in_addr *)he->h_addr;
126 port = strtol(p, (char **)&r, 0);
127 if (r == p)
128 return -1;
129 saddr->sin_port = htons(port);
130 return 0;
133 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
135 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
136 macaddr[0], macaddr[1], macaddr[2],
137 macaddr[3], macaddr[4], macaddr[5]);
140 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
142 snprintf(nc->info_str, sizeof(nc->info_str),
143 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
144 nc->model,
145 macaddr[0], macaddr[1], macaddr[2],
146 macaddr[3], macaddr[4], macaddr[5]);
149 static int mac_table[256] = {0};
151 static void qemu_macaddr_set_used(MACAddr *macaddr)
153 int index;
155 for (index = 0x56; index < 0xFF; index++) {
156 if (macaddr->a[5] == index) {
157 mac_table[index]++;
162 static void qemu_macaddr_set_free(MACAddr *macaddr)
164 int index;
165 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
167 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
168 return;
170 for (index = 0x56; index < 0xFF; index++) {
171 if (macaddr->a[5] == index) {
172 mac_table[index]--;
177 static int qemu_macaddr_get_free(void)
179 int index;
181 for (index = 0x56; index < 0xFF; index++) {
182 if (mac_table[index] == 0) {
183 return index;
187 return -1;
190 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
192 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
193 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
195 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
196 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
197 return;
198 } else {
199 qemu_macaddr_set_used(macaddr);
200 return;
204 macaddr->a[0] = 0x52;
205 macaddr->a[1] = 0x54;
206 macaddr->a[2] = 0x00;
207 macaddr->a[3] = 0x12;
208 macaddr->a[4] = 0x34;
209 macaddr->a[5] = qemu_macaddr_get_free();
210 qemu_macaddr_set_used(macaddr);
214 * Generate a name for net client
216 * Only net clients created with the legacy -net option and NICs need this.
218 static char *assign_name(NetClientState *nc1, const char *model)
220 NetClientState *nc;
221 int id = 0;
223 QTAILQ_FOREACH(nc, &net_clients, next) {
224 if (nc == nc1) {
225 continue;
227 if (strcmp(nc->model, model) == 0) {
228 id++;
232 return g_strdup_printf("%s.%d", model, id);
235 static void qemu_net_client_destructor(NetClientState *nc)
237 g_free(nc);
240 static void qemu_net_client_setup(NetClientState *nc,
241 NetClientInfo *info,
242 NetClientState *peer,
243 const char *model,
244 const char *name,
245 NetClientDestructor *destructor)
247 nc->info = info;
248 nc->model = g_strdup(model);
249 if (name) {
250 nc->name = g_strdup(name);
251 } else {
252 nc->name = assign_name(nc, model);
255 if (peer) {
256 assert(!peer->peer);
257 nc->peer = peer;
258 peer->peer = nc;
260 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
262 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
263 nc->destructor = destructor;
264 QTAILQ_INIT(&nc->filters);
267 NetClientState *qemu_new_net_client(NetClientInfo *info,
268 NetClientState *peer,
269 const char *model,
270 const char *name)
272 NetClientState *nc;
274 assert(info->size >= sizeof(NetClientState));
276 nc = g_malloc0(info->size);
277 qemu_net_client_setup(nc, info, peer, model, name,
278 qemu_net_client_destructor);
280 return nc;
283 NICState *qemu_new_nic(NetClientInfo *info,
284 NICConf *conf,
285 const char *model,
286 const char *name,
287 void *opaque)
289 NetClientState **peers = conf->peers.ncs;
290 NICState *nic;
291 int i, queues = MAX(1, conf->peers.queues);
293 assert(info->type == NET_CLIENT_DRIVER_NIC);
294 assert(info->size >= sizeof(NICState));
296 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
297 nic->ncs = (void *)nic + info->size;
298 nic->conf = conf;
299 nic->opaque = opaque;
301 for (i = 0; i < queues; i++) {
302 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
303 NULL);
304 nic->ncs[i].queue_index = i;
307 return nic;
310 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
312 return nic->ncs + queue_index;
315 NetClientState *qemu_get_queue(NICState *nic)
317 return qemu_get_subqueue(nic, 0);
320 NICState *qemu_get_nic(NetClientState *nc)
322 NetClientState *nc0 = nc - nc->queue_index;
324 return (NICState *)((void *)nc0 - nc->info->size);
327 void *qemu_get_nic_opaque(NetClientState *nc)
329 NICState *nic = qemu_get_nic(nc);
331 return nic->opaque;
334 static void qemu_cleanup_net_client(NetClientState *nc)
336 QTAILQ_REMOVE(&net_clients, nc, next);
338 if (nc->info->cleanup) {
339 nc->info->cleanup(nc);
343 static void qemu_free_net_client(NetClientState *nc)
345 if (nc->incoming_queue) {
346 qemu_del_net_queue(nc->incoming_queue);
348 if (nc->peer) {
349 nc->peer->peer = NULL;
351 g_free(nc->name);
352 g_free(nc->model);
353 if (nc->destructor) {
354 nc->destructor(nc);
358 void qemu_del_net_client(NetClientState *nc)
360 NetClientState *ncs[MAX_QUEUE_NUM];
361 int queues, i;
362 NetFilterState *nf, *next;
364 assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
366 /* If the NetClientState belongs to a multiqueue backend, we will change all
367 * other NetClientStates also.
369 queues = qemu_find_net_clients_except(nc->name, ncs,
370 NET_CLIENT_DRIVER_NIC,
371 MAX_QUEUE_NUM);
372 assert(queues != 0);
374 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
375 object_unparent(OBJECT(nf));
378 /* If there is a peer NIC, delete and cleanup client, but do not free. */
379 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
380 NICState *nic = qemu_get_nic(nc->peer);
381 if (nic->peer_deleted) {
382 return;
384 nic->peer_deleted = true;
386 for (i = 0; i < queues; i++) {
387 ncs[i]->peer->link_down = true;
390 if (nc->peer->info->link_status_changed) {
391 nc->peer->info->link_status_changed(nc->peer);
394 for (i = 0; i < queues; i++) {
395 qemu_cleanup_net_client(ncs[i]);
398 return;
401 for (i = 0; i < queues; i++) {
402 qemu_cleanup_net_client(ncs[i]);
403 qemu_free_net_client(ncs[i]);
407 void qemu_del_nic(NICState *nic)
409 int i, queues = MAX(nic->conf->peers.queues, 1);
411 qemu_macaddr_set_free(&nic->conf->macaddr);
413 /* If this is a peer NIC and peer has already been deleted, free it now. */
414 if (nic->peer_deleted) {
415 for (i = 0; i < queues; i++) {
416 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
420 for (i = queues - 1; i >= 0; i--) {
421 NetClientState *nc = qemu_get_subqueue(nic, i);
423 qemu_cleanup_net_client(nc);
424 qemu_free_net_client(nc);
427 g_free(nic);
430 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
432 NetClientState *nc;
434 QTAILQ_FOREACH(nc, &net_clients, next) {
435 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
436 if (nc->queue_index == 0) {
437 func(qemu_get_nic(nc), opaque);
443 bool qemu_has_ufo(NetClientState *nc)
445 if (!nc || !nc->info->has_ufo) {
446 return false;
449 return nc->info->has_ufo(nc);
452 bool qemu_has_vnet_hdr(NetClientState *nc)
454 if (!nc || !nc->info->has_vnet_hdr) {
455 return false;
458 return nc->info->has_vnet_hdr(nc);
461 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
463 if (!nc || !nc->info->has_vnet_hdr_len) {
464 return false;
467 return nc->info->has_vnet_hdr_len(nc, len);
470 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
472 if (!nc || !nc->info->using_vnet_hdr) {
473 return;
476 nc->info->using_vnet_hdr(nc, enable);
479 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
480 int ecn, int ufo)
482 if (!nc || !nc->info->set_offload) {
483 return;
486 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
489 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
491 if (!nc || !nc->info->set_vnet_hdr_len) {
492 return;
495 nc->info->set_vnet_hdr_len(nc, len);
498 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
500 #ifdef HOST_WORDS_BIGENDIAN
501 if (!nc || !nc->info->set_vnet_le) {
502 return -ENOSYS;
505 return nc->info->set_vnet_le(nc, is_le);
506 #else
507 return 0;
508 #endif
511 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
513 #ifdef HOST_WORDS_BIGENDIAN
514 return 0;
515 #else
516 if (!nc || !nc->info->set_vnet_be) {
517 return -ENOSYS;
520 return nc->info->set_vnet_be(nc, is_be);
521 #endif
524 int qemu_can_send_packet(NetClientState *sender)
526 int vm_running = runstate_is_running();
528 if (!vm_running) {
529 return 0;
532 if (!sender->peer) {
533 return 1;
536 if (sender->peer->receive_disabled) {
537 return 0;
538 } else if (sender->peer->info->can_receive &&
539 !sender->peer->info->can_receive(sender->peer)) {
540 return 0;
542 return 1;
545 static ssize_t filter_receive_iov(NetClientState *nc,
546 NetFilterDirection direction,
547 NetClientState *sender,
548 unsigned flags,
549 const struct iovec *iov,
550 int iovcnt,
551 NetPacketSent *sent_cb)
553 ssize_t ret = 0;
554 NetFilterState *nf = NULL;
556 if (direction == NET_FILTER_DIRECTION_TX) {
557 QTAILQ_FOREACH(nf, &nc->filters, next) {
558 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
559 iovcnt, sent_cb);
560 if (ret) {
561 return ret;
564 } else {
565 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, NetFilterHead, next) {
566 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
567 iovcnt, sent_cb);
568 if (ret) {
569 return ret;
574 return ret;
577 static ssize_t filter_receive(NetClientState *nc,
578 NetFilterDirection direction,
579 NetClientState *sender,
580 unsigned flags,
581 const uint8_t *data,
582 size_t size,
583 NetPacketSent *sent_cb)
585 struct iovec iov = {
586 .iov_base = (void *)data,
587 .iov_len = size
590 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
593 void qemu_purge_queued_packets(NetClientState *nc)
595 if (!nc->peer) {
596 return;
599 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
602 static
603 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
605 nc->receive_disabled = 0;
607 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
608 if (net_hub_flush(nc->peer)) {
609 qemu_notify_event();
612 if (qemu_net_queue_flush(nc->incoming_queue)) {
613 /* We emptied the queue successfully, signal to the IO thread to repoll
614 * the file descriptor (for tap, for example).
616 qemu_notify_event();
617 } else if (purge) {
618 /* Unable to empty the queue, purge remaining packets */
619 qemu_net_queue_purge(nc->incoming_queue, nc);
623 void qemu_flush_queued_packets(NetClientState *nc)
625 qemu_flush_or_purge_queued_packets(nc, false);
628 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
629 unsigned flags,
630 const uint8_t *buf, int size,
631 NetPacketSent *sent_cb)
633 NetQueue *queue;
634 int ret;
636 #ifdef DEBUG_NET
637 printf("qemu_send_packet_async:\n");
638 qemu_hexdump((const char *)buf, stdout, "net", size);
639 #endif
641 if (sender->link_down || !sender->peer) {
642 return size;
645 /* Let filters handle the packet first */
646 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
647 sender, flags, buf, size, sent_cb);
648 if (ret) {
649 return ret;
652 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
653 sender, flags, buf, size, sent_cb);
654 if (ret) {
655 return ret;
658 queue = sender->peer->incoming_queue;
660 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
663 ssize_t qemu_send_packet_async(NetClientState *sender,
664 const uint8_t *buf, int size,
665 NetPacketSent *sent_cb)
667 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
668 buf, size, sent_cb);
671 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
673 qemu_send_packet_async(nc, buf, size, NULL);
676 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
678 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
679 buf, size, NULL);
682 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
683 int iovcnt, unsigned flags)
685 uint8_t *buf = NULL;
686 uint8_t *buffer;
687 size_t offset;
688 ssize_t ret;
690 if (iovcnt == 1) {
691 buffer = iov[0].iov_base;
692 offset = iov[0].iov_len;
693 } else {
694 offset = iov_size(iov, iovcnt);
695 if (offset > NET_BUFSIZE) {
696 return -1;
698 buf = g_malloc(offset);
699 buffer = buf;
700 offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
703 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
704 ret = nc->info->receive_raw(nc, buffer, offset);
705 } else {
706 ret = nc->info->receive(nc, buffer, offset);
709 g_free(buf);
710 return ret;
713 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
714 unsigned flags,
715 const struct iovec *iov,
716 int iovcnt,
717 void *opaque)
719 NetClientState *nc = opaque;
720 int ret;
722 if (nc->link_down) {
723 return iov_size(iov, iovcnt);
726 if (nc->receive_disabled) {
727 return 0;
730 if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
731 ret = nc->info->receive_iov(nc, iov, iovcnt);
732 } else {
733 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
736 if (ret == 0) {
737 nc->receive_disabled = 1;
740 return ret;
743 ssize_t qemu_sendv_packet_async(NetClientState *sender,
744 const struct iovec *iov, int iovcnt,
745 NetPacketSent *sent_cb)
747 NetQueue *queue;
748 int ret;
750 if (sender->link_down || !sender->peer) {
751 return iov_size(iov, iovcnt);
754 /* Let filters handle the packet first */
755 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
756 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
757 if (ret) {
758 return ret;
761 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
762 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
763 if (ret) {
764 return ret;
767 queue = sender->peer->incoming_queue;
769 return qemu_net_queue_send_iov(queue, sender,
770 QEMU_NET_PACKET_FLAG_NONE,
771 iov, iovcnt, sent_cb);
774 ssize_t
775 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
777 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
780 NetClientState *qemu_find_netdev(const char *id)
782 NetClientState *nc;
784 QTAILQ_FOREACH(nc, &net_clients, next) {
785 if (nc->info->type == NET_CLIENT_DRIVER_NIC)
786 continue;
787 if (!strcmp(nc->name, id)) {
788 return nc;
792 return NULL;
795 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
796 NetClientDriver type, int max)
798 NetClientState *nc;
799 int ret = 0;
801 QTAILQ_FOREACH(nc, &net_clients, next) {
802 if (nc->info->type == type) {
803 continue;
805 if (!id || !strcmp(nc->name, id)) {
806 if (ret < max) {
807 ncs[ret] = nc;
809 ret++;
813 return ret;
816 static int nic_get_free_idx(void)
818 int index;
820 for (index = 0; index < MAX_NICS; index++)
821 if (!nd_table[index].used)
822 return index;
823 return -1;
826 int qemu_show_nic_models(const char *arg, const char *const *models)
828 int i;
830 if (!arg || !is_help_option(arg)) {
831 return 0;
834 fprintf(stderr, "qemu: Supported NIC models: ");
835 for (i = 0 ; models[i]; i++)
836 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
837 return 1;
840 void qemu_check_nic_model(NICInfo *nd, const char *model)
842 const char *models[2];
844 models[0] = model;
845 models[1] = NULL;
847 if (qemu_show_nic_models(nd->model, models))
848 exit(0);
849 if (qemu_find_nic_model(nd, models, model) < 0)
850 exit(1);
853 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
854 const char *default_model)
856 int i;
858 if (!nd->model)
859 nd->model = g_strdup(default_model);
861 for (i = 0 ; models[i]; i++) {
862 if (strcmp(nd->model, models[i]) == 0)
863 return i;
866 error_report("Unsupported NIC model: %s", nd->model);
867 return -1;
870 static int net_init_nic(const Netdev *netdev, const char *name,
871 NetClientState *peer, Error **errp)
873 int idx;
874 NICInfo *nd;
875 const NetLegacyNicOptions *nic;
877 assert(netdev->type == NET_CLIENT_DRIVER_NIC);
878 nic = &netdev->u.nic;
880 idx = nic_get_free_idx();
881 if (idx == -1 || nb_nics >= MAX_NICS) {
882 error_setg(errp, "too many NICs");
883 return -1;
886 nd = &nd_table[idx];
888 memset(nd, 0, sizeof(*nd));
890 if (nic->has_netdev) {
891 nd->netdev = qemu_find_netdev(nic->netdev);
892 if (!nd->netdev) {
893 error_setg(errp, "netdev '%s' not found", nic->netdev);
894 return -1;
896 } else {
897 assert(peer);
898 nd->netdev = peer;
900 nd->name = g_strdup(name);
901 if (nic->has_model) {
902 nd->model = g_strdup(nic->model);
904 if (nic->has_addr) {
905 nd->devaddr = g_strdup(nic->addr);
908 if (nic->has_macaddr &&
909 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
910 error_setg(errp, "invalid syntax for ethernet address");
911 return -1;
913 if (nic->has_macaddr &&
914 is_multicast_ether_addr(nd->macaddr.a)) {
915 error_setg(errp,
916 "NIC cannot have multicast MAC address (odd 1st byte)");
917 return -1;
919 qemu_macaddr_default_if_unset(&nd->macaddr);
921 if (nic->has_vectors) {
922 if (nic->vectors > 0x7ffffff) {
923 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
924 return -1;
926 nd->nvectors = nic->vectors;
927 } else {
928 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
931 nd->used = 1;
932 nb_nics++;
934 return idx;
938 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
939 const Netdev *netdev,
940 const char *name,
941 NetClientState *peer, Error **errp) = {
942 [NET_CLIENT_DRIVER_NIC] = net_init_nic,
943 #ifdef CONFIG_SLIRP
944 [NET_CLIENT_DRIVER_USER] = net_init_slirp,
945 #endif
946 [NET_CLIENT_DRIVER_TAP] = net_init_tap,
947 [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
948 #ifdef CONFIG_VDE
949 [NET_CLIENT_DRIVER_VDE] = net_init_vde,
950 #endif
951 #ifdef CONFIG_NETMAP
952 [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
953 #endif
954 [NET_CLIENT_DRIVER_DUMP] = net_init_dump,
955 #ifdef CONFIG_NET_BRIDGE
956 [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
957 #endif
958 [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
959 #ifdef CONFIG_VHOST_NET_USED
960 [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
961 #endif
962 #ifdef CONFIG_L2TPV3
963 [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
964 #endif
968 static int net_client_init1(const void *object, bool is_netdev, Error **errp)
970 Netdev legacy = {0};
971 const Netdev *netdev;
972 const char *name;
973 NetClientState *peer = NULL;
974 static bool vlan_warned;
976 if (is_netdev) {
977 netdev = object;
978 name = netdev->id;
980 if (netdev->type == NET_CLIENT_DRIVER_DUMP ||
981 netdev->type == NET_CLIENT_DRIVER_NIC ||
982 !net_client_init_fun[netdev->type]) {
983 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
984 "a netdev backend type");
985 return -1;
987 } else {
988 const NetLegacy *net = object;
989 const NetLegacyOptions *opts = net->opts;
990 legacy.id = net->id;
991 netdev = &legacy;
992 /* missing optional values have been initialized to "all bits zero" */
993 name = net->has_id ? net->id : net->name;
995 /* Map the old options to the new flat type */
996 switch (opts->type) {
997 case NET_LEGACY_OPTIONS_TYPE_NONE:
998 return 0; /* nothing to do */
999 case NET_LEGACY_OPTIONS_TYPE_NIC:
1000 legacy.type = NET_CLIENT_DRIVER_NIC;
1001 legacy.u.nic = opts->u.nic;
1002 break;
1003 case NET_LEGACY_OPTIONS_TYPE_USER:
1004 legacy.type = NET_CLIENT_DRIVER_USER;
1005 legacy.u.user = opts->u.user;
1006 break;
1007 case NET_LEGACY_OPTIONS_TYPE_TAP:
1008 legacy.type = NET_CLIENT_DRIVER_TAP;
1009 legacy.u.tap = opts->u.tap;
1010 break;
1011 case NET_LEGACY_OPTIONS_TYPE_L2TPV3:
1012 legacy.type = NET_CLIENT_DRIVER_L2TPV3;
1013 legacy.u.l2tpv3 = opts->u.l2tpv3;
1014 break;
1015 case NET_LEGACY_OPTIONS_TYPE_SOCKET:
1016 legacy.type = NET_CLIENT_DRIVER_SOCKET;
1017 legacy.u.socket = opts->u.socket;
1018 break;
1019 case NET_LEGACY_OPTIONS_TYPE_VDE:
1020 legacy.type = NET_CLIENT_DRIVER_VDE;
1021 legacy.u.vde = opts->u.vde;
1022 break;
1023 case NET_LEGACY_OPTIONS_TYPE_DUMP:
1024 legacy.type = NET_CLIENT_DRIVER_DUMP;
1025 legacy.u.dump = opts->u.dump;
1026 break;
1027 case NET_LEGACY_OPTIONS_TYPE_BRIDGE:
1028 legacy.type = NET_CLIENT_DRIVER_BRIDGE;
1029 legacy.u.bridge = opts->u.bridge;
1030 break;
1031 case NET_LEGACY_OPTIONS_TYPE_NETMAP:
1032 legacy.type = NET_CLIENT_DRIVER_NETMAP;
1033 legacy.u.netmap = opts->u.netmap;
1034 break;
1035 case NET_LEGACY_OPTIONS_TYPE_VHOST_USER:
1036 legacy.type = NET_CLIENT_DRIVER_VHOST_USER;
1037 legacy.u.vhost_user = opts->u.vhost_user;
1038 break;
1039 default:
1040 abort();
1043 if (!net_client_init_fun[netdev->type]) {
1044 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1045 "a net backend type (maybe it is not compiled "
1046 "into this binary)");
1047 return -1;
1050 /* Do not add to a vlan if it's a nic with a netdev= parameter. */
1051 if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1052 !opts->u.nic.has_netdev) {
1053 peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
1056 if (net->has_vlan && !vlan_warned) {
1057 error_report("'vlan' is deprecated. Please use 'netdev' instead.");
1058 vlan_warned = true;
1062 if (net_client_init_fun[netdev->type](netdev, name, peer, errp) < 0) {
1063 /* FIXME drop when all init functions store an Error */
1064 if (errp && !*errp) {
1065 error_setg(errp, QERR_DEVICE_INIT_FAILED,
1066 NetClientDriver_lookup[netdev->type]);
1068 return -1;
1070 return 0;
1074 int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1076 void *object = NULL;
1077 Error *err = NULL;
1078 int ret = -1;
1079 Visitor *v = opts_visitor_new(opts);
1082 /* Parse convenience option format ip6-net=fec0::0[/64] */
1083 const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1085 if (ip6_net) {
1086 char buf[strlen(ip6_net) + 1];
1088 if (get_str_sep(buf, sizeof(buf), &ip6_net, '/') < 0) {
1089 /* Default 64bit prefix length. */
1090 qemu_opt_set(opts, "ipv6-prefix", ip6_net, &error_abort);
1091 qemu_opt_set_number(opts, "ipv6-prefixlen", 64, &error_abort);
1092 } else {
1093 /* User-specified prefix length. */
1094 unsigned long len;
1095 int err;
1097 qemu_opt_set(opts, "ipv6-prefix", buf, &error_abort);
1098 err = qemu_strtoul(ip6_net, NULL, 10, &len);
1100 if (err) {
1101 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1102 "ipv6-prefix", "a number");
1103 } else {
1104 qemu_opt_set_number(opts, "ipv6-prefixlen", len,
1105 &error_abort);
1108 qemu_opt_unset(opts, "ipv6-net");
1112 if (is_netdev) {
1113 visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1114 } else {
1115 visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1118 if (!err) {
1119 ret = net_client_init1(object, is_netdev, &err);
1122 if (is_netdev) {
1123 qapi_free_Netdev(object);
1124 } else {
1125 qapi_free_NetLegacy(object);
1128 error_propagate(errp, err);
1129 visit_free(v);
1130 return ret;
1134 static int net_host_check_device(const char *device)
1136 int i;
1137 for (i = 0; host_net_devices[i]; i++) {
1138 if (!strncmp(host_net_devices[i], device,
1139 strlen(host_net_devices[i]))) {
1140 return 1;
1144 return 0;
1147 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1149 const char *device = qdict_get_str(qdict, "device");
1150 const char *opts_str = qdict_get_try_str(qdict, "opts");
1151 Error *local_err = NULL;
1152 QemuOpts *opts;
1153 static bool warned;
1155 if (!warned && !qtest_enabled()) {
1156 error_report("host_net_add is deprecated, use netdev_add instead");
1157 warned = true;
1160 if (!net_host_check_device(device)) {
1161 monitor_printf(mon, "invalid host network device %s\n", device);
1162 return;
1165 opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1166 opts_str ? opts_str : "", false);
1167 if (!opts) {
1168 return;
1171 qemu_opt_set(opts, "type", device, &error_abort);
1173 net_client_init(opts, false, &local_err);
1174 if (local_err) {
1175 error_report_err(local_err);
1176 monitor_printf(mon, "adding host network device %s failed\n", device);
1180 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1182 NetClientState *nc;
1183 int vlan_id = qdict_get_int(qdict, "vlan_id");
1184 const char *device = qdict_get_str(qdict, "device");
1185 static bool warned;
1187 if (!warned && !qtest_enabled()) {
1188 error_report("host_net_remove is deprecated, use netdev_del instead");
1189 warned = true;
1192 nc = net_hub_find_client_by_name(vlan_id, device);
1193 if (!nc) {
1194 error_report("Host network device '%s' on hub '%d' not found",
1195 device, vlan_id);
1196 return;
1198 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1199 error_report("invalid host network device '%s'", device);
1200 return;
1203 qemu_del_net_client(nc->peer);
1204 qemu_del_net_client(nc);
1205 qemu_opts_del(qemu_opts_find(qemu_find_opts("net"), device));
1208 void netdev_add(QemuOpts *opts, Error **errp)
1210 net_client_init(opts, true, errp);
1213 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1215 Error *local_err = NULL;
1216 QemuOptsList *opts_list;
1217 QemuOpts *opts;
1219 opts_list = qemu_find_opts_err("netdev", &local_err);
1220 if (local_err) {
1221 goto out;
1224 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1225 if (local_err) {
1226 goto out;
1229 netdev_add(opts, &local_err);
1230 if (local_err) {
1231 qemu_opts_del(opts);
1232 goto out;
1235 out:
1236 error_propagate(errp, local_err);
1239 void qmp_netdev_del(const char *id, Error **errp)
1241 NetClientState *nc;
1242 QemuOpts *opts;
1244 nc = qemu_find_netdev(id);
1245 if (!nc) {
1246 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1247 "Device '%s' not found", id);
1248 return;
1251 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1252 if (!opts) {
1253 error_setg(errp, "Device '%s' is not a netdev", id);
1254 return;
1257 qemu_del_net_client(nc);
1258 qemu_opts_del(opts);
1261 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1263 char *str;
1264 ObjectProperty *prop;
1265 ObjectPropertyIterator iter;
1266 Visitor *v;
1268 /* generate info str */
1269 object_property_iter_init(&iter, OBJECT(nf));
1270 while ((prop = object_property_iter_next(&iter))) {
1271 if (!strcmp(prop->name, "type")) {
1272 continue;
1274 v = string_output_visitor_new(false, &str);
1275 object_property_get(OBJECT(nf), v, prop->name, NULL);
1276 visit_complete(v, &str);
1277 visit_free(v);
1278 monitor_printf(mon, ",%s=%s", prop->name, str);
1279 g_free(str);
1281 monitor_printf(mon, "\n");
1284 void print_net_client(Monitor *mon, NetClientState *nc)
1286 NetFilterState *nf;
1288 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1289 nc->queue_index,
1290 NetClientDriver_lookup[nc->info->type],
1291 nc->info_str);
1292 if (!QTAILQ_EMPTY(&nc->filters)) {
1293 monitor_printf(mon, "filters:\n");
1295 QTAILQ_FOREACH(nf, &nc->filters, next) {
1296 char *path = object_get_canonical_path_component(OBJECT(nf));
1298 monitor_printf(mon, " - %s: type=%s", path,
1299 object_get_typename(OBJECT(nf)));
1300 netfilter_print_info(mon, nf);
1301 g_free(path);
1305 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1306 Error **errp)
1308 NetClientState *nc;
1309 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1311 QTAILQ_FOREACH(nc, &net_clients, next) {
1312 RxFilterInfoList *entry;
1313 RxFilterInfo *info;
1315 if (has_name && strcmp(nc->name, name) != 0) {
1316 continue;
1319 /* only query rx-filter information of NIC */
1320 if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1321 if (has_name) {
1322 error_setg(errp, "net client(%s) isn't a NIC", name);
1323 return NULL;
1325 continue;
1328 /* only query information on queue 0 since the info is per nic,
1329 * not per queue
1331 if (nc->queue_index != 0)
1332 continue;
1334 if (nc->info->query_rx_filter) {
1335 info = nc->info->query_rx_filter(nc);
1336 entry = g_malloc0(sizeof(*entry));
1337 entry->value = info;
1339 if (!filter_list) {
1340 filter_list = entry;
1341 } else {
1342 last_entry->next = entry;
1344 last_entry = entry;
1345 } else if (has_name) {
1346 error_setg(errp, "net client(%s) doesn't support"
1347 " rx-filter querying", name);
1348 return NULL;
1351 if (has_name) {
1352 break;
1356 if (filter_list == NULL && has_name) {
1357 error_setg(errp, "invalid net client name: %s", name);
1360 return filter_list;
1363 void hmp_info_network(Monitor *mon, const QDict *qdict)
1365 NetClientState *nc, *peer;
1366 NetClientDriver type;
1368 net_hub_info(mon);
1370 QTAILQ_FOREACH(nc, &net_clients, next) {
1371 peer = nc->peer;
1372 type = nc->info->type;
1374 /* Skip if already printed in hub info */
1375 if (net_hub_id_for_client(nc, NULL) == 0) {
1376 continue;
1379 if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1380 print_net_client(mon, nc);
1381 } /* else it's a netdev connected to a NIC, printed with the NIC */
1382 if (peer && type == NET_CLIENT_DRIVER_NIC) {
1383 monitor_printf(mon, " \\ ");
1384 print_net_client(mon, peer);
1389 void qmp_set_link(const char *name, bool up, Error **errp)
1391 NetClientState *ncs[MAX_QUEUE_NUM];
1392 NetClientState *nc;
1393 int queues, i;
1395 queues = qemu_find_net_clients_except(name, ncs,
1396 NET_CLIENT_DRIVER__MAX,
1397 MAX_QUEUE_NUM);
1399 if (queues == 0) {
1400 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1401 "Device '%s' not found", name);
1402 return;
1404 nc = ncs[0];
1406 for (i = 0; i < queues; i++) {
1407 ncs[i]->link_down = !up;
1410 if (nc->info->link_status_changed) {
1411 nc->info->link_status_changed(nc);
1414 if (nc->peer) {
1415 /* Change peer link only if the peer is NIC and then notify peer.
1416 * If the peer is a HUBPORT or a backend, we do not change the
1417 * link status.
1419 * This behavior is compatible with qemu vlans where there could be
1420 * multiple clients that can still communicate with each other in
1421 * disconnected mode. For now maintain this compatibility.
1423 if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1424 for (i = 0; i < queues; i++) {
1425 ncs[i]->peer->link_down = !up;
1428 if (nc->peer->info->link_status_changed) {
1429 nc->peer->info->link_status_changed(nc->peer);
1434 static void net_vm_change_state_handler(void *opaque, int running,
1435 RunState state)
1437 NetClientState *nc;
1438 NetClientState *tmp;
1440 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1441 if (running) {
1442 /* Flush queued packets and wake up backends. */
1443 if (nc->peer && qemu_can_send_packet(nc)) {
1444 qemu_flush_queued_packets(nc->peer);
1446 } else {
1447 /* Complete all queued packets, to guarantee we don't modify
1448 * state later when VM is not running.
1450 qemu_flush_or_purge_queued_packets(nc, true);
1455 void net_cleanup(void)
1457 NetClientState *nc;
1459 /* We may del multiple entries during qemu_del_net_client(),
1460 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1462 while (!QTAILQ_EMPTY(&net_clients)) {
1463 nc = QTAILQ_FIRST(&net_clients);
1464 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1465 qemu_del_nic(qemu_get_nic(nc));
1466 } else {
1467 qemu_del_net_client(nc);
1471 qemu_del_vm_change_state_handler(net_change_state_entry);
1474 void net_check_clients(void)
1476 NetClientState *nc;
1477 int i;
1479 net_hub_check_clients();
1481 QTAILQ_FOREACH(nc, &net_clients, next) {
1482 if (!nc->peer) {
1483 fprintf(stderr, "Warning: %s %s has no peer\n",
1484 nc->info->type == NET_CLIENT_DRIVER_NIC ?
1485 "nic" : "netdev", nc->name);
1489 /* Check that all NICs requested via -net nic actually got created.
1490 * NICs created via -device don't need to be checked here because
1491 * they are always instantiated.
1493 for (i = 0; i < MAX_NICS; i++) {
1494 NICInfo *nd = &nd_table[i];
1495 if (nd->used && !nd->instantiated) {
1496 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1497 "was not created (not supported by this machine?)\n",
1498 nd->name ? nd->name : "anonymous",
1499 nd->model ? nd->model : "unspecified");
1504 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1506 Error *local_err = NULL;
1508 net_client_init(opts, false, &local_err);
1509 if (local_err) {
1510 error_report_err(local_err);
1511 return -1;
1514 return 0;
1517 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1519 Error *local_err = NULL;
1520 int ret;
1522 ret = net_client_init(opts, true, &local_err);
1523 if (local_err) {
1524 error_report_err(local_err);
1525 return -1;
1528 return ret;
1531 int net_init_clients(void)
1533 QemuOptsList *net = qemu_find_opts("net");
1535 net_change_state_entry =
1536 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1538 QTAILQ_INIT(&net_clients);
1540 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1541 net_init_netdev, NULL, NULL)) {
1542 return -1;
1545 if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1546 return -1;
1549 return 0;
1552 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1554 #if defined(CONFIG_SLIRP)
1555 int ret;
1556 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1557 return ret;
1559 #endif
1561 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1562 return -1;
1565 return 0;
1568 /* From FreeBSD */
1569 /* XXX: optimize */
1570 unsigned compute_mcast_idx(const uint8_t *ep)
1572 uint32_t crc;
1573 int carry, i, j;
1574 uint8_t b;
1576 crc = 0xffffffff;
1577 for (i = 0; i < 6; i++) {
1578 b = *ep++;
1579 for (j = 0; j < 8; j++) {
1580 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1581 crc <<= 1;
1582 b >>= 1;
1583 if (carry) {
1584 crc = ((crc ^ POLYNOMIAL) | carry);
1588 return crc >> 26;
1591 QemuOptsList qemu_netdev_opts = {
1592 .name = "netdev",
1593 .implied_opt_name = "type",
1594 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1595 .desc = {
1597 * no elements => accept any params
1598 * validation will happen later
1600 { /* end of list */ }
1604 QemuOptsList qemu_net_opts = {
1605 .name = "net",
1606 .implied_opt_name = "type",
1607 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1608 .desc = {
1610 * no elements => accept any params
1611 * validation will happen later
1613 { /* end of list */ }
1617 void net_socket_rs_init(SocketReadState *rs,
1618 SocketReadStateFinalize *finalize)
1620 rs->state = 0;
1621 rs->index = 0;
1622 rs->packet_len = 0;
1623 memset(rs->buf, 0, sizeof(rs->buf));
1624 rs->finalize = finalize;
1628 * Returns
1629 * 0: success
1630 * -1: error occurs
1632 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1634 unsigned int l;
1636 while (size > 0) {
1637 /* reassemble a packet from the network */
1638 switch (rs->state) { /* 0 = getting length, 1 = getting data */
1639 case 0:
1640 l = 4 - rs->index;
1641 if (l > size) {
1642 l = size;
1644 memcpy(rs->buf + rs->index, buf, l);
1645 buf += l;
1646 size -= l;
1647 rs->index += l;
1648 if (rs->index == 4) {
1649 /* got length */
1650 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1651 rs->index = 0;
1652 rs->state = 1;
1654 break;
1655 case 1:
1656 l = rs->packet_len - rs->index;
1657 if (l > size) {
1658 l = size;
1660 if (rs->index + l <= sizeof(rs->buf)) {
1661 memcpy(rs->buf + rs->index, buf, l);
1662 } else {
1663 fprintf(stderr, "serious error: oversized packet received,"
1664 "connection terminated.\n");
1665 rs->index = rs->state = 0;
1666 return -1;
1669 rs->index += l;
1670 buf += l;
1671 size -= l;
1672 if (rs->index >= rs->packet_len) {
1673 rs->index = 0;
1674 rs->state = 0;
1675 assert(rs->finalize);
1676 rs->finalize(rs);
1678 break;
1682 assert(size == 0);
1683 return 0;