vfio/pci: Rework RTL8168 quirk
[qemu/ar7.git] / net / net.c
blob28a5597b8d8db18ad07047f41c7fc11431120949
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 "config-host.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 "qapi/qmp/qerror.h"
36 #include "qemu/error-report.h"
37 #include "qemu/sockets.h"
38 #include "qemu/config-file.h"
39 #include "qmp-commands.h"
40 #include "hw/qdev.h"
41 #include "qemu/iov.h"
42 #include "qemu/main-loop.h"
43 #include "qapi-visit.h"
44 #include "qapi/opts-visitor.h"
45 #include "qapi/dealloc-visitor.h"
46 #include "sysemu/sysemu.h"
48 /* Net bridge is currently not supported for W32. */
49 #if !defined(_WIN32)
50 # define CONFIG_NET_BRIDGE
51 #endif
53 static VMChangeStateEntry *net_change_state_entry;
54 static QTAILQ_HEAD(, NetClientState) net_clients;
56 const char *host_net_devices[] = {
57 "tap",
58 "socket",
59 "dump",
60 #ifdef CONFIG_NET_BRIDGE
61 "bridge",
62 #endif
63 #ifdef CONFIG_NETMAP
64 "netmap",
65 #endif
66 #ifdef CONFIG_SLIRP
67 "user",
68 #endif
69 #ifdef CONFIG_VDE
70 "vde",
71 #endif
72 "vhost-user",
73 NULL,
76 int default_net = 1;
78 /***********************************************************/
79 /* network device redirectors */
81 #if defined(DEBUG_NET)
82 static void hex_dump(FILE *f, const uint8_t *buf, int size)
84 int len, i, j, c;
86 for(i=0;i<size;i+=16) {
87 len = size - i;
88 if (len > 16)
89 len = 16;
90 fprintf(f, "%08x ", i);
91 for(j=0;j<16;j++) {
92 if (j < len)
93 fprintf(f, " %02x", buf[i+j]);
94 else
95 fprintf(f, " ");
97 fprintf(f, " ");
98 for(j=0;j<len;j++) {
99 c = buf[i+j];
100 if (c < ' ' || c > '~')
101 c = '.';
102 fprintf(f, "%c", c);
104 fprintf(f, "\n");
107 #endif
109 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
111 const char *p, *p1;
112 int len;
113 p = *pp;
114 p1 = strchr(p, sep);
115 if (!p1)
116 return -1;
117 len = p1 - p;
118 p1++;
119 if (buf_size > 0) {
120 if (len > buf_size - 1)
121 len = buf_size - 1;
122 memcpy(buf, p, len);
123 buf[len] = '\0';
125 *pp = p1;
126 return 0;
129 int parse_host_port(struct sockaddr_in *saddr, const char *str)
131 char buf[512];
132 struct hostent *he;
133 const char *p, *r;
134 int port;
136 p = str;
137 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
138 return -1;
139 saddr->sin_family = AF_INET;
140 if (buf[0] == '\0') {
141 saddr->sin_addr.s_addr = 0;
142 } else {
143 if (qemu_isdigit(buf[0])) {
144 if (!inet_aton(buf, &saddr->sin_addr))
145 return -1;
146 } else {
147 if ((he = gethostbyname(buf)) == NULL)
148 return - 1;
149 saddr->sin_addr = *(struct in_addr *)he->h_addr;
152 port = strtol(p, (char **)&r, 0);
153 if (r == p)
154 return -1;
155 saddr->sin_port = htons(port);
156 return 0;
159 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
161 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
162 macaddr[0], macaddr[1], macaddr[2],
163 macaddr[3], macaddr[4], macaddr[5]);
166 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
168 snprintf(nc->info_str, sizeof(nc->info_str),
169 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
170 nc->model,
171 macaddr[0], macaddr[1], macaddr[2],
172 macaddr[3], macaddr[4], macaddr[5]);
175 static int mac_table[256] = {0};
177 static void qemu_macaddr_set_used(MACAddr *macaddr)
179 int index;
181 for (index = 0x56; index < 0xFF; index++) {
182 if (macaddr->a[5] == index) {
183 mac_table[index]++;
188 static void qemu_macaddr_set_free(MACAddr *macaddr)
190 int index;
191 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
193 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
194 return;
196 for (index = 0x56; index < 0xFF; index++) {
197 if (macaddr->a[5] == index) {
198 mac_table[index]--;
203 static int qemu_macaddr_get_free(void)
205 int index;
207 for (index = 0x56; index < 0xFF; index++) {
208 if (mac_table[index] == 0) {
209 return index;
213 return -1;
216 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
218 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
219 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
221 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
222 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
223 return;
224 } else {
225 qemu_macaddr_set_used(macaddr);
226 return;
230 macaddr->a[0] = 0x52;
231 macaddr->a[1] = 0x54;
232 macaddr->a[2] = 0x00;
233 macaddr->a[3] = 0x12;
234 macaddr->a[4] = 0x34;
235 macaddr->a[5] = qemu_macaddr_get_free();
236 qemu_macaddr_set_used(macaddr);
240 * Generate a name for net client
242 * Only net clients created with the legacy -net option and NICs need this.
244 static char *assign_name(NetClientState *nc1, const char *model)
246 NetClientState *nc;
247 int id = 0;
249 QTAILQ_FOREACH(nc, &net_clients, next) {
250 if (nc == nc1) {
251 continue;
253 if (strcmp(nc->model, model) == 0) {
254 id++;
258 return g_strdup_printf("%s.%d", model, id);
261 static void qemu_net_client_destructor(NetClientState *nc)
263 g_free(nc);
266 static void qemu_net_client_setup(NetClientState *nc,
267 NetClientInfo *info,
268 NetClientState *peer,
269 const char *model,
270 const char *name,
271 NetClientDestructor *destructor)
273 nc->info = info;
274 nc->model = g_strdup(model);
275 if (name) {
276 nc->name = g_strdup(name);
277 } else {
278 nc->name = assign_name(nc, model);
281 if (peer) {
282 assert(!peer->peer);
283 nc->peer = peer;
284 peer->peer = nc;
286 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
288 nc->incoming_queue = qemu_new_net_queue(nc);
289 nc->destructor = destructor;
292 NetClientState *qemu_new_net_client(NetClientInfo *info,
293 NetClientState *peer,
294 const char *model,
295 const char *name)
297 NetClientState *nc;
299 assert(info->size >= sizeof(NetClientState));
301 nc = g_malloc0(info->size);
302 qemu_net_client_setup(nc, info, peer, model, name,
303 qemu_net_client_destructor);
305 return nc;
308 NICState *qemu_new_nic(NetClientInfo *info,
309 NICConf *conf,
310 const char *model,
311 const char *name,
312 void *opaque)
314 NetClientState **peers = conf->peers.ncs;
315 NICState *nic;
316 int i, queues = MAX(1, conf->peers.queues);
318 assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
319 assert(info->size >= sizeof(NICState));
321 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
322 nic->ncs = (void *)nic + info->size;
323 nic->conf = conf;
324 nic->opaque = opaque;
326 for (i = 0; i < queues; i++) {
327 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
328 NULL);
329 nic->ncs[i].queue_index = i;
332 return nic;
335 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
337 return nic->ncs + queue_index;
340 NetClientState *qemu_get_queue(NICState *nic)
342 return qemu_get_subqueue(nic, 0);
345 NICState *qemu_get_nic(NetClientState *nc)
347 NetClientState *nc0 = nc - nc->queue_index;
349 return (NICState *)((void *)nc0 - nc->info->size);
352 void *qemu_get_nic_opaque(NetClientState *nc)
354 NICState *nic = qemu_get_nic(nc);
356 return nic->opaque;
359 static void qemu_cleanup_net_client(NetClientState *nc)
361 QTAILQ_REMOVE(&net_clients, nc, next);
363 if (nc->info->cleanup) {
364 nc->info->cleanup(nc);
368 static void qemu_free_net_client(NetClientState *nc)
370 if (nc->incoming_queue) {
371 qemu_del_net_queue(nc->incoming_queue);
373 if (nc->peer) {
374 nc->peer->peer = NULL;
376 g_free(nc->name);
377 g_free(nc->model);
378 if (nc->destructor) {
379 nc->destructor(nc);
383 void qemu_del_net_client(NetClientState *nc)
385 NetClientState *ncs[MAX_QUEUE_NUM];
386 int queues, i;
388 assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
390 /* If the NetClientState belongs to a multiqueue backend, we will change all
391 * other NetClientStates also.
393 queues = qemu_find_net_clients_except(nc->name, ncs,
394 NET_CLIENT_OPTIONS_KIND_NIC,
395 MAX_QUEUE_NUM);
396 assert(queues != 0);
398 /* If there is a peer NIC, delete and cleanup client, but do not free. */
399 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
400 NICState *nic = qemu_get_nic(nc->peer);
401 if (nic->peer_deleted) {
402 return;
404 nic->peer_deleted = true;
406 for (i = 0; i < queues; i++) {
407 ncs[i]->peer->link_down = true;
410 if (nc->peer->info->link_status_changed) {
411 nc->peer->info->link_status_changed(nc->peer);
414 for (i = 0; i < queues; i++) {
415 qemu_cleanup_net_client(ncs[i]);
418 return;
421 for (i = 0; i < queues; i++) {
422 qemu_cleanup_net_client(ncs[i]);
423 qemu_free_net_client(ncs[i]);
427 void qemu_del_nic(NICState *nic)
429 int i, queues = MAX(nic->conf->peers.queues, 1);
431 qemu_macaddr_set_free(&nic->conf->macaddr);
433 /* If this is a peer NIC and peer has already been deleted, free it now. */
434 if (nic->peer_deleted) {
435 for (i = 0; i < queues; i++) {
436 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
440 for (i = queues - 1; i >= 0; i--) {
441 NetClientState *nc = qemu_get_subqueue(nic, i);
443 qemu_cleanup_net_client(nc);
444 qemu_free_net_client(nc);
447 g_free(nic);
450 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
452 NetClientState *nc;
454 QTAILQ_FOREACH(nc, &net_clients, next) {
455 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
456 if (nc->queue_index == 0) {
457 func(qemu_get_nic(nc), opaque);
463 bool qemu_has_ufo(NetClientState *nc)
465 if (!nc || !nc->info->has_ufo) {
466 return false;
469 return nc->info->has_ufo(nc);
472 bool qemu_has_vnet_hdr(NetClientState *nc)
474 if (!nc || !nc->info->has_vnet_hdr) {
475 return false;
478 return nc->info->has_vnet_hdr(nc);
481 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
483 if (!nc || !nc->info->has_vnet_hdr_len) {
484 return false;
487 return nc->info->has_vnet_hdr_len(nc, len);
490 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
492 if (!nc || !nc->info->using_vnet_hdr) {
493 return;
496 nc->info->using_vnet_hdr(nc, enable);
499 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
500 int ecn, int ufo)
502 if (!nc || !nc->info->set_offload) {
503 return;
506 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
509 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
511 if (!nc || !nc->info->set_vnet_hdr_len) {
512 return;
515 nc->info->set_vnet_hdr_len(nc, len);
518 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
520 if (!nc || !nc->info->set_vnet_le) {
521 return -ENOSYS;
524 return nc->info->set_vnet_le(nc, is_le);
527 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
529 if (!nc || !nc->info->set_vnet_be) {
530 return -ENOSYS;
533 return nc->info->set_vnet_be(nc, is_be);
536 int qemu_can_send_packet(NetClientState *sender)
538 int vm_running = runstate_is_running();
540 if (!vm_running) {
541 return 0;
544 if (!sender->peer) {
545 return 1;
548 if (sender->peer->receive_disabled) {
549 return 0;
550 } else if (sender->peer->info->can_receive &&
551 !sender->peer->info->can_receive(sender->peer)) {
552 return 0;
554 return 1;
557 ssize_t qemu_deliver_packet(NetClientState *sender,
558 unsigned flags,
559 const uint8_t *data,
560 size_t size,
561 void *opaque)
563 NetClientState *nc = opaque;
564 ssize_t ret;
566 if (nc->link_down) {
567 return size;
570 if (nc->receive_disabled) {
571 return 0;
574 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
575 ret = nc->info->receive_raw(nc, data, size);
576 } else {
577 ret = nc->info->receive(nc, data, size);
580 if (ret == 0) {
581 nc->receive_disabled = 1;
584 return ret;
587 void qemu_purge_queued_packets(NetClientState *nc)
589 if (!nc->peer) {
590 return;
593 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
596 static
597 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
599 nc->receive_disabled = 0;
601 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
602 if (net_hub_flush(nc->peer)) {
603 qemu_notify_event();
606 if (qemu_net_queue_flush(nc->incoming_queue)) {
607 /* We emptied the queue successfully, signal to the IO thread to repoll
608 * the file descriptor (for tap, for example).
610 qemu_notify_event();
611 } else if (purge) {
612 /* Unable to empty the queue, purge remaining packets */
613 qemu_net_queue_purge(nc->incoming_queue, nc);
617 void qemu_flush_queued_packets(NetClientState *nc)
619 qemu_flush_or_purge_queued_packets(nc, false);
622 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
623 unsigned flags,
624 const uint8_t *buf, int size,
625 NetPacketSent *sent_cb)
627 NetQueue *queue;
629 #ifdef DEBUG_NET
630 printf("qemu_send_packet_async:\n");
631 hex_dump(stdout, buf, size);
632 #endif
634 if (sender->link_down || !sender->peer) {
635 return size;
638 queue = sender->peer->incoming_queue;
640 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
643 ssize_t qemu_send_packet_async(NetClientState *sender,
644 const uint8_t *buf, int size,
645 NetPacketSent *sent_cb)
647 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
648 buf, size, sent_cb);
651 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
653 qemu_send_packet_async(nc, buf, size, NULL);
656 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
658 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
659 buf, size, NULL);
662 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
663 int iovcnt)
665 uint8_t buffer[NET_BUFSIZE];
666 size_t offset;
668 offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
670 return nc->info->receive(nc, buffer, offset);
673 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
674 unsigned flags,
675 const struct iovec *iov,
676 int iovcnt,
677 void *opaque)
679 NetClientState *nc = opaque;
680 int ret;
682 if (nc->link_down) {
683 return iov_size(iov, iovcnt);
686 if (nc->receive_disabled) {
687 return 0;
690 if (nc->info->receive_iov) {
691 ret = nc->info->receive_iov(nc, iov, iovcnt);
692 } else {
693 ret = nc_sendv_compat(nc, iov, iovcnt);
696 if (ret == 0) {
697 nc->receive_disabled = 1;
700 return ret;
703 ssize_t qemu_sendv_packet_async(NetClientState *sender,
704 const struct iovec *iov, int iovcnt,
705 NetPacketSent *sent_cb)
707 NetQueue *queue;
709 if (sender->link_down || !sender->peer) {
710 return iov_size(iov, iovcnt);
713 queue = sender->peer->incoming_queue;
715 return qemu_net_queue_send_iov(queue, sender,
716 QEMU_NET_PACKET_FLAG_NONE,
717 iov, iovcnt, sent_cb);
720 ssize_t
721 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
723 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
726 NetClientState *qemu_find_netdev(const char *id)
728 NetClientState *nc;
730 QTAILQ_FOREACH(nc, &net_clients, next) {
731 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
732 continue;
733 if (!strcmp(nc->name, id)) {
734 return nc;
738 return NULL;
741 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
742 NetClientOptionsKind type, int max)
744 NetClientState *nc;
745 int ret = 0;
747 QTAILQ_FOREACH(nc, &net_clients, next) {
748 if (nc->info->type == type) {
749 continue;
751 if (!id || !strcmp(nc->name, id)) {
752 if (ret < max) {
753 ncs[ret] = nc;
755 ret++;
759 return ret;
762 static int nic_get_free_idx(void)
764 int index;
766 for (index = 0; index < MAX_NICS; index++)
767 if (!nd_table[index].used)
768 return index;
769 return -1;
772 int qemu_show_nic_models(const char *arg, const char *const *models)
774 int i;
776 if (!arg || !is_help_option(arg)) {
777 return 0;
780 fprintf(stderr, "qemu: Supported NIC models: ");
781 for (i = 0 ; models[i]; i++)
782 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
783 return 1;
786 void qemu_check_nic_model(NICInfo *nd, const char *model)
788 const char *models[2];
790 models[0] = model;
791 models[1] = NULL;
793 if (qemu_show_nic_models(nd->model, models))
794 exit(0);
795 if (qemu_find_nic_model(nd, models, model) < 0)
796 exit(1);
799 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
800 const char *default_model)
802 int i;
804 if (!nd->model)
805 nd->model = g_strdup(default_model);
807 for (i = 0 ; models[i]; i++) {
808 if (strcmp(nd->model, models[i]) == 0)
809 return i;
812 error_report("Unsupported NIC model: %s", nd->model);
813 return -1;
816 static int net_init_nic(const NetClientOptions *opts, const char *name,
817 NetClientState *peer, Error **errp)
819 int idx;
820 NICInfo *nd;
821 const NetLegacyNicOptions *nic;
823 assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);
824 nic = opts->nic;
826 idx = nic_get_free_idx();
827 if (idx == -1 || nb_nics >= MAX_NICS) {
828 error_setg(errp, "too many NICs");
829 return -1;
832 nd = &nd_table[idx];
834 memset(nd, 0, sizeof(*nd));
836 if (nic->has_netdev) {
837 nd->netdev = qemu_find_netdev(nic->netdev);
838 if (!nd->netdev) {
839 error_setg(errp, "netdev '%s' not found", nic->netdev);
840 return -1;
842 } else {
843 assert(peer);
844 nd->netdev = peer;
846 nd->name = g_strdup(name);
847 if (nic->has_model) {
848 nd->model = g_strdup(nic->model);
850 if (nic->has_addr) {
851 nd->devaddr = g_strdup(nic->addr);
854 if (nic->has_macaddr &&
855 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
856 error_setg(errp, "invalid syntax for ethernet address");
857 return -1;
859 if (nic->has_macaddr &&
860 is_multicast_ether_addr(nd->macaddr.a)) {
861 error_setg(errp,
862 "NIC cannot have multicast MAC address (odd 1st byte)");
863 return -1;
865 qemu_macaddr_default_if_unset(&nd->macaddr);
867 if (nic->has_vectors) {
868 if (nic->vectors > 0x7ffffff) {
869 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
870 return -1;
872 nd->nvectors = nic->vectors;
873 } else {
874 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
877 nd->used = 1;
878 nb_nics++;
880 return idx;
884 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
885 const NetClientOptions *opts,
886 const char *name,
887 NetClientState *peer, Error **errp) = {
888 [NET_CLIENT_OPTIONS_KIND_NIC] = net_init_nic,
889 #ifdef CONFIG_SLIRP
890 [NET_CLIENT_OPTIONS_KIND_USER] = net_init_slirp,
891 #endif
892 [NET_CLIENT_OPTIONS_KIND_TAP] = net_init_tap,
893 [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
894 #ifdef CONFIG_VDE
895 [NET_CLIENT_OPTIONS_KIND_VDE] = net_init_vde,
896 #endif
897 #ifdef CONFIG_NETMAP
898 [NET_CLIENT_OPTIONS_KIND_NETMAP] = net_init_netmap,
899 #endif
900 [NET_CLIENT_OPTIONS_KIND_DUMP] = net_init_dump,
901 #ifdef CONFIG_NET_BRIDGE
902 [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
903 #endif
904 [NET_CLIENT_OPTIONS_KIND_HUBPORT] = net_init_hubport,
905 #ifdef CONFIG_VHOST_NET_USED
906 [NET_CLIENT_OPTIONS_KIND_VHOST_USER] = net_init_vhost_user,
907 #endif
908 #ifdef CONFIG_L2TPV3
909 [NET_CLIENT_OPTIONS_KIND_L2TPV3] = net_init_l2tpv3,
910 #endif
914 static int net_client_init1(const void *object, int is_netdev, Error **errp)
916 const NetClientOptions *opts;
917 const char *name;
918 NetClientState *peer = NULL;
920 if (is_netdev) {
921 const Netdev *netdev = object;
922 opts = netdev->opts;
923 name = netdev->id;
925 if (opts->kind == NET_CLIENT_OPTIONS_KIND_DUMP ||
926 opts->kind == NET_CLIENT_OPTIONS_KIND_NIC ||
927 !net_client_init_fun[opts->kind]) {
928 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
929 "a netdev backend type");
930 return -1;
932 } else {
933 const NetLegacy *net = object;
934 opts = net->opts;
935 /* missing optional values have been initialized to "all bits zero" */
936 name = net->has_id ? net->id : net->name;
938 if (opts->kind == NET_CLIENT_OPTIONS_KIND_NONE) {
939 return 0; /* nothing to do */
941 if (opts->kind == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
942 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
943 "a net type");
944 return -1;
947 if (!net_client_init_fun[opts->kind]) {
948 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
949 "a net backend type (maybe it is not compiled "
950 "into this binary)");
951 return -1;
954 /* Do not add to a vlan if it's a nic with a netdev= parameter. */
955 if (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
956 !opts->nic->has_netdev) {
957 peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
961 if (net_client_init_fun[opts->kind](opts, name, peer, errp) < 0) {
962 /* FIXME drop when all init functions store an Error */
963 if (errp && !*errp) {
964 error_setg(errp, QERR_DEVICE_INIT_FAILED,
965 NetClientOptionsKind_lookup[opts->kind]);
967 return -1;
969 return 0;
973 static void net_visit(Visitor *v, int is_netdev, void **object, Error **errp)
975 if (is_netdev) {
976 visit_type_Netdev(v, (Netdev **)object, NULL, errp);
977 } else {
978 visit_type_NetLegacy(v, (NetLegacy **)object, NULL, errp);
983 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
985 void *object = NULL;
986 Error *err = NULL;
987 int ret = -1;
990 OptsVisitor *ov = opts_visitor_new(opts);
992 net_visit(opts_get_visitor(ov), is_netdev, &object, &err);
993 opts_visitor_cleanup(ov);
996 if (!err) {
997 ret = net_client_init1(object, is_netdev, &err);
1000 if (object) {
1001 QapiDeallocVisitor *dv = qapi_dealloc_visitor_new();
1003 net_visit(qapi_dealloc_get_visitor(dv), is_netdev, &object, NULL);
1004 qapi_dealloc_visitor_cleanup(dv);
1007 error_propagate(errp, err);
1008 return ret;
1012 static int net_host_check_device(const char *device)
1014 int i;
1015 for (i = 0; host_net_devices[i]; i++) {
1016 if (!strncmp(host_net_devices[i], device,
1017 strlen(host_net_devices[i]))) {
1018 return 1;
1022 return 0;
1025 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1027 const char *device = qdict_get_str(qdict, "device");
1028 const char *opts_str = qdict_get_try_str(qdict, "opts");
1029 Error *local_err = NULL;
1030 QemuOpts *opts;
1032 if (!net_host_check_device(device)) {
1033 monitor_printf(mon, "invalid host network device %s\n", device);
1034 return;
1037 opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1038 opts_str ? opts_str : "", false);
1039 if (!opts) {
1040 return;
1043 qemu_opt_set(opts, "type", device, &error_abort);
1045 net_client_init(opts, 0, &local_err);
1046 if (local_err) {
1047 error_report_err(local_err);
1048 monitor_printf(mon, "adding host network device %s failed\n", device);
1052 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1054 NetClientState *nc;
1055 int vlan_id = qdict_get_int(qdict, "vlan_id");
1056 const char *device = qdict_get_str(qdict, "device");
1058 nc = net_hub_find_client_by_name(vlan_id, device);
1059 if (!nc) {
1060 error_report("Host network device '%s' on hub '%d' not found",
1061 device, vlan_id);
1062 return;
1064 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1065 error_report("invalid host network device '%s'", device);
1066 return;
1069 qemu_del_net_client(nc->peer);
1070 qemu_del_net_client(nc);
1073 void netdev_add(QemuOpts *opts, Error **errp)
1075 net_client_init(opts, 1, errp);
1078 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1080 Error *local_err = NULL;
1081 QemuOptsList *opts_list;
1082 QemuOpts *opts;
1084 opts_list = qemu_find_opts_err("netdev", &local_err);
1085 if (local_err) {
1086 goto out;
1089 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1090 if (local_err) {
1091 goto out;
1094 netdev_add(opts, &local_err);
1095 if (local_err) {
1096 qemu_opts_del(opts);
1097 goto out;
1100 out:
1101 error_propagate(errp, local_err);
1104 void qmp_netdev_del(const char *id, Error **errp)
1106 NetClientState *nc;
1107 QemuOpts *opts;
1109 nc = qemu_find_netdev(id);
1110 if (!nc) {
1111 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1112 "Device '%s' not found", id);
1113 return;
1116 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1117 if (!opts) {
1118 error_setg(errp, "Device '%s' is not a netdev", id);
1119 return;
1122 qemu_del_net_client(nc);
1123 qemu_opts_del(opts);
1126 void print_net_client(Monitor *mon, NetClientState *nc)
1128 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1129 nc->queue_index,
1130 NetClientOptionsKind_lookup[nc->info->type],
1131 nc->info_str);
1134 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1135 Error **errp)
1137 NetClientState *nc;
1138 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1140 QTAILQ_FOREACH(nc, &net_clients, next) {
1141 RxFilterInfoList *entry;
1142 RxFilterInfo *info;
1144 if (has_name && strcmp(nc->name, name) != 0) {
1145 continue;
1148 /* only query rx-filter information of NIC */
1149 if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1150 if (has_name) {
1151 error_setg(errp, "net client(%s) isn't a NIC", name);
1152 return NULL;
1154 continue;
1157 if (nc->info->query_rx_filter) {
1158 info = nc->info->query_rx_filter(nc);
1159 entry = g_malloc0(sizeof(*entry));
1160 entry->value = info;
1162 if (!filter_list) {
1163 filter_list = entry;
1164 } else {
1165 last_entry->next = entry;
1167 last_entry = entry;
1168 } else if (has_name) {
1169 error_setg(errp, "net client(%s) doesn't support"
1170 " rx-filter querying", name);
1171 return NULL;
1174 if (has_name) {
1175 break;
1179 if (filter_list == NULL && has_name) {
1180 error_setg(errp, "invalid net client name: %s", name);
1183 return filter_list;
1186 void hmp_info_network(Monitor *mon, const QDict *qdict)
1188 NetClientState *nc, *peer;
1189 NetClientOptionsKind type;
1191 net_hub_info(mon);
1193 QTAILQ_FOREACH(nc, &net_clients, next) {
1194 peer = nc->peer;
1195 type = nc->info->type;
1197 /* Skip if already printed in hub info */
1198 if (net_hub_id_for_client(nc, NULL) == 0) {
1199 continue;
1202 if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1203 print_net_client(mon, nc);
1204 } /* else it's a netdev connected to a NIC, printed with the NIC */
1205 if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1206 monitor_printf(mon, " \\ ");
1207 print_net_client(mon, peer);
1212 void qmp_set_link(const char *name, bool up, Error **errp)
1214 NetClientState *ncs[MAX_QUEUE_NUM];
1215 NetClientState *nc;
1216 int queues, i;
1218 queues = qemu_find_net_clients_except(name, ncs,
1219 NET_CLIENT_OPTIONS_KIND_MAX,
1220 MAX_QUEUE_NUM);
1222 if (queues == 0) {
1223 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1224 "Device '%s' not found", name);
1225 return;
1227 nc = ncs[0];
1229 for (i = 0; i < queues; i++) {
1230 ncs[i]->link_down = !up;
1233 if (nc->info->link_status_changed) {
1234 nc->info->link_status_changed(nc);
1237 if (nc->peer) {
1238 /* Change peer link only if the peer is NIC and then notify peer.
1239 * If the peer is a HUBPORT or a backend, we do not change the
1240 * link status.
1242 * This behavior is compatible with qemu vlans where there could be
1243 * multiple clients that can still communicate with each other in
1244 * disconnected mode. For now maintain this compatibility.
1246 if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1247 for (i = 0; i < queues; i++) {
1248 ncs[i]->peer->link_down = !up;
1251 if (nc->peer->info->link_status_changed) {
1252 nc->peer->info->link_status_changed(nc->peer);
1257 static void net_vm_change_state_handler(void *opaque, int running,
1258 RunState state)
1260 NetClientState *nc;
1261 NetClientState *tmp;
1263 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1264 if (running) {
1265 /* Flush queued packets and wake up backends. */
1266 if (nc->peer && qemu_can_send_packet(nc)) {
1267 qemu_flush_queued_packets(nc->peer);
1269 } else {
1270 /* Complete all queued packets, to guarantee we don't modify
1271 * state later when VM is not running.
1273 qemu_flush_or_purge_queued_packets(nc, true);
1278 void net_cleanup(void)
1280 NetClientState *nc;
1282 /* We may del multiple entries during qemu_del_net_client(),
1283 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1285 while (!QTAILQ_EMPTY(&net_clients)) {
1286 nc = QTAILQ_FIRST(&net_clients);
1287 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1288 qemu_del_nic(qemu_get_nic(nc));
1289 } else {
1290 qemu_del_net_client(nc);
1294 qemu_del_vm_change_state_handler(net_change_state_entry);
1297 void net_check_clients(void)
1299 NetClientState *nc;
1300 int i;
1302 /* Don't warn about the default network setup that you get if
1303 * no command line -net or -netdev options are specified. There
1304 * are two cases that we would otherwise complain about:
1305 * (1) board doesn't support a NIC but the implicit "-net nic"
1306 * requested one
1307 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1308 * sets up a nic that isn't connected to anything.
1310 if (default_net) {
1311 return;
1314 net_hub_check_clients();
1316 QTAILQ_FOREACH(nc, &net_clients, next) {
1317 if (!nc->peer) {
1318 fprintf(stderr, "Warning: %s %s has no peer\n",
1319 nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1320 "nic" : "netdev", nc->name);
1324 /* Check that all NICs requested via -net nic actually got created.
1325 * NICs created via -device don't need to be checked here because
1326 * they are always instantiated.
1328 for (i = 0; i < MAX_NICS; i++) {
1329 NICInfo *nd = &nd_table[i];
1330 if (nd->used && !nd->instantiated) {
1331 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1332 "was not created (not supported by this machine?)\n",
1333 nd->name ? nd->name : "anonymous",
1334 nd->model ? nd->model : "unspecified");
1339 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1341 Error *local_err = NULL;
1343 net_client_init(opts, 0, &local_err);
1344 if (local_err) {
1345 error_report_err(local_err);
1346 return -1;
1349 return 0;
1352 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1354 Error *local_err = NULL;
1355 int ret;
1357 ret = net_client_init(opts, 1, &local_err);
1358 if (local_err) {
1359 error_report_err(local_err);
1360 return -1;
1363 return ret;
1366 int net_init_clients(void)
1368 QemuOptsList *net = qemu_find_opts("net");
1370 if (default_net) {
1371 /* if no clients, we use a default config */
1372 qemu_opts_set(net, NULL, "type", "nic", &error_abort);
1373 #ifdef CONFIG_SLIRP
1374 qemu_opts_set(net, NULL, "type", "user", &error_abort);
1375 #endif
1378 net_change_state_entry =
1379 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1381 QTAILQ_INIT(&net_clients);
1383 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1384 net_init_netdev, NULL, NULL)) {
1385 return -1;
1388 if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1389 return -1;
1392 return 0;
1395 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1397 #if defined(CONFIG_SLIRP)
1398 int ret;
1399 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1400 return ret;
1402 #endif
1404 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1405 return -1;
1408 default_net = 0;
1409 return 0;
1412 /* From FreeBSD */
1413 /* XXX: optimize */
1414 unsigned compute_mcast_idx(const uint8_t *ep)
1416 uint32_t crc;
1417 int carry, i, j;
1418 uint8_t b;
1420 crc = 0xffffffff;
1421 for (i = 0; i < 6; i++) {
1422 b = *ep++;
1423 for (j = 0; j < 8; j++) {
1424 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1425 crc <<= 1;
1426 b >>= 1;
1427 if (carry) {
1428 crc = ((crc ^ POLYNOMIAL) | carry);
1432 return crc >> 26;
1435 QemuOptsList qemu_netdev_opts = {
1436 .name = "netdev",
1437 .implied_opt_name = "type",
1438 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1439 .desc = {
1441 * no elements => accept any params
1442 * validation will happen later
1444 { /* end of list */ }
1448 QemuOptsList qemu_net_opts = {
1449 .name = "net",
1450 .implied_opt_name = "type",
1451 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1452 .desc = {
1454 * no elements => accept any params
1455 * validation will happen later
1457 { /* end of list */ }