virtio: make virtio_queue_notify_vq static
[qemu/cris-port.git] / net / net.c
blob594c3b8b5d40e9126789322c0671a13e6de31063
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 "net/filter.h"
49 #include "qapi/string-output-visitor.h"
51 /* Net bridge is currently not supported for W32. */
52 #if !defined(_WIN32)
53 # define CONFIG_NET_BRIDGE
54 #endif
56 static VMChangeStateEntry *net_change_state_entry;
57 static QTAILQ_HEAD(, NetClientState) net_clients;
59 const char *host_net_devices[] = {
60 "tap",
61 "socket",
62 "dump",
63 #ifdef CONFIG_NET_BRIDGE
64 "bridge",
65 #endif
66 #ifdef CONFIG_NETMAP
67 "netmap",
68 #endif
69 #ifdef CONFIG_SLIRP
70 "user",
71 #endif
72 #ifdef CONFIG_VDE
73 "vde",
74 #endif
75 "vhost-user",
76 NULL,
79 int default_net = 1;
81 /***********************************************************/
82 /* network device redirectors */
84 #if defined(DEBUG_NET)
85 static void hex_dump(FILE *f, const uint8_t *buf, int size)
87 int len, i, j, c;
89 for(i=0;i<size;i+=16) {
90 len = size - i;
91 if (len > 16)
92 len = 16;
93 fprintf(f, "%08x ", i);
94 for(j=0;j<16;j++) {
95 if (j < len)
96 fprintf(f, " %02x", buf[i+j]);
97 else
98 fprintf(f, " ");
100 fprintf(f, " ");
101 for(j=0;j<len;j++) {
102 c = buf[i+j];
103 if (c < ' ' || c > '~')
104 c = '.';
105 fprintf(f, "%c", c);
107 fprintf(f, "\n");
110 #endif
112 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
114 const char *p, *p1;
115 int len;
116 p = *pp;
117 p1 = strchr(p, sep);
118 if (!p1)
119 return -1;
120 len = p1 - p;
121 p1++;
122 if (buf_size > 0) {
123 if (len > buf_size - 1)
124 len = buf_size - 1;
125 memcpy(buf, p, len);
126 buf[len] = '\0';
128 *pp = p1;
129 return 0;
132 int parse_host_port(struct sockaddr_in *saddr, const char *str)
134 char buf[512];
135 struct hostent *he;
136 const char *p, *r;
137 int port;
139 p = str;
140 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
141 return -1;
142 saddr->sin_family = AF_INET;
143 if (buf[0] == '\0') {
144 saddr->sin_addr.s_addr = 0;
145 } else {
146 if (qemu_isdigit(buf[0])) {
147 if (!inet_aton(buf, &saddr->sin_addr))
148 return -1;
149 } else {
150 if ((he = gethostbyname(buf)) == NULL)
151 return - 1;
152 saddr->sin_addr = *(struct in_addr *)he->h_addr;
155 port = strtol(p, (char **)&r, 0);
156 if (r == p)
157 return -1;
158 saddr->sin_port = htons(port);
159 return 0;
162 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
164 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
165 macaddr[0], macaddr[1], macaddr[2],
166 macaddr[3], macaddr[4], macaddr[5]);
169 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
171 snprintf(nc->info_str, sizeof(nc->info_str),
172 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
173 nc->model,
174 macaddr[0], macaddr[1], macaddr[2],
175 macaddr[3], macaddr[4], macaddr[5]);
178 static int mac_table[256] = {0};
180 static void qemu_macaddr_set_used(MACAddr *macaddr)
182 int index;
184 for (index = 0x56; index < 0xFF; index++) {
185 if (macaddr->a[5] == index) {
186 mac_table[index]++;
191 static void qemu_macaddr_set_free(MACAddr *macaddr)
193 int index;
194 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
196 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
197 return;
199 for (index = 0x56; index < 0xFF; index++) {
200 if (macaddr->a[5] == index) {
201 mac_table[index]--;
206 static int qemu_macaddr_get_free(void)
208 int index;
210 for (index = 0x56; index < 0xFF; index++) {
211 if (mac_table[index] == 0) {
212 return index;
216 return -1;
219 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
221 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
222 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
224 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
225 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
226 return;
227 } else {
228 qemu_macaddr_set_used(macaddr);
229 return;
233 macaddr->a[0] = 0x52;
234 macaddr->a[1] = 0x54;
235 macaddr->a[2] = 0x00;
236 macaddr->a[3] = 0x12;
237 macaddr->a[4] = 0x34;
238 macaddr->a[5] = qemu_macaddr_get_free();
239 qemu_macaddr_set_used(macaddr);
243 * Generate a name for net client
245 * Only net clients created with the legacy -net option and NICs need this.
247 static char *assign_name(NetClientState *nc1, const char *model)
249 NetClientState *nc;
250 int id = 0;
252 QTAILQ_FOREACH(nc, &net_clients, next) {
253 if (nc == nc1) {
254 continue;
256 if (strcmp(nc->model, model) == 0) {
257 id++;
261 return g_strdup_printf("%s.%d", model, id);
264 static void qemu_net_client_destructor(NetClientState *nc)
266 g_free(nc);
269 static void qemu_net_client_setup(NetClientState *nc,
270 NetClientInfo *info,
271 NetClientState *peer,
272 const char *model,
273 const char *name,
274 NetClientDestructor *destructor)
276 nc->info = info;
277 nc->model = g_strdup(model);
278 if (name) {
279 nc->name = g_strdup(name);
280 } else {
281 nc->name = assign_name(nc, model);
284 if (peer) {
285 assert(!peer->peer);
286 nc->peer = peer;
287 peer->peer = nc;
289 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
291 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
292 nc->destructor = destructor;
293 QTAILQ_INIT(&nc->filters);
296 NetClientState *qemu_new_net_client(NetClientInfo *info,
297 NetClientState *peer,
298 const char *model,
299 const char *name)
301 NetClientState *nc;
303 assert(info->size >= sizeof(NetClientState));
305 nc = g_malloc0(info->size);
306 qemu_net_client_setup(nc, info, peer, model, name,
307 qemu_net_client_destructor);
309 return nc;
312 NICState *qemu_new_nic(NetClientInfo *info,
313 NICConf *conf,
314 const char *model,
315 const char *name,
316 void *opaque)
318 NetClientState **peers = conf->peers.ncs;
319 NICState *nic;
320 int i, queues = MAX(1, conf->peers.queues);
322 assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
323 assert(info->size >= sizeof(NICState));
325 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
326 nic->ncs = (void *)nic + info->size;
327 nic->conf = conf;
328 nic->opaque = opaque;
330 for (i = 0; i < queues; i++) {
331 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
332 NULL);
333 nic->ncs[i].queue_index = i;
336 return nic;
339 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
341 return nic->ncs + queue_index;
344 NetClientState *qemu_get_queue(NICState *nic)
346 return qemu_get_subqueue(nic, 0);
349 NICState *qemu_get_nic(NetClientState *nc)
351 NetClientState *nc0 = nc - nc->queue_index;
353 return (NICState *)((void *)nc0 - nc->info->size);
356 void *qemu_get_nic_opaque(NetClientState *nc)
358 NICState *nic = qemu_get_nic(nc);
360 return nic->opaque;
363 static void qemu_cleanup_net_client(NetClientState *nc)
365 QTAILQ_REMOVE(&net_clients, nc, next);
367 if (nc->info->cleanup) {
368 nc->info->cleanup(nc);
372 static void qemu_free_net_client(NetClientState *nc)
374 if (nc->incoming_queue) {
375 qemu_del_net_queue(nc->incoming_queue);
377 if (nc->peer) {
378 nc->peer->peer = NULL;
380 g_free(nc->name);
381 g_free(nc->model);
382 if (nc->destructor) {
383 nc->destructor(nc);
387 void qemu_del_net_client(NetClientState *nc)
389 NetClientState *ncs[MAX_QUEUE_NUM];
390 int queues, i;
391 NetFilterState *nf, *next;
393 assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
395 /* If the NetClientState belongs to a multiqueue backend, we will change all
396 * other NetClientStates also.
398 queues = qemu_find_net_clients_except(nc->name, ncs,
399 NET_CLIENT_OPTIONS_KIND_NIC,
400 MAX_QUEUE_NUM);
401 assert(queues != 0);
403 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
404 object_unparent(OBJECT(nf));
407 /* If there is a peer NIC, delete and cleanup client, but do not free. */
408 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
409 NICState *nic = qemu_get_nic(nc->peer);
410 if (nic->peer_deleted) {
411 return;
413 nic->peer_deleted = true;
415 for (i = 0; i < queues; i++) {
416 ncs[i]->peer->link_down = true;
419 if (nc->peer->info->link_status_changed) {
420 nc->peer->info->link_status_changed(nc->peer);
423 for (i = 0; i < queues; i++) {
424 qemu_cleanup_net_client(ncs[i]);
427 return;
430 for (i = 0; i < queues; i++) {
431 qemu_cleanup_net_client(ncs[i]);
432 qemu_free_net_client(ncs[i]);
436 void qemu_del_nic(NICState *nic)
438 int i, queues = MAX(nic->conf->peers.queues, 1);
440 qemu_macaddr_set_free(&nic->conf->macaddr);
442 /* If this is a peer NIC and peer has already been deleted, free it now. */
443 if (nic->peer_deleted) {
444 for (i = 0; i < queues; i++) {
445 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
449 for (i = queues - 1; i >= 0; i--) {
450 NetClientState *nc = qemu_get_subqueue(nic, i);
452 qemu_cleanup_net_client(nc);
453 qemu_free_net_client(nc);
456 g_free(nic);
459 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
461 NetClientState *nc;
463 QTAILQ_FOREACH(nc, &net_clients, next) {
464 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
465 if (nc->queue_index == 0) {
466 func(qemu_get_nic(nc), opaque);
472 bool qemu_has_ufo(NetClientState *nc)
474 if (!nc || !nc->info->has_ufo) {
475 return false;
478 return nc->info->has_ufo(nc);
481 bool qemu_has_vnet_hdr(NetClientState *nc)
483 if (!nc || !nc->info->has_vnet_hdr) {
484 return false;
487 return nc->info->has_vnet_hdr(nc);
490 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
492 if (!nc || !nc->info->has_vnet_hdr_len) {
493 return false;
496 return nc->info->has_vnet_hdr_len(nc, len);
499 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
501 if (!nc || !nc->info->using_vnet_hdr) {
502 return;
505 nc->info->using_vnet_hdr(nc, enable);
508 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
509 int ecn, int ufo)
511 if (!nc || !nc->info->set_offload) {
512 return;
515 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
518 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
520 if (!nc || !nc->info->set_vnet_hdr_len) {
521 return;
524 nc->info->set_vnet_hdr_len(nc, len);
527 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
529 #ifdef HOST_WORDS_BIGENDIAN
530 if (!nc || !nc->info->set_vnet_le) {
531 return -ENOSYS;
534 return nc->info->set_vnet_le(nc, is_le);
535 #else
536 return 0;
537 #endif
540 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
542 #ifdef HOST_WORDS_BIGENDIAN
543 return 0;
544 #else
545 if (!nc || !nc->info->set_vnet_be) {
546 return -ENOSYS;
549 return nc->info->set_vnet_be(nc, is_be);
550 #endif
553 int qemu_can_send_packet(NetClientState *sender)
555 int vm_running = runstate_is_running();
557 if (!vm_running) {
558 return 0;
561 if (!sender->peer) {
562 return 1;
565 if (sender->peer->receive_disabled) {
566 return 0;
567 } else if (sender->peer->info->can_receive &&
568 !sender->peer->info->can_receive(sender->peer)) {
569 return 0;
571 return 1;
574 static ssize_t filter_receive_iov(NetClientState *nc,
575 NetFilterDirection direction,
576 NetClientState *sender,
577 unsigned flags,
578 const struct iovec *iov,
579 int iovcnt,
580 NetPacketSent *sent_cb)
582 ssize_t ret = 0;
583 NetFilterState *nf = NULL;
585 if (direction == NET_FILTER_DIRECTION_TX) {
586 QTAILQ_FOREACH(nf, &nc->filters, next) {
587 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
588 iovcnt, sent_cb);
589 if (ret) {
590 return ret;
593 } else {
594 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, NetFilterHead, next) {
595 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
596 iovcnt, sent_cb);
597 if (ret) {
598 return ret;
603 return ret;
606 static ssize_t filter_receive(NetClientState *nc,
607 NetFilterDirection direction,
608 NetClientState *sender,
609 unsigned flags,
610 const uint8_t *data,
611 size_t size,
612 NetPacketSent *sent_cb)
614 struct iovec iov = {
615 .iov_base = (void *)data,
616 .iov_len = size
619 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
622 void qemu_purge_queued_packets(NetClientState *nc)
624 if (!nc->peer) {
625 return;
628 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
631 static
632 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
634 nc->receive_disabled = 0;
636 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
637 if (net_hub_flush(nc->peer)) {
638 qemu_notify_event();
641 if (qemu_net_queue_flush(nc->incoming_queue)) {
642 /* We emptied the queue successfully, signal to the IO thread to repoll
643 * the file descriptor (for tap, for example).
645 qemu_notify_event();
646 } else if (purge) {
647 /* Unable to empty the queue, purge remaining packets */
648 qemu_net_queue_purge(nc->incoming_queue, nc);
652 void qemu_flush_queued_packets(NetClientState *nc)
654 qemu_flush_or_purge_queued_packets(nc, false);
657 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
658 unsigned flags,
659 const uint8_t *buf, int size,
660 NetPacketSent *sent_cb)
662 NetQueue *queue;
663 int ret;
665 #ifdef DEBUG_NET
666 printf("qemu_send_packet_async:\n");
667 hex_dump(stdout, buf, size);
668 #endif
670 if (sender->link_down || !sender->peer) {
671 return size;
674 /* Let filters handle the packet first */
675 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
676 sender, flags, buf, size, sent_cb);
677 if (ret) {
678 return ret;
681 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
682 sender, flags, buf, size, sent_cb);
683 if (ret) {
684 return ret;
687 queue = sender->peer->incoming_queue;
689 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
692 ssize_t qemu_send_packet_async(NetClientState *sender,
693 const uint8_t *buf, int size,
694 NetPacketSent *sent_cb)
696 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
697 buf, size, sent_cb);
700 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
702 qemu_send_packet_async(nc, buf, size, NULL);
705 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
707 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
708 buf, size, NULL);
711 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
712 int iovcnt, unsigned flags)
714 uint8_t buf[NET_BUFSIZE];
715 uint8_t *buffer;
716 size_t offset;
718 if (iovcnt == 1) {
719 buffer = iov[0].iov_base;
720 offset = iov[0].iov_len;
721 } else {
722 buffer = buf;
723 offset = iov_to_buf(iov, iovcnt, 0, buf, sizeof(buf));
726 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
727 return nc->info->receive_raw(nc, buffer, offset);
728 } else {
729 return nc->info->receive(nc, buffer, offset);
733 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
734 unsigned flags,
735 const struct iovec *iov,
736 int iovcnt,
737 void *opaque)
739 NetClientState *nc = opaque;
740 int ret;
742 if (nc->link_down) {
743 return iov_size(iov, iovcnt);
746 if (nc->receive_disabled) {
747 return 0;
750 if (nc->info->receive_iov) {
751 ret = nc->info->receive_iov(nc, iov, iovcnt);
752 } else {
753 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
756 if (ret == 0) {
757 nc->receive_disabled = 1;
760 return ret;
763 ssize_t qemu_sendv_packet_async(NetClientState *sender,
764 const struct iovec *iov, int iovcnt,
765 NetPacketSent *sent_cb)
767 NetQueue *queue;
768 int ret;
770 if (sender->link_down || !sender->peer) {
771 return iov_size(iov, iovcnt);
774 /* Let filters handle the packet first */
775 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
776 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
777 if (ret) {
778 return ret;
781 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
782 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
783 if (ret) {
784 return ret;
787 queue = sender->peer->incoming_queue;
789 return qemu_net_queue_send_iov(queue, sender,
790 QEMU_NET_PACKET_FLAG_NONE,
791 iov, iovcnt, sent_cb);
794 ssize_t
795 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
797 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
800 NetClientState *qemu_find_netdev(const char *id)
802 NetClientState *nc;
804 QTAILQ_FOREACH(nc, &net_clients, next) {
805 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
806 continue;
807 if (!strcmp(nc->name, id)) {
808 return nc;
812 return NULL;
815 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
816 NetClientOptionsKind type, int max)
818 NetClientState *nc;
819 int ret = 0;
821 QTAILQ_FOREACH(nc, &net_clients, next) {
822 if (nc->info->type == type) {
823 continue;
825 if (!id || !strcmp(nc->name, id)) {
826 if (ret < max) {
827 ncs[ret] = nc;
829 ret++;
833 return ret;
836 static int nic_get_free_idx(void)
838 int index;
840 for (index = 0; index < MAX_NICS; index++)
841 if (!nd_table[index].used)
842 return index;
843 return -1;
846 int qemu_show_nic_models(const char *arg, const char *const *models)
848 int i;
850 if (!arg || !is_help_option(arg)) {
851 return 0;
854 fprintf(stderr, "qemu: Supported NIC models: ");
855 for (i = 0 ; models[i]; i++)
856 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
857 return 1;
860 void qemu_check_nic_model(NICInfo *nd, const char *model)
862 const char *models[2];
864 models[0] = model;
865 models[1] = NULL;
867 if (qemu_show_nic_models(nd->model, models))
868 exit(0);
869 if (qemu_find_nic_model(nd, models, model) < 0)
870 exit(1);
873 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
874 const char *default_model)
876 int i;
878 if (!nd->model)
879 nd->model = g_strdup(default_model);
881 for (i = 0 ; models[i]; i++) {
882 if (strcmp(nd->model, models[i]) == 0)
883 return i;
886 error_report("Unsupported NIC model: %s", nd->model);
887 return -1;
890 static int net_init_nic(const NetClientOptions *opts, const char *name,
891 NetClientState *peer, Error **errp)
893 int idx;
894 NICInfo *nd;
895 const NetLegacyNicOptions *nic;
897 assert(opts->type == NET_CLIENT_OPTIONS_KIND_NIC);
898 nic = opts->u.nic.data;
900 idx = nic_get_free_idx();
901 if (idx == -1 || nb_nics >= MAX_NICS) {
902 error_setg(errp, "too many NICs");
903 return -1;
906 nd = &nd_table[idx];
908 memset(nd, 0, sizeof(*nd));
910 if (nic->has_netdev) {
911 nd->netdev = qemu_find_netdev(nic->netdev);
912 if (!nd->netdev) {
913 error_setg(errp, "netdev '%s' not found", nic->netdev);
914 return -1;
916 } else {
917 assert(peer);
918 nd->netdev = peer;
920 nd->name = g_strdup(name);
921 if (nic->has_model) {
922 nd->model = g_strdup(nic->model);
924 if (nic->has_addr) {
925 nd->devaddr = g_strdup(nic->addr);
928 if (nic->has_macaddr &&
929 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
930 error_setg(errp, "invalid syntax for ethernet address");
931 return -1;
933 if (nic->has_macaddr &&
934 is_multicast_ether_addr(nd->macaddr.a)) {
935 error_setg(errp,
936 "NIC cannot have multicast MAC address (odd 1st byte)");
937 return -1;
939 qemu_macaddr_default_if_unset(&nd->macaddr);
941 if (nic->has_vectors) {
942 if (nic->vectors > 0x7ffffff) {
943 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
944 return -1;
946 nd->nvectors = nic->vectors;
947 } else {
948 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
951 nd->used = 1;
952 nb_nics++;
954 return idx;
958 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND__MAX])(
959 const NetClientOptions *opts,
960 const char *name,
961 NetClientState *peer, Error **errp) = {
962 [NET_CLIENT_OPTIONS_KIND_NIC] = net_init_nic,
963 #ifdef CONFIG_SLIRP
964 [NET_CLIENT_OPTIONS_KIND_USER] = net_init_slirp,
965 #endif
966 [NET_CLIENT_OPTIONS_KIND_TAP] = net_init_tap,
967 [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
968 #ifdef CONFIG_VDE
969 [NET_CLIENT_OPTIONS_KIND_VDE] = net_init_vde,
970 #endif
971 #ifdef CONFIG_NETMAP
972 [NET_CLIENT_OPTIONS_KIND_NETMAP] = net_init_netmap,
973 #endif
974 [NET_CLIENT_OPTIONS_KIND_DUMP] = net_init_dump,
975 #ifdef CONFIG_NET_BRIDGE
976 [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
977 #endif
978 [NET_CLIENT_OPTIONS_KIND_HUBPORT] = net_init_hubport,
979 #ifdef CONFIG_VHOST_NET_USED
980 [NET_CLIENT_OPTIONS_KIND_VHOST_USER] = net_init_vhost_user,
981 #endif
982 #ifdef CONFIG_L2TPV3
983 [NET_CLIENT_OPTIONS_KIND_L2TPV3] = net_init_l2tpv3,
984 #endif
988 static int net_client_init1(const void *object, int is_netdev, Error **errp)
990 const NetClientOptions *opts;
991 const char *name;
992 NetClientState *peer = NULL;
994 if (is_netdev) {
995 const Netdev *netdev = object;
996 opts = netdev->opts;
997 name = netdev->id;
999 if (opts->type == NET_CLIENT_OPTIONS_KIND_DUMP ||
1000 opts->type == NET_CLIENT_OPTIONS_KIND_NIC ||
1001 !net_client_init_fun[opts->type]) {
1002 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1003 "a netdev backend type");
1004 return -1;
1006 } else {
1007 const NetLegacy *net = object;
1008 opts = net->opts;
1009 /* missing optional values have been initialized to "all bits zero" */
1010 name = net->has_id ? net->id : net->name;
1012 if (opts->type == NET_CLIENT_OPTIONS_KIND_NONE) {
1013 return 0; /* nothing to do */
1015 if (opts->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
1016 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1017 "a net type");
1018 return -1;
1021 if (!net_client_init_fun[opts->type]) {
1022 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1023 "a net backend type (maybe it is not compiled "
1024 "into this binary)");
1025 return -1;
1028 /* Do not add to a vlan if it's a nic with a netdev= parameter. */
1029 if (opts->type != NET_CLIENT_OPTIONS_KIND_NIC ||
1030 !opts->u.nic.data->has_netdev) {
1031 peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
1035 if (net_client_init_fun[opts->type](opts, name, peer, errp) < 0) {
1036 /* FIXME drop when all init functions store an Error */
1037 if (errp && !*errp) {
1038 error_setg(errp, QERR_DEVICE_INIT_FAILED,
1039 NetClientOptionsKind_lookup[opts->type]);
1041 return -1;
1043 return 0;
1047 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
1049 void *object = NULL;
1050 Error *err = NULL;
1051 int ret = -1;
1052 OptsVisitor *ov = opts_visitor_new(opts);
1053 Visitor *v = opts_get_visitor(ov);
1056 /* Parse convenience option format ip6-net=fec0::0[/64] */
1057 const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1059 if (ip6_net) {
1060 char buf[strlen(ip6_net) + 1];
1062 if (get_str_sep(buf, sizeof(buf), &ip6_net, '/') < 0) {
1063 /* Default 64bit prefix length. */
1064 qemu_opt_set(opts, "ipv6-prefix", ip6_net, &error_abort);
1065 qemu_opt_set_number(opts, "ipv6-prefixlen", 64, &error_abort);
1066 } else {
1067 /* User-specified prefix length. */
1068 unsigned long len;
1069 int err;
1071 qemu_opt_set(opts, "ipv6-prefix", buf, &error_abort);
1072 err = qemu_strtoul(ip6_net, NULL, 10, &len);
1074 if (err) {
1075 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1076 "ipv6-prefix", "a number");
1077 } else {
1078 qemu_opt_set_number(opts, "ipv6-prefixlen", len,
1079 &error_abort);
1082 qemu_opt_unset(opts, "ipv6-net");
1086 if (is_netdev) {
1087 visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1088 } else {
1089 visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1092 if (!err) {
1093 ret = net_client_init1(object, is_netdev, &err);
1096 if (is_netdev) {
1097 qapi_free_Netdev(object);
1098 } else {
1099 qapi_free_NetLegacy(object);
1102 error_propagate(errp, err);
1103 return ret;
1107 static int net_host_check_device(const char *device)
1109 int i;
1110 for (i = 0; host_net_devices[i]; i++) {
1111 if (!strncmp(host_net_devices[i], device,
1112 strlen(host_net_devices[i]))) {
1113 return 1;
1117 return 0;
1120 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1122 const char *device = qdict_get_str(qdict, "device");
1123 const char *opts_str = qdict_get_try_str(qdict, "opts");
1124 Error *local_err = NULL;
1125 QemuOpts *opts;
1127 if (!net_host_check_device(device)) {
1128 monitor_printf(mon, "invalid host network device %s\n", device);
1129 return;
1132 opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1133 opts_str ? opts_str : "", false);
1134 if (!opts) {
1135 return;
1138 qemu_opt_set(opts, "type", device, &error_abort);
1140 net_client_init(opts, 0, &local_err);
1141 if (local_err) {
1142 error_report_err(local_err);
1143 monitor_printf(mon, "adding host network device %s failed\n", device);
1147 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1149 NetClientState *nc;
1150 int vlan_id = qdict_get_int(qdict, "vlan_id");
1151 const char *device = qdict_get_str(qdict, "device");
1153 nc = net_hub_find_client_by_name(vlan_id, device);
1154 if (!nc) {
1155 error_report("Host network device '%s' on hub '%d' not found",
1156 device, vlan_id);
1157 return;
1159 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1160 error_report("invalid host network device '%s'", device);
1161 return;
1164 qemu_del_net_client(nc->peer);
1165 qemu_del_net_client(nc);
1168 void netdev_add(QemuOpts *opts, Error **errp)
1170 net_client_init(opts, 1, errp);
1173 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1175 Error *local_err = NULL;
1176 QemuOptsList *opts_list;
1177 QemuOpts *opts;
1179 opts_list = qemu_find_opts_err("netdev", &local_err);
1180 if (local_err) {
1181 goto out;
1184 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1185 if (local_err) {
1186 goto out;
1189 netdev_add(opts, &local_err);
1190 if (local_err) {
1191 qemu_opts_del(opts);
1192 goto out;
1195 out:
1196 error_propagate(errp, local_err);
1199 void qmp_netdev_del(const char *id, Error **errp)
1201 NetClientState *nc;
1202 QemuOpts *opts;
1204 nc = qemu_find_netdev(id);
1205 if (!nc) {
1206 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1207 "Device '%s' not found", id);
1208 return;
1211 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1212 if (!opts) {
1213 error_setg(errp, "Device '%s' is not a netdev", id);
1214 return;
1217 qemu_del_net_client(nc);
1218 qemu_opts_del(opts);
1221 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1223 char *str;
1224 ObjectProperty *prop;
1225 ObjectPropertyIterator iter;
1226 StringOutputVisitor *ov;
1228 /* generate info str */
1229 object_property_iter_init(&iter, OBJECT(nf));
1230 while ((prop = object_property_iter_next(&iter))) {
1231 if (!strcmp(prop->name, "type")) {
1232 continue;
1234 ov = string_output_visitor_new(false);
1235 object_property_get(OBJECT(nf), string_output_get_visitor(ov),
1236 prop->name, NULL);
1237 str = string_output_get_string(ov);
1238 string_output_visitor_cleanup(ov);
1239 monitor_printf(mon, ",%s=%s", prop->name, str);
1240 g_free(str);
1242 monitor_printf(mon, "\n");
1245 void print_net_client(Monitor *mon, NetClientState *nc)
1247 NetFilterState *nf;
1249 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1250 nc->queue_index,
1251 NetClientOptionsKind_lookup[nc->info->type],
1252 nc->info_str);
1253 if (!QTAILQ_EMPTY(&nc->filters)) {
1254 monitor_printf(mon, "filters:\n");
1256 QTAILQ_FOREACH(nf, &nc->filters, next) {
1257 char *path = object_get_canonical_path_component(OBJECT(nf));
1259 monitor_printf(mon, " - %s: type=%s", path,
1260 object_get_typename(OBJECT(nf)));
1261 netfilter_print_info(mon, nf);
1262 g_free(path);
1266 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1267 Error **errp)
1269 NetClientState *nc;
1270 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1272 QTAILQ_FOREACH(nc, &net_clients, next) {
1273 RxFilterInfoList *entry;
1274 RxFilterInfo *info;
1276 if (has_name && strcmp(nc->name, name) != 0) {
1277 continue;
1280 /* only query rx-filter information of NIC */
1281 if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1282 if (has_name) {
1283 error_setg(errp, "net client(%s) isn't a NIC", name);
1284 return NULL;
1286 continue;
1289 /* only query information on queue 0 since the info is per nic,
1290 * not per queue
1292 if (nc->queue_index != 0)
1293 continue;
1295 if (nc->info->query_rx_filter) {
1296 info = nc->info->query_rx_filter(nc);
1297 entry = g_malloc0(sizeof(*entry));
1298 entry->value = info;
1300 if (!filter_list) {
1301 filter_list = entry;
1302 } else {
1303 last_entry->next = entry;
1305 last_entry = entry;
1306 } else if (has_name) {
1307 error_setg(errp, "net client(%s) doesn't support"
1308 " rx-filter querying", name);
1309 return NULL;
1312 if (has_name) {
1313 break;
1317 if (filter_list == NULL && has_name) {
1318 error_setg(errp, "invalid net client name: %s", name);
1321 return filter_list;
1324 void hmp_info_network(Monitor *mon, const QDict *qdict)
1326 NetClientState *nc, *peer;
1327 NetClientOptionsKind type;
1329 net_hub_info(mon);
1331 QTAILQ_FOREACH(nc, &net_clients, next) {
1332 peer = nc->peer;
1333 type = nc->info->type;
1335 /* Skip if already printed in hub info */
1336 if (net_hub_id_for_client(nc, NULL) == 0) {
1337 continue;
1340 if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1341 print_net_client(mon, nc);
1342 } /* else it's a netdev connected to a NIC, printed with the NIC */
1343 if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1344 monitor_printf(mon, " \\ ");
1345 print_net_client(mon, peer);
1350 void qmp_set_link(const char *name, bool up, Error **errp)
1352 NetClientState *ncs[MAX_QUEUE_NUM];
1353 NetClientState *nc;
1354 int queues, i;
1356 queues = qemu_find_net_clients_except(name, ncs,
1357 NET_CLIENT_OPTIONS_KIND__MAX,
1358 MAX_QUEUE_NUM);
1360 if (queues == 0) {
1361 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1362 "Device '%s' not found", name);
1363 return;
1365 nc = ncs[0];
1367 for (i = 0; i < queues; i++) {
1368 ncs[i]->link_down = !up;
1371 if (nc->info->link_status_changed) {
1372 nc->info->link_status_changed(nc);
1375 if (nc->peer) {
1376 /* Change peer link only if the peer is NIC and then notify peer.
1377 * If the peer is a HUBPORT or a backend, we do not change the
1378 * link status.
1380 * This behavior is compatible with qemu vlans where there could be
1381 * multiple clients that can still communicate with each other in
1382 * disconnected mode. For now maintain this compatibility.
1384 if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1385 for (i = 0; i < queues; i++) {
1386 ncs[i]->peer->link_down = !up;
1389 if (nc->peer->info->link_status_changed) {
1390 nc->peer->info->link_status_changed(nc->peer);
1395 static void net_vm_change_state_handler(void *opaque, int running,
1396 RunState state)
1398 NetClientState *nc;
1399 NetClientState *tmp;
1401 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1402 if (running) {
1403 /* Flush queued packets and wake up backends. */
1404 if (nc->peer && qemu_can_send_packet(nc)) {
1405 qemu_flush_queued_packets(nc->peer);
1407 } else {
1408 /* Complete all queued packets, to guarantee we don't modify
1409 * state later when VM is not running.
1411 qemu_flush_or_purge_queued_packets(nc, true);
1416 void net_cleanup(void)
1418 NetClientState *nc;
1420 /* We may del multiple entries during qemu_del_net_client(),
1421 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1423 while (!QTAILQ_EMPTY(&net_clients)) {
1424 nc = QTAILQ_FIRST(&net_clients);
1425 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1426 qemu_del_nic(qemu_get_nic(nc));
1427 } else {
1428 qemu_del_net_client(nc);
1432 qemu_del_vm_change_state_handler(net_change_state_entry);
1435 void net_check_clients(void)
1437 NetClientState *nc;
1438 int i;
1440 /* Don't warn about the default network setup that you get if
1441 * no command line -net or -netdev options are specified. There
1442 * are two cases that we would otherwise complain about:
1443 * (1) board doesn't support a NIC but the implicit "-net nic"
1444 * requested one
1445 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1446 * sets up a nic that isn't connected to anything.
1448 if (default_net) {
1449 return;
1452 net_hub_check_clients();
1454 QTAILQ_FOREACH(nc, &net_clients, next) {
1455 if (!nc->peer) {
1456 fprintf(stderr, "Warning: %s %s has no peer\n",
1457 nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1458 "nic" : "netdev", nc->name);
1462 /* Check that all NICs requested via -net nic actually got created.
1463 * NICs created via -device don't need to be checked here because
1464 * they are always instantiated.
1466 for (i = 0; i < MAX_NICS; i++) {
1467 NICInfo *nd = &nd_table[i];
1468 if (nd->used && !nd->instantiated) {
1469 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1470 "was not created (not supported by this machine?)\n",
1471 nd->name ? nd->name : "anonymous",
1472 nd->model ? nd->model : "unspecified");
1477 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1479 Error *local_err = NULL;
1481 net_client_init(opts, 0, &local_err);
1482 if (local_err) {
1483 error_report_err(local_err);
1484 return -1;
1487 return 0;
1490 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1492 Error *local_err = NULL;
1493 int ret;
1495 ret = net_client_init(opts, 1, &local_err);
1496 if (local_err) {
1497 error_report_err(local_err);
1498 return -1;
1501 return ret;
1504 int net_init_clients(void)
1506 QemuOptsList *net = qemu_find_opts("net");
1508 if (default_net) {
1509 /* if no clients, we use a default config */
1510 qemu_opts_set(net, NULL, "type", "nic", &error_abort);
1511 #ifdef CONFIG_SLIRP
1512 qemu_opts_set(net, NULL, "type", "user", &error_abort);
1513 #endif
1516 net_change_state_entry =
1517 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1519 QTAILQ_INIT(&net_clients);
1521 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1522 net_init_netdev, NULL, NULL)) {
1523 return -1;
1526 if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1527 return -1;
1530 return 0;
1533 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1535 #if defined(CONFIG_SLIRP)
1536 int ret;
1537 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1538 return ret;
1540 #endif
1542 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1543 return -1;
1546 default_net = 0;
1547 return 0;
1550 /* From FreeBSD */
1551 /* XXX: optimize */
1552 unsigned compute_mcast_idx(const uint8_t *ep)
1554 uint32_t crc;
1555 int carry, i, j;
1556 uint8_t b;
1558 crc = 0xffffffff;
1559 for (i = 0; i < 6; i++) {
1560 b = *ep++;
1561 for (j = 0; j < 8; j++) {
1562 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1563 crc <<= 1;
1564 b >>= 1;
1565 if (carry) {
1566 crc = ((crc ^ POLYNOMIAL) | carry);
1570 return crc >> 26;
1573 QemuOptsList qemu_netdev_opts = {
1574 .name = "netdev",
1575 .implied_opt_name = "type",
1576 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1577 .desc = {
1579 * no elements => accept any params
1580 * validation will happen later
1582 { /* end of list */ }
1586 QemuOptsList qemu_net_opts = {
1587 .name = "net",
1588 .implied_opt_name = "type",
1589 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1590 .desc = {
1592 * no elements => accept any params
1593 * validation will happen later
1595 { /* end of list */ }