1 /* 2 * QEMU live migration 3 * 4 * Copyright IBM, Corp. 2008 5 * 6 * Authors: 7 * Anthony Liguori <aliguori@us.ibm.com> 8 * 9 * This work is licensed under the terms of the GNU GPL, version 2. See 10 * the COPYING file in the top-level directory. 11 * 12 * Contributions after 2012-01-13 are licensed under the terms of the 13 * GNU GPL, version 2 or (at your option) any later version. 14 */ 15 16 #include "qemu/osdep.h" 17 #include "qemu/cutils.h" 18 #include "qemu/error-report.h" 19 #include "qemu/main-loop.h" 20 #include "migration/blocker.h" 21 #include "exec.h" 22 #include "fd.h" 23 #include "socket.h" 24 #include "sysemu/runstate.h" 25 #include "sysemu/sysemu.h" 26 #include "sysemu/cpu-throttle.h" 27 #include "rdma.h" 28 #include "ram.h" 29 #include "ram-compress.h" 30 #include "migration/global_state.h" 31 #include "migration/misc.h" 32 #include "migration.h" 33 #include "migration-stats.h" 34 #include "savevm.h" 35 #include "qemu-file.h" 36 #include "channel.h" 37 #include "migration/vmstate.h" 38 #include "block/block.h" 39 #include "qapi/error.h" 40 #include "qapi/clone-visitor.h" 41 #include "qapi/qapi-visit-migration.h" 42 #include "qapi/qapi-visit-sockets.h" 43 #include "qapi/qapi-commands-migration.h" 44 #include "qapi/qapi-events-migration.h" 45 #include "qapi/qmp/qerror.h" 46 #include "qapi/qmp/qnull.h" 47 #include "qemu/rcu.h" 48 #include "block.h" 49 #include "postcopy-ram.h" 50 #include "qemu/thread.h" 51 #include "trace.h" 52 #include "exec/target_page.h" 53 #include "io/channel-buffer.h" 54 #include "io/channel-tls.h" 55 #include "migration/colo.h" 56 #include "hw/boards.h" 57 #include "monitor/monitor.h" 58 #include "net/announce.h" 59 #include "qemu/queue.h" 60 #include "multifd.h" 61 #include "threadinfo.h" 62 #include "qemu/yank.h" 63 #include "sysemu/cpus.h" 64 #include "yank_functions.h" 65 #include "sysemu/qtest.h" 66 #include "options.h" 67 68 static NotifierList migration_state_notifiers = 69 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers); 70 71 /* Messages sent on the return path from destination to source */ 72 enum mig_rp_message_type { 73 MIG_RP_MSG_INVALID = 0, /* Must be 0 */ 74 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */ 75 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */ 76 77 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */ 78 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */ 79 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */ 80 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */ 81 82 MIG_RP_MSG_MAX 83 }; 84 85 /* When we add fault tolerance, we could have several 86 migrations at once. For now we don't need to add 87 dynamic creation of migration */ 88 89 static MigrationState *current_migration; 90 static MigrationIncomingState *current_incoming; 91 92 static GSList *migration_blockers; 93 94 static bool migration_object_check(MigrationState *ms, Error **errp); 95 static int migration_maybe_pause(MigrationState *s, 96 int *current_active_state, 97 int new_state); 98 static void migrate_fd_cancel(MigrationState *s); 99 100 static bool migration_needs_multiple_sockets(void) 101 { 102 return migrate_multifd() || migrate_postcopy_preempt(); 103 } 104 105 static bool uri_supports_multi_channels(const char *uri) 106 { 107 return strstart(uri, "tcp:", NULL) || strstart(uri, "unix:", NULL) || 108 strstart(uri, "vsock:", NULL); 109 } 110 111 static bool 112 migration_channels_and_uri_compatible(const char *uri, Error **errp) 113 { 114 if (migration_needs_multiple_sockets() && 115 !uri_supports_multi_channels(uri)) { 116 error_setg(errp, "Migration requires multi-channel URIs (e.g. tcp)"); 117 return false; 118 } 119 120 return true; 121 } 122 123 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp) 124 { 125 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp; 126 127 return (a > b) - (a < b); 128 } 129 130 void migration_object_init(void) 131 { 132 /* This can only be called once. */ 133 assert(!current_migration); 134 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION)); 135 136 /* 137 * Init the migrate incoming object as well no matter whether 138 * we'll use it or not. 139 */ 140 assert(!current_incoming); 141 current_incoming = g_new0(MigrationIncomingState, 1); 142 current_incoming->state = MIGRATION_STATUS_NONE; 143 current_incoming->postcopy_remote_fds = 144 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD)); 145 qemu_mutex_init(¤t_incoming->rp_mutex); 146 qemu_mutex_init(¤t_incoming->postcopy_prio_thread_mutex); 147 qemu_event_init(¤t_incoming->main_thread_load_event, false); 148 qemu_sem_init(¤t_incoming->postcopy_pause_sem_dst, 0); 149 qemu_sem_init(¤t_incoming->postcopy_pause_sem_fault, 0); 150 qemu_sem_init(¤t_incoming->postcopy_pause_sem_fast_load, 0); 151 qemu_sem_init(¤t_incoming->postcopy_qemufile_dst_done, 0); 152 153 qemu_mutex_init(¤t_incoming->page_request_mutex); 154 current_incoming->page_requested = g_tree_new(page_request_addr_cmp); 155 156 migration_object_check(current_migration, &error_fatal); 157 158 blk_mig_init(); 159 ram_mig_init(); 160 dirty_bitmap_mig_init(); 161 } 162 163 void migration_cancel(const Error *error) 164 { 165 if (error) { 166 migrate_set_error(current_migration, error); 167 } 168 migrate_fd_cancel(current_migration); 169 } 170 171 void migration_shutdown(void) 172 { 173 /* 174 * When the QEMU main thread exit, the COLO thread 175 * may wait a semaphore. So, we should wakeup the 176 * COLO thread before migration shutdown. 177 */ 178 colo_shutdown(); 179 /* 180 * Cancel the current migration - that will (eventually) 181 * stop the migration using this structure 182 */ 183 migration_cancel(NULL); 184 object_unref(OBJECT(current_migration)); 185 186 /* 187 * Cancel outgoing migration of dirty bitmaps. It should 188 * at least unref used block nodes. 189 */ 190 dirty_bitmap_mig_cancel_outgoing(); 191 192 /* 193 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps 194 * are non-critical data, and their loss never considered as 195 * something serious. 196 */ 197 dirty_bitmap_mig_cancel_incoming(); 198 } 199 200 /* For outgoing */ 201 MigrationState *migrate_get_current(void) 202 { 203 /* This can only be called after the object created. */ 204 assert(current_migration); 205 return current_migration; 206 } 207 208 MigrationIncomingState *migration_incoming_get_current(void) 209 { 210 assert(current_incoming); 211 return current_incoming; 212 } 213 214 void migration_incoming_transport_cleanup(MigrationIncomingState *mis) 215 { 216 if (mis->socket_address_list) { 217 qapi_free_SocketAddressList(mis->socket_address_list); 218 mis->socket_address_list = NULL; 219 } 220 221 if (mis->transport_cleanup) { 222 mis->transport_cleanup(mis->transport_data); 223 mis->transport_data = mis->transport_cleanup = NULL; 224 } 225 } 226 227 void migration_incoming_state_destroy(void) 228 { 229 struct MigrationIncomingState *mis = migration_incoming_get_current(); 230 231 multifd_load_cleanup(); 232 compress_threads_load_cleanup(); 233 234 if (mis->to_src_file) { 235 /* Tell source that we are done */ 236 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0); 237 qemu_fclose(mis->to_src_file); 238 mis->to_src_file = NULL; 239 } 240 241 if (mis->from_src_file) { 242 migration_ioc_unregister_yank_from_file(mis->from_src_file); 243 qemu_fclose(mis->from_src_file); 244 mis->from_src_file = NULL; 245 } 246 if (mis->postcopy_remote_fds) { 247 g_array_free(mis->postcopy_remote_fds, TRUE); 248 mis->postcopy_remote_fds = NULL; 249 } 250 251 migration_incoming_transport_cleanup(mis); 252 qemu_event_reset(&mis->main_thread_load_event); 253 254 if (mis->page_requested) { 255 g_tree_destroy(mis->page_requested); 256 mis->page_requested = NULL; 257 } 258 259 if (mis->postcopy_qemufile_dst) { 260 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst); 261 qemu_fclose(mis->postcopy_qemufile_dst); 262 mis->postcopy_qemufile_dst = NULL; 263 } 264 265 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 266 } 267 268 static void migrate_generate_event(int new_state) 269 { 270 if (migrate_events()) { 271 qapi_event_send_migration(new_state); 272 } 273 } 274 275 /* 276 * Send a message on the return channel back to the source 277 * of the migration. 278 */ 279 static int migrate_send_rp_message(MigrationIncomingState *mis, 280 enum mig_rp_message_type message_type, 281 uint16_t len, void *data) 282 { 283 int ret = 0; 284 285 trace_migrate_send_rp_message((int)message_type, len); 286 QEMU_LOCK_GUARD(&mis->rp_mutex); 287 288 /* 289 * It's possible that the file handle got lost due to network 290 * failures. 291 */ 292 if (!mis->to_src_file) { 293 ret = -EIO; 294 return ret; 295 } 296 297 qemu_put_be16(mis->to_src_file, (unsigned int)message_type); 298 qemu_put_be16(mis->to_src_file, len); 299 qemu_put_buffer(mis->to_src_file, data, len); 300 qemu_fflush(mis->to_src_file); 301 302 /* It's possible that qemu file got error during sending */ 303 ret = qemu_file_get_error(mis->to_src_file); 304 305 return ret; 306 } 307 308 /* Request one page from the source VM at the given start address. 309 * rb: the RAMBlock to request the page in 310 * Start: Address offset within the RB 311 * Len: Length in bytes required - must be a multiple of pagesize 312 */ 313 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis, 314 RAMBlock *rb, ram_addr_t start) 315 { 316 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */ 317 size_t msglen = 12; /* start + len */ 318 size_t len = qemu_ram_pagesize(rb); 319 enum mig_rp_message_type msg_type; 320 const char *rbname; 321 int rbname_len; 322 323 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start); 324 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len); 325 326 /* 327 * We maintain the last ramblock that we requested for page. Note that we 328 * don't need locking because this function will only be called within the 329 * postcopy ram fault thread. 330 */ 331 if (rb != mis->last_rb) { 332 mis->last_rb = rb; 333 334 rbname = qemu_ram_get_idstr(rb); 335 rbname_len = strlen(rbname); 336 337 assert(rbname_len < 256); 338 339 bufc[msglen++] = rbname_len; 340 memcpy(bufc + msglen, rbname, rbname_len); 341 msglen += rbname_len; 342 msg_type = MIG_RP_MSG_REQ_PAGES_ID; 343 } else { 344 msg_type = MIG_RP_MSG_REQ_PAGES; 345 } 346 347 return migrate_send_rp_message(mis, msg_type, msglen, bufc); 348 } 349 350 int migrate_send_rp_req_pages(MigrationIncomingState *mis, 351 RAMBlock *rb, ram_addr_t start, uint64_t haddr) 352 { 353 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb)); 354 bool received = false; 355 356 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) { 357 received = ramblock_recv_bitmap_test_byte_offset(rb, start); 358 if (!received && !g_tree_lookup(mis->page_requested, aligned)) { 359 /* 360 * The page has not been received, and it's not yet in the page 361 * request list. Queue it. Set the value of element to 1, so that 362 * things like g_tree_lookup() will return TRUE (1) when found. 363 */ 364 g_tree_insert(mis->page_requested, aligned, (gpointer)1); 365 mis->page_requested_count++; 366 trace_postcopy_page_req_add(aligned, mis->page_requested_count); 367 } 368 } 369 370 /* 371 * If the page is there, skip sending the message. We don't even need the 372 * lock because as long as the page arrived, it'll be there forever. 373 */ 374 if (received) { 375 return 0; 376 } 377 378 return migrate_send_rp_message_req_pages(mis, rb, start); 379 } 380 381 static bool migration_colo_enabled; 382 bool migration_incoming_colo_enabled(void) 383 { 384 return migration_colo_enabled; 385 } 386 387 void migration_incoming_disable_colo(void) 388 { 389 ram_block_discard_disable(false); 390 migration_colo_enabled = false; 391 } 392 393 int migration_incoming_enable_colo(void) 394 { 395 #ifndef CONFIG_REPLICATION 396 error_report("ENABLE_COLO command come in migration stream, but COLO " 397 "module is not built in"); 398 return -ENOTSUP; 399 #endif 400 401 if (!migrate_colo()) { 402 error_report("ENABLE_COLO command come in migration stream, but c-colo " 403 "capability is not set"); 404 return -EINVAL; 405 } 406 407 if (ram_block_discard_disable(true)) { 408 error_report("COLO: cannot disable RAM discard"); 409 return -EBUSY; 410 } 411 migration_colo_enabled = true; 412 return 0; 413 } 414 415 void migrate_add_address(SocketAddress *address) 416 { 417 MigrationIncomingState *mis = migration_incoming_get_current(); 418 419 QAPI_LIST_PREPEND(mis->socket_address_list, 420 QAPI_CLONE(SocketAddress, address)); 421 } 422 423 static void qemu_start_incoming_migration(const char *uri, Error **errp) 424 { 425 const char *p = NULL; 426 427 /* URI is not suitable for migration? */ 428 if (!migration_channels_and_uri_compatible(uri, errp)) { 429 return; 430 } 431 432 qapi_event_send_migration(MIGRATION_STATUS_SETUP); 433 if (strstart(uri, "tcp:", &p) || 434 strstart(uri, "unix:", NULL) || 435 strstart(uri, "vsock:", NULL)) { 436 socket_start_incoming_migration(p ? p : uri, errp); 437 #ifdef CONFIG_RDMA 438 } else if (strstart(uri, "rdma:", &p)) { 439 rdma_start_incoming_migration(p, errp); 440 #endif 441 } else if (strstart(uri, "exec:", &p)) { 442 exec_start_incoming_migration(p, errp); 443 } else if (strstart(uri, "fd:", &p)) { 444 fd_start_incoming_migration(p, errp); 445 } else { 446 error_setg(errp, "unknown migration protocol: %s", uri); 447 } 448 } 449 450 static void process_incoming_migration_bh(void *opaque) 451 { 452 Error *local_err = NULL; 453 MigrationIncomingState *mis = opaque; 454 455 /* If capability late_block_activate is set: 456 * Only fire up the block code now if we're going to restart the 457 * VM, else 'cont' will do it. 458 * This causes file locking to happen; so we don't want it to happen 459 * unless we really are starting the VM. 460 */ 461 if (!migrate_late_block_activate() || 462 (autostart && (!global_state_received() || 463 global_state_get_runstate() == RUN_STATE_RUNNING))) { 464 /* Make sure all file formats throw away their mutable metadata. 465 * If we get an error here, just don't restart the VM yet. */ 466 bdrv_activate_all(&local_err); 467 if (local_err) { 468 error_report_err(local_err); 469 local_err = NULL; 470 autostart = false; 471 } 472 } 473 474 /* 475 * This must happen after all error conditions are dealt with and 476 * we're sure the VM is going to be running on this host. 477 */ 478 qemu_announce_self(&mis->announce_timer, migrate_announce_params()); 479 480 multifd_load_shutdown(); 481 482 dirty_bitmap_mig_before_vm_start(); 483 484 if (!global_state_received() || 485 global_state_get_runstate() == RUN_STATE_RUNNING) { 486 if (autostart) { 487 vm_start(); 488 } else { 489 runstate_set(RUN_STATE_PAUSED); 490 } 491 } else if (migration_incoming_colo_enabled()) { 492 migration_incoming_disable_colo(); 493 vm_start(); 494 } else { 495 runstate_set(global_state_get_runstate()); 496 } 497 /* 498 * This must happen after any state changes since as soon as an external 499 * observer sees this event they might start to prod at the VM assuming 500 * it's ready to use. 501 */ 502 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE, 503 MIGRATION_STATUS_COMPLETED); 504 qemu_bh_delete(mis->bh); 505 migration_incoming_state_destroy(); 506 } 507 508 static void coroutine_fn 509 process_incoming_migration_co(void *opaque) 510 { 511 MigrationIncomingState *mis = migration_incoming_get_current(); 512 PostcopyState ps; 513 int ret; 514 Error *local_err = NULL; 515 516 assert(mis->from_src_file); 517 518 if (compress_threads_load_setup(mis->from_src_file)) { 519 error_report("Failed to setup decompress threads"); 520 goto fail; 521 } 522 523 mis->migration_incoming_co = qemu_coroutine_self(); 524 mis->largest_page_size = qemu_ram_pagesize_largest(); 525 postcopy_state_set(POSTCOPY_INCOMING_NONE); 526 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE, 527 MIGRATION_STATUS_ACTIVE); 528 ret = qemu_loadvm_state(mis->from_src_file); 529 530 ps = postcopy_state_get(); 531 trace_process_incoming_migration_co_end(ret, ps); 532 if (ps != POSTCOPY_INCOMING_NONE) { 533 if (ps == POSTCOPY_INCOMING_ADVISE) { 534 /* 535 * Where a migration had postcopy enabled (and thus went to advise) 536 * but managed to complete within the precopy period, we can use 537 * the normal exit. 538 */ 539 postcopy_ram_incoming_cleanup(mis); 540 } else if (ret >= 0) { 541 /* 542 * Postcopy was started, cleanup should happen at the end of the 543 * postcopy thread. 544 */ 545 trace_process_incoming_migration_co_postcopy_end_main(); 546 return; 547 } 548 /* Else if something went wrong then just fall out of the normal exit */ 549 } 550 551 if (ret < 0) { 552 error_report("load of migration failed: %s", strerror(-ret)); 553 goto fail; 554 } 555 556 /* we get COLO info, and know if we are in COLO mode */ 557 if (migration_incoming_colo_enabled()) { 558 QemuThread colo_incoming_thread; 559 560 /* Make sure all file formats throw away their mutable metadata */ 561 bdrv_activate_all(&local_err); 562 if (local_err) { 563 error_report_err(local_err); 564 goto fail; 565 } 566 567 qemu_thread_create(&colo_incoming_thread, "COLO incoming", 568 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE); 569 qemu_coroutine_yield(); 570 571 qemu_mutex_unlock_iothread(); 572 /* Wait checkpoint incoming thread exit before free resource */ 573 qemu_thread_join(&colo_incoming_thread); 574 qemu_mutex_lock_iothread(); 575 /* We hold the global iothread lock, so it is safe here */ 576 colo_release_ram_cache(); 577 } 578 579 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis); 580 qemu_bh_schedule(mis->bh); 581 mis->migration_incoming_co = NULL; 582 return; 583 fail: 584 local_err = NULL; 585 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE, 586 MIGRATION_STATUS_FAILED); 587 qemu_fclose(mis->from_src_file); 588 589 multifd_load_cleanup(); 590 compress_threads_load_cleanup(); 591 592 exit(EXIT_FAILURE); 593 } 594 595 /** 596 * migration_incoming_setup: Setup incoming migration 597 * @f: file for main migration channel 598 * @errp: where to put errors 599 * 600 * Returns: %true on success, %false on error. 601 */ 602 static bool migration_incoming_setup(QEMUFile *f, Error **errp) 603 { 604 MigrationIncomingState *mis = migration_incoming_get_current(); 605 606 if (!mis->from_src_file) { 607 mis->from_src_file = f; 608 } 609 qemu_file_set_blocking(f, false); 610 return true; 611 } 612 613 void migration_incoming_process(void) 614 { 615 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL); 616 qemu_coroutine_enter(co); 617 } 618 619 /* Returns true if recovered from a paused migration, otherwise false */ 620 static bool postcopy_try_recover(void) 621 { 622 MigrationIncomingState *mis = migration_incoming_get_current(); 623 624 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) { 625 /* Resumed from a paused postcopy migration */ 626 627 /* This should be set already in migration_incoming_setup() */ 628 assert(mis->from_src_file); 629 /* Postcopy has standalone thread to do vm load */ 630 qemu_file_set_blocking(mis->from_src_file, true); 631 632 /* Re-configure the return path */ 633 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file); 634 635 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED, 636 MIGRATION_STATUS_POSTCOPY_RECOVER); 637 638 /* 639 * Here, we only wake up the main loading thread (while the 640 * rest threads will still be waiting), so that we can receive 641 * commands from source now, and answer it if needed. The 642 * rest threads will be woken up afterwards until we are sure 643 * that source is ready to reply to page requests. 644 */ 645 qemu_sem_post(&mis->postcopy_pause_sem_dst); 646 return true; 647 } 648 649 return false; 650 } 651 652 void migration_fd_process_incoming(QEMUFile *f, Error **errp) 653 { 654 if (!migration_incoming_setup(f, errp)) { 655 return; 656 } 657 if (postcopy_try_recover()) { 658 return; 659 } 660 migration_incoming_process(); 661 } 662 663 /* 664 * Returns true when we want to start a new incoming migration process, 665 * false otherwise. 666 */ 667 static bool migration_should_start_incoming(bool main_channel) 668 { 669 /* Multifd doesn't start unless all channels are established */ 670 if (migrate_multifd()) { 671 return migration_has_all_channels(); 672 } 673 674 /* Preempt channel only starts when the main channel is created */ 675 if (migrate_postcopy_preempt()) { 676 return main_channel; 677 } 678 679 /* 680 * For all the rest types of migration, we should only reach here when 681 * it's the main channel that's being created, and we should always 682 * proceed with this channel. 683 */ 684 assert(main_channel); 685 return true; 686 } 687 688 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp) 689 { 690 MigrationIncomingState *mis = migration_incoming_get_current(); 691 Error *local_err = NULL; 692 QEMUFile *f; 693 bool default_channel = true; 694 uint32_t channel_magic = 0; 695 int ret = 0; 696 697 if (migrate_multifd() && !migrate_postcopy_ram() && 698 qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { 699 /* 700 * With multiple channels, it is possible that we receive channels 701 * out of order on destination side, causing incorrect mapping of 702 * source channels on destination side. Check channel MAGIC to 703 * decide type of channel. Please note this is best effort, postcopy 704 * preempt channel does not send any magic number so avoid it for 705 * postcopy live migration. Also tls live migration already does 706 * tls handshake while initializing main channel so with tls this 707 * issue is not possible. 708 */ 709 ret = migration_channel_read_peek(ioc, (void *)&channel_magic, 710 sizeof(channel_magic), &local_err); 711 712 if (ret != 0) { 713 error_propagate(errp, local_err); 714 return; 715 } 716 717 default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC)); 718 } else { 719 default_channel = !mis->from_src_file; 720 } 721 722 if (multifd_load_setup(errp) != 0) { 723 error_setg(errp, "Failed to setup multifd channels"); 724 return; 725 } 726 727 if (default_channel) { 728 f = qemu_file_new_input(ioc); 729 730 if (!migration_incoming_setup(f, errp)) { 731 return; 732 } 733 } else { 734 /* Multiple connections */ 735 assert(migration_needs_multiple_sockets()); 736 if (migrate_multifd()) { 737 multifd_recv_new_channel(ioc, &local_err); 738 } else { 739 assert(migrate_postcopy_preempt()); 740 f = qemu_file_new_input(ioc); 741 postcopy_preempt_new_channel(mis, f); 742 } 743 if (local_err) { 744 error_propagate(errp, local_err); 745 return; 746 } 747 } 748 749 if (migration_should_start_incoming(default_channel)) { 750 /* If it's a recovery, we're done */ 751 if (postcopy_try_recover()) { 752 return; 753 } 754 migration_incoming_process(); 755 } 756 } 757 758 /** 759 * @migration_has_all_channels: We have received all channels that we need 760 * 761 * Returns true when we have got connections to all the channels that 762 * we need for migration. 763 */ 764 bool migration_has_all_channels(void) 765 { 766 MigrationIncomingState *mis = migration_incoming_get_current(); 767 768 if (!mis->from_src_file) { 769 return false; 770 } 771 772 if (migrate_multifd()) { 773 return multifd_recv_all_channels_created(); 774 } 775 776 if (migrate_postcopy_preempt()) { 777 return mis->postcopy_qemufile_dst != NULL; 778 } 779 780 return true; 781 } 782 783 /* 784 * Send a 'SHUT' message on the return channel with the given value 785 * to indicate that we've finished with the RP. Non-0 value indicates 786 * error. 787 */ 788 void migrate_send_rp_shut(MigrationIncomingState *mis, 789 uint32_t value) 790 { 791 uint32_t buf; 792 793 buf = cpu_to_be32(value); 794 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf); 795 } 796 797 /* 798 * Send a 'PONG' message on the return channel with the given value 799 * (normally in response to a 'PING') 800 */ 801 void migrate_send_rp_pong(MigrationIncomingState *mis, 802 uint32_t value) 803 { 804 uint32_t buf; 805 806 buf = cpu_to_be32(value); 807 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf); 808 } 809 810 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis, 811 char *block_name) 812 { 813 char buf[512]; 814 int len; 815 int64_t res; 816 817 /* 818 * First, we send the header part. It contains only the len of 819 * idstr, and the idstr itself. 820 */ 821 len = strlen(block_name); 822 buf[0] = len; 823 memcpy(buf + 1, block_name, len); 824 825 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) { 826 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery", 827 __func__); 828 return; 829 } 830 831 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf); 832 833 /* 834 * Next, we dump the received bitmap to the stream. 835 * 836 * TODO: currently we are safe since we are the only one that is 837 * using the to_src_file handle (fault thread is still paused), 838 * and it's ok even not taking the mutex. However the best way is 839 * to take the lock before sending the message header, and release 840 * the lock after sending the bitmap. 841 */ 842 qemu_mutex_lock(&mis->rp_mutex); 843 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name); 844 qemu_mutex_unlock(&mis->rp_mutex); 845 846 trace_migrate_send_rp_recv_bitmap(block_name, res); 847 } 848 849 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value) 850 { 851 uint32_t buf; 852 853 buf = cpu_to_be32(value); 854 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf); 855 } 856 857 /* 858 * Return true if we're already in the middle of a migration 859 * (i.e. any of the active or setup states) 860 */ 861 bool migration_is_setup_or_active(int state) 862 { 863 switch (state) { 864 case MIGRATION_STATUS_ACTIVE: 865 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 866 case MIGRATION_STATUS_POSTCOPY_PAUSED: 867 case MIGRATION_STATUS_POSTCOPY_RECOVER: 868 case MIGRATION_STATUS_SETUP: 869 case MIGRATION_STATUS_PRE_SWITCHOVER: 870 case MIGRATION_STATUS_DEVICE: 871 case MIGRATION_STATUS_WAIT_UNPLUG: 872 case MIGRATION_STATUS_COLO: 873 return true; 874 875 default: 876 return false; 877 878 } 879 } 880 881 bool migration_is_running(int state) 882 { 883 switch (state) { 884 case MIGRATION_STATUS_ACTIVE: 885 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 886 case MIGRATION_STATUS_POSTCOPY_PAUSED: 887 case MIGRATION_STATUS_POSTCOPY_RECOVER: 888 case MIGRATION_STATUS_SETUP: 889 case MIGRATION_STATUS_PRE_SWITCHOVER: 890 case MIGRATION_STATUS_DEVICE: 891 case MIGRATION_STATUS_WAIT_UNPLUG: 892 case MIGRATION_STATUS_CANCELLING: 893 return true; 894 895 default: 896 return false; 897 898 } 899 } 900 901 static bool migrate_show_downtime(MigrationState *s) 902 { 903 return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy(); 904 } 905 906 static void populate_time_info(MigrationInfo *info, MigrationState *s) 907 { 908 info->has_status = true; 909 info->has_setup_time = true; 910 info->setup_time = s->setup_time; 911 912 if (s->state == MIGRATION_STATUS_COMPLETED) { 913 info->has_total_time = true; 914 info->total_time = s->total_time; 915 } else { 916 info->has_total_time = true; 917 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - 918 s->start_time; 919 } 920 921 if (migrate_show_downtime(s)) { 922 info->has_downtime = true; 923 info->downtime = s->downtime; 924 } else { 925 info->has_expected_downtime = true; 926 info->expected_downtime = s->expected_downtime; 927 } 928 } 929 930 static void populate_ram_info(MigrationInfo *info, MigrationState *s) 931 { 932 size_t page_size = qemu_target_page_size(); 933 934 info->ram = g_malloc0(sizeof(*info->ram)); 935 info->ram->transferred = stat64_get(&mig_stats.transferred); 936 info->ram->total = ram_bytes_total(); 937 info->ram->duplicate = stat64_get(&mig_stats.zero_pages); 938 /* legacy value. It is not used anymore */ 939 info->ram->skipped = 0; 940 info->ram->normal = stat64_get(&mig_stats.normal_pages); 941 info->ram->normal_bytes = info->ram->normal * page_size; 942 info->ram->mbps = s->mbps; 943 info->ram->dirty_sync_count = 944 stat64_get(&mig_stats.dirty_sync_count); 945 info->ram->dirty_sync_missed_zero_copy = 946 stat64_get(&mig_stats.dirty_sync_missed_zero_copy); 947 info->ram->postcopy_requests = 948 stat64_get(&mig_stats.postcopy_requests); 949 info->ram->page_size = page_size; 950 info->ram->multifd_bytes = stat64_get(&mig_stats.multifd_bytes); 951 info->ram->pages_per_second = s->pages_per_second; 952 info->ram->precopy_bytes = stat64_get(&mig_stats.precopy_bytes); 953 info->ram->downtime_bytes = stat64_get(&mig_stats.downtime_bytes); 954 info->ram->postcopy_bytes = stat64_get(&mig_stats.postcopy_bytes); 955 956 if (migrate_xbzrle()) { 957 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache)); 958 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size(); 959 info->xbzrle_cache->bytes = xbzrle_counters.bytes; 960 info->xbzrle_cache->pages = xbzrle_counters.pages; 961 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss; 962 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate; 963 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate; 964 info->xbzrle_cache->overflow = xbzrle_counters.overflow; 965 } 966 967 if (migrate_compress()) { 968 info->compression = g_malloc0(sizeof(*info->compression)); 969 info->compression->pages = compression_counters.pages; 970 info->compression->busy = compression_counters.busy; 971 info->compression->busy_rate = compression_counters.busy_rate; 972 info->compression->compressed_size = 973 compression_counters.compressed_size; 974 info->compression->compression_rate = 975 compression_counters.compression_rate; 976 } 977 978 if (cpu_throttle_active()) { 979 info->has_cpu_throttle_percentage = true; 980 info->cpu_throttle_percentage = cpu_throttle_get_percentage(); 981 } 982 983 if (s->state != MIGRATION_STATUS_COMPLETED) { 984 info->ram->remaining = ram_bytes_remaining(); 985 info->ram->dirty_pages_rate = 986 stat64_get(&mig_stats.dirty_pages_rate); 987 } 988 } 989 990 static void populate_disk_info(MigrationInfo *info) 991 { 992 if (blk_mig_active()) { 993 info->disk = g_malloc0(sizeof(*info->disk)); 994 info->disk->transferred = blk_mig_bytes_transferred(); 995 info->disk->remaining = blk_mig_bytes_remaining(); 996 info->disk->total = blk_mig_bytes_total(); 997 } 998 } 999 1000 static void fill_source_migration_info(MigrationInfo *info) 1001 { 1002 MigrationState *s = migrate_get_current(); 1003 int state = qatomic_read(&s->state); 1004 GSList *cur_blocker = migration_blockers; 1005 1006 info->blocked_reasons = NULL; 1007 1008 /* 1009 * There are two types of reasons a migration might be blocked; 1010 * a) devices marked in VMState as non-migratable, and 1011 * b) Explicit migration blockers 1012 * We need to add both of them here. 1013 */ 1014 qemu_savevm_non_migratable_list(&info->blocked_reasons); 1015 1016 while (cur_blocker) { 1017 QAPI_LIST_PREPEND(info->blocked_reasons, 1018 g_strdup(error_get_pretty(cur_blocker->data))); 1019 cur_blocker = g_slist_next(cur_blocker); 1020 } 1021 info->has_blocked_reasons = info->blocked_reasons != NULL; 1022 1023 switch (state) { 1024 case MIGRATION_STATUS_NONE: 1025 /* no migration has happened ever */ 1026 /* do not overwrite destination migration status */ 1027 return; 1028 case MIGRATION_STATUS_SETUP: 1029 info->has_status = true; 1030 info->has_total_time = false; 1031 break; 1032 case MIGRATION_STATUS_ACTIVE: 1033 case MIGRATION_STATUS_CANCELLING: 1034 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1035 case MIGRATION_STATUS_PRE_SWITCHOVER: 1036 case MIGRATION_STATUS_DEVICE: 1037 case MIGRATION_STATUS_POSTCOPY_PAUSED: 1038 case MIGRATION_STATUS_POSTCOPY_RECOVER: 1039 /* TODO add some postcopy stats */ 1040 populate_time_info(info, s); 1041 populate_ram_info(info, s); 1042 populate_disk_info(info); 1043 populate_vfio_info(info); 1044 break; 1045 case MIGRATION_STATUS_COLO: 1046 info->has_status = true; 1047 /* TODO: display COLO specific information (checkpoint info etc.) */ 1048 break; 1049 case MIGRATION_STATUS_COMPLETED: 1050 populate_time_info(info, s); 1051 populate_ram_info(info, s); 1052 populate_vfio_info(info); 1053 break; 1054 case MIGRATION_STATUS_FAILED: 1055 info->has_status = true; 1056 if (s->error) { 1057 info->error_desc = g_strdup(error_get_pretty(s->error)); 1058 } 1059 break; 1060 case MIGRATION_STATUS_CANCELLED: 1061 info->has_status = true; 1062 break; 1063 case MIGRATION_STATUS_WAIT_UNPLUG: 1064 info->has_status = true; 1065 break; 1066 } 1067 info->status = state; 1068 } 1069 1070 static void fill_destination_migration_info(MigrationInfo *info) 1071 { 1072 MigrationIncomingState *mis = migration_incoming_get_current(); 1073 1074 if (mis->socket_address_list) { 1075 info->has_socket_address = true; 1076 info->socket_address = 1077 QAPI_CLONE(SocketAddressList, mis->socket_address_list); 1078 } 1079 1080 switch (mis->state) { 1081 case MIGRATION_STATUS_NONE: 1082 return; 1083 case MIGRATION_STATUS_SETUP: 1084 case MIGRATION_STATUS_CANCELLING: 1085 case MIGRATION_STATUS_CANCELLED: 1086 case MIGRATION_STATUS_ACTIVE: 1087 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1088 case MIGRATION_STATUS_POSTCOPY_PAUSED: 1089 case MIGRATION_STATUS_POSTCOPY_RECOVER: 1090 case MIGRATION_STATUS_FAILED: 1091 case MIGRATION_STATUS_COLO: 1092 info->has_status = true; 1093 break; 1094 case MIGRATION_STATUS_COMPLETED: 1095 info->has_status = true; 1096 fill_destination_postcopy_migration_info(info); 1097 break; 1098 } 1099 info->status = mis->state; 1100 } 1101 1102 MigrationInfo *qmp_query_migrate(Error **errp) 1103 { 1104 MigrationInfo *info = g_malloc0(sizeof(*info)); 1105 1106 fill_destination_migration_info(info); 1107 fill_source_migration_info(info); 1108 1109 return info; 1110 } 1111 1112 void qmp_migrate_start_postcopy(Error **errp) 1113 { 1114 MigrationState *s = migrate_get_current(); 1115 1116 if (!migrate_postcopy()) { 1117 error_setg(errp, "Enable postcopy with migrate_set_capability before" 1118 " the start of migration"); 1119 return; 1120 } 1121 1122 if (s->state == MIGRATION_STATUS_NONE) { 1123 error_setg(errp, "Postcopy must be started after migration has been" 1124 " started"); 1125 return; 1126 } 1127 /* 1128 * we don't error if migration has finished since that would be racy 1129 * with issuing this command. 1130 */ 1131 qatomic_set(&s->start_postcopy, true); 1132 } 1133 1134 /* shared migration helpers */ 1135 1136 void migrate_set_state(int *state, int old_state, int new_state) 1137 { 1138 assert(new_state < MIGRATION_STATUS__MAX); 1139 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) { 1140 trace_migrate_set_state(MigrationStatus_str(new_state)); 1141 migrate_generate_event(new_state); 1142 } 1143 } 1144 1145 static void migrate_fd_cleanup(MigrationState *s) 1146 { 1147 qemu_bh_delete(s->cleanup_bh); 1148 s->cleanup_bh = NULL; 1149 1150 g_free(s->hostname); 1151 s->hostname = NULL; 1152 json_writer_free(s->vmdesc); 1153 s->vmdesc = NULL; 1154 1155 qemu_savevm_state_cleanup(); 1156 1157 if (s->to_dst_file) { 1158 QEMUFile *tmp; 1159 1160 trace_migrate_fd_cleanup(); 1161 qemu_mutex_unlock_iothread(); 1162 if (s->migration_thread_running) { 1163 qemu_thread_join(&s->thread); 1164 s->migration_thread_running = false; 1165 } 1166 qemu_mutex_lock_iothread(); 1167 1168 multifd_save_cleanup(); 1169 qemu_mutex_lock(&s->qemu_file_lock); 1170 tmp = s->to_dst_file; 1171 s->to_dst_file = NULL; 1172 qemu_mutex_unlock(&s->qemu_file_lock); 1173 /* 1174 * Close the file handle without the lock to make sure the 1175 * critical section won't block for long. 1176 */ 1177 migration_ioc_unregister_yank_from_file(tmp); 1178 qemu_fclose(tmp); 1179 } 1180 1181 if (s->postcopy_qemufile_src) { 1182 migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src); 1183 qemu_fclose(s->postcopy_qemufile_src); 1184 s->postcopy_qemufile_src = NULL; 1185 } 1186 1187 assert(!migration_is_active(s)); 1188 1189 if (s->state == MIGRATION_STATUS_CANCELLING) { 1190 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING, 1191 MIGRATION_STATUS_CANCELLED); 1192 } 1193 1194 if (s->error) { 1195 /* It is used on info migrate. We can't free it */ 1196 error_report_err(error_copy(s->error)); 1197 } 1198 notifier_list_notify(&migration_state_notifiers, s); 1199 block_cleanup_parameters(); 1200 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 1201 } 1202 1203 static void migrate_fd_cleanup_schedule(MigrationState *s) 1204 { 1205 /* 1206 * Ref the state for bh, because it may be called when 1207 * there're already no other refs 1208 */ 1209 object_ref(OBJECT(s)); 1210 qemu_bh_schedule(s->cleanup_bh); 1211 } 1212 1213 static void migrate_fd_cleanup_bh(void *opaque) 1214 { 1215 MigrationState *s = opaque; 1216 migrate_fd_cleanup(s); 1217 object_unref(OBJECT(s)); 1218 } 1219 1220 void migrate_set_error(MigrationState *s, const Error *error) 1221 { 1222 QEMU_LOCK_GUARD(&s->error_mutex); 1223 if (!s->error) { 1224 s->error = error_copy(error); 1225 } 1226 } 1227 1228 static void migrate_error_free(MigrationState *s) 1229 { 1230 QEMU_LOCK_GUARD(&s->error_mutex); 1231 if (s->error) { 1232 error_free(s->error); 1233 s->error = NULL; 1234 } 1235 } 1236 1237 void migrate_fd_error(MigrationState *s, const Error *error) 1238 { 1239 trace_migrate_fd_error(error_get_pretty(error)); 1240 assert(s->to_dst_file == NULL); 1241 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 1242 MIGRATION_STATUS_FAILED); 1243 migrate_set_error(s, error); 1244 } 1245 1246 static void migrate_fd_cancel(MigrationState *s) 1247 { 1248 int old_state ; 1249 QEMUFile *f = migrate_get_current()->to_dst_file; 1250 trace_migrate_fd_cancel(); 1251 1252 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) { 1253 if (s->rp_state.from_dst_file) { 1254 /* shutdown the rp socket, so causing the rp thread to shutdown */ 1255 qemu_file_shutdown(s->rp_state.from_dst_file); 1256 } 1257 } 1258 1259 do { 1260 old_state = s->state; 1261 if (!migration_is_running(old_state)) { 1262 break; 1263 } 1264 /* If the migration is paused, kick it out of the pause */ 1265 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) { 1266 qemu_sem_post(&s->pause_sem); 1267 } 1268 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING); 1269 } while (s->state != MIGRATION_STATUS_CANCELLING); 1270 1271 /* 1272 * If we're unlucky the migration code might be stuck somewhere in a 1273 * send/write while the network has failed and is waiting to timeout; 1274 * if we've got shutdown(2) available then we can force it to quit. 1275 * The outgoing qemu file gets closed in migrate_fd_cleanup that is 1276 * called in a bh, so there is no race against this cancel. 1277 */ 1278 if (s->state == MIGRATION_STATUS_CANCELLING && f) { 1279 qemu_file_shutdown(f); 1280 } 1281 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) { 1282 Error *local_err = NULL; 1283 1284 bdrv_activate_all(&local_err); 1285 if (local_err) { 1286 error_report_err(local_err); 1287 } else { 1288 s->block_inactive = false; 1289 } 1290 } 1291 } 1292 1293 void add_migration_state_change_notifier(Notifier *notify) 1294 { 1295 notifier_list_add(&migration_state_notifiers, notify); 1296 } 1297 1298 void remove_migration_state_change_notifier(Notifier *notify) 1299 { 1300 notifier_remove(notify); 1301 } 1302 1303 bool migration_in_setup(MigrationState *s) 1304 { 1305 return s->state == MIGRATION_STATUS_SETUP; 1306 } 1307 1308 bool migration_has_finished(MigrationState *s) 1309 { 1310 return s->state == MIGRATION_STATUS_COMPLETED; 1311 } 1312 1313 bool migration_has_failed(MigrationState *s) 1314 { 1315 return (s->state == MIGRATION_STATUS_CANCELLED || 1316 s->state == MIGRATION_STATUS_FAILED); 1317 } 1318 1319 bool migration_in_postcopy(void) 1320 { 1321 MigrationState *s = migrate_get_current(); 1322 1323 switch (s->state) { 1324 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1325 case MIGRATION_STATUS_POSTCOPY_PAUSED: 1326 case MIGRATION_STATUS_POSTCOPY_RECOVER: 1327 return true; 1328 default: 1329 return false; 1330 } 1331 } 1332 1333 bool migration_in_postcopy_after_devices(MigrationState *s) 1334 { 1335 return migration_in_postcopy() && s->postcopy_after_devices; 1336 } 1337 1338 bool migration_in_incoming_postcopy(void) 1339 { 1340 PostcopyState ps = postcopy_state_get(); 1341 1342 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END; 1343 } 1344 1345 bool migration_incoming_postcopy_advised(void) 1346 { 1347 PostcopyState ps = postcopy_state_get(); 1348 1349 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END; 1350 } 1351 1352 bool migration_in_bg_snapshot(void) 1353 { 1354 MigrationState *s = migrate_get_current(); 1355 1356 return migrate_background_snapshot() && 1357 migration_is_setup_or_active(s->state); 1358 } 1359 1360 bool migration_is_idle(void) 1361 { 1362 MigrationState *s = current_migration; 1363 1364 if (!s) { 1365 return true; 1366 } 1367 1368 switch (s->state) { 1369 case MIGRATION_STATUS_NONE: 1370 case MIGRATION_STATUS_CANCELLED: 1371 case MIGRATION_STATUS_COMPLETED: 1372 case MIGRATION_STATUS_FAILED: 1373 return true; 1374 case MIGRATION_STATUS_SETUP: 1375 case MIGRATION_STATUS_CANCELLING: 1376 case MIGRATION_STATUS_ACTIVE: 1377 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1378 case MIGRATION_STATUS_COLO: 1379 case MIGRATION_STATUS_PRE_SWITCHOVER: 1380 case MIGRATION_STATUS_DEVICE: 1381 case MIGRATION_STATUS_WAIT_UNPLUG: 1382 return false; 1383 case MIGRATION_STATUS__MAX: 1384 g_assert_not_reached(); 1385 } 1386 1387 return false; 1388 } 1389 1390 bool migration_is_active(MigrationState *s) 1391 { 1392 return (s->state == MIGRATION_STATUS_ACTIVE || 1393 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE); 1394 } 1395 1396 void migrate_init(MigrationState *s) 1397 { 1398 /* 1399 * Reinitialise all migration state, except 1400 * parameters/capabilities that the user set, and 1401 * locks. 1402 */ 1403 s->cleanup_bh = 0; 1404 s->vm_start_bh = 0; 1405 s->to_dst_file = NULL; 1406 s->state = MIGRATION_STATUS_NONE; 1407 s->rp_state.from_dst_file = NULL; 1408 s->rp_state.error = false; 1409 s->mbps = 0.0; 1410 s->pages_per_second = 0.0; 1411 s->downtime = 0; 1412 s->expected_downtime = 0; 1413 s->setup_time = 0; 1414 s->start_postcopy = false; 1415 s->postcopy_after_devices = false; 1416 s->migration_thread_running = false; 1417 error_free(s->error); 1418 s->error = NULL; 1419 s->hostname = NULL; 1420 1421 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP); 1422 1423 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 1424 s->total_time = 0; 1425 s->vm_was_running = false; 1426 s->iteration_initial_bytes = 0; 1427 s->threshold_size = 0; 1428 } 1429 1430 int migrate_add_blocker_internal(Error *reason, Error **errp) 1431 { 1432 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */ 1433 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) { 1434 error_propagate_prepend(errp, error_copy(reason), 1435 "disallowing migration blocker " 1436 "(migration/snapshot in progress) for: "); 1437 return -EBUSY; 1438 } 1439 1440 migration_blockers = g_slist_prepend(migration_blockers, reason); 1441 return 0; 1442 } 1443 1444 int migrate_add_blocker(Error *reason, Error **errp) 1445 { 1446 if (only_migratable) { 1447 error_propagate_prepend(errp, error_copy(reason), 1448 "disallowing migration blocker " 1449 "(--only-migratable) for: "); 1450 return -EACCES; 1451 } 1452 1453 return migrate_add_blocker_internal(reason, errp); 1454 } 1455 1456 void migrate_del_blocker(Error *reason) 1457 { 1458 migration_blockers = g_slist_remove(migration_blockers, reason); 1459 } 1460 1461 void qmp_migrate_incoming(const char *uri, Error **errp) 1462 { 1463 Error *local_err = NULL; 1464 static bool once = true; 1465 1466 if (!once) { 1467 error_setg(errp, "The incoming migration has already been started"); 1468 return; 1469 } 1470 if (!runstate_check(RUN_STATE_INMIGRATE)) { 1471 error_setg(errp, "'-incoming' was not specified on the command line"); 1472 return; 1473 } 1474 1475 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) { 1476 return; 1477 } 1478 1479 qemu_start_incoming_migration(uri, &local_err); 1480 1481 if (local_err) { 1482 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 1483 error_propagate(errp, local_err); 1484 return; 1485 } 1486 1487 once = false; 1488 } 1489 1490 void qmp_migrate_recover(const char *uri, Error **errp) 1491 { 1492 MigrationIncomingState *mis = migration_incoming_get_current(); 1493 1494 /* 1495 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by 1496 * callers (no one should ignore a recover failure); if there is, it's a 1497 * programming error. 1498 */ 1499 assert(errp); 1500 1501 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) { 1502 error_setg(errp, "Migrate recover can only be run " 1503 "when postcopy is paused."); 1504 return; 1505 } 1506 1507 /* If there's an existing transport, release it */ 1508 migration_incoming_transport_cleanup(mis); 1509 1510 /* 1511 * Note that this call will never start a real migration; it will 1512 * only re-setup the migration stream and poke existing migration 1513 * to continue using that newly established channel. 1514 */ 1515 qemu_start_incoming_migration(uri, errp); 1516 } 1517 1518 void qmp_migrate_pause(Error **errp) 1519 { 1520 MigrationState *ms = migrate_get_current(); 1521 MigrationIncomingState *mis = migration_incoming_get_current(); 1522 int ret; 1523 1524 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 1525 /* Source side, during postcopy */ 1526 qemu_mutex_lock(&ms->qemu_file_lock); 1527 ret = qemu_file_shutdown(ms->to_dst_file); 1528 qemu_mutex_unlock(&ms->qemu_file_lock); 1529 if (ret) { 1530 error_setg(errp, "Failed to pause source migration"); 1531 } 1532 return; 1533 } 1534 1535 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 1536 ret = qemu_file_shutdown(mis->from_src_file); 1537 if (ret) { 1538 error_setg(errp, "Failed to pause destination migration"); 1539 } 1540 return; 1541 } 1542 1543 error_setg(errp, "migrate-pause is currently only supported " 1544 "during postcopy-active state"); 1545 } 1546 1547 bool migration_is_blocked(Error **errp) 1548 { 1549 if (qemu_savevm_state_blocked(errp)) { 1550 return true; 1551 } 1552 1553 if (migration_blockers) { 1554 error_propagate(errp, error_copy(migration_blockers->data)); 1555 return true; 1556 } 1557 1558 return false; 1559 } 1560 1561 /* Returns true if continue to migrate, or false if error detected */ 1562 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc, 1563 bool resume, Error **errp) 1564 { 1565 Error *local_err = NULL; 1566 1567 if (resume) { 1568 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) { 1569 error_setg(errp, "Cannot resume if there is no " 1570 "paused migration"); 1571 return false; 1572 } 1573 1574 /* 1575 * Postcopy recovery won't work well with release-ram 1576 * capability since release-ram will drop the page buffer as 1577 * long as the page is put into the send buffer. So if there 1578 * is a network failure happened, any page buffers that have 1579 * not yet reached the destination VM but have already been 1580 * sent from the source VM will be lost forever. Let's refuse 1581 * the client from resuming such a postcopy migration. 1582 * Luckily release-ram was designed to only be used when src 1583 * and destination VMs are on the same host, so it should be 1584 * fine. 1585 */ 1586 if (migrate_release_ram()) { 1587 error_setg(errp, "Postcopy recovery cannot work " 1588 "when release-ram capability is set"); 1589 return false; 1590 } 1591 1592 /* This is a resume, skip init status */ 1593 return true; 1594 } 1595 1596 if (migration_is_running(s->state)) { 1597 error_setg(errp, QERR_MIGRATION_ACTIVE); 1598 return false; 1599 } 1600 1601 if (runstate_check(RUN_STATE_INMIGRATE)) { 1602 error_setg(errp, "Guest is waiting for an incoming migration"); 1603 return false; 1604 } 1605 1606 if (runstate_check(RUN_STATE_POSTMIGRATE)) { 1607 error_setg(errp, "Can't migrate the vm that was paused due to " 1608 "previous migration"); 1609 return false; 1610 } 1611 1612 if (migration_is_blocked(errp)) { 1613 return false; 1614 } 1615 1616 if (blk || blk_inc) { 1617 if (migrate_colo()) { 1618 error_setg(errp, "No disk migration is required in COLO mode"); 1619 return false; 1620 } 1621 if (migrate_block() || migrate_block_incremental()) { 1622 error_setg(errp, "Command options are incompatible with " 1623 "current migration capabilities"); 1624 return false; 1625 } 1626 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK, true, &local_err)) { 1627 error_propagate(errp, local_err); 1628 return false; 1629 } 1630 s->must_remove_block_options = true; 1631 } 1632 1633 if (blk_inc) { 1634 migrate_set_block_incremental(true); 1635 } 1636 1637 migrate_init(s); 1638 /* 1639 * set mig_stats compression_counters memory to zero for a 1640 * new migration 1641 */ 1642 memset(&mig_stats, 0, sizeof(mig_stats)); 1643 memset(&compression_counters, 0, sizeof(compression_counters)); 1644 1645 return true; 1646 } 1647 1648 void qmp_migrate(const char *uri, bool has_blk, bool blk, 1649 bool has_inc, bool inc, bool has_detach, bool detach, 1650 bool has_resume, bool resume, Error **errp) 1651 { 1652 Error *local_err = NULL; 1653 MigrationState *s = migrate_get_current(); 1654 const char *p = NULL; 1655 1656 /* URI is not suitable for migration? */ 1657 if (!migration_channels_and_uri_compatible(uri, errp)) { 1658 return; 1659 } 1660 1661 if (!migrate_prepare(s, has_blk && blk, has_inc && inc, 1662 has_resume && resume, errp)) { 1663 /* Error detected, put into errp */ 1664 return; 1665 } 1666 1667 if (!(has_resume && resume)) { 1668 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) { 1669 return; 1670 } 1671 } 1672 1673 if (strstart(uri, "tcp:", &p) || 1674 strstart(uri, "unix:", NULL) || 1675 strstart(uri, "vsock:", NULL)) { 1676 socket_start_outgoing_migration(s, p ? p : uri, &local_err); 1677 #ifdef CONFIG_RDMA 1678 } else if (strstart(uri, "rdma:", &p)) { 1679 rdma_start_outgoing_migration(s, p, &local_err); 1680 #endif 1681 } else if (strstart(uri, "exec:", &p)) { 1682 exec_start_outgoing_migration(s, p, &local_err); 1683 } else if (strstart(uri, "fd:", &p)) { 1684 fd_start_outgoing_migration(s, p, &local_err); 1685 } else { 1686 if (!(has_resume && resume)) { 1687 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 1688 } 1689 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri", 1690 "a valid migration protocol"); 1691 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 1692 MIGRATION_STATUS_FAILED); 1693 block_cleanup_parameters(); 1694 return; 1695 } 1696 1697 if (local_err) { 1698 if (!(has_resume && resume)) { 1699 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 1700 } 1701 migrate_fd_error(s, local_err); 1702 error_propagate(errp, local_err); 1703 return; 1704 } 1705 } 1706 1707 void qmp_migrate_cancel(Error **errp) 1708 { 1709 migration_cancel(NULL); 1710 } 1711 1712 void qmp_migrate_continue(MigrationStatus state, Error **errp) 1713 { 1714 MigrationState *s = migrate_get_current(); 1715 if (s->state != state) { 1716 error_setg(errp, "Migration not in expected state: %s", 1717 MigrationStatus_str(s->state)); 1718 return; 1719 } 1720 qemu_sem_post(&s->pause_sem); 1721 } 1722 1723 /* migration thread support */ 1724 /* 1725 * Something bad happened to the RP stream, mark an error 1726 * The caller shall print or trace something to indicate why 1727 */ 1728 static void mark_source_rp_bad(MigrationState *s) 1729 { 1730 s->rp_state.error = true; 1731 } 1732 1733 static struct rp_cmd_args { 1734 ssize_t len; /* -1 = variable */ 1735 const char *name; 1736 } rp_cmd_args[] = { 1737 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" }, 1738 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" }, 1739 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" }, 1740 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" }, 1741 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" }, 1742 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" }, 1743 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" }, 1744 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" }, 1745 }; 1746 1747 /* 1748 * Process a request for pages received on the return path, 1749 * We're allowed to send more than requested (e.g. to round to our page size) 1750 * and we don't need to send pages that have already been sent. 1751 */ 1752 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname, 1753 ram_addr_t start, size_t len) 1754 { 1755 long our_host_ps = qemu_real_host_page_size(); 1756 1757 trace_migrate_handle_rp_req_pages(rbname, start, len); 1758 1759 /* 1760 * Since we currently insist on matching page sizes, just sanity check 1761 * we're being asked for whole host pages. 1762 */ 1763 if (!QEMU_IS_ALIGNED(start, our_host_ps) || 1764 !QEMU_IS_ALIGNED(len, our_host_ps)) { 1765 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT 1766 " len: %zd", __func__, start, len); 1767 mark_source_rp_bad(ms); 1768 return; 1769 } 1770 1771 if (ram_save_queue_pages(rbname, start, len)) { 1772 mark_source_rp_bad(ms); 1773 } 1774 } 1775 1776 /* Return true to retry, false to quit */ 1777 static bool postcopy_pause_return_path_thread(MigrationState *s) 1778 { 1779 trace_postcopy_pause_return_path(); 1780 1781 qemu_sem_wait(&s->postcopy_pause_rp_sem); 1782 1783 trace_postcopy_pause_return_path_continued(); 1784 1785 return true; 1786 } 1787 1788 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name) 1789 { 1790 RAMBlock *block = qemu_ram_block_by_name(block_name); 1791 1792 if (!block) { 1793 error_report("%s: invalid block name '%s'", __func__, block_name); 1794 return -EINVAL; 1795 } 1796 1797 /* Fetch the received bitmap and refresh the dirty bitmap */ 1798 return ram_dirty_bitmap_reload(s, block); 1799 } 1800 1801 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value) 1802 { 1803 trace_source_return_path_thread_resume_ack(value); 1804 1805 if (value != MIGRATION_RESUME_ACK_VALUE) { 1806 error_report("%s: illegal resume_ack value %"PRIu32, 1807 __func__, value); 1808 return -1; 1809 } 1810 1811 /* Now both sides are active. */ 1812 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER, 1813 MIGRATION_STATUS_POSTCOPY_ACTIVE); 1814 1815 /* Notify send thread that time to continue send pages */ 1816 qemu_sem_post(&s->rp_state.rp_sem); 1817 1818 return 0; 1819 } 1820 1821 /* 1822 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if 1823 * existed) in a safe way. 1824 */ 1825 static void migration_release_dst_files(MigrationState *ms) 1826 { 1827 QEMUFile *file; 1828 1829 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) { 1830 /* 1831 * Reset the from_dst_file pointer first before releasing it, as we 1832 * can't block within lock section 1833 */ 1834 file = ms->rp_state.from_dst_file; 1835 ms->rp_state.from_dst_file = NULL; 1836 } 1837 1838 /* 1839 * Do the same to postcopy fast path socket too if there is. No 1840 * locking needed because this qemufile should only be managed by 1841 * return path thread. 1842 */ 1843 if (ms->postcopy_qemufile_src) { 1844 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src); 1845 qemu_file_shutdown(ms->postcopy_qemufile_src); 1846 qemu_fclose(ms->postcopy_qemufile_src); 1847 ms->postcopy_qemufile_src = NULL; 1848 } 1849 1850 qemu_fclose(file); 1851 } 1852 1853 /* 1854 * Handles messages sent on the return path towards the source VM 1855 * 1856 */ 1857 static void *source_return_path_thread(void *opaque) 1858 { 1859 MigrationState *ms = opaque; 1860 QEMUFile *rp = ms->rp_state.from_dst_file; 1861 uint16_t header_len, header_type; 1862 uint8_t buf[512]; 1863 uint32_t tmp32, sibling_error; 1864 ram_addr_t start = 0; /* =0 to silence warning */ 1865 size_t len = 0, expected_len; 1866 int res; 1867 1868 trace_source_return_path_thread_entry(); 1869 rcu_register_thread(); 1870 1871 retry: 1872 while (!ms->rp_state.error && !qemu_file_get_error(rp) && 1873 migration_is_setup_or_active(ms->state)) { 1874 trace_source_return_path_thread_loop_top(); 1875 header_type = qemu_get_be16(rp); 1876 header_len = qemu_get_be16(rp); 1877 1878 if (qemu_file_get_error(rp)) { 1879 mark_source_rp_bad(ms); 1880 goto out; 1881 } 1882 1883 if (header_type >= MIG_RP_MSG_MAX || 1884 header_type == MIG_RP_MSG_INVALID) { 1885 error_report("RP: Received invalid message 0x%04x length 0x%04x", 1886 header_type, header_len); 1887 mark_source_rp_bad(ms); 1888 goto out; 1889 } 1890 1891 if ((rp_cmd_args[header_type].len != -1 && 1892 header_len != rp_cmd_args[header_type].len) || 1893 header_len > sizeof(buf)) { 1894 error_report("RP: Received '%s' message (0x%04x) with" 1895 "incorrect length %d expecting %zu", 1896 rp_cmd_args[header_type].name, header_type, header_len, 1897 (size_t)rp_cmd_args[header_type].len); 1898 mark_source_rp_bad(ms); 1899 goto out; 1900 } 1901 1902 /* We know we've got a valid header by this point */ 1903 res = qemu_get_buffer(rp, buf, header_len); 1904 if (res != header_len) { 1905 error_report("RP: Failed reading data for message 0x%04x" 1906 " read %d expected %d", 1907 header_type, res, header_len); 1908 mark_source_rp_bad(ms); 1909 goto out; 1910 } 1911 1912 /* OK, we have the message and the data */ 1913 switch (header_type) { 1914 case MIG_RP_MSG_SHUT: 1915 sibling_error = ldl_be_p(buf); 1916 trace_source_return_path_thread_shut(sibling_error); 1917 if (sibling_error) { 1918 error_report("RP: Sibling indicated error %d", sibling_error); 1919 mark_source_rp_bad(ms); 1920 } 1921 /* 1922 * We'll let the main thread deal with closing the RP 1923 * we could do a shutdown(2) on it, but we're the only user 1924 * anyway, so there's nothing gained. 1925 */ 1926 goto out; 1927 1928 case MIG_RP_MSG_PONG: 1929 tmp32 = ldl_be_p(buf); 1930 trace_source_return_path_thread_pong(tmp32); 1931 qemu_sem_post(&ms->rp_state.rp_pong_acks); 1932 break; 1933 1934 case MIG_RP_MSG_REQ_PAGES: 1935 start = ldq_be_p(buf); 1936 len = ldl_be_p(buf + 8); 1937 migrate_handle_rp_req_pages(ms, NULL, start, len); 1938 break; 1939 1940 case MIG_RP_MSG_REQ_PAGES_ID: 1941 expected_len = 12 + 1; /* header + termination */ 1942 1943 if (header_len >= expected_len) { 1944 start = ldq_be_p(buf); 1945 len = ldl_be_p(buf + 8); 1946 /* Now we expect an idstr */ 1947 tmp32 = buf[12]; /* Length of the following idstr */ 1948 buf[13 + tmp32] = '\0'; 1949 expected_len += tmp32; 1950 } 1951 if (header_len != expected_len) { 1952 error_report("RP: Req_Page_id with length %d expecting %zd", 1953 header_len, expected_len); 1954 mark_source_rp_bad(ms); 1955 goto out; 1956 } 1957 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len); 1958 break; 1959 1960 case MIG_RP_MSG_RECV_BITMAP: 1961 if (header_len < 1) { 1962 error_report("%s: missing block name", __func__); 1963 mark_source_rp_bad(ms); 1964 goto out; 1965 } 1966 /* Format: len (1B) + idstr (<255B). This ends the idstr. */ 1967 buf[buf[0] + 1] = '\0'; 1968 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) { 1969 mark_source_rp_bad(ms); 1970 goto out; 1971 } 1972 break; 1973 1974 case MIG_RP_MSG_RESUME_ACK: 1975 tmp32 = ldl_be_p(buf); 1976 if (migrate_handle_rp_resume_ack(ms, tmp32)) { 1977 mark_source_rp_bad(ms); 1978 goto out; 1979 } 1980 break; 1981 1982 default: 1983 break; 1984 } 1985 } 1986 1987 out: 1988 res = qemu_file_get_error(rp); 1989 if (res) { 1990 if (res && migration_in_postcopy()) { 1991 /* 1992 * Maybe there is something we can do: it looks like a 1993 * network down issue, and we pause for a recovery. 1994 */ 1995 migration_release_dst_files(ms); 1996 rp = NULL; 1997 if (postcopy_pause_return_path_thread(ms)) { 1998 /* 1999 * Reload rp, reset the rest. Referencing it is safe since 2000 * it's reset only by us above, or when migration completes 2001 */ 2002 rp = ms->rp_state.from_dst_file; 2003 ms->rp_state.error = false; 2004 goto retry; 2005 } 2006 } 2007 2008 trace_source_return_path_thread_bad_end(); 2009 mark_source_rp_bad(ms); 2010 } 2011 2012 trace_source_return_path_thread_end(); 2013 migration_release_dst_files(ms); 2014 rcu_unregister_thread(); 2015 return NULL; 2016 } 2017 2018 static int open_return_path_on_source(MigrationState *ms, 2019 bool create_thread) 2020 { 2021 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file); 2022 if (!ms->rp_state.from_dst_file) { 2023 return -1; 2024 } 2025 2026 trace_open_return_path_on_source(); 2027 2028 if (!create_thread) { 2029 /* We're done */ 2030 return 0; 2031 } 2032 2033 qemu_thread_create(&ms->rp_state.rp_thread, "return path", 2034 source_return_path_thread, ms, QEMU_THREAD_JOINABLE); 2035 ms->rp_state.rp_thread_created = true; 2036 2037 trace_open_return_path_on_source_continue(); 2038 2039 return 0; 2040 } 2041 2042 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */ 2043 static int await_return_path_close_on_source(MigrationState *ms) 2044 { 2045 /* 2046 * If this is a normal exit then the destination will send a SHUT and the 2047 * rp_thread will exit, however if there's an error we need to cause 2048 * it to exit. 2049 */ 2050 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) { 2051 /* 2052 * shutdown(2), if we have it, will cause it to unblock if it's stuck 2053 * waiting for the destination. 2054 */ 2055 qemu_file_shutdown(ms->rp_state.from_dst_file); 2056 mark_source_rp_bad(ms); 2057 } 2058 trace_await_return_path_close_on_source_joining(); 2059 qemu_thread_join(&ms->rp_state.rp_thread); 2060 ms->rp_state.rp_thread_created = false; 2061 trace_await_return_path_close_on_source_close(); 2062 return ms->rp_state.error; 2063 } 2064 2065 static inline void 2066 migration_wait_main_channel(MigrationState *ms) 2067 { 2068 /* Wait until one PONG message received */ 2069 qemu_sem_wait(&ms->rp_state.rp_pong_acks); 2070 } 2071 2072 /* 2073 * Switch from normal iteration to postcopy 2074 * Returns non-0 on error 2075 */ 2076 static int postcopy_start(MigrationState *ms) 2077 { 2078 int ret; 2079 QIOChannelBuffer *bioc; 2080 QEMUFile *fb; 2081 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2082 uint64_t bandwidth = migrate_max_postcopy_bandwidth(); 2083 bool restart_block = false; 2084 int cur_state = MIGRATION_STATUS_ACTIVE; 2085 2086 if (migrate_postcopy_preempt()) { 2087 migration_wait_main_channel(ms); 2088 if (postcopy_preempt_establish_channel(ms)) { 2089 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED); 2090 return -1; 2091 } 2092 } 2093 2094 if (!migrate_pause_before_switchover()) { 2095 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE, 2096 MIGRATION_STATUS_POSTCOPY_ACTIVE); 2097 } 2098 2099 trace_postcopy_start(); 2100 qemu_mutex_lock_iothread(); 2101 trace_postcopy_start_set_run(); 2102 2103 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL); 2104 global_state_store(); 2105 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE); 2106 if (ret < 0) { 2107 goto fail; 2108 } 2109 2110 ret = migration_maybe_pause(ms, &cur_state, 2111 MIGRATION_STATUS_POSTCOPY_ACTIVE); 2112 if (ret < 0) { 2113 goto fail; 2114 } 2115 2116 ret = bdrv_inactivate_all(); 2117 if (ret < 0) { 2118 goto fail; 2119 } 2120 restart_block = true; 2121 2122 /* 2123 * Cause any non-postcopiable, but iterative devices to 2124 * send out their final data. 2125 */ 2126 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false); 2127 2128 /* 2129 * in Finish migrate and with the io-lock held everything should 2130 * be quiet, but we've potentially still got dirty pages and we 2131 * need to tell the destination to throw any pages it's already received 2132 * that are dirty 2133 */ 2134 if (migrate_postcopy_ram()) { 2135 ram_postcopy_send_discard_bitmap(ms); 2136 } 2137 2138 /* 2139 * send rest of state - note things that are doing postcopy 2140 * will notice we're in POSTCOPY_ACTIVE and not actually 2141 * wrap their state up here 2142 */ 2143 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth); 2144 if (migrate_postcopy_ram()) { 2145 /* Ping just for debugging, helps line traces up */ 2146 qemu_savevm_send_ping(ms->to_dst_file, 2); 2147 } 2148 2149 /* 2150 * While loading the device state we may trigger page transfer 2151 * requests and the fd must be free to process those, and thus 2152 * the destination must read the whole device state off the fd before 2153 * it starts processing it. Unfortunately the ad-hoc migration format 2154 * doesn't allow the destination to know the size to read without fully 2155 * parsing it through each devices load-state code (especially the open 2156 * coded devices that use get/put). 2157 * So we wrap the device state up in a package with a length at the start; 2158 * to do this we use a qemu_buf to hold the whole of the device state. 2159 */ 2160 bioc = qio_channel_buffer_new(4096); 2161 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer"); 2162 fb = qemu_file_new_output(QIO_CHANNEL(bioc)); 2163 object_unref(OBJECT(bioc)); 2164 2165 /* 2166 * Make sure the receiver can get incoming pages before we send the rest 2167 * of the state 2168 */ 2169 qemu_savevm_send_postcopy_listen(fb); 2170 2171 qemu_savevm_state_complete_precopy(fb, false, false); 2172 if (migrate_postcopy_ram()) { 2173 qemu_savevm_send_ping(fb, 3); 2174 } 2175 2176 qemu_savevm_send_postcopy_run(fb); 2177 2178 /* <><> end of stuff going into the package */ 2179 2180 /* Last point of recovery; as soon as we send the package the destination 2181 * can open devices and potentially start running. 2182 * Lets just check again we've not got any errors. 2183 */ 2184 ret = qemu_file_get_error(ms->to_dst_file); 2185 if (ret) { 2186 error_report("postcopy_start: Migration stream errored (pre package)"); 2187 goto fail_closefb; 2188 } 2189 2190 restart_block = false; 2191 2192 /* Now send that blob */ 2193 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) { 2194 goto fail_closefb; 2195 } 2196 qemu_fclose(fb); 2197 2198 /* Send a notify to give a chance for anything that needs to happen 2199 * at the transition to postcopy and after the device state; in particular 2200 * spice needs to trigger a transition now 2201 */ 2202 ms->postcopy_after_devices = true; 2203 notifier_list_notify(&migration_state_notifiers, ms); 2204 2205 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop; 2206 2207 qemu_mutex_unlock_iothread(); 2208 2209 if (migrate_postcopy_ram()) { 2210 /* 2211 * Although this ping is just for debug, it could potentially be 2212 * used for getting a better measurement of downtime at the source. 2213 */ 2214 qemu_savevm_send_ping(ms->to_dst_file, 4); 2215 } 2216 2217 if (migrate_release_ram()) { 2218 ram_postcopy_migrated_memory_release(ms); 2219 } 2220 2221 ret = qemu_file_get_error(ms->to_dst_file); 2222 if (ret) { 2223 error_report("postcopy_start: Migration stream errored"); 2224 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE, 2225 MIGRATION_STATUS_FAILED); 2226 } 2227 2228 trace_postcopy_preempt_enabled(migrate_postcopy_preempt()); 2229 2230 return ret; 2231 2232 fail_closefb: 2233 qemu_fclose(fb); 2234 fail: 2235 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE, 2236 MIGRATION_STATUS_FAILED); 2237 if (restart_block) { 2238 /* A failure happened early enough that we know the destination hasn't 2239 * accessed block devices, so we're safe to recover. 2240 */ 2241 Error *local_err = NULL; 2242 2243 bdrv_activate_all(&local_err); 2244 if (local_err) { 2245 error_report_err(local_err); 2246 } 2247 } 2248 qemu_mutex_unlock_iothread(); 2249 return -1; 2250 } 2251 2252 /** 2253 * migration_maybe_pause: Pause if required to by 2254 * migrate_pause_before_switchover called with the iothread locked 2255 * Returns: 0 on success 2256 */ 2257 static int migration_maybe_pause(MigrationState *s, 2258 int *current_active_state, 2259 int new_state) 2260 { 2261 if (!migrate_pause_before_switchover()) { 2262 return 0; 2263 } 2264 2265 /* Since leaving this state is not atomic with posting the semaphore 2266 * it's possible that someone could have issued multiple migrate_continue 2267 * and the semaphore is incorrectly positive at this point; 2268 * the docs say it's undefined to reinit a semaphore that's already 2269 * init'd, so use timedwait to eat up any existing posts. 2270 */ 2271 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) { 2272 /* This block intentionally left blank */ 2273 } 2274 2275 /* 2276 * If the migration is cancelled when it is in the completion phase, 2277 * the migration state is set to MIGRATION_STATUS_CANCELLING. 2278 * So we don't need to wait a semaphore, otherwise we would always 2279 * wait for the 'pause_sem' semaphore. 2280 */ 2281 if (s->state != MIGRATION_STATUS_CANCELLING) { 2282 qemu_mutex_unlock_iothread(); 2283 migrate_set_state(&s->state, *current_active_state, 2284 MIGRATION_STATUS_PRE_SWITCHOVER); 2285 qemu_sem_wait(&s->pause_sem); 2286 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER, 2287 new_state); 2288 *current_active_state = new_state; 2289 qemu_mutex_lock_iothread(); 2290 } 2291 2292 return s->state == new_state ? 0 : -EINVAL; 2293 } 2294 2295 /** 2296 * migration_completion: Used by migration_thread when there's not much left. 2297 * The caller 'breaks' the loop when this returns. 2298 * 2299 * @s: Current migration state 2300 */ 2301 static void migration_completion(MigrationState *s) 2302 { 2303 int ret; 2304 int current_active_state = s->state; 2305 2306 if (s->state == MIGRATION_STATUS_ACTIVE) { 2307 qemu_mutex_lock_iothread(); 2308 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2309 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL); 2310 s->vm_was_running = runstate_is_running(); 2311 ret = global_state_store(); 2312 2313 if (!ret) { 2314 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE); 2315 trace_migration_completion_vm_stop(ret); 2316 if (ret >= 0) { 2317 ret = migration_maybe_pause(s, ¤t_active_state, 2318 MIGRATION_STATUS_DEVICE); 2319 } 2320 if (ret >= 0) { 2321 /* 2322 * Inactivate disks except in COLO, and track that we 2323 * have done so in order to remember to reactivate 2324 * them if migration fails or is cancelled. 2325 */ 2326 s->block_inactive = !migrate_colo(); 2327 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX); 2328 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false, 2329 s->block_inactive); 2330 } 2331 } 2332 qemu_mutex_unlock_iothread(); 2333 2334 if (ret < 0) { 2335 goto fail; 2336 } 2337 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 2338 trace_migration_completion_postcopy_end(); 2339 2340 qemu_mutex_lock_iothread(); 2341 qemu_savevm_state_complete_postcopy(s->to_dst_file); 2342 qemu_mutex_unlock_iothread(); 2343 2344 /* 2345 * Shutdown the postcopy fast path thread. This is only needed 2346 * when dest QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need 2347 * this. 2348 */ 2349 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) { 2350 postcopy_preempt_shutdown_file(s); 2351 } 2352 2353 trace_migration_completion_postcopy_end_after_complete(); 2354 } else { 2355 goto fail; 2356 } 2357 2358 /* 2359 * If rp was opened we must clean up the thread before 2360 * cleaning everything else up (since if there are no failures 2361 * it will wait for the destination to send it's status in 2362 * a SHUT command). 2363 */ 2364 if (s->rp_state.rp_thread_created) { 2365 int rp_error; 2366 trace_migration_return_path_end_before(); 2367 rp_error = await_return_path_close_on_source(s); 2368 trace_migration_return_path_end_after(rp_error); 2369 if (rp_error) { 2370 goto fail; 2371 } 2372 } 2373 2374 if (qemu_file_get_error(s->to_dst_file)) { 2375 trace_migration_completion_file_err(); 2376 goto fail; 2377 } 2378 2379 if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) { 2380 /* COLO does not support postcopy */ 2381 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE, 2382 MIGRATION_STATUS_COLO); 2383 } else { 2384 migrate_set_state(&s->state, current_active_state, 2385 MIGRATION_STATUS_COMPLETED); 2386 } 2387 2388 return; 2389 2390 fail: 2391 if (s->block_inactive && (s->state == MIGRATION_STATUS_ACTIVE || 2392 s->state == MIGRATION_STATUS_DEVICE)) { 2393 /* 2394 * If not doing postcopy, vm_start() will be called: let's 2395 * regain control on images. 2396 */ 2397 Error *local_err = NULL; 2398 2399 qemu_mutex_lock_iothread(); 2400 bdrv_activate_all(&local_err); 2401 if (local_err) { 2402 error_report_err(local_err); 2403 } else { 2404 s->block_inactive = false; 2405 } 2406 qemu_mutex_unlock_iothread(); 2407 } 2408 2409 migrate_set_state(&s->state, current_active_state, 2410 MIGRATION_STATUS_FAILED); 2411 } 2412 2413 /** 2414 * bg_migration_completion: Used by bg_migration_thread when after all the 2415 * RAM has been saved. The caller 'breaks' the loop when this returns. 2416 * 2417 * @s: Current migration state 2418 */ 2419 static void bg_migration_completion(MigrationState *s) 2420 { 2421 int current_active_state = s->state; 2422 2423 /* 2424 * Stop tracking RAM writes - un-protect memory, un-register UFFD 2425 * memory ranges, flush kernel wait queues and wake up threads 2426 * waiting for write fault to be resolved. 2427 */ 2428 ram_write_tracking_stop(); 2429 2430 if (s->state == MIGRATION_STATUS_ACTIVE) { 2431 /* 2432 * By this moment we have RAM content saved into the migration stream. 2433 * The next step is to flush the non-RAM content (device state) 2434 * right after the ram content. The device state has been stored into 2435 * the temporary buffer before RAM saving started. 2436 */ 2437 qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage); 2438 qemu_fflush(s->to_dst_file); 2439 } else if (s->state == MIGRATION_STATUS_CANCELLING) { 2440 goto fail; 2441 } 2442 2443 if (qemu_file_get_error(s->to_dst_file)) { 2444 trace_migration_completion_file_err(); 2445 goto fail; 2446 } 2447 2448 migrate_set_state(&s->state, current_active_state, 2449 MIGRATION_STATUS_COMPLETED); 2450 return; 2451 2452 fail: 2453 migrate_set_state(&s->state, current_active_state, 2454 MIGRATION_STATUS_FAILED); 2455 } 2456 2457 typedef enum MigThrError { 2458 /* No error detected */ 2459 MIG_THR_ERR_NONE = 0, 2460 /* Detected error, but resumed successfully */ 2461 MIG_THR_ERR_RECOVERED = 1, 2462 /* Detected fatal error, need to exit */ 2463 MIG_THR_ERR_FATAL = 2, 2464 } MigThrError; 2465 2466 static int postcopy_resume_handshake(MigrationState *s) 2467 { 2468 qemu_savevm_send_postcopy_resume(s->to_dst_file); 2469 2470 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) { 2471 qemu_sem_wait(&s->rp_state.rp_sem); 2472 } 2473 2474 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 2475 return 0; 2476 } 2477 2478 return -1; 2479 } 2480 2481 /* Return zero if success, or <0 for error */ 2482 static int postcopy_do_resume(MigrationState *s) 2483 { 2484 int ret; 2485 2486 /* 2487 * Call all the resume_prepare() hooks, so that modules can be 2488 * ready for the migration resume. 2489 */ 2490 ret = qemu_savevm_state_resume_prepare(s); 2491 if (ret) { 2492 error_report("%s: resume_prepare() failure detected: %d", 2493 __func__, ret); 2494 return ret; 2495 } 2496 2497 /* 2498 * If preempt is enabled, re-establish the preempt channel. Note that 2499 * we do it after resume prepare to make sure the main channel will be 2500 * created before the preempt channel. E.g. with weak network, the 2501 * dest QEMU may get messed up with the preempt and main channels on 2502 * the order of connection setup. This guarantees the correct order. 2503 */ 2504 ret = postcopy_preempt_establish_channel(s); 2505 if (ret) { 2506 error_report("%s: postcopy_preempt_establish_channel(): %d", 2507 __func__, ret); 2508 return ret; 2509 } 2510 2511 /* 2512 * Last handshake with destination on the resume (destination will 2513 * switch to postcopy-active afterwards) 2514 */ 2515 ret = postcopy_resume_handshake(s); 2516 if (ret) { 2517 error_report("%s: handshake failed: %d", __func__, ret); 2518 return ret; 2519 } 2520 2521 return 0; 2522 } 2523 2524 /* 2525 * We don't return until we are in a safe state to continue current 2526 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or 2527 * MIG_THR_ERR_FATAL if unrecovery failure happened. 2528 */ 2529 static MigThrError postcopy_pause(MigrationState *s) 2530 { 2531 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE); 2532 2533 while (true) { 2534 QEMUFile *file; 2535 2536 /* 2537 * Current channel is possibly broken. Release it. Note that this is 2538 * guaranteed even without lock because to_dst_file should only be 2539 * modified by the migration thread. That also guarantees that the 2540 * unregister of yank is safe too without the lock. It should be safe 2541 * even to be within the qemu_file_lock, but we didn't do that to avoid 2542 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make 2543 * the qemu_file_lock critical section as small as possible. 2544 */ 2545 assert(s->to_dst_file); 2546 migration_ioc_unregister_yank_from_file(s->to_dst_file); 2547 qemu_mutex_lock(&s->qemu_file_lock); 2548 file = s->to_dst_file; 2549 s->to_dst_file = NULL; 2550 qemu_mutex_unlock(&s->qemu_file_lock); 2551 2552 qemu_file_shutdown(file); 2553 qemu_fclose(file); 2554 2555 migrate_set_state(&s->state, s->state, 2556 MIGRATION_STATUS_POSTCOPY_PAUSED); 2557 2558 error_report("Detected IO failure for postcopy. " 2559 "Migration paused."); 2560 2561 /* 2562 * We wait until things fixed up. Then someone will setup the 2563 * status back for us. 2564 */ 2565 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) { 2566 qemu_sem_wait(&s->postcopy_pause_sem); 2567 } 2568 2569 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) { 2570 /* Woken up by a recover procedure. Give it a shot */ 2571 2572 /* 2573 * Firstly, let's wake up the return path now, with a new 2574 * return path channel. 2575 */ 2576 qemu_sem_post(&s->postcopy_pause_rp_sem); 2577 2578 /* Do the resume logic */ 2579 if (postcopy_do_resume(s) == 0) { 2580 /* Let's continue! */ 2581 trace_postcopy_pause_continued(); 2582 return MIG_THR_ERR_RECOVERED; 2583 } else { 2584 /* 2585 * Something wrong happened during the recovery, let's 2586 * pause again. Pause is always better than throwing 2587 * data away. 2588 */ 2589 continue; 2590 } 2591 } else { 2592 /* This is not right... Time to quit. */ 2593 return MIG_THR_ERR_FATAL; 2594 } 2595 } 2596 } 2597 2598 static MigThrError migration_detect_error(MigrationState *s) 2599 { 2600 int ret; 2601 int state = s->state; 2602 Error *local_error = NULL; 2603 2604 if (state == MIGRATION_STATUS_CANCELLING || 2605 state == MIGRATION_STATUS_CANCELLED) { 2606 /* End the migration, but don't set the state to failed */ 2607 return MIG_THR_ERR_FATAL; 2608 } 2609 2610 /* 2611 * Try to detect any file errors. Note that postcopy_qemufile_src will 2612 * be NULL when postcopy preempt is not enabled. 2613 */ 2614 ret = qemu_file_get_error_obj_any(s->to_dst_file, 2615 s->postcopy_qemufile_src, 2616 &local_error); 2617 if (!ret) { 2618 /* Everything is fine */ 2619 assert(!local_error); 2620 return MIG_THR_ERR_NONE; 2621 } 2622 2623 if (local_error) { 2624 migrate_set_error(s, local_error); 2625 error_free(local_error); 2626 } 2627 2628 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) { 2629 /* 2630 * For postcopy, we allow the network to be down for a 2631 * while. After that, it can be continued by a 2632 * recovery phase. 2633 */ 2634 return postcopy_pause(s); 2635 } else { 2636 /* 2637 * For precopy (or postcopy with error outside IO), we fail 2638 * with no time. 2639 */ 2640 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED); 2641 trace_migration_thread_file_err(); 2642 2643 /* Time to stop the migration, now. */ 2644 return MIG_THR_ERR_FATAL; 2645 } 2646 } 2647 2648 /* How many bytes have we transferred since the beginning of the migration */ 2649 static uint64_t migration_total_bytes(MigrationState *s) 2650 { 2651 return qemu_file_transferred(s->to_dst_file) + 2652 stat64_get(&mig_stats.multifd_bytes); 2653 } 2654 2655 static void migration_calculate_complete(MigrationState *s) 2656 { 2657 uint64_t bytes = migration_total_bytes(s); 2658 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2659 int64_t transfer_time; 2660 2661 s->total_time = end_time - s->start_time; 2662 if (!s->downtime) { 2663 /* 2664 * It's still not set, so we are precopy migration. For 2665 * postcopy, downtime is calculated during postcopy_start(). 2666 */ 2667 s->downtime = end_time - s->downtime_start; 2668 } 2669 2670 transfer_time = s->total_time - s->setup_time; 2671 if (transfer_time) { 2672 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000; 2673 } 2674 } 2675 2676 static void update_iteration_initial_status(MigrationState *s) 2677 { 2678 /* 2679 * Update these three fields at the same time to avoid mismatch info lead 2680 * wrong speed calculation. 2681 */ 2682 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2683 s->iteration_initial_bytes = migration_total_bytes(s); 2684 s->iteration_initial_pages = ram_get_total_transferred_pages(); 2685 } 2686 2687 static void migration_update_counters(MigrationState *s, 2688 int64_t current_time) 2689 { 2690 uint64_t transferred, transferred_pages, time_spent; 2691 uint64_t current_bytes; /* bytes transferred since the beginning */ 2692 double bandwidth; 2693 2694 if (current_time < s->iteration_start_time + BUFFER_DELAY) { 2695 return; 2696 } 2697 2698 current_bytes = migration_total_bytes(s); 2699 transferred = current_bytes - s->iteration_initial_bytes; 2700 time_spent = current_time - s->iteration_start_time; 2701 bandwidth = (double)transferred / time_spent; 2702 s->threshold_size = bandwidth * migrate_downtime_limit(); 2703 2704 s->mbps = (((double) transferred * 8.0) / 2705 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0; 2706 2707 transferred_pages = ram_get_total_transferred_pages() - 2708 s->iteration_initial_pages; 2709 s->pages_per_second = (double) transferred_pages / 2710 (((double) time_spent / 1000.0)); 2711 2712 /* 2713 * if we haven't sent anything, we don't want to 2714 * recalculate. 10000 is a small enough number for our purposes 2715 */ 2716 if (stat64_get(&mig_stats.dirty_pages_rate) && 2717 transferred > 10000) { 2718 s->expected_downtime = 2719 stat64_get(&mig_stats.dirty_bytes_last_sync) / bandwidth; 2720 } 2721 2722 qemu_file_reset_rate_limit(s->to_dst_file); 2723 2724 update_iteration_initial_status(s); 2725 2726 trace_migrate_transferred(transferred, time_spent, 2727 bandwidth, s->threshold_size); 2728 } 2729 2730 /* Migration thread iteration status */ 2731 typedef enum { 2732 MIG_ITERATE_RESUME, /* Resume current iteration */ 2733 MIG_ITERATE_SKIP, /* Skip current iteration */ 2734 MIG_ITERATE_BREAK, /* Break the loop */ 2735 } MigIterateState; 2736 2737 /* 2738 * Return true if continue to the next iteration directly, false 2739 * otherwise. 2740 */ 2741 static MigIterateState migration_iteration_run(MigrationState *s) 2742 { 2743 uint64_t must_precopy, can_postcopy; 2744 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE; 2745 2746 qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy); 2747 uint64_t pending_size = must_precopy + can_postcopy; 2748 2749 trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy); 2750 2751 if (must_precopy <= s->threshold_size) { 2752 qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy); 2753 pending_size = must_precopy + can_postcopy; 2754 trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy); 2755 } 2756 2757 if (!pending_size || pending_size < s->threshold_size) { 2758 trace_migration_thread_low_pending(pending_size); 2759 migration_completion(s); 2760 return MIG_ITERATE_BREAK; 2761 } 2762 2763 /* Still a significant amount to transfer */ 2764 if (!in_postcopy && must_precopy <= s->threshold_size && 2765 qatomic_read(&s->start_postcopy)) { 2766 if (postcopy_start(s)) { 2767 error_report("%s: postcopy failed to start", __func__); 2768 } 2769 return MIG_ITERATE_SKIP; 2770 } 2771 2772 /* Just another iteration step */ 2773 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy); 2774 return MIG_ITERATE_RESUME; 2775 } 2776 2777 static void migration_iteration_finish(MigrationState *s) 2778 { 2779 /* If we enabled cpu throttling for auto-converge, turn it off. */ 2780 cpu_throttle_stop(); 2781 2782 qemu_mutex_lock_iothread(); 2783 switch (s->state) { 2784 case MIGRATION_STATUS_COMPLETED: 2785 migration_calculate_complete(s); 2786 runstate_set(RUN_STATE_POSTMIGRATE); 2787 break; 2788 case MIGRATION_STATUS_COLO: 2789 assert(migrate_colo()); 2790 migrate_start_colo_process(s); 2791 s->vm_was_running = true; 2792 /* Fallthrough */ 2793 case MIGRATION_STATUS_FAILED: 2794 case MIGRATION_STATUS_CANCELLED: 2795 case MIGRATION_STATUS_CANCELLING: 2796 if (s->vm_was_running) { 2797 if (!runstate_check(RUN_STATE_SHUTDOWN)) { 2798 vm_start(); 2799 } 2800 } else { 2801 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) { 2802 runstate_set(RUN_STATE_POSTMIGRATE); 2803 } 2804 } 2805 break; 2806 2807 default: 2808 /* Should not reach here, but if so, forgive the VM. */ 2809 error_report("%s: Unknown ending state %d", __func__, s->state); 2810 break; 2811 } 2812 migrate_fd_cleanup_schedule(s); 2813 qemu_mutex_unlock_iothread(); 2814 } 2815 2816 static void bg_migration_iteration_finish(MigrationState *s) 2817 { 2818 qemu_mutex_lock_iothread(); 2819 switch (s->state) { 2820 case MIGRATION_STATUS_COMPLETED: 2821 migration_calculate_complete(s); 2822 break; 2823 2824 case MIGRATION_STATUS_ACTIVE: 2825 case MIGRATION_STATUS_FAILED: 2826 case MIGRATION_STATUS_CANCELLED: 2827 case MIGRATION_STATUS_CANCELLING: 2828 break; 2829 2830 default: 2831 /* Should not reach here, but if so, forgive the VM. */ 2832 error_report("%s: Unknown ending state %d", __func__, s->state); 2833 break; 2834 } 2835 2836 migrate_fd_cleanup_schedule(s); 2837 qemu_mutex_unlock_iothread(); 2838 } 2839 2840 /* 2841 * Return true if continue to the next iteration directly, false 2842 * otherwise. 2843 */ 2844 static MigIterateState bg_migration_iteration_run(MigrationState *s) 2845 { 2846 int res; 2847 2848 res = qemu_savevm_state_iterate(s->to_dst_file, false); 2849 if (res > 0) { 2850 bg_migration_completion(s); 2851 return MIG_ITERATE_BREAK; 2852 } 2853 2854 return MIG_ITERATE_RESUME; 2855 } 2856 2857 void migration_make_urgent_request(void) 2858 { 2859 qemu_sem_post(&migrate_get_current()->rate_limit_sem); 2860 } 2861 2862 void migration_consume_urgent_request(void) 2863 { 2864 qemu_sem_wait(&migrate_get_current()->rate_limit_sem); 2865 } 2866 2867 /* Returns true if the rate limiting was broken by an urgent request */ 2868 bool migration_rate_limit(void) 2869 { 2870 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2871 MigrationState *s = migrate_get_current(); 2872 2873 bool urgent = false; 2874 migration_update_counters(s, now); 2875 if (qemu_file_rate_limit(s->to_dst_file)) { 2876 2877 if (qemu_file_get_error(s->to_dst_file)) { 2878 return false; 2879 } 2880 /* 2881 * Wait for a delay to do rate limiting OR 2882 * something urgent to post the semaphore. 2883 */ 2884 int ms = s->iteration_start_time + BUFFER_DELAY - now; 2885 trace_migration_rate_limit_pre(ms); 2886 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) { 2887 /* 2888 * We were woken by one or more urgent things but 2889 * the timedwait will have consumed one of them. 2890 * The service routine for the urgent wake will dec 2891 * the semaphore itself for each item it consumes, 2892 * so add this one we just eat back. 2893 */ 2894 qemu_sem_post(&s->rate_limit_sem); 2895 urgent = true; 2896 } 2897 trace_migration_rate_limit_post(urgent); 2898 } 2899 return urgent; 2900 } 2901 2902 /* 2903 * if failover devices are present, wait they are completely 2904 * unplugged 2905 */ 2906 2907 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state, 2908 int new_state) 2909 { 2910 if (qemu_savevm_state_guest_unplug_pending()) { 2911 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG); 2912 2913 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG && 2914 qemu_savevm_state_guest_unplug_pending()) { 2915 qemu_sem_timedwait(&s->wait_unplug_sem, 250); 2916 } 2917 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) { 2918 int timeout = 120; /* 30 seconds */ 2919 /* 2920 * migration has been canceled 2921 * but as we have started an unplug we must wait the end 2922 * to be able to plug back the card 2923 */ 2924 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) { 2925 qemu_sem_timedwait(&s->wait_unplug_sem, 250); 2926 } 2927 if (qemu_savevm_state_guest_unplug_pending() && 2928 !qtest_enabled()) { 2929 warn_report("migration: partially unplugged device on " 2930 "failure"); 2931 } 2932 } 2933 2934 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state); 2935 } else { 2936 migrate_set_state(&s->state, old_state, new_state); 2937 } 2938 } 2939 2940 /* 2941 * Master migration thread on the source VM. 2942 * It drives the migration and pumps the data down the outgoing channel. 2943 */ 2944 static void *migration_thread(void *opaque) 2945 { 2946 MigrationState *s = opaque; 2947 MigrationThread *thread = NULL; 2948 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST); 2949 MigThrError thr_error; 2950 bool urgent = false; 2951 2952 thread = MigrationThreadAdd("live_migration", qemu_get_thread_id()); 2953 2954 rcu_register_thread(); 2955 2956 object_ref(OBJECT(s)); 2957 update_iteration_initial_status(s); 2958 2959 qemu_savevm_state_header(s->to_dst_file); 2960 2961 /* 2962 * If we opened the return path, we need to make sure dst has it 2963 * opened as well. 2964 */ 2965 if (s->rp_state.rp_thread_created) { 2966 /* Now tell the dest that it should open its end so it can reply */ 2967 qemu_savevm_send_open_return_path(s->to_dst_file); 2968 2969 /* And do a ping that will make stuff easier to debug */ 2970 qemu_savevm_send_ping(s->to_dst_file, 1); 2971 } 2972 2973 if (migrate_postcopy()) { 2974 /* 2975 * Tell the destination that we *might* want to do postcopy later; 2976 * if the other end can't do postcopy it should fail now, nice and 2977 * early. 2978 */ 2979 qemu_savevm_send_postcopy_advise(s->to_dst_file); 2980 } 2981 2982 if (migrate_colo()) { 2983 /* Notify migration destination that we enable COLO */ 2984 qemu_savevm_send_colo_enable(s->to_dst_file); 2985 } 2986 2987 qemu_savevm_state_setup(s->to_dst_file); 2988 2989 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP, 2990 MIGRATION_STATUS_ACTIVE); 2991 2992 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start; 2993 2994 trace_migration_thread_setup_complete(); 2995 2996 while (migration_is_active(s)) { 2997 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) { 2998 MigIterateState iter_state = migration_iteration_run(s); 2999 if (iter_state == MIG_ITERATE_SKIP) { 3000 continue; 3001 } else if (iter_state == MIG_ITERATE_BREAK) { 3002 break; 3003 } 3004 } 3005 3006 /* 3007 * Try to detect any kind of failures, and see whether we 3008 * should stop the migration now. 3009 */ 3010 thr_error = migration_detect_error(s); 3011 if (thr_error == MIG_THR_ERR_FATAL) { 3012 /* Stop migration */ 3013 break; 3014 } else if (thr_error == MIG_THR_ERR_RECOVERED) { 3015 /* 3016 * Just recovered from a e.g. network failure, reset all 3017 * the local variables. This is important to avoid 3018 * breaking transferred_bytes and bandwidth calculation 3019 */ 3020 update_iteration_initial_status(s); 3021 } 3022 3023 urgent = migration_rate_limit(); 3024 } 3025 3026 trace_migration_thread_after_loop(); 3027 migration_iteration_finish(s); 3028 object_unref(OBJECT(s)); 3029 rcu_unregister_thread(); 3030 MigrationThreadDel(thread); 3031 return NULL; 3032 } 3033 3034 static void bg_migration_vm_start_bh(void *opaque) 3035 { 3036 MigrationState *s = opaque; 3037 3038 qemu_bh_delete(s->vm_start_bh); 3039 s->vm_start_bh = NULL; 3040 3041 vm_start(); 3042 s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start; 3043 } 3044 3045 /** 3046 * Background snapshot thread, based on live migration code. 3047 * This is an alternative implementation of live migration mechanism 3048 * introduced specifically to support background snapshots. 3049 * 3050 * It takes advantage of userfault_fd write protection mechanism introduced 3051 * in v5.7 kernel. Compared to existing dirty page logging migration much 3052 * lesser stream traffic is produced resulting in smaller snapshot images, 3053 * simply cause of no page duplicates can get into the stream. 3054 * 3055 * Another key point is that generated vmstate stream reflects machine state 3056 * 'frozen' at the beginning of snapshot creation compared to dirty page logging 3057 * mechanism, which effectively results in that saved snapshot is the state of VM 3058 * at the end of the process. 3059 */ 3060 static void *bg_migration_thread(void *opaque) 3061 { 3062 MigrationState *s = opaque; 3063 int64_t setup_start; 3064 MigThrError thr_error; 3065 QEMUFile *fb; 3066 bool early_fail = true; 3067 3068 rcu_register_thread(); 3069 object_ref(OBJECT(s)); 3070 3071 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX); 3072 3073 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST); 3074 /* 3075 * We want to save vmstate for the moment when migration has been 3076 * initiated but also we want to save RAM content while VM is running. 3077 * The RAM content should appear first in the vmstate. So, we first 3078 * stash the non-RAM part of the vmstate to the temporary buffer, 3079 * then write RAM part of the vmstate to the migration stream 3080 * with vCPUs running and, finally, write stashed non-RAM part of 3081 * the vmstate from the buffer to the migration stream. 3082 */ 3083 s->bioc = qio_channel_buffer_new(512 * 1024); 3084 qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer"); 3085 fb = qemu_file_new_output(QIO_CHANNEL(s->bioc)); 3086 object_unref(OBJECT(s->bioc)); 3087 3088 update_iteration_initial_status(s); 3089 3090 /* 3091 * Prepare for tracking memory writes with UFFD-WP - populate 3092 * RAM pages before protecting. 3093 */ 3094 #ifdef __linux__ 3095 ram_write_tracking_prepare(); 3096 #endif 3097 3098 qemu_savevm_state_header(s->to_dst_file); 3099 qemu_savevm_state_setup(s->to_dst_file); 3100 3101 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP, 3102 MIGRATION_STATUS_ACTIVE); 3103 3104 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start; 3105 3106 trace_migration_thread_setup_complete(); 3107 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 3108 3109 qemu_mutex_lock_iothread(); 3110 3111 /* 3112 * If VM is currently in suspended state, then, to make a valid runstate 3113 * transition in vm_stop_force_state() we need to wakeup it up. 3114 */ 3115 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL); 3116 s->vm_was_running = runstate_is_running(); 3117 3118 if (global_state_store()) { 3119 goto fail; 3120 } 3121 /* Forcibly stop VM before saving state of vCPUs and devices */ 3122 if (vm_stop_force_state(RUN_STATE_PAUSED)) { 3123 goto fail; 3124 } 3125 /* 3126 * Put vCPUs in sync with shadow context structures, then 3127 * save their state to channel-buffer along with devices. 3128 */ 3129 cpu_synchronize_all_states(); 3130 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) { 3131 goto fail; 3132 } 3133 /* 3134 * Since we are going to get non-iterable state data directly 3135 * from s->bioc->data, explicit flush is needed here. 3136 */ 3137 qemu_fflush(fb); 3138 3139 /* Now initialize UFFD context and start tracking RAM writes */ 3140 if (ram_write_tracking_start()) { 3141 goto fail; 3142 } 3143 early_fail = false; 3144 3145 /* 3146 * Start VM from BH handler to avoid write-fault lock here. 3147 * UFFD-WP protection for the whole RAM is already enabled so 3148 * calling VM state change notifiers from vm_start() would initiate 3149 * writes to virtio VQs memory which is in write-protected region. 3150 */ 3151 s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s); 3152 qemu_bh_schedule(s->vm_start_bh); 3153 3154 qemu_mutex_unlock_iothread(); 3155 3156 while (migration_is_active(s)) { 3157 MigIterateState iter_state = bg_migration_iteration_run(s); 3158 if (iter_state == MIG_ITERATE_SKIP) { 3159 continue; 3160 } else if (iter_state == MIG_ITERATE_BREAK) { 3161 break; 3162 } 3163 3164 /* 3165 * Try to detect any kind of failures, and see whether we 3166 * should stop the migration now. 3167 */ 3168 thr_error = migration_detect_error(s); 3169 if (thr_error == MIG_THR_ERR_FATAL) { 3170 /* Stop migration */ 3171 break; 3172 } 3173 3174 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME)); 3175 } 3176 3177 trace_migration_thread_after_loop(); 3178 3179 fail: 3180 if (early_fail) { 3181 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE, 3182 MIGRATION_STATUS_FAILED); 3183 qemu_mutex_unlock_iothread(); 3184 } 3185 3186 bg_migration_iteration_finish(s); 3187 3188 qemu_fclose(fb); 3189 object_unref(OBJECT(s)); 3190 rcu_unregister_thread(); 3191 3192 return NULL; 3193 } 3194 3195 void migrate_fd_connect(MigrationState *s, Error *error_in) 3196 { 3197 Error *local_err = NULL; 3198 uint64_t rate_limit; 3199 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED; 3200 3201 /* 3202 * If there's a previous error, free it and prepare for another one. 3203 * Meanwhile if migration completes successfully, there won't have an error 3204 * dumped when calling migrate_fd_cleanup(). 3205 */ 3206 migrate_error_free(s); 3207 3208 s->expected_downtime = migrate_downtime_limit(); 3209 if (resume) { 3210 assert(s->cleanup_bh); 3211 } else { 3212 assert(!s->cleanup_bh); 3213 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s); 3214 } 3215 if (error_in) { 3216 migrate_fd_error(s, error_in); 3217 if (resume) { 3218 /* 3219 * Don't do cleanup for resume if channel is invalid, but only dump 3220 * the error. We wait for another channel connect from the user. 3221 * The error_report still gives HMP user a hint on what failed. 3222 * It's normally done in migrate_fd_cleanup(), but call it here 3223 * explicitly. 3224 */ 3225 error_report_err(error_copy(s->error)); 3226 } else { 3227 migrate_fd_cleanup(s); 3228 } 3229 return; 3230 } 3231 3232 if (resume) { 3233 /* This is a resumed migration */ 3234 rate_limit = migrate_max_postcopy_bandwidth(); 3235 } else { 3236 /* This is a fresh new migration */ 3237 rate_limit = migrate_max_bandwidth(); 3238 3239 /* Notify before starting migration thread */ 3240 notifier_list_notify(&migration_state_notifiers, s); 3241 } 3242 3243 qemu_file_set_rate_limit(s->to_dst_file, rate_limit); 3244 qemu_file_set_blocking(s->to_dst_file, true); 3245 3246 /* 3247 * Open the return path. For postcopy, it is used exclusively. For 3248 * precopy, only if user specified "return-path" capability would 3249 * QEMU uses the return path. 3250 */ 3251 if (migrate_postcopy_ram() || migrate_return_path()) { 3252 if (open_return_path_on_source(s, !resume)) { 3253 error_report("Unable to open return-path for postcopy"); 3254 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED); 3255 migrate_fd_cleanup(s); 3256 return; 3257 } 3258 } 3259 3260 /* 3261 * This needs to be done before resuming a postcopy. Note: for newer 3262 * QEMUs we will delay the channel creation until postcopy_start(), to 3263 * avoid disorder of channel creations. 3264 */ 3265 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) { 3266 postcopy_preempt_setup(s); 3267 } 3268 3269 if (resume) { 3270 /* Wakeup the main migration thread to do the recovery */ 3271 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED, 3272 MIGRATION_STATUS_POSTCOPY_RECOVER); 3273 qemu_sem_post(&s->postcopy_pause_sem); 3274 return; 3275 } 3276 3277 if (multifd_save_setup(&local_err) != 0) { 3278 error_report_err(local_err); 3279 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 3280 MIGRATION_STATUS_FAILED); 3281 migrate_fd_cleanup(s); 3282 return; 3283 } 3284 3285 if (migrate_background_snapshot()) { 3286 qemu_thread_create(&s->thread, "bg_snapshot", 3287 bg_migration_thread, s, QEMU_THREAD_JOINABLE); 3288 } else { 3289 qemu_thread_create(&s->thread, "live_migration", 3290 migration_thread, s, QEMU_THREAD_JOINABLE); 3291 } 3292 s->migration_thread_running = true; 3293 } 3294 3295 static void migration_class_init(ObjectClass *klass, void *data) 3296 { 3297 DeviceClass *dc = DEVICE_CLASS(klass); 3298 3299 dc->user_creatable = false; 3300 device_class_set_props(dc, migration_properties); 3301 } 3302 3303 static void migration_instance_finalize(Object *obj) 3304 { 3305 MigrationState *ms = MIGRATION_OBJ(obj); 3306 3307 qemu_mutex_destroy(&ms->error_mutex); 3308 qemu_mutex_destroy(&ms->qemu_file_lock); 3309 qemu_sem_destroy(&ms->wait_unplug_sem); 3310 qemu_sem_destroy(&ms->rate_limit_sem); 3311 qemu_sem_destroy(&ms->pause_sem); 3312 qemu_sem_destroy(&ms->postcopy_pause_sem); 3313 qemu_sem_destroy(&ms->postcopy_pause_rp_sem); 3314 qemu_sem_destroy(&ms->rp_state.rp_sem); 3315 qemu_sem_destroy(&ms->rp_state.rp_pong_acks); 3316 qemu_sem_destroy(&ms->postcopy_qemufile_src_sem); 3317 error_free(ms->error); 3318 } 3319 3320 static void migration_instance_init(Object *obj) 3321 { 3322 MigrationState *ms = MIGRATION_OBJ(obj); 3323 3324 ms->state = MIGRATION_STATUS_NONE; 3325 ms->mbps = -1; 3326 ms->pages_per_second = -1; 3327 qemu_sem_init(&ms->pause_sem, 0); 3328 qemu_mutex_init(&ms->error_mutex); 3329 3330 migrate_params_init(&ms->parameters); 3331 3332 qemu_sem_init(&ms->postcopy_pause_sem, 0); 3333 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0); 3334 qemu_sem_init(&ms->rp_state.rp_sem, 0); 3335 qemu_sem_init(&ms->rp_state.rp_pong_acks, 0); 3336 qemu_sem_init(&ms->rate_limit_sem, 0); 3337 qemu_sem_init(&ms->wait_unplug_sem, 0); 3338 qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0); 3339 qemu_mutex_init(&ms->qemu_file_lock); 3340 } 3341 3342 /* 3343 * Return true if check pass, false otherwise. Error will be put 3344 * inside errp if provided. 3345 */ 3346 static bool migration_object_check(MigrationState *ms, Error **errp) 3347 { 3348 /* Assuming all off */ 3349 bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 }; 3350 3351 if (!migrate_params_check(&ms->parameters, errp)) { 3352 return false; 3353 } 3354 3355 return migrate_caps_check(old_caps, ms->capabilities, errp); 3356 } 3357 3358 static const TypeInfo migration_type = { 3359 .name = TYPE_MIGRATION, 3360 /* 3361 * NOTE: TYPE_MIGRATION is not really a device, as the object is 3362 * not created using qdev_new(), it is not attached to the qdev 3363 * device tree, and it is never realized. 3364 * 3365 * TODO: Make this TYPE_OBJECT once QOM provides something like 3366 * TYPE_DEVICE's "-global" properties. 3367 */ 3368 .parent = TYPE_DEVICE, 3369 .class_init = migration_class_init, 3370 .class_size = sizeof(MigrationClass), 3371 .instance_size = sizeof(MigrationState), 3372 .instance_init = migration_instance_init, 3373 .instance_finalize = migration_instance_finalize, 3374 }; 3375 3376 static void register_migration_types(void) 3377 { 3378 type_register_static(&migration_type); 3379 } 3380 3381 type_init(register_migration_types); 3382