Merge tag 'net-pull-request' of https://github.com/jasowang/qemu into staging
[qemu/ar7.git] / net / net.c
blob840ad9dca5d8fb63433d8602eb99176b25884449
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.
25 #include "qemu/osdep.h"
27 #include "net/net.h"
28 #include "clients.h"
29 #include "hub.h"
30 #include "hw/qdev-properties.h"
31 #include "net/slirp.h"
32 #include "net/eth.h"
33 #include "util.h"
35 #include "monitor/monitor.h"
36 #include "qemu/help_option.h"
37 #include "qapi/qapi-commands-net.h"
38 #include "qapi/qapi-visit-net.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qmp/qerror.h"
41 #include "qemu/error-report.h"
42 #include "qemu/sockets.h"
43 #include "qemu/cutils.h"
44 #include "qemu/config-file.h"
45 #include "qemu/ctype.h"
46 #include "qemu/id.h"
47 #include "qemu/iov.h"
48 #include "qemu/qemu-print.h"
49 #include "qemu/main-loop.h"
50 #include "qemu/option.h"
51 #include "qemu/keyval.h"
52 #include "qapi/error.h"
53 #include "qapi/opts-visitor.h"
54 #include "sysemu/runstate.h"
55 #include "net/colo-compare.h"
56 #include "net/filter.h"
57 #include "qapi/string-output-visitor.h"
58 #include "qapi/qobject-input-visitor.h"
60 /* Net bridge is currently not supported for W32. */
61 #if !defined(_WIN32)
62 # define CONFIG_NET_BRIDGE
63 #endif
65 static VMChangeStateEntry *net_change_state_entry;
66 static QTAILQ_HEAD(, NetClientState) net_clients;
68 typedef struct NetdevQueueEntry {
69 Netdev *nd;
70 Location loc;
71 QSIMPLEQ_ENTRY(NetdevQueueEntry) entry;
72 } NetdevQueueEntry;
74 typedef QSIMPLEQ_HEAD(, NetdevQueueEntry) NetdevQueue;
76 static NetdevQueue nd_queue = QSIMPLEQ_HEAD_INITIALIZER(nd_queue);
78 /***********************************************************/
79 /* network device redirectors */
81 int convert_host_port(struct sockaddr_in *saddr, const char *host,
82 const char *port, Error **errp)
84 struct hostent *he;
85 const char *r;
86 long p;
88 memset(saddr, 0, sizeof(*saddr));
90 saddr->sin_family = AF_INET;
91 if (host[0] == '\0') {
92 saddr->sin_addr.s_addr = 0;
93 } else {
94 if (qemu_isdigit(host[0])) {
95 if (!inet_aton(host, &saddr->sin_addr)) {
96 error_setg(errp, "host address '%s' is not a valid "
97 "IPv4 address", host);
98 return -1;
100 } else {
101 he = gethostbyname(host);
102 if (he == NULL) {
103 error_setg(errp, "can't resolve host address '%s'", host);
104 return -1;
106 saddr->sin_addr = *(struct in_addr *)he->h_addr;
109 if (qemu_strtol(port, &r, 0, &p) != 0) {
110 error_setg(errp, "port number '%s' is invalid", port);
111 return -1;
113 saddr->sin_port = htons(p);
114 return 0;
117 int parse_host_port(struct sockaddr_in *saddr, const char *str,
118 Error **errp)
120 gchar **substrings;
121 int ret;
123 substrings = g_strsplit(str, ":", 2);
124 if (!substrings || !substrings[0] || !substrings[1]) {
125 error_setg(errp, "host address '%s' doesn't contain ':' "
126 "separating host from port", str);
127 ret = -1;
128 goto out;
131 ret = convert_host_port(saddr, substrings[0], substrings[1], errp);
133 out:
134 g_strfreev(substrings);
135 return ret;
138 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
140 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
141 macaddr[0], macaddr[1], macaddr[2],
142 macaddr[3], macaddr[4], macaddr[5]);
145 void qemu_set_info_str(NetClientState *nc, const char *fmt, ...)
147 va_list ap;
149 va_start(ap, fmt);
150 vsnprintf(nc->info_str, sizeof(nc->info_str), fmt, ap);
151 va_end(ap);
154 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
156 qemu_set_info_str(nc, "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
157 nc->model, macaddr[0], macaddr[1], macaddr[2],
158 macaddr[3], macaddr[4], macaddr[5]);
161 static int mac_table[256] = {0};
163 static void qemu_macaddr_set_used(MACAddr *macaddr)
165 int index;
167 for (index = 0x56; index < 0xFF; index++) {
168 if (macaddr->a[5] == index) {
169 mac_table[index]++;
174 static void qemu_macaddr_set_free(MACAddr *macaddr)
176 int index;
177 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
179 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
180 return;
182 for (index = 0x56; index < 0xFF; index++) {
183 if (macaddr->a[5] == index) {
184 mac_table[index]--;
189 static int qemu_macaddr_get_free(void)
191 int index;
193 for (index = 0x56; index < 0xFF; index++) {
194 if (mac_table[index] == 0) {
195 return index;
199 return -1;
202 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
204 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
205 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
207 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
208 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
209 return;
210 } else {
211 qemu_macaddr_set_used(macaddr);
212 return;
216 macaddr->a[0] = 0x52;
217 macaddr->a[1] = 0x54;
218 macaddr->a[2] = 0x00;
219 macaddr->a[3] = 0x12;
220 macaddr->a[4] = 0x34;
221 macaddr->a[5] = qemu_macaddr_get_free();
222 qemu_macaddr_set_used(macaddr);
226 * Generate a name for net client
228 * Only net clients created with the legacy -net option and NICs need this.
230 static char *assign_name(NetClientState *nc1, const char *model)
232 NetClientState *nc;
233 int id = 0;
235 QTAILQ_FOREACH(nc, &net_clients, next) {
236 if (nc == nc1) {
237 continue;
239 if (strcmp(nc->model, model) == 0) {
240 id++;
244 return g_strdup_printf("%s.%d", model, id);
247 static void qemu_net_client_destructor(NetClientState *nc)
249 g_free(nc);
251 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
252 unsigned flags,
253 const struct iovec *iov,
254 int iovcnt,
255 void *opaque);
257 static void qemu_net_client_setup(NetClientState *nc,
258 NetClientInfo *info,
259 NetClientState *peer,
260 const char *model,
261 const char *name,
262 NetClientDestructor *destructor,
263 bool is_datapath)
265 nc->info = info;
266 nc->model = g_strdup(model);
267 if (name) {
268 nc->name = g_strdup(name);
269 } else {
270 nc->name = assign_name(nc, model);
273 if (peer) {
274 assert(!peer->peer);
275 nc->peer = peer;
276 peer->peer = nc;
278 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
280 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc);
281 nc->destructor = destructor;
282 nc->is_datapath = is_datapath;
283 QTAILQ_INIT(&nc->filters);
286 NetClientState *qemu_new_net_client(NetClientInfo *info,
287 NetClientState *peer,
288 const char *model,
289 const char *name)
291 NetClientState *nc;
293 assert(info->size >= sizeof(NetClientState));
295 nc = g_malloc0(info->size);
296 qemu_net_client_setup(nc, info, peer, model, name,
297 qemu_net_client_destructor, true);
299 return nc;
302 NetClientState *qemu_new_net_control_client(NetClientInfo *info,
303 NetClientState *peer,
304 const char *model,
305 const char *name)
307 NetClientState *nc;
309 assert(info->size >= sizeof(NetClientState));
311 nc = g_malloc0(info->size);
312 qemu_net_client_setup(nc, info, peer, model, name,
313 qemu_net_client_destructor, false);
315 return nc;
318 NICState *qemu_new_nic(NetClientInfo *info,
319 NICConf *conf,
320 const char *model,
321 const char *name,
322 void *opaque)
324 NetClientState **peers = conf->peers.ncs;
325 NICState *nic;
326 int i, queues = MAX(1, conf->peers.queues);
328 assert(info->type == NET_CLIENT_DRIVER_NIC);
329 assert(info->size >= sizeof(NICState));
331 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
332 nic->ncs = (void *)nic + info->size;
333 nic->conf = conf;
334 nic->opaque = opaque;
336 for (i = 0; i < queues; i++) {
337 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
338 NULL, true);
339 nic->ncs[i].queue_index = i;
342 return nic;
345 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
347 return nic->ncs + queue_index;
350 NetClientState *qemu_get_queue(NICState *nic)
352 return qemu_get_subqueue(nic, 0);
355 NICState *qemu_get_nic(NetClientState *nc)
357 NetClientState *nc0 = nc - nc->queue_index;
359 return (NICState *)((void *)nc0 - nc->info->size);
362 void *qemu_get_nic_opaque(NetClientState *nc)
364 NICState *nic = qemu_get_nic(nc);
366 return nic->opaque;
369 NetClientState *qemu_get_peer(NetClientState *nc, int queue_index)
371 assert(nc != NULL);
372 NetClientState *ncs = nc + queue_index;
373 return ncs->peer;
376 static void qemu_cleanup_net_client(NetClientState *nc)
378 QTAILQ_REMOVE(&net_clients, nc, next);
380 if (nc->info->cleanup) {
381 nc->info->cleanup(nc);
385 static void qemu_free_net_client(NetClientState *nc)
387 if (nc->incoming_queue) {
388 qemu_del_net_queue(nc->incoming_queue);
390 if (nc->peer) {
391 nc->peer->peer = NULL;
393 g_free(nc->name);
394 g_free(nc->model);
395 if (nc->destructor) {
396 nc->destructor(nc);
400 void qemu_del_net_client(NetClientState *nc)
402 NetClientState *ncs[MAX_QUEUE_NUM];
403 int queues, i;
404 NetFilterState *nf, *next;
406 assert(nc->info->type != NET_CLIENT_DRIVER_NIC);
408 /* If the NetClientState belongs to a multiqueue backend, we will change all
409 * other NetClientStates also.
411 queues = qemu_find_net_clients_except(nc->name, ncs,
412 NET_CLIENT_DRIVER_NIC,
413 MAX_QUEUE_NUM);
414 assert(queues != 0);
416 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) {
417 object_unparent(OBJECT(nf));
420 /* If there is a peer NIC, delete and cleanup client, but do not free. */
421 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
422 NICState *nic = qemu_get_nic(nc->peer);
423 if (nic->peer_deleted) {
424 return;
426 nic->peer_deleted = true;
428 for (i = 0; i < queues; i++) {
429 ncs[i]->peer->link_down = true;
432 if (nc->peer->info->link_status_changed) {
433 nc->peer->info->link_status_changed(nc->peer);
436 for (i = 0; i < queues; i++) {
437 qemu_cleanup_net_client(ncs[i]);
440 return;
443 for (i = 0; i < queues; i++) {
444 qemu_cleanup_net_client(ncs[i]);
445 qemu_free_net_client(ncs[i]);
449 void qemu_del_nic(NICState *nic)
451 int i, queues = MAX(nic->conf->peers.queues, 1);
453 qemu_macaddr_set_free(&nic->conf->macaddr);
455 for (i = 0; i < queues; i++) {
456 NetClientState *nc = qemu_get_subqueue(nic, i);
457 /* If this is a peer NIC and peer has already been deleted, free it now. */
458 if (nic->peer_deleted) {
459 qemu_free_net_client(nc->peer);
460 } else if (nc->peer) {
461 /* if there are RX packets pending, complete them */
462 qemu_purge_queued_packets(nc->peer);
466 for (i = queues - 1; i >= 0; i--) {
467 NetClientState *nc = qemu_get_subqueue(nic, i);
469 qemu_cleanup_net_client(nc);
470 qemu_free_net_client(nc);
473 g_free(nic);
476 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
478 NetClientState *nc;
480 QTAILQ_FOREACH(nc, &net_clients, next) {
481 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
482 if (nc->queue_index == 0) {
483 func(qemu_get_nic(nc), opaque);
489 bool qemu_has_ufo(NetClientState *nc)
491 if (!nc || !nc->info->has_ufo) {
492 return false;
495 return nc->info->has_ufo(nc);
498 bool qemu_has_vnet_hdr(NetClientState *nc)
500 if (!nc || !nc->info->has_vnet_hdr) {
501 return false;
504 return nc->info->has_vnet_hdr(nc);
507 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
509 if (!nc || !nc->info->has_vnet_hdr_len) {
510 return false;
513 return nc->info->has_vnet_hdr_len(nc, len);
516 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
518 if (!nc || !nc->info->using_vnet_hdr) {
519 return;
522 nc->info->using_vnet_hdr(nc, enable);
525 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
526 int ecn, int ufo)
528 if (!nc || !nc->info->set_offload) {
529 return;
532 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
535 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
537 if (!nc || !nc->info->set_vnet_hdr_len) {
538 return;
541 nc->vnet_hdr_len = len;
542 nc->info->set_vnet_hdr_len(nc, len);
545 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
547 #if HOST_BIG_ENDIAN
548 if (!nc || !nc->info->set_vnet_le) {
549 return -ENOSYS;
552 return nc->info->set_vnet_le(nc, is_le);
553 #else
554 return 0;
555 #endif
558 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
560 #if HOST_BIG_ENDIAN
561 return 0;
562 #else
563 if (!nc || !nc->info->set_vnet_be) {
564 return -ENOSYS;
567 return nc->info->set_vnet_be(nc, is_be);
568 #endif
571 int qemu_can_receive_packet(NetClientState *nc)
573 if (nc->receive_disabled) {
574 return 0;
575 } else if (nc->info->can_receive &&
576 !nc->info->can_receive(nc)) {
577 return 0;
579 return 1;
582 int qemu_can_send_packet(NetClientState *sender)
584 int vm_running = runstate_is_running();
586 if (!vm_running) {
587 return 0;
590 if (!sender->peer) {
591 return 1;
594 return qemu_can_receive_packet(sender->peer);
597 static ssize_t filter_receive_iov(NetClientState *nc,
598 NetFilterDirection direction,
599 NetClientState *sender,
600 unsigned flags,
601 const struct iovec *iov,
602 int iovcnt,
603 NetPacketSent *sent_cb)
605 ssize_t ret = 0;
606 NetFilterState *nf = NULL;
608 if (direction == NET_FILTER_DIRECTION_TX) {
609 QTAILQ_FOREACH(nf, &nc->filters, next) {
610 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
611 iovcnt, sent_cb);
612 if (ret) {
613 return ret;
616 } else {
617 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) {
618 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov,
619 iovcnt, sent_cb);
620 if (ret) {
621 return ret;
626 return ret;
629 static ssize_t filter_receive(NetClientState *nc,
630 NetFilterDirection direction,
631 NetClientState *sender,
632 unsigned flags,
633 const uint8_t *data,
634 size_t size,
635 NetPacketSent *sent_cb)
637 struct iovec iov = {
638 .iov_base = (void *)data,
639 .iov_len = size
642 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb);
645 void qemu_purge_queued_packets(NetClientState *nc)
647 if (!nc->peer) {
648 return;
651 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
654 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
656 nc->receive_disabled = 0;
658 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) {
659 if (net_hub_flush(nc->peer)) {
660 qemu_notify_event();
663 if (qemu_net_queue_flush(nc->incoming_queue)) {
664 /* We emptied the queue successfully, signal to the IO thread to repoll
665 * the file descriptor (for tap, for example).
667 qemu_notify_event();
668 } else if (purge) {
669 /* Unable to empty the queue, purge remaining packets */
670 qemu_net_queue_purge(nc->incoming_queue, nc->peer);
674 void qemu_flush_queued_packets(NetClientState *nc)
676 qemu_flush_or_purge_queued_packets(nc, false);
679 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
680 unsigned flags,
681 const uint8_t *buf, int size,
682 NetPacketSent *sent_cb)
684 NetQueue *queue;
685 int ret;
687 #ifdef DEBUG_NET
688 printf("qemu_send_packet_async:\n");
689 qemu_hexdump(stdout, "net", buf, size);
690 #endif
692 if (sender->link_down || !sender->peer) {
693 return size;
696 /* Let filters handle the packet first */
697 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX,
698 sender, flags, buf, size, sent_cb);
699 if (ret) {
700 return ret;
703 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX,
704 sender, flags, buf, size, sent_cb);
705 if (ret) {
706 return ret;
709 queue = sender->peer->incoming_queue;
711 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
714 ssize_t qemu_send_packet_async(NetClientState *sender,
715 const uint8_t *buf, int size,
716 NetPacketSent *sent_cb)
718 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
719 buf, size, sent_cb);
722 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
724 return qemu_send_packet_async(nc, buf, size, NULL);
727 ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size)
729 if (!qemu_can_receive_packet(nc)) {
730 return 0;
733 return qemu_net_queue_receive(nc->incoming_queue, buf, size);
736 ssize_t qemu_receive_packet_iov(NetClientState *nc, const struct iovec *iov,
737 int iovcnt)
739 if (!qemu_can_receive_packet(nc)) {
740 return 0;
743 return qemu_net_queue_receive_iov(nc->incoming_queue, iov, iovcnt);
746 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
748 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
749 buf, size, NULL);
752 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
753 int iovcnt, unsigned flags)
755 uint8_t *buf = NULL;
756 uint8_t *buffer;
757 size_t offset;
758 ssize_t ret;
760 if (iovcnt == 1) {
761 buffer = iov[0].iov_base;
762 offset = iov[0].iov_len;
763 } else {
764 offset = iov_size(iov, iovcnt);
765 if (offset > NET_BUFSIZE) {
766 return -1;
768 buf = g_malloc(offset);
769 buffer = buf;
770 offset = iov_to_buf(iov, iovcnt, 0, buf, offset);
773 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
774 ret = nc->info->receive_raw(nc, buffer, offset);
775 } else {
776 ret = nc->info->receive(nc, buffer, offset);
779 g_free(buf);
780 return ret;
783 static ssize_t qemu_deliver_packet_iov(NetClientState *sender,
784 unsigned flags,
785 const struct iovec *iov,
786 int iovcnt,
787 void *opaque)
789 NetClientState *nc = opaque;
790 int ret;
793 if (nc->link_down) {
794 return iov_size(iov, iovcnt);
797 if (nc->receive_disabled) {
798 return 0;
801 if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) {
802 ret = nc->info->receive_iov(nc, iov, iovcnt);
803 } else {
804 ret = nc_sendv_compat(nc, iov, iovcnt, flags);
807 if (ret == 0) {
808 nc->receive_disabled = 1;
811 return ret;
814 ssize_t qemu_sendv_packet_async(NetClientState *sender,
815 const struct iovec *iov, int iovcnt,
816 NetPacketSent *sent_cb)
818 NetQueue *queue;
819 size_t size = iov_size(iov, iovcnt);
820 int ret;
822 if (size > NET_BUFSIZE) {
823 return size;
826 if (sender->link_down || !sender->peer) {
827 return size;
830 /* Let filters handle the packet first */
831 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender,
832 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
833 if (ret) {
834 return ret;
837 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender,
838 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb);
839 if (ret) {
840 return ret;
843 queue = sender->peer->incoming_queue;
845 return qemu_net_queue_send_iov(queue, sender,
846 QEMU_NET_PACKET_FLAG_NONE,
847 iov, iovcnt, sent_cb);
850 ssize_t
851 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
853 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
856 NetClientState *qemu_find_netdev(const char *id)
858 NetClientState *nc;
860 QTAILQ_FOREACH(nc, &net_clients, next) {
861 if (nc->info->type == NET_CLIENT_DRIVER_NIC)
862 continue;
863 if (!strcmp(nc->name, id)) {
864 return nc;
868 return NULL;
871 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
872 NetClientDriver type, int max)
874 NetClientState *nc;
875 int ret = 0;
877 QTAILQ_FOREACH(nc, &net_clients, next) {
878 if (nc->info->type == type) {
879 continue;
881 if (!id || !strcmp(nc->name, id)) {
882 if (ret < max) {
883 ncs[ret] = nc;
885 ret++;
889 return ret;
892 static int nic_get_free_idx(void)
894 int index;
896 for (index = 0; index < MAX_NICS; index++)
897 if (!nd_table[index].used)
898 return index;
899 return -1;
902 int qemu_show_nic_models(const char *arg, const char *const *models)
904 int i;
906 if (!arg || !is_help_option(arg)) {
907 return 0;
910 printf("Supported NIC models:\n");
911 for (i = 0 ; models[i]; i++) {
912 printf("%s\n", models[i]);
914 return 1;
917 void qemu_check_nic_model(NICInfo *nd, const char *model)
919 const char *models[2];
921 models[0] = model;
922 models[1] = NULL;
924 if (qemu_show_nic_models(nd->model, models))
925 exit(0);
926 if (qemu_find_nic_model(nd, models, model) < 0)
927 exit(1);
930 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
931 const char *default_model)
933 int i;
935 if (!nd->model)
936 nd->model = g_strdup(default_model);
938 for (i = 0 ; models[i]; i++) {
939 if (strcmp(nd->model, models[i]) == 0)
940 return i;
943 error_report("Unsupported NIC model: %s", nd->model);
944 return -1;
947 static int net_init_nic(const Netdev *netdev, const char *name,
948 NetClientState *peer, Error **errp)
950 int idx;
951 NICInfo *nd;
952 const NetLegacyNicOptions *nic;
954 assert(netdev->type == NET_CLIENT_DRIVER_NIC);
955 nic = &netdev->u.nic;
957 idx = nic_get_free_idx();
958 if (idx == -1 || nb_nics >= MAX_NICS) {
959 error_setg(errp, "too many NICs");
960 return -1;
963 nd = &nd_table[idx];
965 memset(nd, 0, sizeof(*nd));
967 if (nic->has_netdev) {
968 nd->netdev = qemu_find_netdev(nic->netdev);
969 if (!nd->netdev) {
970 error_setg(errp, "netdev '%s' not found", nic->netdev);
971 return -1;
973 } else {
974 assert(peer);
975 nd->netdev = peer;
977 nd->name = g_strdup(name);
978 if (nic->has_model) {
979 nd->model = g_strdup(nic->model);
981 if (nic->has_addr) {
982 nd->devaddr = g_strdup(nic->addr);
985 if (nic->has_macaddr &&
986 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
987 error_setg(errp, "invalid syntax for ethernet address");
988 return -1;
990 if (nic->has_macaddr &&
991 is_multicast_ether_addr(nd->macaddr.a)) {
992 error_setg(errp,
993 "NIC cannot have multicast MAC address (odd 1st byte)");
994 return -1;
996 qemu_macaddr_default_if_unset(&nd->macaddr);
998 if (nic->has_vectors) {
999 if (nic->vectors > 0x7ffffff) {
1000 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
1001 return -1;
1003 nd->nvectors = nic->vectors;
1004 } else {
1005 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
1008 nd->used = 1;
1009 nb_nics++;
1011 return idx;
1015 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])(
1016 const Netdev *netdev,
1017 const char *name,
1018 NetClientState *peer, Error **errp) = {
1019 [NET_CLIENT_DRIVER_NIC] = net_init_nic,
1020 #ifdef CONFIG_SLIRP
1021 [NET_CLIENT_DRIVER_USER] = net_init_slirp,
1022 #endif
1023 [NET_CLIENT_DRIVER_TAP] = net_init_tap,
1024 [NET_CLIENT_DRIVER_SOCKET] = net_init_socket,
1025 [NET_CLIENT_DRIVER_STREAM] = net_init_stream,
1026 [NET_CLIENT_DRIVER_DGRAM] = net_init_dgram,
1027 #ifdef CONFIG_VDE
1028 [NET_CLIENT_DRIVER_VDE] = net_init_vde,
1029 #endif
1030 #ifdef CONFIG_NETMAP
1031 [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap,
1032 #endif
1033 #ifdef CONFIG_NET_BRIDGE
1034 [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge,
1035 #endif
1036 [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport,
1037 #ifdef CONFIG_VHOST_NET_USER
1038 [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user,
1039 #endif
1040 #ifdef CONFIG_VHOST_NET_VDPA
1041 [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa,
1042 #endif
1043 #ifdef CONFIG_L2TPV3
1044 [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3,
1045 #endif
1046 #ifdef CONFIG_VMNET
1047 [NET_CLIENT_DRIVER_VMNET_HOST] = net_init_vmnet_host,
1048 [NET_CLIENT_DRIVER_VMNET_SHARED] = net_init_vmnet_shared,
1049 [NET_CLIENT_DRIVER_VMNET_BRIDGED] = net_init_vmnet_bridged,
1050 #endif /* CONFIG_VMNET */
1054 static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp)
1056 NetClientState *peer = NULL;
1057 NetClientState *nc;
1059 if (is_netdev) {
1060 if (netdev->type == NET_CLIENT_DRIVER_NIC ||
1061 !net_client_init_fun[netdev->type]) {
1062 error_setg(errp, "network backend '%s' is not compiled into this binary",
1063 NetClientDriver_str(netdev->type));
1064 return -1;
1066 } else {
1067 if (netdev->type == NET_CLIENT_DRIVER_NONE) {
1068 return 0; /* nothing to do */
1070 if (netdev->type == NET_CLIENT_DRIVER_HUBPORT) {
1071 error_setg(errp, "network backend '%s' is only supported with -netdev/-nic",
1072 NetClientDriver_str(netdev->type));
1073 return -1;
1076 if (!net_client_init_fun[netdev->type]) {
1077 error_setg(errp, "network backend '%s' is not compiled into this binary",
1078 NetClientDriver_str(netdev->type));
1079 return -1;
1082 /* Do not add to a hub if it's a nic with a netdev= parameter. */
1083 if (netdev->type != NET_CLIENT_DRIVER_NIC ||
1084 !netdev->u.nic.has_netdev) {
1085 peer = net_hub_add_port(0, NULL, NULL);
1089 nc = qemu_find_netdev(netdev->id);
1090 if (nc) {
1091 error_setg(errp, "Duplicate ID '%s'", netdev->id);
1092 return -1;
1095 if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) {
1096 /* FIXME drop when all init functions store an Error */
1097 if (errp && !*errp) {
1098 error_setg(errp, "Device '%s' could not be initialized",
1099 NetClientDriver_str(netdev->type));
1101 return -1;
1104 if (is_netdev) {
1105 nc = qemu_find_netdev(netdev->id);
1106 assert(nc);
1107 nc->is_netdev = true;
1110 return 0;
1113 void show_netdevs(void)
1115 int idx;
1116 const char *available_netdevs[] = {
1117 "socket",
1118 "stream",
1119 "dgram",
1120 "hubport",
1121 "tap",
1122 #ifdef CONFIG_SLIRP
1123 "user",
1124 #endif
1125 #ifdef CONFIG_L2TPV3
1126 "l2tpv3",
1127 #endif
1128 #ifdef CONFIG_VDE
1129 "vde",
1130 #endif
1131 #ifdef CONFIG_NET_BRIDGE
1132 "bridge",
1133 #endif
1134 #ifdef CONFIG_NETMAP
1135 "netmap",
1136 #endif
1137 #ifdef CONFIG_POSIX
1138 "vhost-user",
1139 #endif
1140 #ifdef CONFIG_VHOST_VDPA
1141 "vhost-vdpa",
1142 #endif
1143 #ifdef CONFIG_VMNET
1144 "vmnet-host",
1145 "vmnet-shared",
1146 "vmnet-bridged",
1147 #endif
1150 qemu_printf("Available netdev backend types:\n");
1151 for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) {
1152 qemu_printf("%s\n", available_netdevs[idx]);
1156 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp)
1158 gchar **substrings = NULL;
1159 Netdev *object = NULL;
1160 int ret = -1;
1161 Visitor *v = opts_visitor_new(opts);
1163 /* Parse convenience option format ip6-net=fec0::0[/64] */
1164 const char *ip6_net = qemu_opt_get(opts, "ipv6-net");
1166 if (ip6_net) {
1167 char *prefix_addr;
1168 unsigned long prefix_len = 64; /* Default 64bit prefix length. */
1170 substrings = g_strsplit(ip6_net, "/", 2);
1171 if (!substrings || !substrings[0]) {
1172 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net",
1173 "a valid IPv6 prefix");
1174 goto out;
1177 prefix_addr = substrings[0];
1179 /* Handle user-specified prefix length. */
1180 if (substrings[1] &&
1181 qemu_strtoul(substrings[1], NULL, 10, &prefix_len))
1183 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1184 "ipv6-prefixlen", "a number");
1185 goto out;
1188 qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort);
1189 qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len,
1190 &error_abort);
1191 qemu_opt_unset(opts, "ipv6-net");
1194 /* Create an ID for -net if the user did not specify one */
1195 if (!is_netdev && !qemu_opts_id(opts)) {
1196 qemu_opts_set_id(opts, id_generate(ID_NET));
1199 if (visit_type_Netdev(v, NULL, &object, errp)) {
1200 ret = net_client_init1(object, is_netdev, errp);
1203 qapi_free_Netdev(object);
1205 out:
1206 g_strfreev(substrings);
1207 visit_free(v);
1208 return ret;
1211 void netdev_add(QemuOpts *opts, Error **errp)
1213 net_client_init(opts, true, errp);
1216 void qmp_netdev_add(Netdev *netdev, Error **errp)
1218 if (!id_wellformed(netdev->id)) {
1219 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");
1220 return;
1223 net_client_init1(netdev, true, errp);
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 if (!nc->is_netdev) {
1239 error_setg(errp, "Device '%s' is not a netdev", id);
1240 return;
1243 qemu_del_net_client(nc);
1246 * Wart: we need to delete the QemuOpts associated with netdevs
1247 * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in
1248 * HMP netdev_add.
1250 opts = qemu_opts_find(qemu_find_opts("netdev"), id);
1251 if (opts) {
1252 qemu_opts_del(opts);
1256 static void netfilter_print_info(Monitor *mon, NetFilterState *nf)
1258 char *str;
1259 ObjectProperty *prop;
1260 ObjectPropertyIterator iter;
1261 Visitor *v;
1263 /* generate info str */
1264 object_property_iter_init(&iter, OBJECT(nf));
1265 while ((prop = object_property_iter_next(&iter))) {
1266 if (!strcmp(prop->name, "type")) {
1267 continue;
1269 v = string_output_visitor_new(false, &str);
1270 object_property_get(OBJECT(nf), prop->name, v, NULL);
1271 visit_complete(v, &str);
1272 visit_free(v);
1273 monitor_printf(mon, ",%s=%s", prop->name, str);
1274 g_free(str);
1276 monitor_printf(mon, "\n");
1279 void print_net_client(Monitor *mon, NetClientState *nc)
1281 NetFilterState *nf;
1283 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1284 nc->queue_index,
1285 NetClientDriver_str(nc->info->type),
1286 nc->info_str);
1287 if (!QTAILQ_EMPTY(&nc->filters)) {
1288 monitor_printf(mon, "filters:\n");
1290 QTAILQ_FOREACH(nf, &nc->filters, next) {
1291 monitor_printf(mon, " - %s: type=%s",
1292 object_get_canonical_path_component(OBJECT(nf)),
1293 object_get_typename(OBJECT(nf)));
1294 netfilter_print_info(mon, nf);
1298 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1299 Error **errp)
1301 NetClientState *nc;
1302 RxFilterInfoList *filter_list = NULL, **tail = &filter_list;
1304 QTAILQ_FOREACH(nc, &net_clients, next) {
1305 RxFilterInfo *info;
1307 if (has_name && strcmp(nc->name, name) != 0) {
1308 continue;
1311 /* only query rx-filter information of NIC */
1312 if (nc->info->type != NET_CLIENT_DRIVER_NIC) {
1313 if (has_name) {
1314 error_setg(errp, "net client(%s) isn't a NIC", name);
1315 assert(!filter_list);
1316 return NULL;
1318 continue;
1321 /* only query information on queue 0 since the info is per nic,
1322 * not per queue
1324 if (nc->queue_index != 0)
1325 continue;
1327 if (nc->info->query_rx_filter) {
1328 info = nc->info->query_rx_filter(nc);
1329 QAPI_LIST_APPEND(tail, info);
1330 } else if (has_name) {
1331 error_setg(errp, "net client(%s) doesn't support"
1332 " rx-filter querying", name);
1333 assert(!filter_list);
1334 return NULL;
1337 if (has_name) {
1338 break;
1342 if (filter_list == NULL && has_name) {
1343 error_setg(errp, "invalid net client name: %s", name);
1346 return filter_list;
1349 void hmp_info_network(Monitor *mon, const QDict *qdict)
1351 NetClientState *nc, *peer;
1352 NetClientDriver type;
1354 net_hub_info(mon);
1356 QTAILQ_FOREACH(nc, &net_clients, next) {
1357 peer = nc->peer;
1358 type = nc->info->type;
1360 /* Skip if already printed in hub info */
1361 if (net_hub_id_for_client(nc, NULL) == 0) {
1362 continue;
1365 if (!peer || type == NET_CLIENT_DRIVER_NIC) {
1366 print_net_client(mon, nc);
1367 } /* else it's a netdev connected to a NIC, printed with the NIC */
1368 if (peer && type == NET_CLIENT_DRIVER_NIC) {
1369 monitor_printf(mon, " \\ ");
1370 print_net_client(mon, peer);
1375 void colo_notify_filters_event(int event, Error **errp)
1377 NetClientState *nc;
1378 NetFilterState *nf;
1379 NetFilterClass *nfc = NULL;
1380 Error *local_err = NULL;
1382 QTAILQ_FOREACH(nc, &net_clients, next) {
1383 QTAILQ_FOREACH(nf, &nc->filters, next) {
1384 nfc = NETFILTER_GET_CLASS(OBJECT(nf));
1385 nfc->handle_event(nf, event, &local_err);
1386 if (local_err) {
1387 error_propagate(errp, local_err);
1388 return;
1394 void qmp_set_link(const char *name, bool up, Error **errp)
1396 NetClientState *ncs[MAX_QUEUE_NUM];
1397 NetClientState *nc;
1398 int queues, i;
1400 queues = qemu_find_net_clients_except(name, ncs,
1401 NET_CLIENT_DRIVER__MAX,
1402 MAX_QUEUE_NUM);
1404 if (queues == 0) {
1405 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1406 "Device '%s' not found", name);
1407 return;
1409 nc = ncs[0];
1411 for (i = 0; i < queues; i++) {
1412 ncs[i]->link_down = !up;
1415 if (nc->info->link_status_changed) {
1416 nc->info->link_status_changed(nc);
1419 if (nc->peer) {
1420 /* Change peer link only if the peer is NIC and then notify peer.
1421 * If the peer is a HUBPORT or a backend, we do not change the
1422 * link status.
1424 * This behavior is compatible with qemu hubs where there could be
1425 * multiple clients that can still communicate with each other in
1426 * disconnected mode. For now maintain this compatibility.
1428 if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) {
1429 for (i = 0; i < queues; i++) {
1430 ncs[i]->peer->link_down = !up;
1433 if (nc->peer->info->link_status_changed) {
1434 nc->peer->info->link_status_changed(nc->peer);
1439 static void net_vm_change_state_handler(void *opaque, bool running,
1440 RunState state)
1442 NetClientState *nc;
1443 NetClientState *tmp;
1445 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1446 if (running) {
1447 /* Flush queued packets and wake up backends. */
1448 if (nc->peer && qemu_can_send_packet(nc)) {
1449 qemu_flush_queued_packets(nc->peer);
1451 } else {
1452 /* Complete all queued packets, to guarantee we don't modify
1453 * state later when VM is not running.
1455 qemu_flush_or_purge_queued_packets(nc, true);
1460 void net_cleanup(void)
1462 NetClientState *nc;
1464 /*cleanup colo compare module for COLO*/
1465 colo_compare_cleanup();
1467 /* We may del multiple entries during qemu_del_net_client(),
1468 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1470 while (!QTAILQ_EMPTY(&net_clients)) {
1471 nc = QTAILQ_FIRST(&net_clients);
1472 if (nc->info->type == NET_CLIENT_DRIVER_NIC) {
1473 qemu_del_nic(qemu_get_nic(nc));
1474 } else {
1475 qemu_del_net_client(nc);
1479 qemu_del_vm_change_state_handler(net_change_state_entry);
1482 void net_check_clients(void)
1484 NetClientState *nc;
1485 int i;
1487 net_hub_check_clients();
1489 QTAILQ_FOREACH(nc, &net_clients, next) {
1490 if (!nc->peer) {
1491 warn_report("%s %s has no peer",
1492 nc->info->type == NET_CLIENT_DRIVER_NIC
1493 ? "nic" : "netdev",
1494 nc->name);
1498 /* Check that all NICs requested via -net nic actually got created.
1499 * NICs created via -device don't need to be checked here because
1500 * they are always instantiated.
1502 for (i = 0; i < MAX_NICS; i++) {
1503 NICInfo *nd = &nd_table[i];
1504 if (nd->used && !nd->instantiated) {
1505 warn_report("requested NIC (%s, model %s) "
1506 "was not created (not supported by this machine?)",
1507 nd->name ? nd->name : "anonymous",
1508 nd->model ? nd->model : "unspecified");
1513 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1515 return net_client_init(opts, false, errp);
1518 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1520 const char *type = qemu_opt_get(opts, "type");
1522 if (type && is_help_option(type)) {
1523 show_netdevs();
1524 exit(0);
1526 return net_client_init(opts, true, errp);
1529 /* For the convenience "--nic" parameter */
1530 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp)
1532 char *mac, *nd_id;
1533 int idx, ret;
1534 NICInfo *ni;
1535 const char *type;
1537 type = qemu_opt_get(opts, "type");
1538 if (type && g_str_equal(type, "none")) {
1539 return 0; /* Nothing to do, default_net is cleared in vl.c */
1542 idx = nic_get_free_idx();
1543 if (idx == -1 || nb_nics >= MAX_NICS) {
1544 error_setg(errp, "no more on-board/default NIC slots available");
1545 return -1;
1548 if (!type) {
1549 qemu_opt_set(opts, "type", "user", &error_abort);
1552 ni = &nd_table[idx];
1553 memset(ni, 0, sizeof(*ni));
1554 ni->model = qemu_opt_get_del(opts, "model");
1556 /* Create an ID if the user did not specify one */
1557 nd_id = g_strdup(qemu_opts_id(opts));
1558 if (!nd_id) {
1559 nd_id = id_generate(ID_NET);
1560 qemu_opts_set_id(opts, nd_id);
1563 /* Handle MAC address */
1564 mac = qemu_opt_get_del(opts, "mac");
1565 if (mac) {
1566 ret = net_parse_macaddr(ni->macaddr.a, mac);
1567 g_free(mac);
1568 if (ret) {
1569 error_setg(errp, "invalid syntax for ethernet address");
1570 goto out;
1572 if (is_multicast_ether_addr(ni->macaddr.a)) {
1573 error_setg(errp, "NIC cannot have multicast MAC address");
1574 ret = -1;
1575 goto out;
1578 qemu_macaddr_default_if_unset(&ni->macaddr);
1580 ret = net_client_init(opts, true, errp);
1581 if (ret == 0) {
1582 ni->netdev = qemu_find_netdev(nd_id);
1583 ni->used = true;
1584 nb_nics++;
1587 out:
1588 g_free(nd_id);
1589 return ret;
1592 static void netdev_init_modern(void)
1594 while (!QSIMPLEQ_EMPTY(&nd_queue)) {
1595 NetdevQueueEntry *nd = QSIMPLEQ_FIRST(&nd_queue);
1597 QSIMPLEQ_REMOVE_HEAD(&nd_queue, entry);
1598 loc_push_restore(&nd->loc);
1599 net_client_init1(nd->nd, true, &error_fatal);
1600 loc_pop(&nd->loc);
1601 qapi_free_Netdev(nd->nd);
1602 g_free(nd);
1606 void net_init_clients(void)
1608 net_change_state_entry =
1609 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1611 QTAILQ_INIT(&net_clients);
1613 netdev_init_modern();
1615 qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL,
1616 &error_fatal);
1618 qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL,
1619 &error_fatal);
1621 qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL,
1622 &error_fatal);
1626 * Does this -netdev argument use modern rather than traditional syntax?
1627 * Modern syntax is to be parsed with netdev_parse_modern().
1628 * Traditional syntax is to be parsed with net_client_parse().
1630 bool netdev_is_modern(const char *optarg)
1632 QemuOpts *opts;
1633 bool is_modern;
1634 const char *type;
1635 static QemuOptsList dummy_opts = {
1636 .name = "netdev",
1637 .implied_opt_name = "type",
1638 .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head),
1639 .desc = { { } },
1642 if (optarg[0] == '{') {
1643 /* This is JSON, which means it's modern syntax */
1644 return true;
1647 opts = qemu_opts_create(&dummy_opts, NULL, false, &error_abort);
1648 qemu_opts_do_parse(opts, optarg, dummy_opts.implied_opt_name,
1649 &error_abort);
1650 type = qemu_opt_get(opts, "type");
1651 is_modern = !g_strcmp0(type, "stream") || !g_strcmp0(type, "dgram");
1653 qemu_opts_reset(&dummy_opts);
1655 return is_modern;
1659 * netdev_parse_modern() uses modern, more expressive syntax than
1660 * net_client_parse(), but supports only the -netdev option.
1661 * netdev_parse_modern() appends to @nd_queue, whereas net_client_parse()
1662 * appends to @qemu_netdev_opts.
1664 void netdev_parse_modern(const char *optarg)
1666 Visitor *v;
1667 NetdevQueueEntry *nd;
1669 v = qobject_input_visitor_new_str(optarg, "type", &error_fatal);
1670 nd = g_new(NetdevQueueEntry, 1);
1671 visit_type_Netdev(v, NULL, &nd->nd, &error_fatal);
1672 visit_free(v);
1673 loc_save(&nd->loc);
1675 QSIMPLEQ_INSERT_TAIL(&nd_queue, nd, entry);
1678 void net_client_parse(QemuOptsList *opts_list, const char *optarg)
1680 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1681 exit(1);
1685 /* From FreeBSD */
1686 /* XXX: optimize */
1687 uint32_t net_crc32(const uint8_t *p, int len)
1689 uint32_t crc;
1690 int carry, i, j;
1691 uint8_t b;
1693 crc = 0xffffffff;
1694 for (i = 0; i < len; i++) {
1695 b = *p++;
1696 for (j = 0; j < 8; j++) {
1697 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1698 crc <<= 1;
1699 b >>= 1;
1700 if (carry) {
1701 crc = ((crc ^ POLYNOMIAL_BE) | carry);
1706 return crc;
1709 uint32_t net_crc32_le(const uint8_t *p, int len)
1711 uint32_t crc;
1712 int carry, i, j;
1713 uint8_t b;
1715 crc = 0xffffffff;
1716 for (i = 0; i < len; i++) {
1717 b = *p++;
1718 for (j = 0; j < 8; j++) {
1719 carry = (crc & 0x1) ^ (b & 0x01);
1720 crc >>= 1;
1721 b >>= 1;
1722 if (carry) {
1723 crc ^= POLYNOMIAL_LE;
1728 return crc;
1731 QemuOptsList qemu_netdev_opts = {
1732 .name = "netdev",
1733 .implied_opt_name = "type",
1734 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1735 .desc = {
1737 * no elements => accept any params
1738 * validation will happen later
1740 { /* end of list */ }
1744 QemuOptsList qemu_nic_opts = {
1745 .name = "nic",
1746 .implied_opt_name = "type",
1747 .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head),
1748 .desc = {
1750 * no elements => accept any params
1751 * validation will happen later
1753 { /* end of list */ }
1757 QemuOptsList qemu_net_opts = {
1758 .name = "net",
1759 .implied_opt_name = "type",
1760 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1761 .desc = {
1763 * no elements => accept any params
1764 * validation will happen later
1766 { /* end of list */ }
1770 void net_socket_rs_init(SocketReadState *rs,
1771 SocketReadStateFinalize *finalize,
1772 bool vnet_hdr)
1774 rs->state = 0;
1775 rs->vnet_hdr = vnet_hdr;
1776 rs->index = 0;
1777 rs->packet_len = 0;
1778 rs->vnet_hdr_len = 0;
1779 memset(rs->buf, 0, sizeof(rs->buf));
1780 rs->finalize = finalize;
1784 * Returns
1785 * 0: success
1786 * -1: error occurs
1788 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size)
1790 unsigned int l;
1792 while (size > 0) {
1793 /* Reassemble a packet from the network.
1794 * 0 = getting length.
1795 * 1 = getting vnet header length.
1796 * 2 = getting data.
1798 switch (rs->state) {
1799 case 0:
1800 l = 4 - rs->index;
1801 if (l > size) {
1802 l = size;
1804 memcpy(rs->buf + rs->index, buf, l);
1805 buf += l;
1806 size -= l;
1807 rs->index += l;
1808 if (rs->index == 4) {
1809 /* got length */
1810 rs->packet_len = ntohl(*(uint32_t *)rs->buf);
1811 rs->index = 0;
1812 if (rs->vnet_hdr) {
1813 rs->state = 1;
1814 } else {
1815 rs->state = 2;
1816 rs->vnet_hdr_len = 0;
1819 break;
1820 case 1:
1821 l = 4 - rs->index;
1822 if (l > size) {
1823 l = size;
1825 memcpy(rs->buf + rs->index, buf, l);
1826 buf += l;
1827 size -= l;
1828 rs->index += l;
1829 if (rs->index == 4) {
1830 /* got vnet header length */
1831 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf);
1832 rs->index = 0;
1833 rs->state = 2;
1835 break;
1836 case 2:
1837 l = rs->packet_len - rs->index;
1838 if (l > size) {
1839 l = size;
1841 if (rs->index + l <= sizeof(rs->buf)) {
1842 memcpy(rs->buf + rs->index, buf, l);
1843 } else {
1844 fprintf(stderr, "serious error: oversized packet received,"
1845 "connection terminated.\n");
1846 rs->index = rs->state = 0;
1847 return -1;
1850 rs->index += l;
1851 buf += l;
1852 size -= l;
1853 if (rs->index >= rs->packet_len) {
1854 rs->index = 0;
1855 rs->state = 0;
1856 assert(rs->finalize);
1857 rs->finalize(rs);
1859 break;
1863 assert(size == 0);
1864 return 0;