]> git.proxmox.com Git - mirror_qemu.git/blob - net/net.c
qerror: Move #include out of qerror.h
[mirror_qemu.git] / net / net.c
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2008 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24 #include "config-host.h"
25
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"
32
33 #include "monitor/monitor.h"
34 #include "qemu-common.h"
35 #include "qemu/error-report.h"
36 #include "qemu/sockets.h"
37 #include "qemu/config-file.h"
38 #include "qmp-commands.h"
39 #include "hw/qdev.h"
40 #include "qemu/iov.h"
41 #include "qemu/main-loop.h"
42 #include "qapi-visit.h"
43 #include "qapi/opts-visitor.h"
44 #include "qapi/dealloc-visitor.h"
45 #include "sysemu/sysemu.h"
46
47 /* Net bridge is currently not supported for W32. */
48 #if !defined(_WIN32)
49 # define CONFIG_NET_BRIDGE
50 #endif
51
52 static VMChangeStateEntry *net_change_state_entry;
53 static QTAILQ_HEAD(, NetClientState) net_clients;
54
55 const char *host_net_devices[] = {
56 "tap",
57 "socket",
58 "dump",
59 #ifdef CONFIG_NET_BRIDGE
60 "bridge",
61 #endif
62 #ifdef CONFIG_SLIRP
63 "user",
64 #endif
65 #ifdef CONFIG_VDE
66 "vde",
67 #endif
68 "vhost-user",
69 NULL,
70 };
71
72 int default_net = 1;
73
74 /***********************************************************/
75 /* network device redirectors */
76
77 #if defined(DEBUG_NET)
78 static void hex_dump(FILE *f, const uint8_t *buf, int size)
79 {
80 int len, i, j, c;
81
82 for(i=0;i<size;i+=16) {
83 len = size - i;
84 if (len > 16)
85 len = 16;
86 fprintf(f, "%08x ", i);
87 for(j=0;j<16;j++) {
88 if (j < len)
89 fprintf(f, " %02x", buf[i+j]);
90 else
91 fprintf(f, " ");
92 }
93 fprintf(f, " ");
94 for(j=0;j<len;j++) {
95 c = buf[i+j];
96 if (c < ' ' || c > '~')
97 c = '.';
98 fprintf(f, "%c", c);
99 }
100 fprintf(f, "\n");
101 }
102 }
103 #endif
104
105 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
106 {
107 const char *p, *p1;
108 int len;
109 p = *pp;
110 p1 = strchr(p, sep);
111 if (!p1)
112 return -1;
113 len = p1 - p;
114 p1++;
115 if (buf_size > 0) {
116 if (len > buf_size - 1)
117 len = buf_size - 1;
118 memcpy(buf, p, len);
119 buf[len] = '\0';
120 }
121 *pp = p1;
122 return 0;
123 }
124
125 int parse_host_port(struct sockaddr_in *saddr, const char *str)
126 {
127 char buf[512];
128 struct hostent *he;
129 const char *p, *r;
130 int port;
131
132 p = str;
133 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
134 return -1;
135 saddr->sin_family = AF_INET;
136 if (buf[0] == '\0') {
137 saddr->sin_addr.s_addr = 0;
138 } else {
139 if (qemu_isdigit(buf[0])) {
140 if (!inet_aton(buf, &saddr->sin_addr))
141 return -1;
142 } else {
143 if ((he = gethostbyname(buf)) == NULL)
144 return - 1;
145 saddr->sin_addr = *(struct in_addr *)he->h_addr;
146 }
147 }
148 port = strtol(p, (char **)&r, 0);
149 if (r == p)
150 return -1;
151 saddr->sin_port = htons(port);
152 return 0;
153 }
154
155 char *qemu_mac_strdup_printf(const uint8_t *macaddr)
156 {
157 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
158 macaddr[0], macaddr[1], macaddr[2],
159 macaddr[3], macaddr[4], macaddr[5]);
160 }
161
162 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6])
163 {
164 snprintf(nc->info_str, sizeof(nc->info_str),
165 "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x",
166 nc->model,
167 macaddr[0], macaddr[1], macaddr[2],
168 macaddr[3], macaddr[4], macaddr[5]);
169 }
170
171 static int mac_table[256] = {0};
172
173 static void qemu_macaddr_set_used(MACAddr *macaddr)
174 {
175 int index;
176
177 for (index = 0x56; index < 0xFF; index++) {
178 if (macaddr->a[5] == index) {
179 mac_table[index]++;
180 }
181 }
182 }
183
184 static void qemu_macaddr_set_free(MACAddr *macaddr)
185 {
186 int index;
187 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
188
189 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
190 return;
191 }
192 for (index = 0x56; index < 0xFF; index++) {
193 if (macaddr->a[5] == index) {
194 mac_table[index]--;
195 }
196 }
197 }
198
199 static int qemu_macaddr_get_free(void)
200 {
201 int index;
202
203 for (index = 0x56; index < 0xFF; index++) {
204 if (mac_table[index] == 0) {
205 return index;
206 }
207 }
208
209 return -1;
210 }
211
212 void qemu_macaddr_default_if_unset(MACAddr *macaddr)
213 {
214 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } };
215 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } };
216
217 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) {
218 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) {
219 return;
220 } else {
221 qemu_macaddr_set_used(macaddr);
222 return;
223 }
224 }
225
226 macaddr->a[0] = 0x52;
227 macaddr->a[1] = 0x54;
228 macaddr->a[2] = 0x00;
229 macaddr->a[3] = 0x12;
230 macaddr->a[4] = 0x34;
231 macaddr->a[5] = qemu_macaddr_get_free();
232 qemu_macaddr_set_used(macaddr);
233 }
234
235 /**
236 * Generate a name for net client
237 *
238 * Only net clients created with the legacy -net option and NICs need this.
239 */
240 static char *assign_name(NetClientState *nc1, const char *model)
241 {
242 NetClientState *nc;
243 int id = 0;
244
245 QTAILQ_FOREACH(nc, &net_clients, next) {
246 if (nc == nc1) {
247 continue;
248 }
249 if (strcmp(nc->model, model) == 0) {
250 id++;
251 }
252 }
253
254 return g_strdup_printf("%s.%d", model, id);
255 }
256
257 static void qemu_net_client_destructor(NetClientState *nc)
258 {
259 g_free(nc);
260 }
261
262 static void qemu_net_client_setup(NetClientState *nc,
263 NetClientInfo *info,
264 NetClientState *peer,
265 const char *model,
266 const char *name,
267 NetClientDestructor *destructor)
268 {
269 nc->info = info;
270 nc->model = g_strdup(model);
271 if (name) {
272 nc->name = g_strdup(name);
273 } else {
274 nc->name = assign_name(nc, model);
275 }
276
277 if (peer) {
278 assert(!peer->peer);
279 nc->peer = peer;
280 peer->peer = nc;
281 }
282 QTAILQ_INSERT_TAIL(&net_clients, nc, next);
283
284 nc->incoming_queue = qemu_new_net_queue(nc);
285 nc->destructor = destructor;
286 }
287
288 NetClientState *qemu_new_net_client(NetClientInfo *info,
289 NetClientState *peer,
290 const char *model,
291 const char *name)
292 {
293 NetClientState *nc;
294
295 assert(info->size >= sizeof(NetClientState));
296
297 nc = g_malloc0(info->size);
298 qemu_net_client_setup(nc, info, peer, model, name,
299 qemu_net_client_destructor);
300
301 return nc;
302 }
303
304 NICState *qemu_new_nic(NetClientInfo *info,
305 NICConf *conf,
306 const char *model,
307 const char *name,
308 void *opaque)
309 {
310 NetClientState **peers = conf->peers.ncs;
311 NICState *nic;
312 int i, queues = MAX(1, conf->peers.queues);
313
314 assert(info->type == NET_CLIENT_OPTIONS_KIND_NIC);
315 assert(info->size >= sizeof(NICState));
316
317 nic = g_malloc0(info->size + sizeof(NetClientState) * queues);
318 nic->ncs = (void *)nic + info->size;
319 nic->conf = conf;
320 nic->opaque = opaque;
321
322 for (i = 0; i < queues; i++) {
323 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name,
324 NULL);
325 nic->ncs[i].queue_index = i;
326 }
327
328 return nic;
329 }
330
331 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index)
332 {
333 return nic->ncs + queue_index;
334 }
335
336 NetClientState *qemu_get_queue(NICState *nic)
337 {
338 return qemu_get_subqueue(nic, 0);
339 }
340
341 NICState *qemu_get_nic(NetClientState *nc)
342 {
343 NetClientState *nc0 = nc - nc->queue_index;
344
345 return (NICState *)((void *)nc0 - nc->info->size);
346 }
347
348 void *qemu_get_nic_opaque(NetClientState *nc)
349 {
350 NICState *nic = qemu_get_nic(nc);
351
352 return nic->opaque;
353 }
354
355 static void qemu_cleanup_net_client(NetClientState *nc)
356 {
357 QTAILQ_REMOVE(&net_clients, nc, next);
358
359 if (nc->info->cleanup) {
360 nc->info->cleanup(nc);
361 }
362 }
363
364 static void qemu_free_net_client(NetClientState *nc)
365 {
366 if (nc->incoming_queue) {
367 qemu_del_net_queue(nc->incoming_queue);
368 }
369 if (nc->peer) {
370 nc->peer->peer = NULL;
371 }
372 g_free(nc->name);
373 g_free(nc->model);
374 if (nc->destructor) {
375 nc->destructor(nc);
376 }
377 }
378
379 void qemu_del_net_client(NetClientState *nc)
380 {
381 NetClientState *ncs[MAX_QUEUE_NUM];
382 int queues, i;
383
384 assert(nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC);
385
386 /* If the NetClientState belongs to a multiqueue backend, we will change all
387 * other NetClientStates also.
388 */
389 queues = qemu_find_net_clients_except(nc->name, ncs,
390 NET_CLIENT_OPTIONS_KIND_NIC,
391 MAX_QUEUE_NUM);
392 assert(queues != 0);
393
394 /* If there is a peer NIC, delete and cleanup client, but do not free. */
395 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
396 NICState *nic = qemu_get_nic(nc->peer);
397 if (nic->peer_deleted) {
398 return;
399 }
400 nic->peer_deleted = true;
401
402 for (i = 0; i < queues; i++) {
403 ncs[i]->peer->link_down = true;
404 }
405
406 if (nc->peer->info->link_status_changed) {
407 nc->peer->info->link_status_changed(nc->peer);
408 }
409
410 for (i = 0; i < queues; i++) {
411 qemu_cleanup_net_client(ncs[i]);
412 }
413
414 return;
415 }
416
417 for (i = 0; i < queues; i++) {
418 qemu_cleanup_net_client(ncs[i]);
419 qemu_free_net_client(ncs[i]);
420 }
421 }
422
423 void qemu_del_nic(NICState *nic)
424 {
425 int i, queues = MAX(nic->conf->peers.queues, 1);
426
427 qemu_macaddr_set_free(&nic->conf->macaddr);
428
429 /* If this is a peer NIC and peer has already been deleted, free it now. */
430 if (nic->peer_deleted) {
431 for (i = 0; i < queues; i++) {
432 qemu_free_net_client(qemu_get_subqueue(nic, i)->peer);
433 }
434 }
435
436 for (i = queues - 1; i >= 0; i--) {
437 NetClientState *nc = qemu_get_subqueue(nic, i);
438
439 qemu_cleanup_net_client(nc);
440 qemu_free_net_client(nc);
441 }
442
443 g_free(nic);
444 }
445
446 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque)
447 {
448 NetClientState *nc;
449
450 QTAILQ_FOREACH(nc, &net_clients, next) {
451 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
452 if (nc->queue_index == 0) {
453 func(qemu_get_nic(nc), opaque);
454 }
455 }
456 }
457 }
458
459 bool qemu_has_ufo(NetClientState *nc)
460 {
461 if (!nc || !nc->info->has_ufo) {
462 return false;
463 }
464
465 return nc->info->has_ufo(nc);
466 }
467
468 bool qemu_has_vnet_hdr(NetClientState *nc)
469 {
470 if (!nc || !nc->info->has_vnet_hdr) {
471 return false;
472 }
473
474 return nc->info->has_vnet_hdr(nc);
475 }
476
477 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len)
478 {
479 if (!nc || !nc->info->has_vnet_hdr_len) {
480 return false;
481 }
482
483 return nc->info->has_vnet_hdr_len(nc, len);
484 }
485
486 void qemu_using_vnet_hdr(NetClientState *nc, bool enable)
487 {
488 if (!nc || !nc->info->using_vnet_hdr) {
489 return;
490 }
491
492 nc->info->using_vnet_hdr(nc, enable);
493 }
494
495 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6,
496 int ecn, int ufo)
497 {
498 if (!nc || !nc->info->set_offload) {
499 return;
500 }
501
502 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo);
503 }
504
505 void qemu_set_vnet_hdr_len(NetClientState *nc, int len)
506 {
507 if (!nc || !nc->info->set_vnet_hdr_len) {
508 return;
509 }
510
511 nc->info->set_vnet_hdr_len(nc, len);
512 }
513
514 int qemu_set_vnet_le(NetClientState *nc, bool is_le)
515 {
516 if (!nc || !nc->info->set_vnet_le) {
517 return -ENOSYS;
518 }
519
520 return nc->info->set_vnet_le(nc, is_le);
521 }
522
523 int qemu_set_vnet_be(NetClientState *nc, bool is_be)
524 {
525 if (!nc || !nc->info->set_vnet_be) {
526 return -ENOSYS;
527 }
528
529 return nc->info->set_vnet_be(nc, is_be);
530 }
531
532 int qemu_can_send_packet(NetClientState *sender)
533 {
534 int vm_running = runstate_is_running();
535
536 if (!vm_running) {
537 return 0;
538 }
539
540 if (!sender->peer) {
541 return 1;
542 }
543
544 if (sender->peer->receive_disabled) {
545 return 0;
546 } else if (sender->peer->info->can_receive &&
547 !sender->peer->info->can_receive(sender->peer)) {
548 return 0;
549 }
550 return 1;
551 }
552
553 ssize_t qemu_deliver_packet(NetClientState *sender,
554 unsigned flags,
555 const uint8_t *data,
556 size_t size,
557 void *opaque)
558 {
559 NetClientState *nc = opaque;
560 ssize_t ret;
561
562 if (nc->link_down) {
563 return size;
564 }
565
566 if (nc->receive_disabled) {
567 return 0;
568 }
569
570 if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) {
571 ret = nc->info->receive_raw(nc, data, size);
572 } else {
573 ret = nc->info->receive(nc, data, size);
574 }
575
576 if (ret == 0) {
577 nc->receive_disabled = 1;
578 }
579
580 return ret;
581 }
582
583 void qemu_purge_queued_packets(NetClientState *nc)
584 {
585 if (!nc->peer) {
586 return;
587 }
588
589 qemu_net_queue_purge(nc->peer->incoming_queue, nc);
590 }
591
592 static
593 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge)
594 {
595 nc->receive_disabled = 0;
596
597 if (nc->peer && nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
598 if (net_hub_flush(nc->peer)) {
599 qemu_notify_event();
600 }
601 }
602 if (qemu_net_queue_flush(nc->incoming_queue)) {
603 /* We emptied the queue successfully, signal to the IO thread to repoll
604 * the file descriptor (for tap, for example).
605 */
606 qemu_notify_event();
607 } else if (purge) {
608 /* Unable to empty the queue, purge remaining packets */
609 qemu_net_queue_purge(nc->incoming_queue, nc);
610 }
611 }
612
613 void qemu_flush_queued_packets(NetClientState *nc)
614 {
615 qemu_flush_or_purge_queued_packets(nc, false);
616 }
617
618 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender,
619 unsigned flags,
620 const uint8_t *buf, int size,
621 NetPacketSent *sent_cb)
622 {
623 NetQueue *queue;
624
625 #ifdef DEBUG_NET
626 printf("qemu_send_packet_async:\n");
627 hex_dump(stdout, buf, size);
628 #endif
629
630 if (sender->link_down || !sender->peer) {
631 return size;
632 }
633
634 queue = sender->peer->incoming_queue;
635
636 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb);
637 }
638
639 ssize_t qemu_send_packet_async(NetClientState *sender,
640 const uint8_t *buf, int size,
641 NetPacketSent *sent_cb)
642 {
643 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE,
644 buf, size, sent_cb);
645 }
646
647 void qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size)
648 {
649 qemu_send_packet_async(nc, buf, size, NULL);
650 }
651
652 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size)
653 {
654 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW,
655 buf, size, NULL);
656 }
657
658 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov,
659 int iovcnt)
660 {
661 uint8_t buffer[NET_BUFSIZE];
662 size_t offset;
663
664 offset = iov_to_buf(iov, iovcnt, 0, buffer, sizeof(buffer));
665
666 return nc->info->receive(nc, buffer, offset);
667 }
668
669 ssize_t qemu_deliver_packet_iov(NetClientState *sender,
670 unsigned flags,
671 const struct iovec *iov,
672 int iovcnt,
673 void *opaque)
674 {
675 NetClientState *nc = opaque;
676 int ret;
677
678 if (nc->link_down) {
679 return iov_size(iov, iovcnt);
680 }
681
682 if (nc->receive_disabled) {
683 return 0;
684 }
685
686 if (nc->info->receive_iov) {
687 ret = nc->info->receive_iov(nc, iov, iovcnt);
688 } else {
689 ret = nc_sendv_compat(nc, iov, iovcnt);
690 }
691
692 if (ret == 0) {
693 nc->receive_disabled = 1;
694 }
695
696 return ret;
697 }
698
699 ssize_t qemu_sendv_packet_async(NetClientState *sender,
700 const struct iovec *iov, int iovcnt,
701 NetPacketSent *sent_cb)
702 {
703 NetQueue *queue;
704
705 if (sender->link_down || !sender->peer) {
706 return iov_size(iov, iovcnt);
707 }
708
709 queue = sender->peer->incoming_queue;
710
711 return qemu_net_queue_send_iov(queue, sender,
712 QEMU_NET_PACKET_FLAG_NONE,
713 iov, iovcnt, sent_cb);
714 }
715
716 ssize_t
717 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt)
718 {
719 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL);
720 }
721
722 NetClientState *qemu_find_netdev(const char *id)
723 {
724 NetClientState *nc;
725
726 QTAILQ_FOREACH(nc, &net_clients, next) {
727 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC)
728 continue;
729 if (!strcmp(nc->name, id)) {
730 return nc;
731 }
732 }
733
734 return NULL;
735 }
736
737 int qemu_find_net_clients_except(const char *id, NetClientState **ncs,
738 NetClientOptionsKind type, int max)
739 {
740 NetClientState *nc;
741 int ret = 0;
742
743 QTAILQ_FOREACH(nc, &net_clients, next) {
744 if (nc->info->type == type) {
745 continue;
746 }
747 if (!id || !strcmp(nc->name, id)) {
748 if (ret < max) {
749 ncs[ret] = nc;
750 }
751 ret++;
752 }
753 }
754
755 return ret;
756 }
757
758 static int nic_get_free_idx(void)
759 {
760 int index;
761
762 for (index = 0; index < MAX_NICS; index++)
763 if (!nd_table[index].used)
764 return index;
765 return -1;
766 }
767
768 int qemu_show_nic_models(const char *arg, const char *const *models)
769 {
770 int i;
771
772 if (!arg || !is_help_option(arg)) {
773 return 0;
774 }
775
776 fprintf(stderr, "qemu: Supported NIC models: ");
777 for (i = 0 ; models[i]; i++)
778 fprintf(stderr, "%s%c", models[i], models[i+1] ? ',' : '\n');
779 return 1;
780 }
781
782 void qemu_check_nic_model(NICInfo *nd, const char *model)
783 {
784 const char *models[2];
785
786 models[0] = model;
787 models[1] = NULL;
788
789 if (qemu_show_nic_models(nd->model, models))
790 exit(0);
791 if (qemu_find_nic_model(nd, models, model) < 0)
792 exit(1);
793 }
794
795 int qemu_find_nic_model(NICInfo *nd, const char * const *models,
796 const char *default_model)
797 {
798 int i;
799
800 if (!nd->model)
801 nd->model = g_strdup(default_model);
802
803 for (i = 0 ; models[i]; i++) {
804 if (strcmp(nd->model, models[i]) == 0)
805 return i;
806 }
807
808 error_report("Unsupported NIC model: %s", nd->model);
809 return -1;
810 }
811
812 static int net_init_nic(const NetClientOptions *opts, const char *name,
813 NetClientState *peer, Error **errp)
814 {
815 int idx;
816 NICInfo *nd;
817 const NetLegacyNicOptions *nic;
818
819 assert(opts->kind == NET_CLIENT_OPTIONS_KIND_NIC);
820 nic = opts->nic;
821
822 idx = nic_get_free_idx();
823 if (idx == -1 || nb_nics >= MAX_NICS) {
824 error_setg(errp, "too many NICs");
825 return -1;
826 }
827
828 nd = &nd_table[idx];
829
830 memset(nd, 0, sizeof(*nd));
831
832 if (nic->has_netdev) {
833 nd->netdev = qemu_find_netdev(nic->netdev);
834 if (!nd->netdev) {
835 error_setg(errp, "netdev '%s' not found", nic->netdev);
836 return -1;
837 }
838 } else {
839 assert(peer);
840 nd->netdev = peer;
841 }
842 nd->name = g_strdup(name);
843 if (nic->has_model) {
844 nd->model = g_strdup(nic->model);
845 }
846 if (nic->has_addr) {
847 nd->devaddr = g_strdup(nic->addr);
848 }
849
850 if (nic->has_macaddr &&
851 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) {
852 error_setg(errp, "invalid syntax for ethernet address");
853 return -1;
854 }
855 if (nic->has_macaddr &&
856 is_multicast_ether_addr(nd->macaddr.a)) {
857 error_setg(errp,
858 "NIC cannot have multicast MAC address (odd 1st byte)");
859 return -1;
860 }
861 qemu_macaddr_default_if_unset(&nd->macaddr);
862
863 if (nic->has_vectors) {
864 if (nic->vectors > 0x7ffffff) {
865 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors);
866 return -1;
867 }
868 nd->nvectors = nic->vectors;
869 } else {
870 nd->nvectors = DEV_NVECTORS_UNSPECIFIED;
871 }
872
873 nd->used = 1;
874 nb_nics++;
875
876 return idx;
877 }
878
879
880 static int (* const net_client_init_fun[NET_CLIENT_OPTIONS_KIND_MAX])(
881 const NetClientOptions *opts,
882 const char *name,
883 NetClientState *peer, Error **errp) = {
884 [NET_CLIENT_OPTIONS_KIND_NIC] = net_init_nic,
885 #ifdef CONFIG_SLIRP
886 [NET_CLIENT_OPTIONS_KIND_USER] = net_init_slirp,
887 #endif
888 [NET_CLIENT_OPTIONS_KIND_TAP] = net_init_tap,
889 [NET_CLIENT_OPTIONS_KIND_SOCKET] = net_init_socket,
890 #ifdef CONFIG_VDE
891 [NET_CLIENT_OPTIONS_KIND_VDE] = net_init_vde,
892 #endif
893 #ifdef CONFIG_NETMAP
894 [NET_CLIENT_OPTIONS_KIND_NETMAP] = net_init_netmap,
895 #endif
896 [NET_CLIENT_OPTIONS_KIND_DUMP] = net_init_dump,
897 #ifdef CONFIG_NET_BRIDGE
898 [NET_CLIENT_OPTIONS_KIND_BRIDGE] = net_init_bridge,
899 #endif
900 [NET_CLIENT_OPTIONS_KIND_HUBPORT] = net_init_hubport,
901 #ifdef CONFIG_VHOST_NET_USED
902 [NET_CLIENT_OPTIONS_KIND_VHOST_USER] = net_init_vhost_user,
903 #endif
904 #ifdef CONFIG_L2TPV3
905 [NET_CLIENT_OPTIONS_KIND_L2TPV3] = net_init_l2tpv3,
906 #endif
907 };
908
909
910 static int net_client_init1(const void *object, int is_netdev, Error **errp)
911 {
912 union {
913 const Netdev *netdev;
914 const NetLegacy *net;
915 } u;
916 const NetClientOptions *opts;
917 const char *name;
918
919 if (is_netdev) {
920 u.netdev = object;
921 opts = u.netdev->opts;
922 name = u.netdev->id;
923
924 switch (opts->kind) {
925 #ifdef CONFIG_SLIRP
926 case NET_CLIENT_OPTIONS_KIND_USER:
927 #endif
928 case NET_CLIENT_OPTIONS_KIND_TAP:
929 case NET_CLIENT_OPTIONS_KIND_SOCKET:
930 #ifdef CONFIG_VDE
931 case NET_CLIENT_OPTIONS_KIND_VDE:
932 #endif
933 #ifdef CONFIG_NETMAP
934 case NET_CLIENT_OPTIONS_KIND_NETMAP:
935 #endif
936 #ifdef CONFIG_NET_BRIDGE
937 case NET_CLIENT_OPTIONS_KIND_BRIDGE:
938 #endif
939 case NET_CLIENT_OPTIONS_KIND_HUBPORT:
940 #ifdef CONFIG_VHOST_NET_USED
941 case NET_CLIENT_OPTIONS_KIND_VHOST_USER:
942 #endif
943 #ifdef CONFIG_L2TPV3
944 case NET_CLIENT_OPTIONS_KIND_L2TPV3:
945 #endif
946 break;
947
948 default:
949 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
950 "a netdev backend type");
951 return -1;
952 }
953 } else {
954 u.net = object;
955 opts = u.net->opts;
956 if (opts->kind == NET_CLIENT_OPTIONS_KIND_HUBPORT) {
957 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "type",
958 "a net type");
959 return -1;
960 }
961 /* missing optional values have been initialized to "all bits zero" */
962 name = u.net->has_id ? u.net->id : u.net->name;
963 }
964
965 if (net_client_init_fun[opts->kind]) {
966 NetClientState *peer = NULL;
967
968 /* Do not add to a vlan if it's a -netdev or a nic with a netdev=
969 * parameter. */
970 if (!is_netdev &&
971 (opts->kind != NET_CLIENT_OPTIONS_KIND_NIC ||
972 !opts->nic->has_netdev)) {
973 peer = net_hub_add_port(u.net->has_vlan ? u.net->vlan : 0, NULL);
974 }
975
976 if (net_client_init_fun[opts->kind](opts, name, peer, errp) < 0) {
977 /* FIXME drop when all init functions store an Error */
978 if (errp && !*errp) {
979 error_setg(errp, QERR_DEVICE_INIT_FAILED,
980 NetClientOptionsKind_lookup[opts->kind]);
981 }
982 return -1;
983 }
984 }
985 return 0;
986 }
987
988
989 static void net_visit(Visitor *v, int is_netdev, void **object, Error **errp)
990 {
991 if (is_netdev) {
992 visit_type_Netdev(v, (Netdev **)object, NULL, errp);
993 } else {
994 visit_type_NetLegacy(v, (NetLegacy **)object, NULL, errp);
995 }
996 }
997
998
999 int net_client_init(QemuOpts *opts, int is_netdev, Error **errp)
1000 {
1001 void *object = NULL;
1002 Error *err = NULL;
1003 int ret = -1;
1004
1005 {
1006 OptsVisitor *ov = opts_visitor_new(opts);
1007
1008 net_visit(opts_get_visitor(ov), is_netdev, &object, &err);
1009 opts_visitor_cleanup(ov);
1010 }
1011
1012 if (!err) {
1013 ret = net_client_init1(object, is_netdev, &err);
1014 }
1015
1016 if (object) {
1017 QapiDeallocVisitor *dv = qapi_dealloc_visitor_new();
1018
1019 net_visit(qapi_dealloc_get_visitor(dv), is_netdev, &object, NULL);
1020 qapi_dealloc_visitor_cleanup(dv);
1021 }
1022
1023 error_propagate(errp, err);
1024 return ret;
1025 }
1026
1027
1028 static int net_host_check_device(const char *device)
1029 {
1030 int i;
1031 for (i = 0; host_net_devices[i]; i++) {
1032 if (!strncmp(host_net_devices[i], device,
1033 strlen(host_net_devices[i]))) {
1034 return 1;
1035 }
1036 }
1037
1038 return 0;
1039 }
1040
1041 void hmp_host_net_add(Monitor *mon, const QDict *qdict)
1042 {
1043 const char *device = qdict_get_str(qdict, "device");
1044 const char *opts_str = qdict_get_try_str(qdict, "opts");
1045 Error *local_err = NULL;
1046 QemuOpts *opts;
1047
1048 if (!net_host_check_device(device)) {
1049 monitor_printf(mon, "invalid host network device %s\n", device);
1050 return;
1051 }
1052
1053 opts = qemu_opts_parse_noisily(qemu_find_opts("net"),
1054 opts_str ? opts_str : "", false);
1055 if (!opts) {
1056 return;
1057 }
1058
1059 qemu_opt_set(opts, "type", device, &error_abort);
1060
1061 net_client_init(opts, 0, &local_err);
1062 if (local_err) {
1063 error_report_err(local_err);
1064 monitor_printf(mon, "adding host network device %s failed\n", device);
1065 }
1066 }
1067
1068 void hmp_host_net_remove(Monitor *mon, const QDict *qdict)
1069 {
1070 NetClientState *nc;
1071 int vlan_id = qdict_get_int(qdict, "vlan_id");
1072 const char *device = qdict_get_str(qdict, "device");
1073
1074 nc = net_hub_find_client_by_name(vlan_id, device);
1075 if (!nc) {
1076 error_report("Host network device '%s' on hub '%d' not found",
1077 device, vlan_id);
1078 return;
1079 }
1080 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1081 error_report("invalid host network device '%s'", device);
1082 return;
1083 }
1084
1085 qemu_del_net_client(nc->peer);
1086 qemu_del_net_client(nc);
1087 }
1088
1089 void netdev_add(QemuOpts *opts, Error **errp)
1090 {
1091 net_client_init(opts, 1, errp);
1092 }
1093
1094 void qmp_netdev_add(QDict *qdict, QObject **ret, Error **errp)
1095 {
1096 Error *local_err = NULL;
1097 QemuOptsList *opts_list;
1098 QemuOpts *opts;
1099
1100 opts_list = qemu_find_opts_err("netdev", &local_err);
1101 if (local_err) {
1102 goto out;
1103 }
1104
1105 opts = qemu_opts_from_qdict(opts_list, qdict, &local_err);
1106 if (local_err) {
1107 goto out;
1108 }
1109
1110 netdev_add(opts, &local_err);
1111 if (local_err) {
1112 qemu_opts_del(opts);
1113 goto out;
1114 }
1115
1116 out:
1117 error_propagate(errp, local_err);
1118 }
1119
1120 void qmp_netdev_del(const char *id, Error **errp)
1121 {
1122 NetClientState *nc;
1123 QemuOpts *opts;
1124
1125 nc = qemu_find_netdev(id);
1126 if (!nc) {
1127 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1128 "Device '%s' not found", id);
1129 return;
1130 }
1131
1132 opts = qemu_opts_find(qemu_find_opts_err("netdev", NULL), id);
1133 if (!opts) {
1134 error_setg(errp, "Device '%s' is not a netdev", id);
1135 return;
1136 }
1137
1138 qemu_del_net_client(nc);
1139 qemu_opts_del(opts);
1140 }
1141
1142 void print_net_client(Monitor *mon, NetClientState *nc)
1143 {
1144 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name,
1145 nc->queue_index,
1146 NetClientOptionsKind_lookup[nc->info->type],
1147 nc->info_str);
1148 }
1149
1150 RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,
1151 Error **errp)
1152 {
1153 NetClientState *nc;
1154 RxFilterInfoList *filter_list = NULL, *last_entry = NULL;
1155
1156 QTAILQ_FOREACH(nc, &net_clients, next) {
1157 RxFilterInfoList *entry;
1158 RxFilterInfo *info;
1159
1160 if (has_name && strcmp(nc->name, name) != 0) {
1161 continue;
1162 }
1163
1164 /* only query rx-filter information of NIC */
1165 if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {
1166 if (has_name) {
1167 error_setg(errp, "net client(%s) isn't a NIC", name);
1168 return NULL;
1169 }
1170 continue;
1171 }
1172
1173 if (nc->info->query_rx_filter) {
1174 info = nc->info->query_rx_filter(nc);
1175 entry = g_malloc0(sizeof(*entry));
1176 entry->value = info;
1177
1178 if (!filter_list) {
1179 filter_list = entry;
1180 } else {
1181 last_entry->next = entry;
1182 }
1183 last_entry = entry;
1184 } else if (has_name) {
1185 error_setg(errp, "net client(%s) doesn't support"
1186 " rx-filter querying", name);
1187 return NULL;
1188 }
1189
1190 if (has_name) {
1191 break;
1192 }
1193 }
1194
1195 if (filter_list == NULL && has_name) {
1196 error_setg(errp, "invalid net client name: %s", name);
1197 }
1198
1199 return filter_list;
1200 }
1201
1202 void hmp_info_network(Monitor *mon, const QDict *qdict)
1203 {
1204 NetClientState *nc, *peer;
1205 NetClientOptionsKind type;
1206
1207 net_hub_info(mon);
1208
1209 QTAILQ_FOREACH(nc, &net_clients, next) {
1210 peer = nc->peer;
1211 type = nc->info->type;
1212
1213 /* Skip if already printed in hub info */
1214 if (net_hub_id_for_client(nc, NULL) == 0) {
1215 continue;
1216 }
1217
1218 if (!peer || type == NET_CLIENT_OPTIONS_KIND_NIC) {
1219 print_net_client(mon, nc);
1220 } /* else it's a netdev connected to a NIC, printed with the NIC */
1221 if (peer && type == NET_CLIENT_OPTIONS_KIND_NIC) {
1222 monitor_printf(mon, " \\ ");
1223 print_net_client(mon, peer);
1224 }
1225 }
1226 }
1227
1228 void qmp_set_link(const char *name, bool up, Error **errp)
1229 {
1230 NetClientState *ncs[MAX_QUEUE_NUM];
1231 NetClientState *nc;
1232 int queues, i;
1233
1234 queues = qemu_find_net_clients_except(name, ncs,
1235 NET_CLIENT_OPTIONS_KIND_MAX,
1236 MAX_QUEUE_NUM);
1237
1238 if (queues == 0) {
1239 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1240 "Device '%s' not found", name);
1241 return;
1242 }
1243 nc = ncs[0];
1244
1245 for (i = 0; i < queues; i++) {
1246 ncs[i]->link_down = !up;
1247 }
1248
1249 if (nc->info->link_status_changed) {
1250 nc->info->link_status_changed(nc);
1251 }
1252
1253 if (nc->peer) {
1254 /* Change peer link only if the peer is NIC and then notify peer.
1255 * If the peer is a HUBPORT or a backend, we do not change the
1256 * link status.
1257 *
1258 * This behavior is compatible with qemu vlans where there could be
1259 * multiple clients that can still communicate with each other in
1260 * disconnected mode. For now maintain this compatibility.
1261 */
1262 if (nc->peer->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1263 for (i = 0; i < queues; i++) {
1264 ncs[i]->peer->link_down = !up;
1265 }
1266 }
1267 if (nc->peer->info->link_status_changed) {
1268 nc->peer->info->link_status_changed(nc->peer);
1269 }
1270 }
1271 }
1272
1273 static void net_vm_change_state_handler(void *opaque, int running,
1274 RunState state)
1275 {
1276 /* Complete all queued packets, to guarantee we don't modify
1277 * state later when VM is not running.
1278 */
1279 if (!running) {
1280 NetClientState *nc;
1281 NetClientState *tmp;
1282
1283 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) {
1284 qemu_flush_or_purge_queued_packets(nc, true);
1285 }
1286 }
1287 }
1288
1289 void net_cleanup(void)
1290 {
1291 NetClientState *nc;
1292
1293 /* We may del multiple entries during qemu_del_net_client(),
1294 * so QTAILQ_FOREACH_SAFE() is also not safe here.
1295 */
1296 while (!QTAILQ_EMPTY(&net_clients)) {
1297 nc = QTAILQ_FIRST(&net_clients);
1298 if (nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC) {
1299 qemu_del_nic(qemu_get_nic(nc));
1300 } else {
1301 qemu_del_net_client(nc);
1302 }
1303 }
1304
1305 qemu_del_vm_change_state_handler(net_change_state_entry);
1306 }
1307
1308 void net_check_clients(void)
1309 {
1310 NetClientState *nc;
1311 int i;
1312
1313 /* Don't warn about the default network setup that you get if
1314 * no command line -net or -netdev options are specified. There
1315 * are two cases that we would otherwise complain about:
1316 * (1) board doesn't support a NIC but the implicit "-net nic"
1317 * requested one
1318 * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"
1319 * sets up a nic that isn't connected to anything.
1320 */
1321 if (default_net) {
1322 return;
1323 }
1324
1325 net_hub_check_clients();
1326
1327 QTAILQ_FOREACH(nc, &net_clients, next) {
1328 if (!nc->peer) {
1329 fprintf(stderr, "Warning: %s %s has no peer\n",
1330 nc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ?
1331 "nic" : "netdev", nc->name);
1332 }
1333 }
1334
1335 /* Check that all NICs requested via -net nic actually got created.
1336 * NICs created via -device don't need to be checked here because
1337 * they are always instantiated.
1338 */
1339 for (i = 0; i < MAX_NICS; i++) {
1340 NICInfo *nd = &nd_table[i];
1341 if (nd->used && !nd->instantiated) {
1342 fprintf(stderr, "Warning: requested NIC (%s, model %s) "
1343 "was not created (not supported by this machine?)\n",
1344 nd->name ? nd->name : "anonymous",
1345 nd->model ? nd->model : "unspecified");
1346 }
1347 }
1348 }
1349
1350 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp)
1351 {
1352 Error *local_err = NULL;
1353
1354 net_client_init(opts, 0, &local_err);
1355 if (local_err) {
1356 error_report_err(local_err);
1357 return -1;
1358 }
1359
1360 return 0;
1361 }
1362
1363 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp)
1364 {
1365 Error *local_err = NULL;
1366 int ret;
1367
1368 ret = net_client_init(opts, 1, &local_err);
1369 if (local_err) {
1370 error_report_err(local_err);
1371 return -1;
1372 }
1373
1374 return ret;
1375 }
1376
1377 int net_init_clients(void)
1378 {
1379 QemuOptsList *net = qemu_find_opts("net");
1380
1381 if (default_net) {
1382 /* if no clients, we use a default config */
1383 qemu_opts_set(net, NULL, "type", "nic", &error_abort);
1384 #ifdef CONFIG_SLIRP
1385 qemu_opts_set(net, NULL, "type", "user", &error_abort);
1386 #endif
1387 }
1388
1389 net_change_state_entry =
1390 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL);
1391
1392 QTAILQ_INIT(&net_clients);
1393
1394 if (qemu_opts_foreach(qemu_find_opts("netdev"),
1395 net_init_netdev, NULL, NULL)) {
1396 return -1;
1397 }
1398
1399 if (qemu_opts_foreach(net, net_init_client, NULL, NULL)) {
1400 return -1;
1401 }
1402
1403 return 0;
1404 }
1405
1406 int net_client_parse(QemuOptsList *opts_list, const char *optarg)
1407 {
1408 #if defined(CONFIG_SLIRP)
1409 int ret;
1410 if (net_slirp_parse_legacy(opts_list, optarg, &ret)) {
1411 return ret;
1412 }
1413 #endif
1414
1415 if (!qemu_opts_parse_noisily(opts_list, optarg, true)) {
1416 return -1;
1417 }
1418
1419 default_net = 0;
1420 return 0;
1421 }
1422
1423 /* From FreeBSD */
1424 /* XXX: optimize */
1425 unsigned compute_mcast_idx(const uint8_t *ep)
1426 {
1427 uint32_t crc;
1428 int carry, i, j;
1429 uint8_t b;
1430
1431 crc = 0xffffffff;
1432 for (i = 0; i < 6; i++) {
1433 b = *ep++;
1434 for (j = 0; j < 8; j++) {
1435 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01);
1436 crc <<= 1;
1437 b >>= 1;
1438 if (carry) {
1439 crc = ((crc ^ POLYNOMIAL) | carry);
1440 }
1441 }
1442 }
1443 return crc >> 26;
1444 }
1445
1446 QemuOptsList qemu_netdev_opts = {
1447 .name = "netdev",
1448 .implied_opt_name = "type",
1449 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head),
1450 .desc = {
1451 /*
1452 * no elements => accept any params
1453 * validation will happen later
1454 */
1455 { /* end of list */ }
1456 },
1457 };
1458
1459 QemuOptsList qemu_net_opts = {
1460 .name = "net",
1461 .implied_opt_name = "type",
1462 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head),
1463 .desc = {
1464 /*
1465 * no elements => accept any params
1466 * validation will happen later
1467 */
1468 { /* end of list */ }
1469 },
1470 };