net: Forbid dealing with packets when VM is not running
[qemu/ar7.git] / net / net.c
blob962c05f6db042a4db5e0b1bbd9916d9e871362f0
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 "qemu/sockets.h"
36 #include "qemu/config-file.h"
37 #include "qmp-commands.h"
38 #include "hw/qdev.h"
39 #include "qemu/iov.h"
40 #include "qemu/main-loop.h"
41 #include "qapi-visit.h"
42 #include "qapi/opts-visitor.h"
43 #include "qapi/dealloc-visitor.h"
44 #include "sysemu/sysemu.h"
46 /* Net bridge is currently not supported for W32. */
47 #if !defined(_WIN32)
48 # define CONFIG_NET_BRIDGE
49 #endif
51 static QTAILQ_HEAD(, NetClientState) net_clients;
53 const char *host_net_devices[] = {
54 "tap",
55 "socket",
56 "dump",
57 #ifdef CONFIG_NET_BRIDGE
58 "bridge",
59 #endif
60 #ifdef CONFIG_SLIRP
61 "user",
62 #endif
63 #ifdef CONFIG_VDE
64 "vde",
65 #endif
66 "vhost-user",
67 NULL,
70 int default_net = 1;
72 /***********************************************************/
73 /* network device redirectors */
75 #if defined(DEBUG_NET)
76 static void hex_dump(FILE *f, const uint8_t *buf, int size)
78 int len, i, j, c;
80 for(i=0;i<size;i+=16) {
81 len = size - i;
82 if (len > 16)
83 len = 16;
84 fprintf(f, "%08x ", i);
85 for(j=0;j<16;j++) {
86 if (j < len)
87 fprintf(f, " %02x", buf[i+j]);
88 else
89 fprintf(f, " ");
91 fprintf(f, " ");
92 for(j=0;j<len;j++) {
93 c = buf[i+j];
94 if (c < ' ' || c > '~')
95 c = '.';
96 fprintf(f, "%c", c);
98 fprintf(f, "\n");
101 #endif
103 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
105 const char *p, *p1;
106 int len;
107 p = *pp;
108 p1 = strchr(p, sep);
109 if (!p1)
110 return -1;
111 len = p1 - p;
112 p1++;
113 if (buf_size > 0) {
114 if (len > buf_size - 1)
115 len = buf_size - 1;
116 memcpy(buf, p, len);
117 buf[len] = '\0';
119 *pp = p1;
120 return 0;
123 int parse_host_port(struct sockaddr_in *saddr, const char *str)
125 char buf[512];
126 struct hostent *he;
127 const char *p, *r;
128 int port;
130 p = str;
131 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
132 return -1;
133 saddr->sin_family = AF_INET;
134 if (buf[0] == '\0') {
135 saddr->sin_addr.s_addr = 0;
136 } else {
137 if (qemu_isdigit(buf[0])) {
138 if (!inet_aton(buf, &saddr->sin_addr))
139 return -1;
140 } else {
141 if ((he = gethostbyname(buf)) == NULL)
142 return - 1;
143 saddr->sin_addr = *(struct in_addr *)he->h_addr;
146 port = strtol(p, (char **)&r, 0);
147 if (r == p)
148 return -1;
149 saddr->sin_port = htons(port);
150 return 0;
153 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
155 snprintf(nc->info_str, sizeof(nc->info_str),
156 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
157 nc->model,
158 macaddr[0], macaddr[1], macaddr[2],
159 macaddr[3], macaddr[4], macaddr[5]);
162 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
164 static int index = 0;
165 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
167 if (memcmp(macaddr, &zero, sizeof(zero)) != 0)
168 return;
169 macaddr->a[0] = 0x52;
170 macaddr->a[1] = 0x54;
171 macaddr->a[2] = 0x00;
172 macaddr->a[3] = 0x12;
173 macaddr->a[4] = 0x34;
174 macaddr->a[5] = 0x56 + index++;
178 * Generate a name for net client
180 * Only net clients created with the legacy -net option and NICs need this.
182 static char *assign_name(NetClientState *nc1, const char *model)
184 NetClientState *nc;
185 int id = 0;
187 QTAILQ_FOREACH(nc, &net_clients, next) {
188 if (nc == nc1) {
189 continue;
191 if (strcmp(nc->model, model) == 0) {
192 id++;
196 return g_strdup_printf("%s.%d", model, id);
199 static void qemu_net_client_destructor(NetClientState *nc)
201 g_free(nc);
204 static void qemu_net_client_setup(NetClientState *nc,
205 NetClientInfo *info,
206 NetClientState *peer,
207 const char *model,
208 const char *name,
209 NetClientDestructor *destructor)
211 nc->info = info;
212 nc->model = g_strdup(model);
213 if (name) {
214 nc->name = g_strdup(name);
215 } else {
216 nc->name = assign_name(nc, model);
219 if (peer) {
220 assert(!peer->peer);
221 nc->peer = peer;
222 peer->peer = nc;
224 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
226 nc->incoming_queue = qemu_new_net_queue(nc);
227 nc->destructor = destructor;
230 NetClientState *qemu_new_net_client(NetClientInfo *info,
231 NetClientState *peer,
232 const char *model,
233 const char *name)
235 NetClientState *nc;
237 assert(info->size >= sizeof(NetClientState));
239 nc = g_malloc0(info->size);
240 qemu_net_client_setup(nc, info, peer, model, name,
241 qemu_net_client_destructor);
243 return nc;
246 NICState *qemu_new_nic(NetClientInfo *info,
247 NICConf *conf,
248 const char *model,
249 const char *name,
250 void *opaque)
252 NetClientState **peers = conf->peers.ncs;
253 NICState *nic;
254 int i, queues = MAX(1, conf->peers.queues);
256 assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
257 assert(info->size >= sizeof(NICState));
259 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
260 nic->ncs = (void *)nic + info->size;
261 nic->conf = conf;
262 nic->opaque = opaque;
264 for (i = 0; i < queues; i++) {
265 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
266 NULL);
267 nic->ncs[i].queue_index = i;
270 return nic;
273 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
275 return nic->ncs + queue_index;
278 NetClientState *qemu_get_queue(NICState *nic)
280 return qemu_get_subqueue(nic, 0);
283 NICState *qemu_get_nic(NetClientState *nc)
285 NetClientState *nc0 = nc - nc->queue_index;
287 return (NICState *)((void *)nc0 - nc->info->size);
290 void *qemu_get_nic_opaque(NetClientState *nc)
292 NICState *nic = qemu_get_nic(nc);
294 return nic->opaque;
297 static void qemu_cleanup_net_client(NetClientState *nc)
299 QTAILQ_REMOVE(&net_clients, nc, next);
301 if (nc->info->cleanup) {
302 nc->info->cleanup(nc);
306 static void qemu_free_net_client(NetClientState *nc)
308 if (nc->incoming_queue) {
309 qemu_del_net_queue(nc->incoming_queue);
311 if (nc->peer) {
312 nc->peer->peer = NULL;
314 g_free(nc->name);
315 g_free(nc->model);
316 if (nc->destructor) {
317 nc->destructor(nc);
321 void qemu_del_net_client(NetClientState *nc)
323 NetClientState *ncs[MAX_QUEUE_NUM];
324 int queues, i;
326 /* If the NetClientState belongs to a multiqueue backend, we will change all
327 * other NetClientStates also.
329 queues = qemu_find_net_clients_except(nc->name, ncs,
330 NET_CLIENT_OPTIONS_KIND_NIC,
331 MAX_QUEUE_NUM);
332 assert(queues != 0);
334 /* If there is a peer NIC, delete and cleanup client, but do not free. */
335 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
336 NICState *nic = qemu_get_nic(nc->peer);
337 if (nic->peer_deleted) {
338 return;
340 nic->peer_deleted = true;
342 for (i = 0; i < queues; i++) {
343 ncs[i]->peer->link_down = true;
346 if (nc->peer->info->link_status_changed) {
347 nc->peer->info->link_status_changed(nc->peer);
350 for (i = 0; i < queues; i++) {
351 qemu_cleanup_net_client(ncs[i]);
354 return;
357 assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
359 for (i = 0; i < queues; i++) {
360 qemu_cleanup_net_client(ncs[i]);
361 qemu_free_net_client(ncs[i]);
365 void qemu_del_nic(NICState *nic)
367 int i, queues = MAX(nic->conf->peers.queues, 1);
369 /* If this is a peer NIC and peer has already been deleted, free it now. */
370 if (nic->peer_deleted) {
371 for (i = 0; i < queues; i++) {
372 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
376 for (i = queues - 1; i >= 0; i--) {
377 NetClientState *nc = qemu_get_subqueue(nic, i);
379 qemu_cleanup_net_client(nc);
380 qemu_free_net_client(nc);
383 g_free(nic);
386 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
388 NetClientState *nc;
390 QTAILQ_FOREACH(nc, &net_clients, next) {
391 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
392 if (nc->queue_index == 0) {
393 func(qemu_get_nic(nc), opaque);
399 bool qemu_has_ufo(NetClientState *nc)
401 if (!nc || !nc->info->has_ufo) {
402 return false;
405 return nc->info->has_ufo(nc);
408 bool qemu_has_vnet_hdr(NetClientState *nc)
410 if (!nc || !nc->info->has_vnet_hdr) {
411 return false;
414 return nc->info->has_vnet_hdr(nc);
417 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
419 if (!nc || !nc->info->has_vnet_hdr_len) {
420 return false;
423 return nc->info->has_vnet_hdr_len(nc, len);
426 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
428 if (!nc || !nc->info->using_vnet_hdr) {
429 return;
432 nc->info->using_vnet_hdr(nc, enable);
435 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
436 int ecn, int ufo)
438 if (!nc || !nc->info->set_offload) {
439 return;
442 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
445 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
447 if (!nc || !nc->info->set_vnet_hdr_len) {
448 return;
451 nc->info->set_vnet_hdr_len(nc, len);
454 int qemu_can_send_packet(NetClientState *sender)
456 int vm_running = runstate_is_running();
458 if (!vm_running) {
459 return 0;
462 if (!sender->peer) {
463 return 1;
466 if (sender->peer->receive_disabled) {
467 return 0;
468 } else if (sender->peer->info->can_receive &&
469 !sender->peer->info->can_receive(sender->peer)) {
470 return 0;
472 return 1;
475 ssize_t qemu_deliver_packet(NetClientState *sender,
476 unsigned flags,
477 const uint8_t *data,
478 size_t size,
479 void *opaque)
481 NetClientState *nc = opaque;
482 ssize_t ret;
484 if (nc->link_down) {
485 return size;
488 if (nc->receive_disabled) {
489 return 0;
492 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
493 ret = nc->info->receive_raw(nc, data, size);
494 } else {
495 ret = nc->info->receive(nc, data, size);
498 if (ret == 0) {
499 nc->receive_disabled = 1;
502 return ret;
505 void qemu_purge_queued_packets(NetClientState *nc)
507 if (!nc->peer) {
508 return;
511 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
514 void qemu_flush_queued_packets(NetClientState *nc)
516 nc->receive_disabled = 0;
518 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
519 if (net_hub_flush(nc->peer)) {
520 qemu_notify_event();
523 if (qemu_net_queue_flush(nc->incoming_queue)) {
524 /* We emptied the queue successfully, signal to the IO thread to repoll
525 * the file descriptor (for tap, for example).
527 qemu_notify_event();
531 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
532 unsigned flags,
533 const uint8_t *buf, int size,
534 NetPacketSent *sent_cb)
536 NetQueue *queue;
538 #ifdef DEBUG_NET
539 printf("qemu_send_packet_async:\n");
540 hex_dump(stdout, buf, size);
541 #endif
543 if (sender->link_down || !sender->peer) {
544 return size;
547 queue = sender->peer->incoming_queue;
549 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
552 ssize_t qemu_send_packet_async(NetClientState *sender,
553 const uint8_t *buf, int size,
554 NetPacketSent *sent_cb)
556 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
557 buf, size, sent_cb);
560 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
562 qemu_send_packet_async(nc, buf, size, NULL);
565 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
567 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
568 buf, size, NULL);
571 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
572 int iovcnt)
574 uint8_t buffer[NET_BUFSIZE];
575 size_t offset;
577 offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
579 return nc->info->receive(nc, buffer, offset);
582 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
583 unsigned flags,
584 const struct iovec *iov,
585 int iovcnt,
586 void *opaque)
588 NetClientState *nc = opaque;
589 int ret;
591 if (nc->link_down) {
592 return iov_size(iov, iovcnt);
595 if (nc->receive_disabled) {
596 return 0;
599 if (nc->info->receive_iov) {
600 ret = nc->info->receive_iov(nc, iov, iovcnt);
601 } else {
602 ret = nc_sendv_compat(nc, iov, iovcnt);
605 if (ret == 0) {
606 nc->receive_disabled = 1;
609 return ret;
612 ssize_t qemu_sendv_packet_async(NetClientState *sender,
613 const struct iovec *iov, int iovcnt,
614 NetPacketSent *sent_cb)
616 NetQueue *queue;
618 if (sender->link_down || !sender->peer) {
619 return iov_size(iov, iovcnt);
622 queue = sender->peer->incoming_queue;
624 return qemu_net_queue_send_iov(queue, sender,
625 QEMU_NET_PACKET_FLAG_NONE,
626 iov, iovcnt, sent_cb);
629 ssize_t
630 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
632 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
635 NetClientState *qemu_find_netdev(const char *id)
637 NetClientState *nc;
639 QTAILQ_FOREACH(nc, &net_clients, next) {
640 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
641 continue;
642 if (!strcmp(nc->name, id)) {
643 return nc;
647 return NULL;
650 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
651 NetClientOptionsKind type, int max)
653 NetClientState *nc;
654 int ret = 0;
656 QTAILQ_FOREACH(nc, &net_clients, next) {
657 if (nc->info->type == type) {
658 continue;
660 if (!id || !strcmp(nc->name, id)) {
661 if (ret < max) {
662 ncs[ret] = nc;
664 ret++;
668 return ret;
671 static int nic_get_free_idx(void)
673 int index;
675 for (index = 0; index < MAX_NICS; index++)
676 if (!nd_table[index].used)
677 return index;
678 return -1;
681 int qemu_show_nic_models(const char *arg, const char *const *models)
683 int i;
685 if (!arg || !is_help_option(arg)) {
686 return 0;
689 fprintf(stderr, "qemu: Supported NIC models: ");
690 for (i = 0 ; models[i]; i++)
691 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
692 return 1;
695 void qemu_check_nic_model(NICInfo *nd, const char *model)
697 const char *models[2];
699 models[0] = model;
700 models[1] = NULL;
702 if (qemu_show_nic_models(nd->model, models))
703 exit(0);
704 if (qemu_find_nic_model(nd, models, model) < 0)
705 exit(1);
708 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
709 const char *default_model)
711 int i;
713 if (!nd->model)
714 nd->model = g_strdup(default_model);
716 for (i = 0 ; models[i]; i++) {
717 if (strcmp(nd->model, models[i]) == 0)
718 return i;
721 error_report("Unsupported NIC model: %s", nd->model);
722 return -1;
725 static int net_init_nic(const NetClientOptions *opts, const char *name,
726 NetClientState *peer)
728 int idx;
729 NICInfo *nd;
730 const NetLegacyNicOptions *nic;
732 assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);
733 nic = opts->nic;
735 idx = nic_get_free_idx();
736 if (idx == -1 || nb_nics >= MAX_NICS) {
737 error_report("Too Many NICs");
738 return -1;
741 nd = &nd_table[idx];
743 memset(nd, 0, sizeof(*nd));
745 if (nic->has_netdev) {
746 nd->netdev = qemu_find_netdev(nic->netdev);
747 if (!nd->netdev) {
748 error_report("netdev '%s' not found", nic->netdev);
749 return -1;
751 } else {
752 assert(peer);
753 nd->netdev = peer;
755 nd->name = g_strdup(name);
756 if (nic->has_model) {
757 nd->model = g_strdup(nic->model);
759 if (nic->has_addr) {
760 nd->devaddr = g_strdup(nic->addr);
763 if (nic->has_macaddr &&
764 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
765 error_report("invalid syntax for ethernet address");
766 return -1;
768 if (nic->has_macaddr &&
769 is_multicast_ether_addr(nd->macaddr.a)) {
770 error_report("NIC cannot have multicast MAC address (odd 1st byte)");
771 return -1;
773 qemu_macaddr_default_if_unset(&nd->macaddr);
775 if (nic->has_vectors) {
776 if (nic->vectors > 0x7ffffff) {
777 error_report("invalid # of vectors: %"PRIu32, nic->vectors);
778 return -1;
780 nd->nvectors = nic->vectors;
781 } else {
782 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
785 nd->used = 1;
786 nb_nics++;
788 return idx;
792 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
793 const NetClientOptions *opts,
794 const char *name,
795 NetClientState *peer) = {
796 [NET_CLIENT_OPTIONS_KIND_NIC] = net_init_nic,
797 #ifdef CONFIG_SLIRP
798 [NET_CLIENT_OPTIONS_KIND_USER] = net_init_slirp,
799 #endif
800 [NET_CLIENT_OPTIONS_KIND_TAP] = net_init_tap,
801 [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
802 #ifdef CONFIG_VDE
803 [NET_CLIENT_OPTIONS_KIND_VDE] = net_init_vde,
804 #endif
805 #ifdef CONFIG_NETMAP
806 [NET_CLIENT_OPTIONS_KIND_NETMAP] = net_init_netmap,
807 #endif
808 [NET_CLIENT_OPTIONS_KIND_DUMP] = net_init_dump,
809 #ifdef CONFIG_NET_BRIDGE
810 [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
811 #endif
812 [NET_CLIENT_OPTIONS_KIND_HUBPORT] = net_init_hubport,
813 #ifdef CONFIG_VHOST_NET_USED
814 [NET_CLIENT_OPTIONS_KIND_VHOST_USER] = net_init_vhost_user,
815 #endif
816 #ifdef CONFIG_L2TPV3
817 [NET_CLIENT_OPTIONS_KIND_L2TPV3] = net_init_l2tpv3,
818 #endif
822 static int net_client_init1(const void *object, int is_netdev, Error **errp)
824 union {
825 const Netdev *netdev;
826 const NetLegacy *net;
827 } u;
828 const NetClientOptions *opts;
829 const char *name;
831 if (is_netdev) {
832 u.netdev = object;
833 opts = u.netdev->opts;
834 name = u.netdev->id;
836 switch (opts->kind) {
837 #ifdef CONFIG_SLIRP
838 case NET_CLIENT_OPTIONS_KIND_USER:
839 #endif
840 case NET_CLIENT_OPTIONS_KIND_TAP:
841 case NET_CLIENT_OPTIONS_KIND_SOCKET:
842 #ifdef CONFIG_VDE
843 case NET_CLIENT_OPTIONS_KIND_VDE:
844 #endif
845 #ifdef CONFIG_NETMAP
846 case NET_CLIENT_OPTIONS_KIND_NETMAP:
847 #endif
848 #ifdef CONFIG_NET_BRIDGE
849 case NET_CLIENT_OPTIONS_KIND_BRIDGE:
850 #endif
851 case NET_CLIENT_OPTIONS_KIND_HUBPORT:
852 #ifdef CONFIG_VHOST_NET_USED
853 case NET_CLIENT_OPTIONS_KIND_VHOST_USER:
854 #endif
855 #ifdef CONFIG_L2TPV3
856 case NET_CLIENT_OPTIONS_KIND_L2TPV3:
857 #endif
858 break;
860 default:
861 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "type",
862 "a netdev backend type");
863 return -1;
865 } else {
866 u.net = object;
867 opts = u.net->opts;
868 /* missing optional values have been initialized to "all bits zero" */
869 name = u.net->has_id ? u.net->id : u.net->name;
872 if (net_client_init_fun[opts->kind]) {
873 NetClientState *peer = NULL;
875 /* Do not add to a vlan if it's a -netdev or a nic with a netdev=
876 * parameter. */
877 if (!is_netdev &&
878 (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
879 !opts->nic->has_netdev)) {
880 peer = net_hub_add_port(u.net->has_vlan ? u.net->vlan : 0, NULL);
883 if (net_client_init_fun[opts->kind](opts, name, peer) < 0) {
884 /* TODO push error reporting into init() methods */
885 error_set(errp, QERR_DEVICE_INIT_FAILED,
886 NetClientOptionsKind_lookup[opts->kind]);
887 return -1;
890 return 0;
894 static void net_visit(Visitor *v, int is_netdev, void **object, Error **errp)
896 if (is_netdev) {
897 visit_type_Netdev(v, (Netdev **)object, NULL, errp);
898 } else {
899 visit_type_NetLegacy(v, (NetLegacy **)object, NULL, errp);
904 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
906 void *object = NULL;
907 Error *err = NULL;
908 int ret = -1;
911 OptsVisitor *ov = opts_visitor_new(opts);
913 net_visit(opts_get_visitor(ov), is_netdev, &object, &err);
914 opts_visitor_cleanup(ov);
917 if (!err) {
918 ret = net_client_init1(object, is_netdev, &err);
921 if (object) {
922 QapiDeallocVisitor *dv = qapi_dealloc_visitor_new();
924 net_visit(qapi_dealloc_get_visitor(dv), is_netdev, &object, NULL);
925 qapi_dealloc_visitor_cleanup(dv);
928 error_propagate(errp, err);
929 return ret;
933 static int net_host_check_device(const char *device)
935 int i;
936 for (i = 0; host_net_devices[i]; i++) {
937 if (!strncmp(host_net_devices[i], device,
938 strlen(host_net_devices[i]))) {
939 return 1;
943 return 0;
946 void net_host_device_add(Monitor *mon, const QDict *qdict)
948 const char *device = qdict_get_str(qdict, "device");
949 const char *opts_str = qdict_get_try_str(qdict, "opts");
950 Error *local_err = NULL;
951 QemuOpts *opts;
953 if (!net_host_check_device(device)) {
954 monitor_printf(mon, "invalid host network device %s\n", device);
955 return;
958 opts = qemu_opts_parse(qemu_find_opts("net"), opts_str ? opts_str : "", 0);
959 if (!opts) {
960 return;
963 qemu_opt_set(opts, "type", device);
965 net_client_init(opts, 0, &local_err);
966 if (local_err) {
967 qerror_report_err(local_err);
968 error_free(local_err);
969 monitor_printf(mon, "adding host network device %s failed\n", device);
973 void net_host_device_remove(Monitor *mon, const QDict *qdict)
975 NetClientState *nc;
976 int vlan_id = qdict_get_int(qdict, "vlan_id");
977 const char *device = qdict_get_str(qdict, "device");
979 nc = net_hub_find_client_by_name(vlan_id, device);
980 if (!nc) {
981 error_report("Host network device '%s' on hub '%d' not found",
982 device, vlan_id);
983 return;
985 if (!net_host_check_device(nc->model)) {
986 error_report("invalid host network device '%s'", device);
987 return;
989 qemu_del_net_client(nc);
992 void netdev_add(QemuOpts *opts, Error **errp)
994 net_client_init(opts, 1, errp);
997 int qmp_netdev_add(Monitor *mon, const QDict *qdict, QObject **ret)
999 Error *local_err = NULL;
1000 QemuOptsList *opts_list;
1001 QemuOpts *opts;
1003 opts_list = qemu_find_opts_err("netdev", &local_err);
1004 if (local_err) {
1005 goto exit_err;
1008 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1009 if (local_err) {
1010 goto exit_err;
1013 netdev_add(opts, &local_err);
1014 if (local_err) {
1015 qemu_opts_del(opts);
1016 goto exit_err;
1019 return 0;
1021 exit_err:
1022 qerror_report_err(local_err);
1023 error_free(local_err);
1024 return -1;
1027 void qmp_netdev_del(const char *id, Error **errp)
1029 NetClientState *nc;
1030 QemuOpts *opts;
1032 nc = qemu_find_netdev(id);
1033 if (!nc) {
1034 error_set(errp, QERR_DEVICE_NOT_FOUND, id);
1035 return;
1038 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1039 if (!opts) {
1040 error_setg(errp, "Device '%s' is not a netdev", id);
1041 return;
1044 qemu_del_net_client(nc);
1045 qemu_opts_del(opts);
1048 void print_net_client(Monitor *mon, NetClientState *nc)
1050 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1051 nc->queue_index,
1052 NetClientOptionsKind_lookup[nc->info->type],
1053 nc->info_str);
1056 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1057 Error **errp)
1059 NetClientState *nc;
1060 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1062 QTAILQ_FOREACH(nc, &net_clients, next) {
1063 RxFilterInfoList *entry;
1064 RxFilterInfo *info;
1066 if (has_name && strcmp(nc->name, name) != 0) {
1067 continue;
1070 /* only query rx-filter information of NIC */
1071 if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1072 if (has_name) {
1073 error_setg(errp, "net client(%s) isn't a NIC", name);
1074 return NULL;
1076 continue;
1079 if (nc->info->query_rx_filter) {
1080 info = nc->info->query_rx_filter(nc);
1081 entry = g_malloc0(sizeof(*entry));
1082 entry->value = info;
1084 if (!filter_list) {
1085 filter_list = entry;
1086 } else {
1087 last_entry->next = entry;
1089 last_entry = entry;
1090 } else if (has_name) {
1091 error_setg(errp, "net client(%s) doesn't support"
1092 " rx-filter querying", name);
1093 return NULL;
1096 if (has_name) {
1097 break;
1101 if (filter_list == NULL && has_name) {
1102 error_setg(errp, "invalid net client name: %s", name);
1105 return filter_list;
1108 void do_info_network(Monitor *mon, const QDict *qdict)
1110 NetClientState *nc, *peer;
1111 NetClientOptionsKind type;
1113 net_hub_info(mon);
1115 QTAILQ_FOREACH(nc, &net_clients, next) {
1116 peer = nc->peer;
1117 type = nc->info->type;
1119 /* Skip if already printed in hub info */
1120 if (net_hub_id_for_client(nc, NULL) == 0) {
1121 continue;
1124 if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1125 print_net_client(mon, nc);
1126 } /* else it's a netdev connected to a NIC, printed with the NIC */
1127 if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1128 monitor_printf(mon, " \\ ");
1129 print_net_client(mon, peer);
1134 void qmp_set_link(const char *name, bool up, Error **errp)
1136 NetClientState *ncs[MAX_QUEUE_NUM];
1137 NetClientState *nc;
1138 int queues, i;
1140 queues = qemu_find_net_clients_except(name, ncs,
1141 NET_CLIENT_OPTIONS_KIND_MAX,
1142 MAX_QUEUE_NUM);
1144 if (queues == 0) {
1145 error_set(errp, QERR_DEVICE_NOT_FOUND, name);
1146 return;
1148 nc = ncs[0];
1150 for (i = 0; i < queues; i++) {
1151 ncs[i]->link_down = !up;
1154 if (nc->info->link_status_changed) {
1155 nc->info->link_status_changed(nc);
1158 if (nc->peer) {
1159 /* Change peer link only if the peer is NIC and then notify peer.
1160 * If the peer is a HUBPORT or a backend, we do not change the
1161 * link status.
1163 * This behavior is compatible with qemu vlans where there could be
1164 * multiple clients that can still communicate with each other in
1165 * disconnected mode. For now maintain this compatibility.
1167 if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1168 for (i = 0; i < queues; i++) {
1169 ncs[i]->peer->link_down = !up;
1172 if (nc->peer->info->link_status_changed) {
1173 nc->peer->info->link_status_changed(nc->peer);
1178 void net_cleanup(void)
1180 NetClientState *nc;
1182 /* We may del multiple entries during qemu_del_net_client(),
1183 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1185 while (!QTAILQ_EMPTY(&net_clients)) {
1186 nc = QTAILQ_FIRST(&net_clients);
1187 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1188 qemu_del_nic(qemu_get_nic(nc));
1189 } else {
1190 qemu_del_net_client(nc);
1195 void net_check_clients(void)
1197 NetClientState *nc;
1198 int i;
1200 /* Don't warn about the default network setup that you get if
1201 * no command line -net or -netdev options are specified. There
1202 * are two cases that we would otherwise complain about:
1203 * (1) board doesn't support a NIC but the implicit "-net nic"
1204 * requested one
1205 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1206 * sets up a nic that isn't connected to anything.
1208 if (default_net) {
1209 return;
1212 net_hub_check_clients();
1214 QTAILQ_FOREACH(nc, &net_clients, next) {
1215 if (!nc->peer) {
1216 fprintf(stderr, "Warning: %s %s has no peer\n",
1217 nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1218 "nic" : "netdev", nc->name);
1222 /* Check that all NICs requested via -net nic actually got created.
1223 * NICs created via -device don't need to be checked here because
1224 * they are always instantiated.
1226 for (i = 0; i < MAX_NICS; i++) {
1227 NICInfo *nd = &nd_table[i];
1228 if (nd->used && !nd->instantiated) {
1229 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1230 "was not created (not supported by this machine?)\n",
1231 nd->name ? nd->name : "anonymous",
1232 nd->model ? nd->model : "unspecified");
1237 static int net_init_client(QemuOpts *opts, void *dummy)
1239 Error *local_err = NULL;
1241 net_client_init(opts, 0, &local_err);
1242 if (local_err) {
1243 qerror_report_err(local_err);
1244 error_free(local_err);
1245 return -1;
1248 return 0;
1251 static int net_init_netdev(QemuOpts *opts, void *dummy)
1253 Error *local_err = NULL;
1254 int ret;
1256 ret = net_client_init(opts, 1, &local_err);
1257 if (local_err) {
1258 qerror_report_err(local_err);
1259 error_free(local_err);
1260 return -1;
1263 return ret;
1266 int net_init_clients(void)
1268 QemuOptsList *net = qemu_find_opts("net");
1270 if (default_net) {
1271 /* if no clients, we use a default config */
1272 qemu_opts_set(net, NULL, "type", "nic");
1273 #ifdef CONFIG_SLIRP
1274 qemu_opts_set(net, NULL, "type", "user");
1275 #endif
1278 QTAILQ_INIT(&net_clients);
1280 if (qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL, 1) == -1)
1281 return -1;
1283 if (qemu_opts_foreach(net, net_init_client, NULL, 1) == -1) {
1284 return -1;
1287 return 0;
1290 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1292 #if defined(CONFIG_SLIRP)
1293 int ret;
1294 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1295 return ret;
1297 #endif
1299 if (!qemu_opts_parse(opts_list, optarg, 1)) {
1300 return -1;
1303 default_net = 0;
1304 return 0;
1307 /* From FreeBSD */
1308 /* XXX: optimize */
1309 unsigned compute_mcast_idx(const uint8_t *ep)
1311 uint32_t crc;
1312 int carry, i, j;
1313 uint8_t b;
1315 crc = 0xffffffff;
1316 for (i = 0; i < 6; i++) {
1317 b = *ep++;
1318 for (j = 0; j < 8; j++) {
1319 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1320 crc <<= 1;
1321 b >>= 1;
1322 if (carry) {
1323 crc = ((crc ^ POLYNOMIAL) | carry);
1327 return crc >> 26;
1330 QemuOptsList qemu_netdev_opts = {
1331 .name = "netdev",
1332 .implied_opt_name = "type",
1333 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1334 .desc = {
1336 * no elements => accept any params
1337 * validation will happen later
1339 { /* end of list */ }
1343 QemuOptsList qemu_net_opts = {
1344 .name = "net",
1345 .implied_opt_name = "type",
1346 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1347 .desc = {
1349 * no elements => accept any params
1350 * validation will happen later
1352 { /* end of list */ }