Update version for v2.9.0-rc4 release
[qemu/ar7.git] / net / net.c
blob0ac3b9e80c64ce46875b7dfaf6399d96f429ea3e
1 /*
2 * QEMU System Emulator
4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
26 #include "net/net.h"
27 #include "clients.h"
28 #include "hub.h"
29 #include "net/slirp.h"
30 #include "net/eth.h"
31 #include "util.h"
33 #include "monitor/monitor.h"
34 #include "qemu-common.h"
35 #include "qemu/help_option.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qemu/error-report.h"
38 #include "qemu/sockets.h"
39 #include "qemu/cutils.h"
40 #include "qemu/config-file.h"
41 #include "qmp-commands.h"
42 #include "hw/qdev.h"
43 #include "qemu/iov.h"
44 #include "qemu/main-loop.h"
45 #include "qapi-visit.h"
46 #include "qapi/opts-visitor.h"
47 #include "sysemu/sysemu.h"
48 #include "net/filter.h"
49 #include "qapi/string-output-visitor.h"
51 /* Net bridge is currently not supported for W32. */
52 #if !defined(_WIN32)
53 # define CONFIG_NET_BRIDGE
54 #endif
56 static VMChangeStateEntry *net_change_state_entry;
57 static QTAILQ_HEAD(, NetClientState) net_clients;
59 const char *host_net_devices[] = {
60 "tap",
61 "socket",
62 "dump",
63 #ifdef CONFIG_NET_BRIDGE
64 "bridge",
65 #endif
66 #ifdef CONFIG_NETMAP
67 "netmap",
68 #endif
69 #ifdef CONFIG_SLIRP
70 "user",
71 #endif
72 #ifdef CONFIG_VDE
73 "vde",
74 #endif
75 "vhost-user",
76 NULL,
79 /***********************************************************/
80 /* network device redirectors */
82 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
84 const char *p, *p1;
85 int len;
86 p = *pp;
87 p1 = strchr(p, sep);
88 if (!p1)
89 return -1;
90 len = p1 - p;
91 p1++;
92 if (buf_size > 0) {
93 if (len > buf_size - 1)
94 len = buf_size - 1;
95 memcpy(buf, p, len);
96 buf[len] = '\0';
98 *pp = p1;
99 return 0;
102 int parse_host_port(struct sockaddr_in *saddr, const char *str)
104 char buf[512];
105 struct hostent *he;
106 const char *p, *r;
107 int port;
109 p = str;
110 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
111 return -1;
112 saddr->sin_family = AF_INET;
113 if (buf[0] == '\0') {
114 saddr->sin_addr.s_addr = 0;
115 } else {
116 if (qemu_isdigit(buf[0])) {
117 if (!inet_aton(buf, &saddr->sin_addr))
118 return -1;
119 } else {
120 if ((he = gethostbyname(buf)) == NULL)
121 return - 1;
122 saddr->sin_addr = *(struct in_addr *)he->h_addr;
125 port = strtol(p, (char **)&r, 0);
126 if (r == p)
127 return -1;
128 saddr->sin_port = htons(port);
129 return 0;
132 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
134 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
135 macaddr[0], macaddr[1], macaddr[2],
136 macaddr[3], macaddr[4], macaddr[5]);
139 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
141 snprintf(nc->info_str, sizeof(nc->info_str),
142 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
143 nc->model,
144 macaddr[0], macaddr[1], macaddr[2],
145 macaddr[3], macaddr[4], macaddr[5]);
148 static int mac_table[256] = {0};
150 static void qemu_macaddr_set_used(MACAddr *macaddr)
152 int index;
154 for (index = 0x56; index < 0xFF; index++) {
155 if (macaddr->a[5] == index) {
156 mac_table[index]++;
161 static void qemu_macaddr_set_free(MACAddr *macaddr)
163 int index;
164 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
166 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
167 return;
169 for (index = 0x56; index < 0xFF; index++) {
170 if (macaddr->a[5] == index) {
171 mac_table[index]--;
176 static int qemu_macaddr_get_free(void)
178 int index;
180 for (index = 0x56; index < 0xFF; index++) {
181 if (mac_table[index] == 0) {
182 return index;
186 return -1;
189 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
191 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
192 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
194 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
195 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
196 return;
197 } else {
198 qemu_macaddr_set_used(macaddr);
199 return;
203 macaddr->a[0] = 0x52;
204 macaddr->a[1] = 0x54;
205 macaddr->a[2] = 0x00;
206 macaddr->a[3] = 0x12;
207 macaddr->a[4] = 0x34;
208 macaddr->a[5] = qemu_macaddr_get_free();
209 qemu_macaddr_set_used(macaddr);
213 * Generate a name for net client
215 * Only net clients created with the legacy -net option and NICs need this.
217 static char *assign_name(NetClientState *nc1, const char *model)
219 NetClientState *nc;
220 int id = 0;
222 QTAILQ_FOREACH(nc, &net_clients, next) {
223 if (nc == nc1) {
224 continue;
226 if (strcmp(nc->model, model) == 0) {
227 id++;
231 return g_strdup_printf("%s.%d", model, id);
234 static void qemu_net_client_destructor(NetClientState *nc)
236 g_free(nc);
239 static void qemu_net_client_setup(NetClientState *nc,
240 NetClientInfo *info,
241 NetClientState *peer,
242 const char *model,
243 const char *name,
244 NetClientDestructor *destructor)
246 nc->info = info;
247 nc->model = g_strdup(model);
248 if (name) {
249 nc->name = g_strdup(name);
250 } else {
251 nc->name = assign_name(nc, model);
254 if (peer) {
255 assert(!peer->peer);
256 nc->peer = peer;
257 peer->peer = nc;
259 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
261 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
262 nc->destructor = destructor;
263 QTAILQ_INIT(&nc->filters);
266 NetClientState *qemu_new_net_client(NetClientInfo *info,
267 NetClientState *peer,
268 const char *model,
269 const char *name)
271 NetClientState *nc;
273 assert(info->size >= sizeof(NetClientState));
275 nc = g_malloc0(info->size);
276 qemu_net_client_setup(nc, info, peer, model, name,
277 qemu_net_client_destructor);
279 return nc;
282 NICState *qemu_new_nic(NetClientInfo *info,
283 NICConf *conf,
284 const char *model,
285 const char *name,
286 void *opaque)
288 NetClientState **peers = conf->peers.ncs;
289 NICState *nic;
290 int i, queues = MAX(1, conf->peers.queues);
292 assert(info->type == NET_CLIENT_DRIVER_NIC);
293 assert(info->size >= sizeof(NICState));
295 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
296 nic->ncs = (void *)nic + info->size;
297 nic->conf = conf;
298 nic->opaque = opaque;
300 for (i = 0; i < queues; i++) {
301 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
302 NULL);
303 nic->ncs[i].queue_index = i;
306 return nic;
309 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
311 return nic->ncs + queue_index;
314 NetClientState *qemu_get_queue(NICState *nic)
316 return qemu_get_subqueue(nic, 0);
319 NICState *qemu_get_nic(NetClientState *nc)
321 NetClientState *nc0 = nc - nc->queue_index;
323 return (NICState *)((void *)nc0 - nc->info->size);
326 void *qemu_get_nic_opaque(NetClientState *nc)
328 NICState *nic = qemu_get_nic(nc);
330 return nic->opaque;
333 static void qemu_cleanup_net_client(NetClientState *nc)
335 QTAILQ_REMOVE(&net_clients, nc, next);
337 if (nc->info->cleanup) {
338 nc->info->cleanup(nc);
342 static void qemu_free_net_client(NetClientState *nc)
344 if (nc->incoming_queue) {
345 qemu_del_net_queue(nc->incoming_queue);
347 if (nc->peer) {
348 nc->peer->peer = NULL;
350 g_free(nc->name);
351 g_free(nc->model);
352 if (nc->destructor) {
353 nc->destructor(nc);
357 void qemu_del_net_client(NetClientState *nc)
359 NetClientState *ncs[MAX_QUEUE_NUM];
360 int queues, i;
361 NetFilterState *nf, *next;
363 assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
365 /* If the NetClientState belongs to a multiqueue backend, we will change all
366 * other NetClientStates also.
368 queues = qemu_find_net_clients_except(nc->name, ncs,
369 NET_CLIENT_DRIVER_NIC,
370 MAX_QUEUE_NUM);
371 assert(queues != 0);
373 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
374 object_unparent(OBJECT(nf));
377 /* If there is a peer NIC, delete and cleanup client, but do not free. */
378 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
379 NICState *nic = qemu_get_nic(nc->peer);
380 if (nic->peer_deleted) {
381 return;
383 nic->peer_deleted = true;
385 for (i = 0; i < queues; i++) {
386 ncs[i]->peer->link_down = true;
389 if (nc->peer->info->link_status_changed) {
390 nc->peer->info->link_status_changed(nc->peer);
393 for (i = 0; i < queues; i++) {
394 qemu_cleanup_net_client(ncs[i]);
397 return;
400 for (i = 0; i < queues; i++) {
401 qemu_cleanup_net_client(ncs[i]);
402 qemu_free_net_client(ncs[i]);
406 void qemu_del_nic(NICState *nic)
408 int i, queues = MAX(nic->conf->peers.queues, 1);
410 qemu_macaddr_set_free(&nic->conf->macaddr);
412 /* If this is a peer NIC and peer has already been deleted, free it now. */
413 if (nic->peer_deleted) {
414 for (i = 0; i < queues; i++) {
415 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
419 for (i = queues - 1; i >= 0; i--) {
420 NetClientState *nc = qemu_get_subqueue(nic, i);
422 qemu_cleanup_net_client(nc);
423 qemu_free_net_client(nc);
426 g_free(nic);
429 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
431 NetClientState *nc;
433 QTAILQ_FOREACH(nc, &net_clients, next) {
434 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
435 if (nc->queue_index == 0) {
436 func(qemu_get_nic(nc), opaque);
442 bool qemu_has_ufo(NetClientState *nc)
444 if (!nc || !nc->info->has_ufo) {
445 return false;
448 return nc->info->has_ufo(nc);
451 bool qemu_has_vnet_hdr(NetClientState *nc)
453 if (!nc || !nc->info->has_vnet_hdr) {
454 return false;
457 return nc->info->has_vnet_hdr(nc);
460 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
462 if (!nc || !nc->info->has_vnet_hdr_len) {
463 return false;
466 return nc->info->has_vnet_hdr_len(nc, len);
469 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
471 if (!nc || !nc->info->using_vnet_hdr) {
472 return;
475 nc->info->using_vnet_hdr(nc, enable);
478 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
479 int ecn, int ufo)
481 if (!nc || !nc->info->set_offload) {
482 return;
485 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
488 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
490 if (!nc || !nc->info->set_vnet_hdr_len) {
491 return;
494 nc->info->set_vnet_hdr_len(nc, len);
497 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
499 #ifdef HOST_WORDS_BIGENDIAN
500 if (!nc || !nc->info->set_vnet_le) {
501 return -ENOSYS;
504 return nc->info->set_vnet_le(nc, is_le);
505 #else
506 return 0;
507 #endif
510 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
512 #ifdef HOST_WORDS_BIGENDIAN
513 return 0;
514 #else
515 if (!nc || !nc->info->set_vnet_be) {
516 return -ENOSYS;
519 return nc->info->set_vnet_be(nc, is_be);
520 #endif
523 int qemu_can_send_packet(NetClientState *sender)
525 int vm_running = runstate_is_running();
527 if (!vm_running) {
528 return 0;
531 if (!sender->peer) {
532 return 1;
535 if (sender->peer->receive_disabled) {
536 return 0;
537 } else if (sender->peer->info->can_receive &&
538 !sender->peer->info->can_receive(sender->peer)) {
539 return 0;
541 return 1;
544 static ssize_t filter_receive_iov(NetClientState *nc,
545 NetFilterDirection direction,
546 NetClientState *sender,
547 unsigned flags,
548 const struct iovec *iov,
549 int iovcnt,
550 NetPacketSent *sent_cb)
552 ssize_t ret = 0;
553 NetFilterState *nf = NULL;
555 if (direction == NET_FILTER_DIRECTION_TX) {
556 QTAILQ_FOREACH(nf, &nc->filters, next) {
557 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
558 iovcnt, sent_cb);
559 if (ret) {
560 return ret;
563 } else {
564 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, NetFilterHead, next) {
565 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
566 iovcnt, sent_cb);
567 if (ret) {
568 return ret;
573 return ret;
576 static ssize_t filter_receive(NetClientState *nc,
577 NetFilterDirection direction,
578 NetClientState *sender,
579 unsigned flags,
580 const uint8_t *data,
581 size_t size,
582 NetPacketSent *sent_cb)
584 struct iovec iov = {
585 .iov_base = (void *)data,
586 .iov_len = size
589 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
592 void qemu_purge_queued_packets(NetClientState *nc)
594 if (!nc->peer) {
595 return;
598 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
601 static
602 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
604 nc->receive_disabled = 0;
606 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
607 if (net_hub_flush(nc->peer)) {
608 qemu_notify_event();
611 if (qemu_net_queue_flush(nc->incoming_queue)) {
612 /* We emptied the queue successfully, signal to the IO thread to repoll
613 * the file descriptor (for tap, for example).
615 qemu_notify_event();
616 } else if (purge) {
617 /* Unable to empty the queue, purge remaining packets */
618 qemu_net_queue_purge(nc->incoming_queue, nc);
622 void qemu_flush_queued_packets(NetClientState *nc)
624 qemu_flush_or_purge_queued_packets(nc, false);
627 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
628 unsigned flags,
629 const uint8_t *buf, int size,
630 NetPacketSent *sent_cb)
632 NetQueue *queue;
633 int ret;
635 #ifdef DEBUG_NET
636 printf("qemu_send_packet_async:\n");
637 qemu_hexdump((const char *)buf, stdout, "net", size);
638 #endif
640 if (sender->link_down || !sender->peer) {
641 return size;
644 /* Let filters handle the packet first */
645 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
646 sender, flags, buf, size, sent_cb);
647 if (ret) {
648 return ret;
651 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
652 sender, flags, buf, size, sent_cb);
653 if (ret) {
654 return ret;
657 queue = sender->peer->incoming_queue;
659 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
662 ssize_t qemu_send_packet_async(NetClientState *sender,
663 const uint8_t *buf, int size,
664 NetPacketSent *sent_cb)
666 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
667 buf, size, sent_cb);
670 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
672 qemu_send_packet_async(nc, buf, size, NULL);
675 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
677 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
678 buf, size, NULL);
681 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
682 int iovcnt, unsigned flags)
684 uint8_t *buf = NULL;
685 uint8_t *buffer;
686 size_t offset;
687 ssize_t ret;
689 if (iovcnt == 1) {
690 buffer = iov[0].iov_base;
691 offset = iov[0].iov_len;
692 } else {
693 offset = iov_size(iov, iovcnt);
694 if (offset > NET_BUFSIZE) {
695 return -1;
697 buf = g_malloc(offset);
698 buffer = buf;
699 offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
702 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
703 ret = nc->info->receive_raw(nc, buffer, offset);
704 } else {
705 ret = nc->info->receive(nc, buffer, offset);
708 g_free(buf);
709 return ret;
712 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
713 unsigned flags,
714 const struct iovec *iov,
715 int iovcnt,
716 void *opaque)
718 NetClientState *nc = opaque;
719 int ret;
721 if (nc->link_down) {
722 return iov_size(iov, iovcnt);
725 if (nc->receive_disabled) {
726 return 0;
729 if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
730 ret = nc->info->receive_iov(nc, iov, iovcnt);
731 } else {
732 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
735 if (ret == 0) {
736 nc->receive_disabled = 1;
739 return ret;
742 ssize_t qemu_sendv_packet_async(NetClientState *sender,
743 const struct iovec *iov, int iovcnt,
744 NetPacketSent *sent_cb)
746 NetQueue *queue;
747 int ret;
749 if (sender->link_down || !sender->peer) {
750 return iov_size(iov, iovcnt);
753 /* Let filters handle the packet first */
754 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
755 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
756 if (ret) {
757 return ret;
760 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
761 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
762 if (ret) {
763 return ret;
766 queue = sender->peer->incoming_queue;
768 return qemu_net_queue_send_iov(queue, sender,
769 QEMU_NET_PACKET_FLAG_NONE,
770 iov, iovcnt, sent_cb);
773 ssize_t
774 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
776 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
779 NetClientState *qemu_find_netdev(const char *id)
781 NetClientState *nc;
783 QTAILQ_FOREACH(nc, &net_clients, next) {
784 if (nc->info->type == NET_CLIENT_DRIVER_NIC)
785 continue;
786 if (!strcmp(nc->name, id)) {
787 return nc;
791 return NULL;
794 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
795 NetClientDriver type, int max)
797 NetClientState *nc;
798 int ret = 0;
800 QTAILQ_FOREACH(nc, &net_clients, next) {
801 if (nc->info->type == type) {
802 continue;
804 if (!id || !strcmp(nc->name, id)) {
805 if (ret < max) {
806 ncs[ret] = nc;
808 ret++;
812 return ret;
815 static int nic_get_free_idx(void)
817 int index;
819 for (index = 0; index < MAX_NICS; index++)
820 if (!nd_table[index].used)
821 return index;
822 return -1;
825 int qemu_show_nic_models(const char *arg, const char *const *models)
827 int i;
829 if (!arg || !is_help_option(arg)) {
830 return 0;
833 fprintf(stderr, "qemu: Supported NIC models: ");
834 for (i = 0 ; models[i]; i++)
835 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
836 return 1;
839 void qemu_check_nic_model(NICInfo *nd, const char *model)
841 const char *models[2];
843 models[0] = model;
844 models[1] = NULL;
846 if (qemu_show_nic_models(nd->model, models))
847 exit(0);
848 if (qemu_find_nic_model(nd, models, model) < 0)
849 exit(1);
852 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
853 const char *default_model)
855 int i;
857 if (!nd->model)
858 nd->model = g_strdup(default_model);
860 for (i = 0 ; models[i]; i++) {
861 if (strcmp(nd->model, models[i]) == 0)
862 return i;
865 error_report("Unsupported NIC model: %s", nd->model);
866 return -1;
869 static int net_init_nic(const Netdev *netdev, const char *name,
870 NetClientState *peer, Error **errp)
872 int idx;
873 NICInfo *nd;
874 const NetLegacyNicOptions *nic;
876 assert(netdev->type == NET_CLIENT_DRIVER_NIC);
877 nic = &netdev->u.nic;
879 idx = nic_get_free_idx();
880 if (idx == -1 || nb_nics >= MAX_NICS) {
881 error_setg(errp, "too many NICs");
882 return -1;
885 nd = &nd_table[idx];
887 memset(nd, 0, sizeof(*nd));
889 if (nic->has_netdev) {
890 nd->netdev = qemu_find_netdev(nic->netdev);
891 if (!nd->netdev) {
892 error_setg(errp, "netdev '%s' not found", nic->netdev);
893 return -1;
895 } else {
896 assert(peer);
897 nd->netdev = peer;
899 nd->name = g_strdup(name);
900 if (nic->has_model) {
901 nd->model = g_strdup(nic->model);
903 if (nic->has_addr) {
904 nd->devaddr = g_strdup(nic->addr);
907 if (nic->has_macaddr &&
908 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
909 error_setg(errp, "invalid syntax for ethernet address");
910 return -1;
912 if (nic->has_macaddr &&
913 is_multicast_ether_addr(nd->macaddr.a)) {
914 error_setg(errp,
915 "NIC cannot have multicast MAC address (odd 1st byte)");
916 return -1;
918 qemu_macaddr_default_if_unset(&nd->macaddr);
920 if (nic->has_vectors) {
921 if (nic->vectors > 0x7ffffff) {
922 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
923 return -1;
925 nd->nvectors = nic->vectors;
926 } else {
927 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
930 nd->used = 1;
931 nb_nics++;
933 return idx;
937 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
938 const Netdev *netdev,
939 const char *name,
940 NetClientState *peer, Error **errp) = {
941 [NET_CLIENT_DRIVER_NIC] = net_init_nic,
942 #ifdef CONFIG_SLIRP
943 [NET_CLIENT_DRIVER_USER] = net_init_slirp,
944 #endif
945 [NET_CLIENT_DRIVER_TAP] = net_init_tap,
946 [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
947 #ifdef CONFIG_VDE
948 [NET_CLIENT_DRIVER_VDE] = net_init_vde,
949 #endif
950 #ifdef CONFIG_NETMAP
951 [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
952 #endif
953 [NET_CLIENT_DRIVER_DUMP] = net_init_dump,
954 #ifdef CONFIG_NET_BRIDGE
955 [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
956 #endif
957 [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
958 #ifdef CONFIG_VHOST_NET_USED
959 [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
960 #endif
961 #ifdef CONFIG_L2TPV3
962 [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
963 #endif
967 static int net_client_init1(const void *object, bool is_netdev, Error **errp)
969 Netdev legacy = {0};
970 const Netdev *netdev;
971 const char *name;
972 NetClientState *peer = NULL;
973 static bool vlan_warned;
975 if (is_netdev) {
976 netdev = object;
977 name = netdev->id;
979 if (netdev->type == NET_CLIENT_DRIVER_DUMP ||
980 netdev->type == NET_CLIENT_DRIVER_NIC ||
981 !net_client_init_fun[netdev->type]) {
982 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
983 "a netdev backend type");
984 return -1;
986 } else {
987 const NetLegacy *net = object;
988 const NetLegacyOptions *opts = net->opts;
989 legacy.id = net->id;
990 netdev = &legacy;
991 /* missing optional values have been initialized to "all bits zero" */
992 name = net->has_id ? net->id : net->name;
994 /* Map the old options to the new flat type */
995 switch (opts->type) {
996 case NET_LEGACY_OPTIONS_TYPE_NONE:
997 return 0; /* nothing to do */
998 case NET_LEGACY_OPTIONS_TYPE_NIC:
999 legacy.type = NET_CLIENT_DRIVER_NIC;
1000 legacy.u.nic = opts->u.nic;
1001 break;
1002 case NET_LEGACY_OPTIONS_TYPE_USER:
1003 legacy.type = NET_CLIENT_DRIVER_USER;
1004 legacy.u.user = opts->u.user;
1005 break;
1006 case NET_LEGACY_OPTIONS_TYPE_TAP:
1007 legacy.type = NET_CLIENT_DRIVER_TAP;
1008 legacy.u.tap = opts->u.tap;
1009 break;
1010 case NET_LEGACY_OPTIONS_TYPE_L2TPV3:
1011 legacy.type = NET_CLIENT_DRIVER_L2TPV3;
1012 legacy.u.l2tpv3 = opts->u.l2tpv3;
1013 break;
1014 case NET_LEGACY_OPTIONS_TYPE_SOCKET:
1015 legacy.type = NET_CLIENT_DRIVER_SOCKET;
1016 legacy.u.socket = opts->u.socket;
1017 break;
1018 case NET_LEGACY_OPTIONS_TYPE_VDE:
1019 legacy.type = NET_CLIENT_DRIVER_VDE;
1020 legacy.u.vde = opts->u.vde;
1021 break;
1022 case NET_LEGACY_OPTIONS_TYPE_DUMP:
1023 legacy.type = NET_CLIENT_DRIVER_DUMP;
1024 legacy.u.dump = opts->u.dump;
1025 break;
1026 case NET_LEGACY_OPTIONS_TYPE_BRIDGE:
1027 legacy.type = NET_CLIENT_DRIVER_BRIDGE;
1028 legacy.u.bridge = opts->u.bridge;
1029 break;
1030 case NET_LEGACY_OPTIONS_TYPE_NETMAP:
1031 legacy.type = NET_CLIENT_DRIVER_NETMAP;
1032 legacy.u.netmap = opts->u.netmap;
1033 break;
1034 case NET_LEGACY_OPTIONS_TYPE_VHOST_USER:
1035 legacy.type = NET_CLIENT_DRIVER_VHOST_USER;
1036 legacy.u.vhost_user = opts->u.vhost_user;
1037 break;
1038 default:
1039 abort();
1042 if (!net_client_init_fun[netdev->type]) {
1043 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
1044 "a net backend type (maybe it is not compiled "
1045 "into this binary)");
1046 return -1;
1049 /* Do not add to a vlan if it's a nic with a netdev= parameter. */
1050 if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1051 !opts->u.nic.has_netdev) {
1052 peer = net_hub_add_port(net->has_vlan ? net->vlan : 0, NULL);
1055 if (net->has_vlan && !vlan_warned) {
1056 error_report("'vlan' is deprecated. Please use 'netdev' instead.");
1057 vlan_warned = true;
1061 if (net_client_init_fun[netdev->type](netdev, name, peer, errp) < 0) {
1062 /* FIXME drop when all init functions store an Error */
1063 if (errp && !*errp) {
1064 error_setg(errp, QERR_DEVICE_INIT_FAILED,
1065 NetClientDriver_lookup[netdev->type]);
1067 return -1;
1069 return 0;
1073 int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1075 void *object = NULL;
1076 Error *err = NULL;
1077 int ret = -1;
1078 Visitor *v = opts_visitor_new(opts);
1081 /* Parse convenience option format ip6-net=fec0::0[/64] */
1082 const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1084 if (ip6_net) {
1085 char buf[strlen(ip6_net) + 1];
1087 if (get_str_sep(buf, sizeof(buf), &ip6_net, '/') < 0) {
1088 /* Default 64bit prefix length. */
1089 qemu_opt_set(opts, "ipv6-prefix", ip6_net, &error_abort);
1090 qemu_opt_set_number(opts, "ipv6-prefixlen", 64, &error_abort);
1091 } else {
1092 /* User-specified prefix length. */
1093 unsigned long len;
1094 int err;
1096 qemu_opt_set(opts, "ipv6-prefix", buf, &error_abort);
1097 err = qemu_strtoul(ip6_net, NULL, 10, &len);
1099 if (err) {
1100 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1101 "ipv6-prefix", "a number");
1102 } else {
1103 qemu_opt_set_number(opts, "ipv6-prefixlen", len,
1104 &error_abort);
1107 qemu_opt_unset(opts, "ipv6-net");
1111 if (is_netdev) {
1112 visit_type_Netdev(v, NULL, (Netdev **)&object, &err);
1113 } else {
1114 visit_type_NetLegacy(v, NULL, (NetLegacy **)&object, &err);
1117 if (!err) {
1118 ret = net_client_init1(object, is_netdev, &err);
1121 if (is_netdev) {
1122 qapi_free_Netdev(object);
1123 } else {
1124 qapi_free_NetLegacy(object);
1127 error_propagate(errp, err);
1128 visit_free(v);
1129 return ret;
1133 static int net_host_check_device(const char *device)
1135 int i;
1136 for (i = 0; host_net_devices[i]; i++) {
1137 if (!strncmp(host_net_devices[i], device,
1138 strlen(host_net_devices[i]))) {
1139 return 1;
1143 return 0;
1146 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1148 const char *device = qdict_get_str(qdict, "device");
1149 const char *opts_str = qdict_get_try_str(qdict, "opts");
1150 Error *local_err = NULL;
1151 QemuOpts *opts;
1153 if (!net_host_check_device(device)) {
1154 monitor_printf(mon, "invalid host network device %s\n", device);
1155 return;
1158 opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1159 opts_str ? opts_str : "", false);
1160 if (!opts) {
1161 return;
1164 qemu_opt_set(opts, "type", device, &error_abort);
1166 net_client_init(opts, false, &local_err);
1167 if (local_err) {
1168 error_report_err(local_err);
1169 monitor_printf(mon, "adding host network device %s failed\n", device);
1173 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1175 NetClientState *nc;
1176 int vlan_id = qdict_get_int(qdict, "vlan_id");
1177 const char *device = qdict_get_str(qdict, "device");
1179 nc = net_hub_find_client_by_name(vlan_id, device);
1180 if (!nc) {
1181 error_report("Host network device '%s' on hub '%d' not found",
1182 device, vlan_id);
1183 return;
1185 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1186 error_report("invalid host network device '%s'", device);
1187 return;
1190 qemu_del_net_client(nc->peer);
1191 qemu_del_net_client(nc);
1192 qemu_opts_del(qemu_opts_find(qemu_find_opts("net"), device));
1195 void netdev_add(QemuOpts *opts, Error **errp)
1197 net_client_init(opts, true, errp);
1200 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1202 Error *local_err = NULL;
1203 QemuOptsList *opts_list;
1204 QemuOpts *opts;
1206 opts_list = qemu_find_opts_err("netdev", &local_err);
1207 if (local_err) {
1208 goto out;
1211 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1212 if (local_err) {
1213 goto out;
1216 netdev_add(opts, &local_err);
1217 if (local_err) {
1218 qemu_opts_del(opts);
1219 goto out;
1222 out:
1223 error_propagate(errp, local_err);
1226 void qmp_netdev_del(const char *id, Error **errp)
1228 NetClientState *nc;
1229 QemuOpts *opts;
1231 nc = qemu_find_netdev(id);
1232 if (!nc) {
1233 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1234 "Device '%s' not found", id);
1235 return;
1238 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1239 if (!opts) {
1240 error_setg(errp, "Device '%s' is not a netdev", id);
1241 return;
1244 qemu_del_net_client(nc);
1245 qemu_opts_del(opts);
1248 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1250 char *str;
1251 ObjectProperty *prop;
1252 ObjectPropertyIterator iter;
1253 Visitor *v;
1255 /* generate info str */
1256 object_property_iter_init(&iter, OBJECT(nf));
1257 while ((prop = object_property_iter_next(&iter))) {
1258 if (!strcmp(prop->name, "type")) {
1259 continue;
1261 v = string_output_visitor_new(false, &str);
1262 object_property_get(OBJECT(nf), v, prop->name, NULL);
1263 visit_complete(v, &str);
1264 visit_free(v);
1265 monitor_printf(mon, ",%s=%s", prop->name, str);
1266 g_free(str);
1268 monitor_printf(mon, "\n");
1271 void print_net_client(Monitor *mon, NetClientState *nc)
1273 NetFilterState *nf;
1275 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1276 nc->queue_index,
1277 NetClientDriver_lookup[nc->info->type],
1278 nc->info_str);
1279 if (!QTAILQ_EMPTY(&nc->filters)) {
1280 monitor_printf(mon, "filters:\n");
1282 QTAILQ_FOREACH(nf, &nc->filters, next) {
1283 char *path = object_get_canonical_path_component(OBJECT(nf));
1285 monitor_printf(mon, " - %s: type=%s", path,
1286 object_get_typename(OBJECT(nf)));
1287 netfilter_print_info(mon, nf);
1288 g_free(path);
1292 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1293 Error **errp)
1295 NetClientState *nc;
1296 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1298 QTAILQ_FOREACH(nc, &net_clients, next) {
1299 RxFilterInfoList *entry;
1300 RxFilterInfo *info;
1302 if (has_name && strcmp(nc->name, name) != 0) {
1303 continue;
1306 /* only query rx-filter information of NIC */
1307 if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1308 if (has_name) {
1309 error_setg(errp, "net client(%s) isn't a NIC", name);
1310 return NULL;
1312 continue;
1315 /* only query information on queue 0 since the info is per nic,
1316 * not per queue
1318 if (nc->queue_index != 0)
1319 continue;
1321 if (nc->info->query_rx_filter) {
1322 info = nc->info->query_rx_filter(nc);
1323 entry = g_malloc0(sizeof(*entry));
1324 entry->value = info;
1326 if (!filter_list) {
1327 filter_list = entry;
1328 } else {
1329 last_entry->next = entry;
1331 last_entry = entry;
1332 } else if (has_name) {
1333 error_setg(errp, "net client(%s) doesn't support"
1334 " rx-filter querying", name);
1335 return NULL;
1338 if (has_name) {
1339 break;
1343 if (filter_list == NULL && has_name) {
1344 error_setg(errp, "invalid net client name: %s", name);
1347 return filter_list;
1350 void hmp_info_network(Monitor *mon, const QDict *qdict)
1352 NetClientState *nc, *peer;
1353 NetClientDriver type;
1355 net_hub_info(mon);
1357 QTAILQ_FOREACH(nc, &net_clients, next) {
1358 peer = nc->peer;
1359 type = nc->info->type;
1361 /* Skip if already printed in hub info */
1362 if (net_hub_id_for_client(nc, NULL) == 0) {
1363 continue;
1366 if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1367 print_net_client(mon, nc);
1368 } /* else it's a netdev connected to a NIC, printed with the NIC */
1369 if (peer && type == NET_CLIENT_DRIVER_NIC) {
1370 monitor_printf(mon, " \\ ");
1371 print_net_client(mon, peer);
1376 void qmp_set_link(const char *name, bool up, Error **errp)
1378 NetClientState *ncs[MAX_QUEUE_NUM];
1379 NetClientState *nc;
1380 int queues, i;
1382 queues = qemu_find_net_clients_except(name, ncs,
1383 NET_CLIENT_DRIVER__MAX,
1384 MAX_QUEUE_NUM);
1386 if (queues == 0) {
1387 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1388 "Device '%s' not found", name);
1389 return;
1391 nc = ncs[0];
1393 for (i = 0; i < queues; i++) {
1394 ncs[i]->link_down = !up;
1397 if (nc->info->link_status_changed) {
1398 nc->info->link_status_changed(nc);
1401 if (nc->peer) {
1402 /* Change peer link only if the peer is NIC and then notify peer.
1403 * If the peer is a HUBPORT or a backend, we do not change the
1404 * link status.
1406 * This behavior is compatible with qemu vlans where there could be
1407 * multiple clients that can still communicate with each other in
1408 * disconnected mode. For now maintain this compatibility.
1410 if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1411 for (i = 0; i < queues; i++) {
1412 ncs[i]->peer->link_down = !up;
1415 if (nc->peer->info->link_status_changed) {
1416 nc->peer->info->link_status_changed(nc->peer);
1421 static void net_vm_change_state_handler(void *opaque, int running,
1422 RunState state)
1424 NetClientState *nc;
1425 NetClientState *tmp;
1427 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1428 if (running) {
1429 /* Flush queued packets and wake up backends. */
1430 if (nc->peer && qemu_can_send_packet(nc)) {
1431 qemu_flush_queued_packets(nc->peer);
1433 } else {
1434 /* Complete all queued packets, to guarantee we don't modify
1435 * state later when VM is not running.
1437 qemu_flush_or_purge_queued_packets(nc, true);
1442 void net_cleanup(void)
1444 NetClientState *nc;
1446 /* We may del multiple entries during qemu_del_net_client(),
1447 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1449 while (!QTAILQ_EMPTY(&net_clients)) {
1450 nc = QTAILQ_FIRST(&net_clients);
1451 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1452 qemu_del_nic(qemu_get_nic(nc));
1453 } else {
1454 qemu_del_net_client(nc);
1458 qemu_del_vm_change_state_handler(net_change_state_entry);
1461 void net_check_clients(void)
1463 NetClientState *nc;
1464 int i;
1466 net_hub_check_clients();
1468 QTAILQ_FOREACH(nc, &net_clients, next) {
1469 if (!nc->peer) {
1470 fprintf(stderr, "Warning: %s %s has no peer\n",
1471 nc->info->type == NET_CLIENT_DRIVER_NIC ?
1472 "nic" : "netdev", nc->name);
1476 /* Check that all NICs requested via -net nic actually got created.
1477 * NICs created via -device don't need to be checked here because
1478 * they are always instantiated.
1480 for (i = 0; i < MAX_NICS; i++) {
1481 NICInfo *nd = &nd_table[i];
1482 if (nd->used && !nd->instantiated) {
1483 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1484 "was not created (not supported by this machine?)\n",
1485 nd->name ? nd->name : "anonymous",
1486 nd->model ? nd->model : "unspecified");
1491 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1493 Error *local_err = NULL;
1495 net_client_init(opts, false, &local_err);
1496 if (local_err) {
1497 error_report_err(local_err);
1498 return -1;
1501 return 0;
1504 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1506 Error *local_err = NULL;
1507 int ret;
1509 ret = net_client_init(opts, true, &local_err);
1510 if (local_err) {
1511 error_report_err(local_err);
1512 return -1;
1515 return ret;
1518 int net_init_clients(void)
1520 QemuOptsList *net = qemu_find_opts("net");
1522 net_change_state_entry =
1523 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1525 QTAILQ_INIT(&net_clients);
1527 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1528 net_init_netdev, NULL, NULL)) {
1529 return -1;
1532 if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1533 return -1;
1536 return 0;
1539 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1541 #if defined(CONFIG_SLIRP)
1542 int ret;
1543 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1544 return ret;
1546 #endif
1548 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1549 return -1;
1552 return 0;
1555 /* From FreeBSD */
1556 /* XXX: optimize */
1557 unsigned compute_mcast_idx(const uint8_t *ep)
1559 uint32_t crc;
1560 int carry, i, j;
1561 uint8_t b;
1563 crc = 0xffffffff;
1564 for (i = 0; i < 6; i++) {
1565 b = *ep++;
1566 for (j = 0; j < 8; j++) {
1567 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1568 crc <<= 1;
1569 b >>= 1;
1570 if (carry) {
1571 crc = ((crc ^ POLYNOMIAL) | carry);
1575 return crc >> 26;
1578 QemuOptsList qemu_netdev_opts = {
1579 .name = "netdev",
1580 .implied_opt_name = "type",
1581 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1582 .desc = {
1584 * no elements => accept any params
1585 * validation will happen later
1587 { /* end of list */ }
1591 QemuOptsList qemu_net_opts = {
1592 .name = "net",
1593 .implied_opt_name = "type",
1594 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1595 .desc = {
1597 * no elements => accept any params
1598 * validation will happen later
1600 { /* end of list */ }
1604 void net_socket_rs_init(SocketReadState *rs,
1605 SocketReadStateFinalize *finalize)
1607 rs->state = 0;
1608 rs->index = 0;
1609 rs->packet_len = 0;
1610 memset(rs->buf, 0, sizeof(rs->buf));
1611 rs->finalize = finalize;
1615 * Returns
1616 * 0: success
1617 * -1: error occurs
1619 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1621 unsigned int l;
1623 while (size > 0) {
1624 /* reassemble a packet from the network */
1625 switch (rs->state) { /* 0 = getting length, 1 = getting data */
1626 case 0:
1627 l = 4 - rs->index;
1628 if (l > size) {
1629 l = size;
1631 memcpy(rs->buf + rs->index, buf, l);
1632 buf += l;
1633 size -= l;
1634 rs->index += l;
1635 if (rs->index == 4) {
1636 /* got length */
1637 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1638 rs->index = 0;
1639 rs->state = 1;
1641 break;
1642 case 1:
1643 l = rs->packet_len - rs->index;
1644 if (l > size) {
1645 l = size;
1647 if (rs->index + l <= sizeof(rs->buf)) {
1648 memcpy(rs->buf + rs->index, buf, l);
1649 } else {
1650 fprintf(stderr, "serious error: oversized packet received,"
1651 "connection terminated.\n");
1652 rs->index = rs->state = 0;
1653 return -1;
1656 rs->index += l;
1657 buf += l;
1658 size -= l;
1659 if (rs->index >= rs->packet_len) {
1660 rs->index = 0;
1661 rs->state = 0;
1662 assert(rs->finalize);
1663 rs->finalize(rs);
1665 break;
1669 assert(size == 0);
1670 return 0;