block/iscsi: fix potential segfault on early callback
[qemu/ar7.git] / net / net.c
blob63441604032b13f5bcab04424a1bda12c0c931fb
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"
45 /* Net bridge is currently not supported for W32. */
46 #if !defined(_WIN32)
47 # define CONFIG_NET_BRIDGE
48 #endif
50 static QTAILQ_HEAD(, NetClientState) net_clients;
52 const char *host_net_devices[] = {
53 "tap",
54 "socket",
55 "dump",
56 #ifdef CONFIG_NET_BRIDGE
57 "bridge",
58 #endif
59 #ifdef CONFIG_SLIRP
60 "user",
61 #endif
62 #ifdef CONFIG_VDE
63 "vde",
64 #endif
65 NULL,
68 int default_net = 1;
70 /***********************************************************/
71 /* network device redirectors */
73 #if defined(DEBUG_NET)
74 static void hex_dump(FILE *f, const uint8_t *buf, int size)
76 int len, i, j, c;
78 for(i=0;i<size;i+=16) {
79 len = size - i;
80 if (len > 16)
81 len = 16;
82 fprintf(f, "%08x ", i);
83 for(j=0;j<16;j++) {
84 if (j < len)
85 fprintf(f, " %02x", buf[i+j]);
86 else
87 fprintf(f, " ");
89 fprintf(f, " ");
90 for(j=0;j<len;j++) {
91 c = buf[i+j];
92 if (c < ' ' || c > '~')
93 c = '.';
94 fprintf(f, "%c", c);
96 fprintf(f, "\n");
99 #endif
101 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
103 const char *p, *p1;
104 int len;
105 p = *pp;
106 p1 = strchr(p, sep);
107 if (!p1)
108 return -1;
109 len = p1 - p;
110 p1++;
111 if (buf_size > 0) {
112 if (len > buf_size - 1)
113 len = buf_size - 1;
114 memcpy(buf, p, len);
115 buf[len] = '\0';
117 *pp = p1;
118 return 0;
121 int parse_host_port(struct sockaddr_in *saddr, const char *str)
123 char buf[512];
124 struct hostent *he;
125 const char *p, *r;
126 int port;
128 p = str;
129 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
130 return -1;
131 saddr->sin_family = AF_INET;
132 if (buf[0] == '\0') {
133 saddr->sin_addr.s_addr = 0;
134 } else {
135 if (qemu_isdigit(buf[0])) {
136 if (!inet_aton(buf, &saddr->sin_addr))
137 return -1;
138 } else {
139 if ((he = gethostbyname(buf)) == NULL)
140 return - 1;
141 saddr->sin_addr = *(struct in_addr *)he->h_addr;
144 port = strtol(p, (char **)&r, 0);
145 if (r == p)
146 return -1;
147 saddr->sin_port = htons(port);
148 return 0;
151 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
153 snprintf(nc->info_str, sizeof(nc->info_str),
154 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
155 nc->model,
156 macaddr[0], macaddr[1], macaddr[2],
157 macaddr[3], macaddr[4], macaddr[5]);
160 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
162 static int index = 0;
163 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
165 if (memcmp(macaddr, &zero, sizeof(zero)) != 0)
166 return;
167 macaddr->a[0] = 0x52;
168 macaddr->a[1] = 0x54;
169 macaddr->a[2] = 0x00;
170 macaddr->a[3] = 0x12;
171 macaddr->a[4] = 0x34;
172 macaddr->a[5] = 0x56 + index++;
176 * Generate a name for net client
178 * Only net clients created with the legacy -net option and NICs need this.
180 static char *assign_name(NetClientState *nc1, const char *model)
182 NetClientState *nc;
183 int id = 0;
185 QTAILQ_FOREACH(nc, &net_clients, next) {
186 if (nc == nc1) {
187 continue;
189 if (strcmp(nc->model, model) == 0) {
190 id++;
194 return g_strdup_printf("%s.%d", model, id);
197 static void qemu_net_client_destructor(NetClientState *nc)
199 g_free(nc);
202 static void qemu_net_client_setup(NetClientState *nc,
203 NetClientInfo *info,
204 NetClientState *peer,
205 const char *model,
206 const char *name,
207 NetClientDestructor *destructor)
209 nc->info = info;
210 nc->model = g_strdup(model);
211 if (name) {
212 nc->name = g_strdup(name);
213 } else {
214 nc->name = assign_name(nc, model);
217 if (peer) {
218 assert(!peer->peer);
219 nc->peer = peer;
220 peer->peer = nc;
222 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
224 nc->incoming_queue = qemu_new_net_queue(nc);
225 nc->destructor = destructor;
228 NetClientState *qemu_new_net_client(NetClientInfo *info,
229 NetClientState *peer,
230 const char *model,
231 const char *name)
233 NetClientState *nc;
235 assert(info->size >= sizeof(NetClientState));
237 nc = g_malloc0(info->size);
238 qemu_net_client_setup(nc, info, peer, model, name,
239 qemu_net_client_destructor);
241 return nc;
244 NICState *qemu_new_nic(NetClientInfo *info,
245 NICConf *conf,
246 const char *model,
247 const char *name,
248 void *opaque)
250 NetClientState **peers = conf->peers.ncs;
251 NICState *nic;
252 int i, queues = MAX(1, conf->queues);
254 assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
255 assert(info->size >= sizeof(NICState));
257 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
258 nic->ncs = (void *)nic + info->size;
259 nic->conf = conf;
260 nic->opaque = opaque;
262 for (i = 0; i < queues; i++) {
263 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
264 NULL);
265 nic->ncs[i].queue_index = i;
268 return nic;
271 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
273 return nic->ncs + queue_index;
276 NetClientState *qemu_get_queue(NICState *nic)
278 return qemu_get_subqueue(nic, 0);
281 NICState *qemu_get_nic(NetClientState *nc)
283 NetClientState *nc0 = nc - nc->queue_index;
285 return (NICState *)((void *)nc0 - nc->info->size);
288 void *qemu_get_nic_opaque(NetClientState *nc)
290 NICState *nic = qemu_get_nic(nc);
292 return nic->opaque;
295 static void qemu_cleanup_net_client(NetClientState *nc)
297 QTAILQ_REMOVE(&net_clients, nc, next);
299 if (nc->info->cleanup) {
300 nc->info->cleanup(nc);
304 static void qemu_free_net_client(NetClientState *nc)
306 if (nc->incoming_queue) {
307 qemu_del_net_queue(nc->incoming_queue);
309 if (nc->peer) {
310 nc->peer->peer = NULL;
312 g_free(nc->name);
313 g_free(nc->model);
314 if (nc->destructor) {
315 nc->destructor(nc);
319 void qemu_del_net_client(NetClientState *nc)
321 NetClientState *ncs[MAX_QUEUE_NUM];
322 int queues, i;
324 /* If the NetClientState belongs to a multiqueue backend, we will change all
325 * other NetClientStates also.
327 queues = qemu_find_net_clients_except(nc->name, ncs,
328 NET_CLIENT_OPTIONS_KIND_NIC,
329 MAX_QUEUE_NUM);
330 assert(queues != 0);
332 /* If there is a peer NIC, delete and cleanup client, but do not free. */
333 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
334 NICState *nic = qemu_get_nic(nc->peer);
335 if (nic->peer_deleted) {
336 return;
338 nic->peer_deleted = true;
340 for (i = 0; i < queues; i++) {
341 ncs[i]->peer->link_down = true;
344 if (nc->peer->info->link_status_changed) {
345 nc->peer->info->link_status_changed(nc->peer);
348 for (i = 0; i < queues; i++) {
349 qemu_cleanup_net_client(ncs[i]);
352 return;
355 assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
357 for (i = 0; i < queues; i++) {
358 qemu_cleanup_net_client(ncs[i]);
359 qemu_free_net_client(ncs[i]);
363 void qemu_del_nic(NICState *nic)
365 int i, queues = MAX(nic->conf->queues, 1);
367 /* If this is a peer NIC and peer has already been deleted, free it now. */
368 if (nic->peer_deleted) {
369 for (i = 0; i < queues; i++) {
370 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
374 for (i = queues - 1; i >= 0; i--) {
375 NetClientState *nc = qemu_get_subqueue(nic, i);
377 qemu_cleanup_net_client(nc);
378 qemu_free_net_client(nc);
381 g_free(nic);
384 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
386 NetClientState *nc;
388 QTAILQ_FOREACH(nc, &net_clients, next) {
389 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
390 if (nc->queue_index == 0) {
391 func(qemu_get_nic(nc), opaque);
397 bool qemu_has_ufo(NetClientState *nc)
399 if (!nc || !nc->info->has_ufo) {
400 return false;
403 return nc->info->has_ufo(nc);
406 bool qemu_has_vnet_hdr(NetClientState *nc)
408 if (!nc || !nc->info->has_vnet_hdr) {
409 return false;
412 return nc->info->has_vnet_hdr(nc);
415 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
417 if (!nc || !nc->info->has_vnet_hdr_len) {
418 return false;
421 return nc->info->has_vnet_hdr_len(nc, len);
424 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
426 if (!nc || !nc->info->using_vnet_hdr) {
427 return;
430 nc->info->using_vnet_hdr(nc, enable);
433 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
434 int ecn, int ufo)
436 if (!nc || !nc->info->set_offload) {
437 return;
440 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
443 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
445 if (!nc || !nc->info->set_vnet_hdr_len) {
446 return;
449 nc->info->set_vnet_hdr_len(nc, len);
452 int qemu_can_send_packet(NetClientState *sender)
454 if (!sender->peer) {
455 return 1;
458 if (sender->peer->receive_disabled) {
459 return 0;
460 } else if (sender->peer->info->can_receive &&
461 !sender->peer->info->can_receive(sender->peer)) {
462 return 0;
464 return 1;
467 ssize_t qemu_deliver_packet(NetClientState *sender,
468 unsigned flags,
469 const uint8_t *data,
470 size_t size,
471 void *opaque)
473 NetClientState *nc = opaque;
474 ssize_t ret;
476 if (nc->link_down) {
477 return size;
480 if (nc->receive_disabled) {
481 return 0;
484 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
485 ret = nc->info->receive_raw(nc, data, size);
486 } else {
487 ret = nc->info->receive(nc, data, size);
490 if (ret == 0) {
491 nc->receive_disabled = 1;
494 return ret;
497 void qemu_purge_queued_packets(NetClientState *nc)
499 if (!nc->peer) {
500 return;
503 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
506 void qemu_flush_queued_packets(NetClientState *nc)
508 nc->receive_disabled = 0;
510 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
511 if (net_hub_flush(nc->peer)) {
512 qemu_notify_event();
515 if (qemu_net_queue_flush(nc->incoming_queue)) {
516 /* We emptied the queue successfully, signal to the IO thread to repoll
517 * the file descriptor (for tap, for example).
519 qemu_notify_event();
523 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
524 unsigned flags,
525 const uint8_t *buf, int size,
526 NetPacketSent *sent_cb)
528 NetQueue *queue;
530 #ifdef DEBUG_NET
531 printf("qemu_send_packet_async:\n");
532 hex_dump(stdout, buf, size);
533 #endif
535 if (sender->link_down || !sender->peer) {
536 return size;
539 queue = sender->peer->incoming_queue;
541 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
544 ssize_t qemu_send_packet_async(NetClientState *sender,
545 const uint8_t *buf, int size,
546 NetPacketSent *sent_cb)
548 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
549 buf, size, sent_cb);
552 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
554 qemu_send_packet_async(nc, buf, size, NULL);
557 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
559 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
560 buf, size, NULL);
563 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
564 int iovcnt)
566 uint8_t buffer[NET_BUFSIZE];
567 size_t offset;
569 offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
571 return nc->info->receive(nc, buffer, offset);
574 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
575 unsigned flags,
576 const struct iovec *iov,
577 int iovcnt,
578 void *opaque)
580 NetClientState *nc = opaque;
581 int ret;
583 if (nc->link_down) {
584 return iov_size(iov, iovcnt);
587 if (nc->receive_disabled) {
588 return 0;
591 if (nc->info->receive_iov) {
592 ret = nc->info->receive_iov(nc, iov, iovcnt);
593 } else {
594 ret = nc_sendv_compat(nc, iov, iovcnt);
597 if (ret == 0) {
598 nc->receive_disabled = 1;
601 return ret;
604 ssize_t qemu_sendv_packet_async(NetClientState *sender,
605 const struct iovec *iov, int iovcnt,
606 NetPacketSent *sent_cb)
608 NetQueue *queue;
610 if (sender->link_down || !sender->peer) {
611 return iov_size(iov, iovcnt);
614 queue = sender->peer->incoming_queue;
616 return qemu_net_queue_send_iov(queue, sender,
617 QEMU_NET_PACKET_FLAG_NONE,
618 iov, iovcnt, sent_cb);
621 ssize_t
622 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
624 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
627 NetClientState *qemu_find_netdev(const char *id)
629 NetClientState *nc;
631 QTAILQ_FOREACH(nc, &net_clients, next) {
632 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
633 continue;
634 if (!strcmp(nc->name, id)) {
635 return nc;
639 return NULL;
642 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
643 NetClientOptionsKind type, int max)
645 NetClientState *nc;
646 int ret = 0;
648 QTAILQ_FOREACH(nc, &net_clients, next) {
649 if (nc->info->type == type) {
650 continue;
652 if (!id || !strcmp(nc->name, id)) {
653 if (ret < max) {
654 ncs[ret] = nc;
656 ret++;
660 return ret;
663 static int nic_get_free_idx(void)
665 int index;
667 for (index = 0; index < MAX_NICS; index++)
668 if (!nd_table[index].used)
669 return index;
670 return -1;
673 int qemu_show_nic_models(const char *arg, const char *const *models)
675 int i;
677 if (!arg || !is_help_option(arg)) {
678 return 0;
681 fprintf(stderr, "qemu: Supported NIC models: ");
682 for (i = 0 ; models[i]; i++)
683 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
684 return 1;
687 void qemu_check_nic_model(NICInfo *nd, const char *model)
689 const char *models[2];
691 models[0] = model;
692 models[1] = NULL;
694 if (qemu_show_nic_models(nd->model, models))
695 exit(0);
696 if (qemu_find_nic_model(nd, models, model) < 0)
697 exit(1);
700 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
701 const char *default_model)
703 int i;
705 if (!nd->model)
706 nd->model = g_strdup(default_model);
708 for (i = 0 ; models[i]; i++) {
709 if (strcmp(nd->model, models[i]) == 0)
710 return i;
713 error_report("Unsupported NIC model: %s", nd->model);
714 return -1;
717 static int net_init_nic(const NetClientOptions *opts, const char *name,
718 NetClientState *peer)
720 int idx;
721 NICInfo *nd;
722 const NetLegacyNicOptions *nic;
724 assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);
725 nic = opts->nic;
727 idx = nic_get_free_idx();
728 if (idx == -1 || nb_nics >= MAX_NICS) {
729 error_report("Too Many NICs");
730 return -1;
733 nd = &nd_table[idx];
735 memset(nd, 0, sizeof(*nd));
737 if (nic->has_netdev) {
738 nd->netdev = qemu_find_netdev(nic->netdev);
739 if (!nd->netdev) {
740 error_report("netdev '%s' not found", nic->netdev);
741 return -1;
743 } else {
744 assert(peer);
745 nd->netdev = peer;
747 nd->name = g_strdup(name);
748 if (nic->has_model) {
749 nd->model = g_strdup(nic->model);
751 if (nic->has_addr) {
752 nd->devaddr = g_strdup(nic->addr);
755 if (nic->has_macaddr &&
756 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
757 error_report("invalid syntax for ethernet address");
758 return -1;
760 if (nic->has_macaddr &&
761 is_multicast_ether_addr(nd->macaddr.a)) {
762 error_report("NIC cannot have multicast MAC address (odd 1st byte)");
763 return -1;
765 qemu_macaddr_default_if_unset(&nd->macaddr);
767 if (nic->has_vectors) {
768 if (nic->vectors > 0x7ffffff) {
769 error_report("invalid # of vectors: %"PRIu32, nic->vectors);
770 return -1;
772 nd->nvectors = nic->vectors;
773 } else {
774 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
777 nd->used = 1;
778 nb_nics++;
780 return idx;
784 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
785 const NetClientOptions *opts,
786 const char *name,
787 NetClientState *peer) = {
788 [NET_CLIENT_OPTIONS_KIND_NIC] = net_init_nic,
789 #ifdef CONFIG_SLIRP
790 [NET_CLIENT_OPTIONS_KIND_USER] = net_init_slirp,
791 #endif
792 [NET_CLIENT_OPTIONS_KIND_TAP] = net_init_tap,
793 [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
794 #ifdef CONFIG_VDE
795 [NET_CLIENT_OPTIONS_KIND_VDE] = net_init_vde,
796 #endif
797 #ifdef CONFIG_NETMAP
798 [NET_CLIENT_OPTIONS_KIND_NETMAP] = net_init_netmap,
799 #endif
800 [NET_CLIENT_OPTIONS_KIND_DUMP] = net_init_dump,
801 #ifdef CONFIG_NET_BRIDGE
802 [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
803 #endif
804 [NET_CLIENT_OPTIONS_KIND_HUBPORT] = net_init_hubport,
808 static int net_client_init1(const void *object, int is_netdev, Error **errp)
810 union {
811 const Netdev *netdev;
812 const NetLegacy *net;
813 } u;
814 const NetClientOptions *opts;
815 const char *name;
817 if (is_netdev) {
818 u.netdev = object;
819 opts = u.netdev->opts;
820 name = u.netdev->id;
822 switch (opts->kind) {
823 #ifdef CONFIG_SLIRP
824 case NET_CLIENT_OPTIONS_KIND_USER:
825 #endif
826 case NET_CLIENT_OPTIONS_KIND_TAP:
827 case NET_CLIENT_OPTIONS_KIND_SOCKET:
828 #ifdef CONFIG_VDE
829 case NET_CLIENT_OPTIONS_KIND_VDE:
830 #endif
831 #ifdef CONFIG_NETMAP
832 case NET_CLIENT_OPTIONS_KIND_NETMAP:
833 #endif
834 #ifdef CONFIG_NET_BRIDGE
835 case NET_CLIENT_OPTIONS_KIND_BRIDGE:
836 #endif
837 case NET_CLIENT_OPTIONS_KIND_HUBPORT:
838 break;
840 default:
841 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "type",
842 "a netdev backend type");
843 return -1;
845 } else {
846 u.net = object;
847 opts = u.net->opts;
848 /* missing optional values have been initialized to "all bits zero" */
849 name = u.net->has_id ? u.net->id : u.net->name;
852 if (net_client_init_fun[opts->kind]) {
853 NetClientState *peer = NULL;
855 /* Do not add to a vlan if it's a -netdev or a nic with a netdev=
856 * parameter. */
857 if (!is_netdev &&
858 (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
859 !opts->nic->has_netdev)) {
860 peer = net_hub_add_port(u.net->has_vlan ? u.net->vlan : 0, NULL);
863 if (net_client_init_fun[opts->kind](opts, name, peer) < 0) {
864 /* TODO push error reporting into init() methods */
865 error_set(errp, QERR_DEVICE_INIT_FAILED,
866 NetClientOptionsKind_lookup[opts->kind]);
867 return -1;
870 return 0;
874 static void net_visit(Visitor *v, int is_netdev, void **object, Error **errp)
876 if (is_netdev) {
877 visit_type_Netdev(v, (Netdev **)object, NULL, errp);
878 } else {
879 visit_type_NetLegacy(v, (NetLegacy **)object, NULL, errp);
884 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
886 void *object = NULL;
887 Error *err = NULL;
888 int ret = -1;
891 OptsVisitor *ov = opts_visitor_new(opts);
893 net_visit(opts_get_visitor(ov), is_netdev, &object, &err);
894 opts_visitor_cleanup(ov);
897 if (!err) {
898 ret = net_client_init1(object, is_netdev, &err);
901 if (object) {
902 QapiDeallocVisitor *dv = qapi_dealloc_visitor_new();
904 net_visit(qapi_dealloc_get_visitor(dv), is_netdev, &object, NULL);
905 qapi_dealloc_visitor_cleanup(dv);
908 error_propagate(errp, err);
909 return ret;
913 static int net_host_check_device(const char *device)
915 int i;
916 for (i = 0; host_net_devices[i]; i++) {
917 if (!strncmp(host_net_devices[i], device,
918 strlen(host_net_devices[i]))) {
919 return 1;
923 return 0;
926 void net_host_device_add(Monitor *mon, const QDict *qdict)
928 const char *device = qdict_get_str(qdict, "device");
929 const char *opts_str = qdict_get_try_str(qdict, "opts");
930 Error *local_err = NULL;
931 QemuOpts *opts;
933 if (!net_host_check_device(device)) {
934 monitor_printf(mon, "invalid host network device %s\n", device);
935 return;
938 opts = qemu_opts_parse(qemu_find_opts("net"), opts_str ? opts_str : "", 0);
939 if (!opts) {
940 return;
943 qemu_opt_set(opts, "type", device);
945 net_client_init(opts, 0, &local_err);
946 if (local_err) {
947 qerror_report_err(local_err);
948 error_free(local_err);
949 monitor_printf(mon, "adding host network device %s failed\n", device);
953 void net_host_device_remove(Monitor *mon, const QDict *qdict)
955 NetClientState *nc;
956 int vlan_id = qdict_get_int(qdict, "vlan_id");
957 const char *device = qdict_get_str(qdict, "device");
959 nc = net_hub_find_client_by_name(vlan_id, device);
960 if (!nc) {
961 error_report("Host network device '%s' on hub '%d' not found",
962 device, vlan_id);
963 return;
965 if (!net_host_check_device(nc->model)) {
966 error_report("invalid host network device '%s'", device);
967 return;
969 qemu_del_net_client(nc);
972 void netdev_add(QemuOpts *opts, Error **errp)
974 net_client_init(opts, 1, errp);
977 int qmp_netdev_add(Monitor *mon, const QDict *qdict, QObject **ret)
979 Error *local_err = NULL;
980 QemuOptsList *opts_list;
981 QemuOpts *opts;
983 opts_list = qemu_find_opts_err("netdev", &local_err);
984 if (local_err) {
985 goto exit_err;
988 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
989 if (local_err) {
990 goto exit_err;
993 netdev_add(opts, &local_err);
994 if (local_err) {
995 qemu_opts_del(opts);
996 goto exit_err;
999 return 0;
1001 exit_err:
1002 qerror_report_err(local_err);
1003 error_free(local_err);
1004 return -1;
1007 void qmp_netdev_del(const char *id, Error **errp)
1009 NetClientState *nc;
1010 QemuOpts *opts;
1012 nc = qemu_find_netdev(id);
1013 if (!nc) {
1014 error_set(errp, QERR_DEVICE_NOT_FOUND, id);
1015 return;
1018 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1019 if (!opts) {
1020 error_setg(errp, "Device '%s' is not a netdev", id);
1021 return;
1024 qemu_del_net_client(nc);
1025 qemu_opts_del(opts);
1028 void print_net_client(Monitor *mon, NetClientState *nc)
1030 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1031 nc->queue_index,
1032 NetClientOptionsKind_lookup[nc->info->type],
1033 nc->info_str);
1036 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1037 Error **errp)
1039 NetClientState *nc;
1040 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1042 QTAILQ_FOREACH(nc, &net_clients, next) {
1043 RxFilterInfoList *entry;
1044 RxFilterInfo *info;
1046 if (has_name && strcmp(nc->name, name) != 0) {
1047 continue;
1050 /* only query rx-filter information of NIC */
1051 if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1052 if (has_name) {
1053 error_setg(errp, "net client(%s) isn't a NIC", name);
1054 return NULL;
1056 continue;
1059 if (nc->info->query_rx_filter) {
1060 info = nc->info->query_rx_filter(nc);
1061 entry = g_malloc0(sizeof(*entry));
1062 entry->value = info;
1064 if (!filter_list) {
1065 filter_list = entry;
1066 } else {
1067 last_entry->next = entry;
1069 last_entry = entry;
1070 } else if (has_name) {
1071 error_setg(errp, "net client(%s) doesn't support"
1072 " rx-filter querying", name);
1073 return NULL;
1076 if (has_name) {
1077 break;
1081 if (filter_list == NULL && has_name) {
1082 error_setg(errp, "invalid net client name: %s", name);
1085 return filter_list;
1088 void do_info_network(Monitor *mon, const QDict *qdict)
1090 NetClientState *nc, *peer;
1091 NetClientOptionsKind type;
1093 net_hub_info(mon);
1095 QTAILQ_FOREACH(nc, &net_clients, next) {
1096 peer = nc->peer;
1097 type = nc->info->type;
1099 /* Skip if already printed in hub info */
1100 if (net_hub_id_for_client(nc, NULL) == 0) {
1101 continue;
1104 if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1105 print_net_client(mon, nc);
1106 } /* else it's a netdev connected to a NIC, printed with the NIC */
1107 if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1108 monitor_printf(mon, " \\ ");
1109 print_net_client(mon, peer);
1114 void qmp_set_link(const char *name, bool up, Error **errp)
1116 NetClientState *ncs[MAX_QUEUE_NUM];
1117 NetClientState *nc;
1118 int queues, i;
1120 queues = qemu_find_net_clients_except(name, ncs,
1121 NET_CLIENT_OPTIONS_KIND_MAX,
1122 MAX_QUEUE_NUM);
1124 if (queues == 0) {
1125 error_set(errp, QERR_DEVICE_NOT_FOUND, name);
1126 return;
1128 nc = ncs[0];
1130 for (i = 0; i < queues; i++) {
1131 ncs[i]->link_down = !up;
1134 if (nc->info->link_status_changed) {
1135 nc->info->link_status_changed(nc);
1138 if (nc->peer) {
1139 /* Change peer link only if the peer is NIC and then notify peer.
1140 * If the peer is a HUBPORT or a backend, we do not change the
1141 * link status.
1143 * This behavior is compatible with qemu vlans where there could be
1144 * multiple clients that can still communicate with each other in
1145 * disconnected mode. For now maintain this compatibility.
1147 if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1148 for (i = 0; i < queues; i++) {
1149 ncs[i]->peer->link_down = !up;
1152 if (nc->peer->info->link_status_changed) {
1153 nc->peer->info->link_status_changed(nc->peer);
1158 void net_cleanup(void)
1160 NetClientState *nc;
1162 /* We may del multiple entries during qemu_del_net_client(),
1163 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1165 while (!QTAILQ_EMPTY(&net_clients)) {
1166 nc = QTAILQ_FIRST(&net_clients);
1167 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1168 qemu_del_nic(qemu_get_nic(nc));
1169 } else {
1170 qemu_del_net_client(nc);
1175 void net_check_clients(void)
1177 NetClientState *nc;
1178 int i;
1180 /* Don't warn about the default network setup that you get if
1181 * no command line -net or -netdev options are specified. There
1182 * are two cases that we would otherwise complain about:
1183 * (1) board doesn't support a NIC but the implicit "-net nic"
1184 * requested one
1185 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1186 * sets up a nic that isn't connected to anything.
1188 if (default_net) {
1189 return;
1192 net_hub_check_clients();
1194 QTAILQ_FOREACH(nc, &net_clients, next) {
1195 if (!nc->peer) {
1196 fprintf(stderr, "Warning: %s %s has no peer\n",
1197 nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1198 "nic" : "netdev", nc->name);
1202 /* Check that all NICs requested via -net nic actually got created.
1203 * NICs created via -device don't need to be checked here because
1204 * they are always instantiated.
1206 for (i = 0; i < MAX_NICS; i++) {
1207 NICInfo *nd = &nd_table[i];
1208 if (nd->used && !nd->instantiated) {
1209 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1210 "was not created (not supported by this machine?)\n",
1211 nd->name ? nd->name : "anonymous",
1212 nd->model ? nd->model : "unspecified");
1217 static int net_init_client(QemuOpts *opts, void *dummy)
1219 Error *local_err = NULL;
1221 net_client_init(opts, 0, &local_err);
1222 if (local_err) {
1223 qerror_report_err(local_err);
1224 error_free(local_err);
1225 return -1;
1228 return 0;
1231 static int net_init_netdev(QemuOpts *opts, void *dummy)
1233 Error *local_err = NULL;
1234 int ret;
1236 ret = net_client_init(opts, 1, &local_err);
1237 if (local_err) {
1238 qerror_report_err(local_err);
1239 error_free(local_err);
1240 return -1;
1243 return ret;
1246 int net_init_clients(void)
1248 QemuOptsList *net = qemu_find_opts("net");
1250 if (default_net) {
1251 /* if no clients, we use a default config */
1252 qemu_opts_set(net, NULL, "type", "nic");
1253 #ifdef CONFIG_SLIRP
1254 qemu_opts_set(net, NULL, "type", "user");
1255 #endif
1258 QTAILQ_INIT(&net_clients);
1260 if (qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL, 1) == -1)
1261 return -1;
1263 if (qemu_opts_foreach(net, net_init_client, NULL, 1) == -1) {
1264 return -1;
1267 return 0;
1270 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1272 #if defined(CONFIG_SLIRP)
1273 int ret;
1274 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1275 return ret;
1277 #endif
1279 if (!qemu_opts_parse(opts_list, optarg, 1)) {
1280 return -1;
1283 default_net = 0;
1284 return 0;
1287 /* From FreeBSD */
1288 /* XXX: optimize */
1289 unsigned compute_mcast_idx(const uint8_t *ep)
1291 uint32_t crc;
1292 int carry, i, j;
1293 uint8_t b;
1295 crc = 0xffffffff;
1296 for (i = 0; i < 6; i++) {
1297 b = *ep++;
1298 for (j = 0; j < 8; j++) {
1299 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1300 crc <<= 1;
1301 b >>= 1;
1302 if (carry) {
1303 crc = ((crc ^ POLYNOMIAL) | carry);
1307 return crc >> 26;
1310 QemuOptsList qemu_netdev_opts = {
1311 .name = "netdev",
1312 .implied_opt_name = "type",
1313 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1314 .desc = {
1316 * no elements => accept any params
1317 * validation will happen later
1319 { /* end of list */ }
1323 QemuOptsList qemu_net_opts = {
1324 .name = "net",
1325 .implied_opt_name = "type",
1326 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1327 .desc = {
1329 * no elements => accept any params
1330 * validation will happen later
1332 { /* end of list */ }