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 25 #include "qemu/osdep.h" 26 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" 34 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 "qobject/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 "system/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" 59 #include "standard-headers/linux/virtio_net.h" 60 61 /* Net bridge is currently not supported for W32. */ 62 #if !defined(_WIN32) 63 # define CONFIG_NET_BRIDGE 64 #endif 65 66 static VMChangeStateEntry *net_change_state_entry; 67 NetClientStateList net_clients; 68 69 typedef struct NetdevQueueEntry { 70 Netdev *nd; 71 Location loc; 72 QSIMPLEQ_ENTRY(NetdevQueueEntry) entry; 73 } NetdevQueueEntry; 74 75 typedef QSIMPLEQ_HEAD(, NetdevQueueEntry) NetdevQueue; 76 77 static NetdevQueue nd_queue = QSIMPLEQ_HEAD_INITIALIZER(nd_queue); 78 79 static GHashTable *nic_model_help; 80 81 static int nb_nics; 82 static NICInfo nd_table[MAX_NICS]; 83 84 /***********************************************************/ 85 /* network device redirectors */ 86 87 int convert_host_port(struct sockaddr_in *saddr, const char *host, 88 const char *port, Error **errp) 89 { 90 struct hostent *he; 91 const char *r; 92 long p; 93 94 memset(saddr, 0, sizeof(*saddr)); 95 96 saddr->sin_family = AF_INET; 97 if (host[0] == '\0') { 98 saddr->sin_addr.s_addr = 0; 99 } else { 100 if (qemu_isdigit(host[0])) { 101 if (!inet_aton(host, &saddr->sin_addr)) { 102 error_setg(errp, "host address '%s' is not a valid " 103 "IPv4 address", host); 104 return -1; 105 } 106 } else { 107 he = gethostbyname(host); 108 if (he == NULL) { 109 error_setg(errp, "can't resolve host address '%s'", host); 110 return -1; 111 } 112 saddr->sin_addr = *(struct in_addr *)he->h_addr; 113 } 114 } 115 if (qemu_strtol(port, &r, 0, &p) != 0) { 116 error_setg(errp, "port number '%s' is invalid", port); 117 return -1; 118 } 119 saddr->sin_port = htons(p); 120 return 0; 121 } 122 123 int parse_host_port(struct sockaddr_in *saddr, const char *str, 124 Error **errp) 125 { 126 gchar **substrings; 127 int ret; 128 129 substrings = g_strsplit(str, ":", 2); 130 if (!substrings || !substrings[0] || !substrings[1]) { 131 error_setg(errp, "host address '%s' doesn't contain ':' " 132 "separating host from port", str); 133 ret = -1; 134 goto out; 135 } 136 137 ret = convert_host_port(saddr, substrings[0], substrings[1], errp); 138 139 out: 140 g_strfreev(substrings); 141 return ret; 142 } 143 144 char *qemu_mac_strdup_printf(const uint8_t *macaddr) 145 { 146 return g_strdup_printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x", 147 macaddr[0], macaddr[1], macaddr[2], 148 macaddr[3], macaddr[4], macaddr[5]); 149 } 150 151 void qemu_set_info_str(NetClientState *nc, const char *fmt, ...) 152 { 153 va_list ap; 154 155 va_start(ap, fmt); 156 vsnprintf(nc->info_str, sizeof(nc->info_str), fmt, ap); 157 va_end(ap); 158 } 159 160 void qemu_format_nic_info_str(NetClientState *nc, uint8_t macaddr[6]) 161 { 162 qemu_set_info_str(nc, "model=%s,macaddr=%02x:%02x:%02x:%02x:%02x:%02x", 163 nc->model, macaddr[0], macaddr[1], macaddr[2], 164 macaddr[3], macaddr[4], macaddr[5]); 165 } 166 167 static int mac_table[256] = {0}; 168 169 static void qemu_macaddr_set_used(MACAddr *macaddr) 170 { 171 int index; 172 173 for (index = 0x56; index < 0xFF; index++) { 174 if (macaddr->a[5] == index) { 175 mac_table[index]++; 176 } 177 } 178 } 179 180 static void qemu_macaddr_set_free(MACAddr *macaddr) 181 { 182 int index; 183 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } }; 184 185 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) { 186 return; 187 } 188 for (index = 0x56; index < 0xFF; index++) { 189 if (macaddr->a[5] == index) { 190 mac_table[index]--; 191 } 192 } 193 } 194 195 static int qemu_macaddr_get_free(void) 196 { 197 int index; 198 199 for (index = 0x56; index < 0xFF; index++) { 200 if (mac_table[index] == 0) { 201 return index; 202 } 203 } 204 205 return -1; 206 } 207 208 void qemu_macaddr_default_if_unset(MACAddr *macaddr) 209 { 210 static const MACAddr zero = { .a = { 0,0,0,0,0,0 } }; 211 static const MACAddr base = { .a = { 0x52, 0x54, 0x00, 0x12, 0x34, 0 } }; 212 213 if (memcmp(macaddr, &zero, sizeof(zero)) != 0) { 214 if (memcmp(macaddr->a, &base.a, (sizeof(base.a) - 1)) != 0) { 215 return; 216 } else { 217 qemu_macaddr_set_used(macaddr); 218 return; 219 } 220 } 221 222 macaddr->a[0] = 0x52; 223 macaddr->a[1] = 0x54; 224 macaddr->a[2] = 0x00; 225 macaddr->a[3] = 0x12; 226 macaddr->a[4] = 0x34; 227 macaddr->a[5] = qemu_macaddr_get_free(); 228 qemu_macaddr_set_used(macaddr); 229 } 230 231 /** 232 * Generate a name for net client 233 * 234 * Only net clients created with the legacy -net option and NICs need this. 235 */ 236 static char *assign_name(NetClientState *nc1, const char *model) 237 { 238 NetClientState *nc; 239 int id = 0; 240 241 QTAILQ_FOREACH(nc, &net_clients, next) { 242 if (nc == nc1) { 243 continue; 244 } 245 if (strcmp(nc->model, model) == 0) { 246 id++; 247 } 248 } 249 250 return g_strdup_printf("%s.%d", model, id); 251 } 252 253 static void qemu_net_client_destructor(NetClientState *nc) 254 { 255 g_free(nc); 256 } 257 static ssize_t qemu_deliver_packet_iov(NetClientState *sender, 258 unsigned flags, 259 const struct iovec *iov, 260 int iovcnt, 261 void *opaque); 262 263 static void qemu_net_client_setup(NetClientState *nc, 264 NetClientInfo *info, 265 NetClientState *peer, 266 const char *model, 267 const char *name, 268 NetClientDestructor *destructor, 269 bool is_datapath) 270 { 271 nc->info = info; 272 nc->model = g_strdup(model); 273 if (name) { 274 nc->name = g_strdup(name); 275 } else { 276 nc->name = assign_name(nc, model); 277 } 278 279 if (peer) { 280 assert(!peer->peer); 281 nc->peer = peer; 282 peer->peer = nc; 283 } 284 QTAILQ_INSERT_TAIL(&net_clients, nc, next); 285 286 nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc); 287 nc->destructor = destructor; 288 nc->is_datapath = is_datapath; 289 QTAILQ_INIT(&nc->filters); 290 } 291 292 NetClientState *qemu_new_net_client(NetClientInfo *info, 293 NetClientState *peer, 294 const char *model, 295 const char *name) 296 { 297 NetClientState *nc; 298 299 assert(info->size >= sizeof(NetClientState)); 300 301 nc = g_malloc0(info->size); 302 qemu_net_client_setup(nc, info, peer, model, name, 303 qemu_net_client_destructor, true); 304 305 return nc; 306 } 307 308 NetClientState *qemu_new_net_control_client(NetClientInfo *info, 309 NetClientState *peer, 310 const char *model, 311 const char *name) 312 { 313 NetClientState *nc; 314 315 assert(info->size >= sizeof(NetClientState)); 316 317 nc = g_malloc0(info->size); 318 qemu_net_client_setup(nc, info, peer, model, name, 319 qemu_net_client_destructor, false); 320 321 return nc; 322 } 323 324 NICState *qemu_new_nic(NetClientInfo *info, 325 NICConf *conf, 326 const char *model, 327 const char *name, 328 MemReentrancyGuard *reentrancy_guard, 329 void *opaque) 330 { 331 NetClientState **peers = conf->peers.ncs; 332 NICState *nic; 333 int i, queues = MAX(1, conf->peers.queues); 334 335 assert(info->type == NET_CLIENT_DRIVER_NIC); 336 assert(info->size >= sizeof(NICState)); 337 338 nic = g_malloc0(info->size + sizeof(NetClientState) * queues); 339 nic->ncs = (void *)nic + info->size; 340 nic->conf = conf; 341 nic->reentrancy_guard = reentrancy_guard, 342 nic->opaque = opaque; 343 344 for (i = 0; i < queues; i++) { 345 qemu_net_client_setup(&nic->ncs[i], info, peers[i], model, name, 346 NULL, true); 347 nic->ncs[i].queue_index = i; 348 } 349 350 return nic; 351 } 352 353 NetClientState *qemu_get_subqueue(NICState *nic, int queue_index) 354 { 355 return nic->ncs + queue_index; 356 } 357 358 NetClientState *qemu_get_queue(NICState *nic) 359 { 360 return qemu_get_subqueue(nic, 0); 361 } 362 363 NICState *qemu_get_nic(NetClientState *nc) 364 { 365 NetClientState *nc0 = nc - nc->queue_index; 366 367 return (NICState *)((void *)nc0 - nc->info->size); 368 } 369 370 void *qemu_get_nic_opaque(NetClientState *nc) 371 { 372 NICState *nic = qemu_get_nic(nc); 373 374 return nic->opaque; 375 } 376 377 NetClientState *qemu_get_peer(NetClientState *nc, int queue_index) 378 { 379 assert(nc != NULL); 380 NetClientState *ncs = nc + queue_index; 381 return ncs->peer; 382 } 383 384 static void qemu_cleanup_net_client(NetClientState *nc, 385 bool remove_from_net_clients) 386 { 387 if (remove_from_net_clients) { 388 QTAILQ_REMOVE(&net_clients, nc, next); 389 } 390 391 if (nc->info->cleanup) { 392 nc->info->cleanup(nc); 393 } 394 } 395 396 static void qemu_free_net_client(NetClientState *nc) 397 { 398 if (nc->incoming_queue) { 399 qemu_del_net_queue(nc->incoming_queue); 400 } 401 if (nc->peer) { 402 nc->peer->peer = NULL; 403 } 404 g_free(nc->name); 405 g_free(nc->model); 406 if (nc->destructor) { 407 nc->destructor(nc); 408 } 409 } 410 411 void qemu_del_net_client(NetClientState *nc) 412 { 413 NetClientState *ncs[MAX_QUEUE_NUM]; 414 int queues, i; 415 NetFilterState *nf, *next; 416 417 assert(nc->info->type != NET_CLIENT_DRIVER_NIC); 418 419 /* If the NetClientState belongs to a multiqueue backend, we will change all 420 * other NetClientStates also. 421 */ 422 queues = qemu_find_net_clients_except(nc->name, ncs, 423 NET_CLIENT_DRIVER_NIC, 424 MAX_QUEUE_NUM); 425 assert(queues != 0); 426 427 QTAILQ_FOREACH_SAFE(nf, &nc->filters, next, next) { 428 object_unparent(OBJECT(nf)); 429 } 430 431 /* 432 * If there is a peer NIC, transfer ownership to it. Delete the client 433 * from net_client list but do not cleanup nor free. This way NIC can 434 * still access to members of the backend. 435 * 436 * The cleanup and free will be done when the NIC is free. 437 */ 438 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_NIC) { 439 NICState *nic = qemu_get_nic(nc->peer); 440 if (nic->peer_deleted) { 441 return; 442 } 443 nic->peer_deleted = true; 444 445 for (i = 0; i < queues; i++) { 446 ncs[i]->peer->link_down = true; 447 QTAILQ_REMOVE(&net_clients, ncs[i], next); 448 } 449 450 if (nc->peer->info->link_status_changed) { 451 nc->peer->info->link_status_changed(nc->peer); 452 } 453 454 return; 455 } 456 457 for (i = 0; i < queues; i++) { 458 qemu_cleanup_net_client(ncs[i], true); 459 qemu_free_net_client(ncs[i]); 460 } 461 } 462 463 void qemu_del_nic(NICState *nic) 464 { 465 int i, queues = MAX(nic->conf->peers.queues, 1); 466 467 qemu_macaddr_set_free(&nic->conf->macaddr); 468 469 for (i = 0; i < queues; i++) { 470 NetClientState *nc = qemu_get_subqueue(nic, i); 471 /* 472 * If this is a peer NIC and peer has already been deleted, clean it up 473 * and free it now. 474 */ 475 if (nic->peer_deleted) { 476 qemu_cleanup_net_client(nc->peer, false); 477 qemu_free_net_client(nc->peer); 478 } else if (nc->peer) { 479 /* if there are RX packets pending, complete them */ 480 qemu_purge_queued_packets(nc->peer); 481 } 482 } 483 484 for (i = queues - 1; i >= 0; i--) { 485 NetClientState *nc = qemu_get_subqueue(nic, i); 486 487 qemu_cleanup_net_client(nc, true); 488 qemu_free_net_client(nc); 489 } 490 491 g_free(nic); 492 } 493 494 void qemu_foreach_nic(qemu_nic_foreach func, void *opaque) 495 { 496 NetClientState *nc; 497 498 QTAILQ_FOREACH(nc, &net_clients, next) { 499 if (nc->info->type == NET_CLIENT_DRIVER_NIC) { 500 if (nc->queue_index == 0) { 501 func(qemu_get_nic(nc), opaque); 502 } 503 } 504 } 505 } 506 507 bool qemu_has_ufo(NetClientState *nc) 508 { 509 if (!nc || !nc->info->has_ufo) { 510 return false; 511 } 512 513 return nc->info->has_ufo(nc); 514 } 515 516 bool qemu_has_uso(NetClientState *nc) 517 { 518 if (!nc || !nc->info->has_uso) { 519 return false; 520 } 521 522 return nc->info->has_uso(nc); 523 } 524 525 bool qemu_has_vnet_hdr(NetClientState *nc) 526 { 527 if (!nc || !nc->info->has_vnet_hdr) { 528 return false; 529 } 530 531 return nc->info->has_vnet_hdr(nc); 532 } 533 534 bool qemu_has_vnet_hdr_len(NetClientState *nc, int len) 535 { 536 if (!nc || !nc->info->has_vnet_hdr_len) { 537 return false; 538 } 539 540 return nc->info->has_vnet_hdr_len(nc, len); 541 } 542 543 void qemu_set_offload(NetClientState *nc, int csum, int tso4, int tso6, 544 int ecn, int ufo, int uso4, int uso6) 545 { 546 if (!nc || !nc->info->set_offload) { 547 return; 548 } 549 550 nc->info->set_offload(nc, csum, tso4, tso6, ecn, ufo, uso4, uso6); 551 } 552 553 int qemu_get_vnet_hdr_len(NetClientState *nc) 554 { 555 if (!nc) { 556 return 0; 557 } 558 559 return nc->vnet_hdr_len; 560 } 561 562 void qemu_set_vnet_hdr_len(NetClientState *nc, int len) 563 { 564 if (!nc || !nc->info->set_vnet_hdr_len) { 565 return; 566 } 567 568 assert(len == sizeof(struct virtio_net_hdr_mrg_rxbuf) || 569 len == sizeof(struct virtio_net_hdr) || 570 len == sizeof(struct virtio_net_hdr_v1_hash)); 571 572 nc->vnet_hdr_len = len; 573 nc->info->set_vnet_hdr_len(nc, len); 574 } 575 576 bool qemu_get_vnet_hash_supported_types(NetClientState *nc, uint32_t *types) 577 { 578 if (!nc || !nc->info->get_vnet_hash_supported_types) { 579 return false; 580 } 581 582 return nc->info->get_vnet_hash_supported_types(nc, types); 583 } 584 585 int qemu_set_vnet_le(NetClientState *nc, bool is_le) 586 { 587 #if HOST_BIG_ENDIAN 588 if (!nc || !nc->info->set_vnet_le) { 589 return -ENOSYS; 590 } 591 592 return nc->info->set_vnet_le(nc, is_le); 593 #else 594 return 0; 595 #endif 596 } 597 598 int qemu_set_vnet_be(NetClientState *nc, bool is_be) 599 { 600 #if HOST_BIG_ENDIAN 601 return 0; 602 #else 603 if (!nc || !nc->info->set_vnet_be) { 604 return -ENOSYS; 605 } 606 607 return nc->info->set_vnet_be(nc, is_be); 608 #endif 609 } 610 611 int qemu_can_receive_packet(NetClientState *nc) 612 { 613 if (nc->receive_disabled) { 614 return 0; 615 } else if (nc->info->can_receive && 616 !nc->info->can_receive(nc)) { 617 return 0; 618 } 619 return 1; 620 } 621 622 int qemu_can_send_packet(NetClientState *sender) 623 { 624 int vm_running = runstate_is_running(); 625 626 if (!vm_running) { 627 return 0; 628 } 629 630 if (!sender->peer) { 631 return 1; 632 } 633 634 return qemu_can_receive_packet(sender->peer); 635 } 636 637 static ssize_t filter_receive_iov(NetClientState *nc, 638 NetFilterDirection direction, 639 NetClientState *sender, 640 unsigned flags, 641 const struct iovec *iov, 642 int iovcnt, 643 NetPacketSent *sent_cb) 644 { 645 ssize_t ret = 0; 646 NetFilterState *nf = NULL; 647 648 if (direction == NET_FILTER_DIRECTION_TX) { 649 QTAILQ_FOREACH(nf, &nc->filters, next) { 650 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov, 651 iovcnt, sent_cb); 652 if (ret) { 653 return ret; 654 } 655 } 656 } else { 657 QTAILQ_FOREACH_REVERSE(nf, &nc->filters, next) { 658 ret = qemu_netfilter_receive(nf, direction, sender, flags, iov, 659 iovcnt, sent_cb); 660 if (ret) { 661 return ret; 662 } 663 } 664 } 665 666 return ret; 667 } 668 669 static ssize_t filter_receive(NetClientState *nc, 670 NetFilterDirection direction, 671 NetClientState *sender, 672 unsigned flags, 673 const uint8_t *data, 674 size_t size, 675 NetPacketSent *sent_cb) 676 { 677 struct iovec iov = { 678 .iov_base = (void *)data, 679 .iov_len = size 680 }; 681 682 return filter_receive_iov(nc, direction, sender, flags, &iov, 1, sent_cb); 683 } 684 685 void qemu_purge_queued_packets(NetClientState *nc) 686 { 687 if (!nc->peer) { 688 return; 689 } 690 691 qemu_net_queue_purge(nc->peer->incoming_queue, nc); 692 } 693 694 void qemu_flush_or_purge_queued_packets(NetClientState *nc, bool purge) 695 { 696 nc->receive_disabled = 0; 697 698 if (nc->peer && nc->peer->info->type == NET_CLIENT_DRIVER_HUBPORT) { 699 if (net_hub_flush(nc->peer)) { 700 qemu_notify_event(); 701 } 702 } 703 if (qemu_net_queue_flush(nc->incoming_queue)) { 704 /* We emptied the queue successfully, signal to the IO thread to repoll 705 * the file descriptor (for tap, for example). 706 */ 707 qemu_notify_event(); 708 } else if (purge) { 709 /* Unable to empty the queue, purge remaining packets */ 710 qemu_net_queue_purge(nc->incoming_queue, nc->peer); 711 } 712 } 713 714 void qemu_flush_queued_packets(NetClientState *nc) 715 { 716 qemu_flush_or_purge_queued_packets(nc, false); 717 } 718 719 static ssize_t qemu_send_packet_async_with_flags(NetClientState *sender, 720 unsigned flags, 721 const uint8_t *buf, int size, 722 NetPacketSent *sent_cb) 723 { 724 NetQueue *queue; 725 int ret; 726 727 #ifdef DEBUG_NET 728 printf("qemu_send_packet_async:\n"); 729 qemu_hexdump(stdout, "net", buf, size); 730 #endif 731 732 if (sender->link_down || !sender->peer) { 733 return size; 734 } 735 736 /* Let filters handle the packet first */ 737 ret = filter_receive(sender, NET_FILTER_DIRECTION_TX, 738 sender, flags, buf, size, sent_cb); 739 if (ret) { 740 return ret; 741 } 742 743 ret = filter_receive(sender->peer, NET_FILTER_DIRECTION_RX, 744 sender, flags, buf, size, sent_cb); 745 if (ret) { 746 return ret; 747 } 748 749 queue = sender->peer->incoming_queue; 750 751 return qemu_net_queue_send(queue, sender, flags, buf, size, sent_cb); 752 } 753 754 ssize_t qemu_send_packet_async(NetClientState *sender, 755 const uint8_t *buf, int size, 756 NetPacketSent *sent_cb) 757 { 758 return qemu_send_packet_async_with_flags(sender, QEMU_NET_PACKET_FLAG_NONE, 759 buf, size, sent_cb); 760 } 761 762 ssize_t qemu_send_packet(NetClientState *nc, const uint8_t *buf, int size) 763 { 764 return qemu_send_packet_async(nc, buf, size, NULL); 765 } 766 767 ssize_t qemu_receive_packet(NetClientState *nc, const uint8_t *buf, int size) 768 { 769 if (!qemu_can_receive_packet(nc)) { 770 return 0; 771 } 772 773 return qemu_net_queue_receive(nc->incoming_queue, buf, size); 774 } 775 776 ssize_t qemu_send_packet_raw(NetClientState *nc, const uint8_t *buf, int size) 777 { 778 return qemu_send_packet_async_with_flags(nc, QEMU_NET_PACKET_FLAG_RAW, 779 buf, size, NULL); 780 } 781 782 static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov, 783 int iovcnt, unsigned flags) 784 { 785 uint8_t *buf = NULL; 786 uint8_t *buffer; 787 size_t offset; 788 ssize_t ret; 789 790 if (iovcnt == 1) { 791 buffer = iov[0].iov_base; 792 offset = iov[0].iov_len; 793 } else { 794 offset = iov_size(iov, iovcnt); 795 if (offset > NET_BUFSIZE) { 796 return -1; 797 } 798 buf = g_malloc(offset); 799 buffer = buf; 800 offset = iov_to_buf(iov, iovcnt, 0, buf, offset); 801 } 802 803 ret = nc->info->receive(nc, buffer, offset); 804 805 g_free(buf); 806 return ret; 807 } 808 809 static ssize_t qemu_deliver_packet_iov(NetClientState *sender, 810 unsigned flags, 811 const struct iovec *iov, 812 int iovcnt, 813 void *opaque) 814 { 815 MemReentrancyGuard *owned_reentrancy_guard; 816 NetClientState *nc = opaque; 817 int ret; 818 struct virtio_net_hdr_v1_hash vnet_hdr = { }; 819 g_autofree struct iovec *iov_copy = NULL; 820 821 822 if (nc->link_down) { 823 return iov_size(iov, iovcnt); 824 } 825 826 if (nc->receive_disabled) { 827 return 0; 828 } 829 830 if (nc->info->type != NET_CLIENT_DRIVER_NIC || 831 qemu_get_nic(nc)->reentrancy_guard->engaged_in_io) { 832 owned_reentrancy_guard = NULL; 833 } else { 834 owned_reentrancy_guard = qemu_get_nic(nc)->reentrancy_guard; 835 owned_reentrancy_guard->engaged_in_io = true; 836 } 837 838 if ((flags & QEMU_NET_PACKET_FLAG_RAW) && nc->vnet_hdr_len) { 839 iov_copy = g_new(struct iovec, iovcnt + 1); 840 iov_copy[0].iov_base = &vnet_hdr; 841 iov_copy[0].iov_len = nc->vnet_hdr_len; 842 memcpy(&iov_copy[1], iov, iovcnt * sizeof(*iov)); 843 iov = iov_copy; 844 iovcnt++; 845 } 846 847 if (nc->info->receive_iov) { 848 ret = nc->info->receive_iov(nc, iov, iovcnt); 849 } else { 850 ret = nc_sendv_compat(nc, iov, iovcnt, flags); 851 } 852 853 if (owned_reentrancy_guard) { 854 owned_reentrancy_guard->engaged_in_io = false; 855 } 856 857 if (ret == 0) { 858 nc->receive_disabled = 1; 859 } 860 861 return ret; 862 } 863 864 ssize_t qemu_sendv_packet_async(NetClientState *sender, 865 const struct iovec *iov, int iovcnt, 866 NetPacketSent *sent_cb) 867 { 868 NetQueue *queue; 869 size_t size = iov_size(iov, iovcnt); 870 int ret; 871 872 if (size > NET_BUFSIZE) { 873 return size; 874 } 875 876 if (sender->link_down || !sender->peer) { 877 return size; 878 } 879 880 /* Let filters handle the packet first */ 881 ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender, 882 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb); 883 if (ret) { 884 return ret; 885 } 886 887 ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender, 888 QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb); 889 if (ret) { 890 return ret; 891 } 892 893 queue = sender->peer->incoming_queue; 894 895 return qemu_net_queue_send_iov(queue, sender, 896 QEMU_NET_PACKET_FLAG_NONE, 897 iov, iovcnt, sent_cb); 898 } 899 900 ssize_t 901 qemu_sendv_packet(NetClientState *nc, const struct iovec *iov, int iovcnt) 902 { 903 return qemu_sendv_packet_async(nc, iov, iovcnt, NULL); 904 } 905 906 NetClientState *qemu_find_netdev(const char *id) 907 { 908 NetClientState *nc; 909 910 QTAILQ_FOREACH(nc, &net_clients, next) { 911 if (nc->info->type == NET_CLIENT_DRIVER_NIC) 912 continue; 913 if (!strcmp(nc->name, id)) { 914 return nc; 915 } 916 } 917 918 return NULL; 919 } 920 921 int qemu_find_net_clients_except(const char *id, NetClientState **ncs, 922 NetClientDriver type, int max) 923 { 924 NetClientState *nc; 925 int ret = 0; 926 927 QTAILQ_FOREACH(nc, &net_clients, next) { 928 if (nc->info->type == type) { 929 continue; 930 } 931 if (!id || !strcmp(nc->name, id)) { 932 if (ret < max) { 933 ncs[ret] = nc; 934 } 935 ret++; 936 } 937 } 938 939 return ret; 940 } 941 942 static int nic_get_free_idx(void) 943 { 944 int index; 945 946 for (index = 0; index < MAX_NICS; index++) 947 if (!nd_table[index].used) 948 return index; 949 return -1; 950 } 951 952 GPtrArray *qemu_get_nic_models(const char *device_type) 953 { 954 GPtrArray *nic_models = g_ptr_array_new(); 955 GSList *list = object_class_get_list_sorted(device_type, false); 956 957 while (list) { 958 DeviceClass *dc = OBJECT_CLASS_CHECK(DeviceClass, list->data, 959 TYPE_DEVICE); 960 GSList *next; 961 if (test_bit(DEVICE_CATEGORY_NETWORK, dc->categories) && 962 dc->user_creatable) { 963 const char *name = object_class_get_name(list->data); 964 /* 965 * A network device might also be something else than a NIC, see 966 * e.g. the "rocker" device. Thus we have to look for the "netdev" 967 * property, too. Unfortunately, some devices like virtio-net only 968 * create this property during instance_init, so we have to create 969 * a temporary instance here to be able to check it. 970 */ 971 Object *obj = object_new_with_class(OBJECT_CLASS(dc)); 972 if (object_property_find(obj, "netdev")) { 973 g_ptr_array_add(nic_models, (gpointer)name); 974 } 975 object_unref(obj); 976 } 977 next = list->next; 978 g_slist_free_1(list); 979 list = next; 980 } 981 g_ptr_array_add(nic_models, NULL); 982 983 return nic_models; 984 } 985 986 static int net_init_nic(const Netdev *netdev, const char *name, 987 NetClientState *peer, Error **errp) 988 { 989 int idx; 990 NICInfo *nd; 991 const NetLegacyNicOptions *nic; 992 993 assert(netdev->type == NET_CLIENT_DRIVER_NIC); 994 nic = &netdev->u.nic; 995 996 idx = nic_get_free_idx(); 997 if (idx == -1 || nb_nics >= MAX_NICS) { 998 error_setg(errp, "too many NICs"); 999 return -1; 1000 } 1001 1002 nd = &nd_table[idx]; 1003 1004 memset(nd, 0, sizeof(*nd)); 1005 1006 if (nic->netdev) { 1007 nd->netdev = qemu_find_netdev(nic->netdev); 1008 if (!nd->netdev) { 1009 error_setg(errp, "netdev '%s' not found", nic->netdev); 1010 return -1; 1011 } 1012 } else { 1013 assert(peer); 1014 nd->netdev = peer; 1015 } 1016 nd->name = g_strdup(name); 1017 if (nic->model) { 1018 nd->model = g_strdup(nic->model); 1019 } 1020 if (nic->addr) { 1021 nd->devaddr = g_strdup(nic->addr); 1022 } 1023 1024 if (nic->macaddr && 1025 net_parse_macaddr(nd->macaddr.a, nic->macaddr) < 0) { 1026 error_setg(errp, "invalid syntax for ethernet address"); 1027 return -1; 1028 } 1029 if (nic->macaddr && 1030 is_multicast_ether_addr(nd->macaddr.a)) { 1031 error_setg(errp, 1032 "NIC cannot have multicast MAC address (odd 1st byte)"); 1033 return -1; 1034 } 1035 qemu_macaddr_default_if_unset(&nd->macaddr); 1036 1037 if (nic->has_vectors) { 1038 if (nic->vectors > 0x7ffffff) { 1039 error_setg(errp, "invalid # of vectors: %"PRIu32, nic->vectors); 1040 return -1; 1041 } 1042 nd->nvectors = nic->vectors; 1043 } else { 1044 nd->nvectors = DEV_NVECTORS_UNSPECIFIED; 1045 } 1046 1047 nd->used = 1; 1048 nb_nics++; 1049 1050 return idx; 1051 } 1052 1053 static gboolean add_nic_result(gpointer key, gpointer value, gpointer user_data) 1054 { 1055 GPtrArray *results = user_data; 1056 GPtrArray *alias_list = value; 1057 const char *model = key; 1058 char *result; 1059 1060 if (!alias_list) { 1061 result = g_strdup(model); 1062 } else { 1063 GString *result_str = g_string_new(model); 1064 int i; 1065 1066 g_string_append(result_str, " (aka "); 1067 for (i = 0; i < alias_list->len; i++) { 1068 if (i) { 1069 g_string_append(result_str, ", "); 1070 } 1071 g_string_append(result_str, alias_list->pdata[i]); 1072 } 1073 g_string_append(result_str, ")"); 1074 result = result_str->str; 1075 g_string_free(result_str, false); 1076 g_ptr_array_unref(alias_list); 1077 } 1078 g_ptr_array_add(results, result); 1079 return true; 1080 } 1081 1082 static int model_cmp(char **a, char **b) 1083 { 1084 return strcmp(*a, *b); 1085 } 1086 1087 static void show_nic_models(void) 1088 { 1089 GPtrArray *results = g_ptr_array_new(); 1090 int i; 1091 1092 g_hash_table_foreach_remove(nic_model_help, add_nic_result, results); 1093 g_ptr_array_sort(results, (GCompareFunc)model_cmp); 1094 1095 printf("Available NIC models for this configuration:\n"); 1096 for (i = 0 ; i < results->len; i++) { 1097 printf("%s\n", (char *)results->pdata[i]); 1098 } 1099 g_hash_table_unref(nic_model_help); 1100 nic_model_help = NULL; 1101 } 1102 1103 static void add_nic_model_help(const char *model, const char *alias) 1104 { 1105 GPtrArray *alias_list = NULL; 1106 1107 if (g_hash_table_lookup_extended(nic_model_help, model, NULL, 1108 (gpointer *)&alias_list)) { 1109 /* Already exists, no alias to add: return */ 1110 if (!alias) { 1111 return; 1112 } 1113 if (alias_list) { 1114 /* Check if this alias is already in the list. Add if not. */ 1115 if (!g_ptr_array_find_with_equal_func(alias_list, alias, 1116 g_str_equal, NULL)) { 1117 g_ptr_array_add(alias_list, g_strdup(alias)); 1118 } 1119 return; 1120 } 1121 } 1122 /* Either this model wasn't in the list already, or a first alias added */ 1123 if (alias) { 1124 alias_list = g_ptr_array_new(); 1125 g_ptr_array_set_free_func(alias_list, g_free); 1126 g_ptr_array_add(alias_list, g_strdup(alias)); 1127 } 1128 g_hash_table_replace(nic_model_help, g_strdup(model), alias_list); 1129 } 1130 1131 NICInfo *qemu_find_nic_info(const char *typename, bool match_default, 1132 const char *alias) 1133 { 1134 NICInfo *nd; 1135 int i; 1136 1137 if (nic_model_help) { 1138 add_nic_model_help(typename, alias); 1139 } 1140 1141 for (i = 0; i < nb_nics; i++) { 1142 nd = &nd_table[i]; 1143 1144 if (!nd->used || nd->instantiated) { 1145 continue; 1146 } 1147 1148 if ((match_default && !nd->model) || !g_strcmp0(nd->model, typename) 1149 || (alias && !g_strcmp0(nd->model, alias))) { 1150 return nd; 1151 } 1152 } 1153 return NULL; 1154 } 1155 1156 static bool is_nic_model_help_option(const char *model) 1157 { 1158 if (model && is_help_option(model)) { 1159 /* 1160 * Trigger the help output by instantiating the hash table which 1161 * will gather tha available models as they get registered. 1162 */ 1163 if (!nic_model_help) { 1164 nic_model_help = g_hash_table_new_full(g_str_hash, g_str_equal, 1165 g_free, NULL); 1166 } 1167 return true; 1168 } 1169 return false; 1170 } 1171 1172 /* "I have created a device. Please configure it if you can" */ 1173 bool qemu_configure_nic_device(DeviceState *dev, bool match_default, 1174 const char *alias) 1175 { 1176 NICInfo *nd = qemu_find_nic_info(object_get_typename(OBJECT(dev)), 1177 match_default, alias); 1178 1179 if (nd) { 1180 qdev_set_nic_properties(dev, nd); 1181 return true; 1182 } 1183 return false; 1184 } 1185 1186 /* "Please create a device, if you have a configuration for it" */ 1187 DeviceState *qemu_create_nic_device(const char *typename, bool match_default, 1188 const char *alias) 1189 { 1190 NICInfo *nd = qemu_find_nic_info(typename, match_default, alias); 1191 DeviceState *dev; 1192 1193 if (!nd) { 1194 return NULL; 1195 } 1196 1197 dev = qdev_new(typename); 1198 qdev_set_nic_properties(dev, nd); 1199 return dev; 1200 } 1201 1202 void qemu_create_nic_bus_devices(BusState *bus, const char *parent_type, 1203 const char *default_model, 1204 const char *alias, const char *alias_target) 1205 { 1206 GPtrArray *nic_models = qemu_get_nic_models(parent_type); 1207 const char *model; 1208 DeviceState *dev; 1209 NICInfo *nd; 1210 int i; 1211 1212 if (nic_model_help) { 1213 if (alias_target) { 1214 add_nic_model_help(alias_target, alias); 1215 } 1216 for (i = 0; i < nic_models->len - 1; i++) { 1217 add_nic_model_help(nic_models->pdata[i], NULL); 1218 } 1219 } 1220 1221 /* Drop the NULL terminator which would make g_str_equal() unhappy */ 1222 nic_models->len--; 1223 1224 for (i = 0; i < nb_nics; i++) { 1225 nd = &nd_table[i]; 1226 1227 if (!nd->used || nd->instantiated) { 1228 continue; 1229 } 1230 1231 model = nd->model ? nd->model : default_model; 1232 if (!model) { 1233 continue; 1234 } 1235 1236 /* Each bus type is allowed *one* substitution */ 1237 if (g_str_equal(model, alias)) { 1238 model = alias_target; 1239 } 1240 1241 if (!g_ptr_array_find_with_equal_func(nic_models, model, 1242 g_str_equal, NULL)) { 1243 /* This NIC does not live on this bus. */ 1244 continue; 1245 } 1246 1247 dev = qdev_new(model); 1248 qdev_set_nic_properties(dev, nd); 1249 qdev_realize_and_unref(dev, bus, &error_fatal); 1250 } 1251 1252 g_ptr_array_free(nic_models, true); 1253 } 1254 1255 static int (* const net_client_init_fun[NET_CLIENT_DRIVER__MAX])( 1256 const Netdev *netdev, 1257 const char *name, 1258 NetClientState *peer, Error **errp) = { 1259 [NET_CLIENT_DRIVER_NIC] = net_init_nic, 1260 #ifdef CONFIG_SLIRP 1261 [NET_CLIENT_DRIVER_USER] = net_init_slirp, 1262 #endif 1263 [NET_CLIENT_DRIVER_TAP] = net_init_tap, 1264 [NET_CLIENT_DRIVER_SOCKET] = net_init_socket, 1265 [NET_CLIENT_DRIVER_STREAM] = net_init_stream, 1266 [NET_CLIENT_DRIVER_DGRAM] = net_init_dgram, 1267 #ifdef CONFIG_VDE 1268 [NET_CLIENT_DRIVER_VDE] = net_init_vde, 1269 #endif 1270 #ifdef CONFIG_NETMAP 1271 [NET_CLIENT_DRIVER_NETMAP] = net_init_netmap, 1272 #endif 1273 #ifdef CONFIG_AF_XDP 1274 [NET_CLIENT_DRIVER_AF_XDP] = net_init_af_xdp, 1275 #endif 1276 #ifdef CONFIG_NET_BRIDGE 1277 [NET_CLIENT_DRIVER_BRIDGE] = net_init_bridge, 1278 #endif 1279 [NET_CLIENT_DRIVER_HUBPORT] = net_init_hubport, 1280 #ifdef CONFIG_VHOST_NET_USER 1281 [NET_CLIENT_DRIVER_VHOST_USER] = net_init_vhost_user, 1282 #endif 1283 #ifdef CONFIG_VHOST_NET_VDPA 1284 [NET_CLIENT_DRIVER_VHOST_VDPA] = net_init_vhost_vdpa, 1285 #endif 1286 #ifdef CONFIG_L2TPV3 1287 [NET_CLIENT_DRIVER_L2TPV3] = net_init_l2tpv3, 1288 #endif 1289 #ifdef CONFIG_VMNET 1290 [NET_CLIENT_DRIVER_VMNET_HOST] = net_init_vmnet_host, 1291 [NET_CLIENT_DRIVER_VMNET_SHARED] = net_init_vmnet_shared, 1292 [NET_CLIENT_DRIVER_VMNET_BRIDGED] = net_init_vmnet_bridged, 1293 #endif /* CONFIG_VMNET */ 1294 }; 1295 1296 1297 static int net_client_init1(const Netdev *netdev, bool is_netdev, Error **errp) 1298 { 1299 NetClientState *peer = NULL; 1300 NetClientState *nc; 1301 1302 if (is_netdev) { 1303 if (netdev->type == NET_CLIENT_DRIVER_NIC || 1304 !net_client_init_fun[netdev->type]) { 1305 error_setg(errp, "network backend '%s' is not compiled into this binary", 1306 NetClientDriver_str(netdev->type)); 1307 return -1; 1308 } 1309 } else { 1310 if (netdev->type == NET_CLIENT_DRIVER_NONE) { 1311 return 0; /* nothing to do */ 1312 } 1313 if (netdev->type == NET_CLIENT_DRIVER_HUBPORT) { 1314 error_setg(errp, "network backend '%s' is only supported with -netdev/-nic", 1315 NetClientDriver_str(netdev->type)); 1316 return -1; 1317 } 1318 1319 if (!net_client_init_fun[netdev->type]) { 1320 error_setg(errp, "network backend '%s' is not compiled into this binary", 1321 NetClientDriver_str(netdev->type)); 1322 return -1; 1323 } 1324 1325 /* Do not add to a hub if it's a nic with a netdev= parameter. */ 1326 if (netdev->type != NET_CLIENT_DRIVER_NIC || 1327 !netdev->u.nic.netdev) { 1328 peer = net_hub_add_port(0, NULL, NULL); 1329 } 1330 } 1331 1332 nc = qemu_find_netdev(netdev->id); 1333 if (nc) { 1334 error_setg(errp, "Duplicate ID '%s'", netdev->id); 1335 return -1; 1336 } 1337 1338 if (net_client_init_fun[netdev->type](netdev, netdev->id, peer, errp) < 0) { 1339 /* FIXME drop when all init functions store an Error */ 1340 if (errp && !*errp) { 1341 error_setg(errp, "Device '%s' could not be initialized", 1342 NetClientDriver_str(netdev->type)); 1343 } 1344 return -1; 1345 } 1346 1347 if (is_netdev) { 1348 nc = qemu_find_netdev(netdev->id); 1349 assert(nc); 1350 nc->is_netdev = true; 1351 } 1352 1353 return 0; 1354 } 1355 1356 void show_netdevs(void) 1357 { 1358 int idx; 1359 const char *available_netdevs[] = { 1360 "socket", 1361 "stream", 1362 "dgram", 1363 "hubport", 1364 "tap", 1365 #ifdef CONFIG_SLIRP 1366 "user", 1367 #endif 1368 #ifdef CONFIG_L2TPV3 1369 "l2tpv3", 1370 #endif 1371 #ifdef CONFIG_VDE 1372 "vde", 1373 #endif 1374 #ifdef CONFIG_NET_BRIDGE 1375 "bridge", 1376 #endif 1377 #ifdef CONFIG_NETMAP 1378 "netmap", 1379 #endif 1380 #ifdef CONFIG_AF_XDP 1381 "af-xdp", 1382 #endif 1383 #ifdef CONFIG_POSIX 1384 "vhost-user", 1385 #endif 1386 #ifdef CONFIG_VHOST_VDPA 1387 "vhost-vdpa", 1388 #endif 1389 #ifdef CONFIG_VMNET 1390 "vmnet-host", 1391 "vmnet-shared", 1392 "vmnet-bridged", 1393 #endif 1394 }; 1395 1396 qemu_printf("Available netdev backend types:\n"); 1397 for (idx = 0; idx < ARRAY_SIZE(available_netdevs); idx++) { 1398 qemu_printf("%s\n", available_netdevs[idx]); 1399 } 1400 } 1401 1402 static int net_client_init(QemuOpts *opts, bool is_netdev, Error **errp) 1403 { 1404 gchar **substrings = NULL; 1405 Netdev *object = NULL; 1406 int ret = -1; 1407 Visitor *v = opts_visitor_new(opts); 1408 1409 /* Parse convenience option format ipv6-net=fec0::0[/64] */ 1410 const char *ip6_net = qemu_opt_get(opts, "ipv6-net"); 1411 1412 if (ip6_net) { 1413 char *prefix_addr; 1414 unsigned long prefix_len = 64; /* Default 64bit prefix length. */ 1415 1416 substrings = g_strsplit(ip6_net, "/", 2); 1417 if (!substrings || !substrings[0]) { 1418 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "ipv6-net", 1419 "a valid IPv6 prefix"); 1420 goto out; 1421 } 1422 1423 prefix_addr = substrings[0]; 1424 1425 /* Handle user-specified prefix length. */ 1426 if (substrings[1] && 1427 qemu_strtoul(substrings[1], NULL, 10, &prefix_len)) 1428 { 1429 error_setg(errp, 1430 "parameter 'ipv6-net' expects a number after '/'"); 1431 goto out; 1432 } 1433 1434 qemu_opt_set(opts, "ipv6-prefix", prefix_addr, &error_abort); 1435 qemu_opt_set_number(opts, "ipv6-prefixlen", prefix_len, 1436 &error_abort); 1437 qemu_opt_unset(opts, "ipv6-net"); 1438 } 1439 1440 /* Create an ID for -net if the user did not specify one */ 1441 if (!is_netdev && !qemu_opts_id(opts)) { 1442 qemu_opts_set_id(opts, id_generate(ID_NET)); 1443 } 1444 1445 if (visit_type_Netdev(v, NULL, &object, errp)) { 1446 ret = net_client_init1(object, is_netdev, errp); 1447 } 1448 1449 qapi_free_Netdev(object); 1450 1451 out: 1452 g_strfreev(substrings); 1453 visit_free(v); 1454 return ret; 1455 } 1456 1457 void netdev_add(QemuOpts *opts, Error **errp) 1458 { 1459 net_client_init(opts, true, errp); 1460 } 1461 1462 void qmp_netdev_add(Netdev *netdev, Error **errp) 1463 { 1464 if (!id_wellformed(netdev->id)) { 1465 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "id", "an identifier"); 1466 return; 1467 } 1468 1469 net_client_init1(netdev, true, errp); 1470 } 1471 1472 void qmp_netdev_del(const char *id, Error **errp) 1473 { 1474 NetClientState *nc; 1475 QemuOpts *opts; 1476 1477 nc = qemu_find_netdev(id); 1478 if (!nc) { 1479 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND, 1480 "Device '%s' not found", id); 1481 return; 1482 } 1483 1484 if (!nc->is_netdev) { 1485 error_setg(errp, "Device '%s' is not a netdev", id); 1486 return; 1487 } 1488 1489 qemu_del_net_client(nc); 1490 1491 /* 1492 * Wart: we need to delete the QemuOpts associated with netdevs 1493 * created via CLI or HMP, to avoid bogus "Duplicate ID" errors in 1494 * HMP netdev_add. 1495 */ 1496 opts = qemu_opts_find(qemu_find_opts("netdev"), id); 1497 if (opts) { 1498 qemu_opts_del(opts); 1499 } 1500 } 1501 1502 static void netfilter_print_info(Monitor *mon, NetFilterState *nf) 1503 { 1504 char *str; 1505 ObjectProperty *prop; 1506 ObjectPropertyIterator iter; 1507 Visitor *v; 1508 1509 /* generate info str */ 1510 object_property_iter_init(&iter, OBJECT(nf)); 1511 while ((prop = object_property_iter_next(&iter))) { 1512 if (!strcmp(prop->name, "type")) { 1513 continue; 1514 } 1515 v = string_output_visitor_new(false, &str); 1516 object_property_get(OBJECT(nf), prop->name, v, NULL); 1517 visit_complete(v, &str); 1518 visit_free(v); 1519 monitor_printf(mon, ",%s=%s", prop->name, str); 1520 g_free(str); 1521 } 1522 monitor_printf(mon, "\n"); 1523 } 1524 1525 void print_net_client(Monitor *mon, NetClientState *nc) 1526 { 1527 NetFilterState *nf; 1528 1529 monitor_printf(mon, "%s: index=%d,type=%s,%s\n", nc->name, 1530 nc->queue_index, 1531 NetClientDriver_str(nc->info->type), 1532 nc->info_str); 1533 if (!QTAILQ_EMPTY(&nc->filters)) { 1534 monitor_printf(mon, "filters:\n"); 1535 } 1536 QTAILQ_FOREACH(nf, &nc->filters, next) { 1537 monitor_printf(mon, " - %s: type=%s", 1538 object_get_canonical_path_component(OBJECT(nf)), 1539 object_get_typename(OBJECT(nf))); 1540 netfilter_print_info(mon, nf); 1541 } 1542 } 1543 1544 RxFilterInfoList *qmp_query_rx_filter(const char *name, Error **errp) 1545 { 1546 NetClientState *nc; 1547 RxFilterInfoList *filter_list = NULL, **tail = &filter_list; 1548 1549 QTAILQ_FOREACH(nc, &net_clients, next) { 1550 RxFilterInfo *info; 1551 1552 if (name && strcmp(nc->name, name) != 0) { 1553 continue; 1554 } 1555 1556 /* only query rx-filter information of NIC */ 1557 if (nc->info->type != NET_CLIENT_DRIVER_NIC) { 1558 if (name) { 1559 error_setg(errp, "net client(%s) isn't a NIC", name); 1560 assert(!filter_list); 1561 return NULL; 1562 } 1563 continue; 1564 } 1565 1566 /* only query information on queue 0 since the info is per nic, 1567 * not per queue 1568 */ 1569 if (nc->queue_index != 0) 1570 continue; 1571 1572 if (nc->info->query_rx_filter) { 1573 info = nc->info->query_rx_filter(nc); 1574 QAPI_LIST_APPEND(tail, info); 1575 } else if (name) { 1576 error_setg(errp, "net client(%s) doesn't support" 1577 " rx-filter querying", name); 1578 assert(!filter_list); 1579 return NULL; 1580 } 1581 1582 if (name) { 1583 break; 1584 } 1585 } 1586 1587 if (filter_list == NULL && name) { 1588 error_setg(errp, "invalid net client name: %s", name); 1589 } 1590 1591 return filter_list; 1592 } 1593 1594 void colo_notify_filters_event(int event, Error **errp) 1595 { 1596 NetClientState *nc; 1597 NetFilterState *nf; 1598 NetFilterClass *nfc = NULL; 1599 Error *local_err = NULL; 1600 1601 QTAILQ_FOREACH(nc, &net_clients, next) { 1602 QTAILQ_FOREACH(nf, &nc->filters, next) { 1603 nfc = NETFILTER_GET_CLASS(OBJECT(nf)); 1604 nfc->handle_event(nf, event, &local_err); 1605 if (local_err) { 1606 error_propagate(errp, local_err); 1607 return; 1608 } 1609 } 1610 } 1611 } 1612 1613 void qmp_set_link(const char *name, bool up, Error **errp) 1614 { 1615 NetClientState *ncs[MAX_QUEUE_NUM]; 1616 NetClientState *nc; 1617 int queues, i; 1618 1619 queues = qemu_find_net_clients_except(name, ncs, 1620 NET_CLIENT_DRIVER__MAX, 1621 MAX_QUEUE_NUM); 1622 1623 if (queues == 0) { 1624 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND, 1625 "Device '%s' not found", name); 1626 return; 1627 } 1628 nc = ncs[0]; 1629 1630 for (i = 0; i < queues; i++) { 1631 ncs[i]->link_down = !up; 1632 } 1633 1634 if (nc->info->link_status_changed) { 1635 nc->info->link_status_changed(nc); 1636 } 1637 1638 if (nc->peer) { 1639 /* Change peer link only if the peer is NIC and then notify peer. 1640 * If the peer is a HUBPORT or a backend, we do not change the 1641 * link status. 1642 * 1643 * This behavior is compatible with qemu hubs where there could be 1644 * multiple clients that can still communicate with each other in 1645 * disconnected mode. For now maintain this compatibility. 1646 */ 1647 if (nc->peer->info->type == NET_CLIENT_DRIVER_NIC) { 1648 for (i = 0; i < queues; i++) { 1649 ncs[i]->peer->link_down = !up; 1650 } 1651 } 1652 if (nc->peer->info->link_status_changed) { 1653 nc->peer->info->link_status_changed(nc->peer); 1654 } 1655 } 1656 } 1657 1658 static void net_vm_change_state_handler(void *opaque, bool running, 1659 RunState state) 1660 { 1661 NetClientState *nc; 1662 NetClientState *tmp; 1663 1664 QTAILQ_FOREACH_SAFE(nc, &net_clients, next, tmp) { 1665 if (running) { 1666 /* Flush queued packets and wake up backends. */ 1667 if (nc->peer && qemu_can_send_packet(nc)) { 1668 qemu_flush_queued_packets(nc->peer); 1669 } 1670 } else { 1671 /* Complete all queued packets, to guarantee we don't modify 1672 * state later when VM is not running. 1673 */ 1674 qemu_flush_or_purge_queued_packets(nc, true); 1675 } 1676 } 1677 } 1678 1679 void net_cleanup(void) 1680 { 1681 NetClientState *nc, **p = &QTAILQ_FIRST(&net_clients); 1682 1683 /*cleanup colo compare module for COLO*/ 1684 colo_compare_cleanup(); 1685 1686 /* 1687 * Walk the net_clients list and remove the netdevs but *not* any 1688 * NET_CLIENT_DRIVER_NIC entries. The latter are owned by the device 1689 * model which created them, and in some cases (e.g. xen-net-device) 1690 * the device itself may do cleanup at exit and will be upset if we 1691 * just delete its NIC from underneath it. 1692 * 1693 * Since qemu_del_net_client() may delete multiple entries, using 1694 * QTAILQ_FOREACH_SAFE() is not safe here. The only safe pointer 1695 * to keep as a bookmark is a NET_CLIENT_DRIVER_NIC entry, so keep 1696 * 'p' pointing to either the head of the list, or the 'next' field 1697 * of the latest NET_CLIENT_DRIVER_NIC, and operate on *p as we walk 1698 * the list. 1699 * 1700 * However, the NIC may have peers that trust to be clean beyond this 1701 * point. For example, if they have been removed with device_del. 1702 * 1703 * The 'nc' variable isn't part of the list traversal; it's purely 1704 * for convenience as too much '(*p)->' has a tendency to make the 1705 * readers' eyes bleed. 1706 */ 1707 while (*p) { 1708 nc = *p; 1709 if (nc->info->type == NET_CLIENT_DRIVER_NIC) { 1710 NICState *nic = qemu_get_nic(nc); 1711 1712 if (nic->peer_deleted) { 1713 int queues = MAX(nic->conf->peers.queues, 1); 1714 1715 for (int i = 0; i < queues; i++) { 1716 nc = qemu_get_subqueue(nic, i); 1717 qemu_cleanup_net_client(nc->peer, false); 1718 } 1719 } 1720 1721 /* Skip NET_CLIENT_DRIVER_NIC entries */ 1722 p = &QTAILQ_NEXT(nc, next); 1723 } else { 1724 qemu_del_net_client(nc); 1725 } 1726 } 1727 1728 qemu_del_vm_change_state_handler(net_change_state_entry); 1729 } 1730 1731 void net_check_clients(void) 1732 { 1733 NetClientState *nc; 1734 int i; 1735 1736 if (nic_model_help) { 1737 show_nic_models(); 1738 exit(0); 1739 } 1740 net_hub_check_clients(); 1741 1742 QTAILQ_FOREACH(nc, &net_clients, next) { 1743 if (!nc->peer) { 1744 warn_report("%s %s has no peer", 1745 nc->info->type == NET_CLIENT_DRIVER_NIC 1746 ? "nic" : "netdev", 1747 nc->name); 1748 } 1749 } 1750 1751 /* Check that all NICs requested via -net nic actually got created. 1752 * NICs created via -device don't need to be checked here because 1753 * they are always instantiated. 1754 */ 1755 for (i = 0; i < MAX_NICS; i++) { 1756 NICInfo *nd = &nd_table[i]; 1757 if (nd->used && !nd->instantiated) { 1758 warn_report("requested NIC (%s, model %s) " 1759 "was not created (not supported by this machine?)", 1760 nd->name ? nd->name : "anonymous", 1761 nd->model ? nd->model : "unspecified"); 1762 } 1763 } 1764 } 1765 1766 static int net_init_client(void *dummy, QemuOpts *opts, Error **errp) 1767 { 1768 const char *model = qemu_opt_get(opts, "model"); 1769 1770 if (is_nic_model_help_option(model)) { 1771 return 0; 1772 } 1773 1774 return net_client_init(opts, false, errp); 1775 } 1776 1777 static int net_init_netdev(void *dummy, QemuOpts *opts, Error **errp) 1778 { 1779 const char *type = qemu_opt_get(opts, "type"); 1780 1781 if (type && is_help_option(type)) { 1782 show_netdevs(); 1783 exit(0); 1784 } 1785 return net_client_init(opts, true, errp); 1786 } 1787 1788 /* For the convenience "--nic" parameter */ 1789 static int net_param_nic(void *dummy, QemuOpts *opts, Error **errp) 1790 { 1791 char *mac, *nd_id; 1792 int idx, ret; 1793 NICInfo *ni; 1794 const char *type; 1795 1796 type = qemu_opt_get(opts, "type"); 1797 if (type) { 1798 if (g_str_equal(type, "none")) { 1799 return 0; /* Nothing to do, default_net is cleared in vl.c */ 1800 } 1801 if (is_help_option(type)) { 1802 GPtrArray *nic_models = qemu_get_nic_models(TYPE_DEVICE); 1803 int i; 1804 show_netdevs(); 1805 printf("\n"); 1806 printf("Available NIC models " 1807 "(use -nic model=help for a filtered list):\n"); 1808 for (i = 0 ; nic_models->pdata[i]; i++) { 1809 printf("%s\n", (char *)nic_models->pdata[i]); 1810 } 1811 g_ptr_array_free(nic_models, true); 1812 exit(0); 1813 } 1814 } 1815 1816 idx = nic_get_free_idx(); 1817 if (idx == -1 || nb_nics >= MAX_NICS) { 1818 error_setg(errp, "no more on-board/default NIC slots available"); 1819 return -1; 1820 } 1821 1822 if (!type) { 1823 qemu_opt_set(opts, "type", "user", &error_abort); 1824 } 1825 1826 ni = &nd_table[idx]; 1827 memset(ni, 0, sizeof(*ni)); 1828 ni->model = qemu_opt_get_del(opts, "model"); 1829 1830 if (is_nic_model_help_option(ni->model)) { 1831 return 0; 1832 } 1833 1834 /* Create an ID if the user did not specify one */ 1835 nd_id = g_strdup(qemu_opts_id(opts)); 1836 if (!nd_id) { 1837 nd_id = id_generate(ID_NET); 1838 qemu_opts_set_id(opts, nd_id); 1839 } 1840 1841 /* Handle MAC address */ 1842 mac = qemu_opt_get_del(opts, "mac"); 1843 if (mac) { 1844 ret = net_parse_macaddr(ni->macaddr.a, mac); 1845 g_free(mac); 1846 if (ret) { 1847 error_setg(errp, "invalid syntax for ethernet address"); 1848 goto out; 1849 } 1850 if (is_multicast_ether_addr(ni->macaddr.a)) { 1851 error_setg(errp, "NIC cannot have multicast MAC address"); 1852 ret = -1; 1853 goto out; 1854 } 1855 } 1856 qemu_macaddr_default_if_unset(&ni->macaddr); 1857 1858 ret = net_client_init(opts, true, errp); 1859 if (ret == 0) { 1860 ni->netdev = qemu_find_netdev(nd_id); 1861 ni->used = true; 1862 nb_nics++; 1863 } 1864 1865 out: 1866 g_free(nd_id); 1867 return ret; 1868 } 1869 1870 static void netdev_init_modern(void) 1871 { 1872 while (!QSIMPLEQ_EMPTY(&nd_queue)) { 1873 NetdevQueueEntry *nd = QSIMPLEQ_FIRST(&nd_queue); 1874 1875 QSIMPLEQ_REMOVE_HEAD(&nd_queue, entry); 1876 loc_push_restore(&nd->loc); 1877 net_client_init1(nd->nd, true, &error_fatal); 1878 loc_pop(&nd->loc); 1879 qapi_free_Netdev(nd->nd); 1880 g_free(nd); 1881 } 1882 } 1883 1884 void net_init_clients(void) 1885 { 1886 net_change_state_entry = 1887 qemu_add_vm_change_state_handler(net_vm_change_state_handler, NULL); 1888 1889 QTAILQ_INIT(&net_clients); 1890 1891 netdev_init_modern(); 1892 1893 qemu_opts_foreach(qemu_find_opts("netdev"), net_init_netdev, NULL, 1894 &error_fatal); 1895 1896 qemu_opts_foreach(qemu_find_opts("nic"), net_param_nic, NULL, 1897 &error_fatal); 1898 1899 qemu_opts_foreach(qemu_find_opts("net"), net_init_client, NULL, 1900 &error_fatal); 1901 } 1902 1903 /* 1904 * Does this -netdev argument use modern rather than traditional syntax? 1905 * Modern syntax is to be parsed with netdev_parse_modern(). 1906 * Traditional syntax is to be parsed with net_client_parse(). 1907 */ 1908 bool netdev_is_modern(const char *optstr) 1909 { 1910 QemuOpts *opts; 1911 bool is_modern; 1912 const char *type; 1913 static QemuOptsList dummy_opts = { 1914 .name = "netdev", 1915 .implied_opt_name = "type", 1916 .head = QTAILQ_HEAD_INITIALIZER(dummy_opts.head), 1917 .desc = { { } }, 1918 }; 1919 1920 if (optstr[0] == '{') { 1921 /* This is JSON, which means it's modern syntax */ 1922 return true; 1923 } 1924 1925 opts = qemu_opts_create(&dummy_opts, NULL, false, &error_abort); 1926 qemu_opts_do_parse(opts, optstr, dummy_opts.implied_opt_name, 1927 &error_abort); 1928 type = qemu_opt_get(opts, "type"); 1929 is_modern = !g_strcmp0(type, "stream") || !g_strcmp0(type, "dgram"); 1930 1931 qemu_opts_reset(&dummy_opts); 1932 1933 return is_modern; 1934 } 1935 1936 /* 1937 * netdev_parse_modern() uses modern, more expressive syntax than 1938 * net_client_parse(), but supports only the -netdev option. 1939 * netdev_parse_modern() appends to @nd_queue, whereas net_client_parse() 1940 * appends to @qemu_netdev_opts. 1941 */ 1942 void netdev_parse_modern(const char *optstr) 1943 { 1944 Visitor *v; 1945 NetdevQueueEntry *nd; 1946 1947 v = qobject_input_visitor_new_str(optstr, "type", &error_fatal); 1948 nd = g_new(NetdevQueueEntry, 1); 1949 visit_type_Netdev(v, NULL, &nd->nd, &error_fatal); 1950 visit_free(v); 1951 loc_save(&nd->loc); 1952 1953 QSIMPLEQ_INSERT_TAIL(&nd_queue, nd, entry); 1954 } 1955 1956 void net_client_parse(QemuOptsList *opts_list, const char *optstr) 1957 { 1958 if (!qemu_opts_parse_noisily(opts_list, optstr, true)) { 1959 exit(1); 1960 } 1961 } 1962 1963 /* From FreeBSD */ 1964 /* XXX: optimize */ 1965 uint32_t net_crc32(const uint8_t *p, int len) 1966 { 1967 uint32_t crc; 1968 int carry, i, j; 1969 uint8_t b; 1970 1971 crc = 0xffffffff; 1972 for (i = 0; i < len; i++) { 1973 b = *p++; 1974 for (j = 0; j < 8; j++) { 1975 carry = ((crc & 0x80000000L) ? 1 : 0) ^ (b & 0x01); 1976 crc <<= 1; 1977 b >>= 1; 1978 if (carry) { 1979 crc = ((crc ^ POLYNOMIAL_BE) | carry); 1980 } 1981 } 1982 } 1983 1984 return crc; 1985 } 1986 1987 uint32_t net_crc32_le(const uint8_t *p, int len) 1988 { 1989 uint32_t crc; 1990 int carry, i, j; 1991 uint8_t b; 1992 1993 crc = 0xffffffff; 1994 for (i = 0; i < len; i++) { 1995 b = *p++; 1996 for (j = 0; j < 8; j++) { 1997 carry = (crc & 0x1) ^ (b & 0x01); 1998 crc >>= 1; 1999 b >>= 1; 2000 if (carry) { 2001 crc ^= POLYNOMIAL_LE; 2002 } 2003 } 2004 } 2005 2006 return crc; 2007 } 2008 2009 QemuOptsList qemu_netdev_opts = { 2010 .name = "netdev", 2011 .implied_opt_name = "type", 2012 .head = QTAILQ_HEAD_INITIALIZER(qemu_netdev_opts.head), 2013 .desc = { 2014 /* 2015 * no elements => accept any params 2016 * validation will happen later 2017 */ 2018 { /* end of list */ } 2019 }, 2020 }; 2021 2022 QemuOptsList qemu_nic_opts = { 2023 .name = "nic", 2024 .implied_opt_name = "type", 2025 .head = QTAILQ_HEAD_INITIALIZER(qemu_nic_opts.head), 2026 .desc = { 2027 /* 2028 * no elements => accept any params 2029 * validation will happen later 2030 */ 2031 { /* end of list */ } 2032 }, 2033 }; 2034 2035 QemuOptsList qemu_net_opts = { 2036 .name = "net", 2037 .implied_opt_name = "type", 2038 .head = QTAILQ_HEAD_INITIALIZER(qemu_net_opts.head), 2039 .desc = { 2040 /* 2041 * no elements => accept any params 2042 * validation will happen later 2043 */ 2044 { /* end of list */ } 2045 }, 2046 }; 2047 2048 void net_socket_rs_init(SocketReadState *rs, 2049 SocketReadStateFinalize *finalize, 2050 bool vnet_hdr) 2051 { 2052 rs->state = 0; 2053 rs->vnet_hdr = vnet_hdr; 2054 rs->index = 0; 2055 rs->packet_len = 0; 2056 rs->vnet_hdr_len = 0; 2057 memset(rs->buf, 0, sizeof(rs->buf)); 2058 rs->finalize = finalize; 2059 } 2060 2061 /* 2062 * Returns 2063 * 0: success 2064 * -1: error occurs 2065 */ 2066 int net_fill_rstate(SocketReadState *rs, const uint8_t *buf, int size) 2067 { 2068 unsigned int l; 2069 2070 while (size > 0) { 2071 /* Reassemble a packet from the network. 2072 * 0 = getting length. 2073 * 1 = getting vnet header length. 2074 * 2 = getting data. 2075 */ 2076 switch (rs->state) { 2077 case 0: 2078 l = 4 - rs->index; 2079 if (l > size) { 2080 l = size; 2081 } 2082 memcpy(rs->buf + rs->index, buf, l); 2083 buf += l; 2084 size -= l; 2085 rs->index += l; 2086 if (rs->index == 4) { 2087 /* got length */ 2088 rs->packet_len = ntohl(*(uint32_t *)rs->buf); 2089 rs->index = 0; 2090 if (rs->vnet_hdr) { 2091 rs->state = 1; 2092 } else { 2093 rs->state = 2; 2094 rs->vnet_hdr_len = 0; 2095 } 2096 } 2097 break; 2098 case 1: 2099 l = 4 - rs->index; 2100 if (l > size) { 2101 l = size; 2102 } 2103 memcpy(rs->buf + rs->index, buf, l); 2104 buf += l; 2105 size -= l; 2106 rs->index += l; 2107 if (rs->index == 4) { 2108 /* got vnet header length */ 2109 rs->vnet_hdr_len = ntohl(*(uint32_t *)rs->buf); 2110 rs->index = 0; 2111 rs->state = 2; 2112 } 2113 break; 2114 case 2: 2115 l = rs->packet_len - rs->index; 2116 if (l > size) { 2117 l = size; 2118 } 2119 if (rs->index + l <= sizeof(rs->buf)) { 2120 memcpy(rs->buf + rs->index, buf, l); 2121 } else { 2122 fprintf(stderr, "serious error: oversized packet received," 2123 "connection terminated.\n"); 2124 rs->index = rs->state = 0; 2125 return -1; 2126 } 2127 2128 rs->index += l; 2129 buf += l; 2130 size -= l; 2131 if (rs->index >= rs->packet_len) { 2132 rs->index = 0; 2133 rs->state = 0; 2134 assert(rs->finalize); 2135 rs->finalize(rs); 2136 } 2137 break; 2138 } 2139 } 2140 2141 assert(size == 0); 2142 return 0; 2143 } 2144