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 "migration/global_state.h" 30 #include "migration/misc.h" 31 #include "migration.h" 32 #include "savevm.h" 33 #include "qemu-file.h" 34 #include "channel.h" 35 #include "migration/vmstate.h" 36 #include "block/block.h" 37 #include "qapi/error.h" 38 #include "qapi/clone-visitor.h" 39 #include "qapi/qapi-visit-migration.h" 40 #include "qapi/qapi-visit-sockets.h" 41 #include "qapi/qapi-commands-migration.h" 42 #include "qapi/qapi-events-migration.h" 43 #include "qapi/qmp/qerror.h" 44 #include "qapi/qmp/qnull.h" 45 #include "qemu/rcu.h" 46 #include "block.h" 47 #include "postcopy-ram.h" 48 #include "qemu/thread.h" 49 #include "trace.h" 50 #include "exec/target_page.h" 51 #include "io/channel-buffer.h" 52 #include "io/channel-tls.h" 53 #include "migration/colo.h" 54 #include "hw/boards.h" 55 #include "hw/qdev-properties.h" 56 #include "hw/qdev-properties-system.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 #define MAX_THROTTLE (128 << 20) /* Migration transfer speed throttling */ 69 70 /* Amount of time to allocate to each "chunk" of bandwidth-throttled 71 * data. */ 72 #define BUFFER_DELAY 100 73 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY) 74 75 /* Time in milliseconds we are allowed to stop the source, 76 * for sending the last part */ 77 #define DEFAULT_MIGRATE_SET_DOWNTIME 300 78 79 /* Maximum migrate downtime set to 2000 seconds */ 80 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000 81 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000) 82 83 /* Default compression thread count */ 84 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8 85 /* Default decompression thread count, usually decompression is at 86 * least 4 times as fast as compression.*/ 87 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2 88 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */ 89 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1 90 /* Define default autoconverge cpu throttle migration parameters */ 91 #define DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD 50 92 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20 93 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10 94 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99 95 96 /* Migration XBZRLE default cache size */ 97 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024) 98 99 /* The delay time (in ms) between two COLO checkpoints */ 100 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100) 101 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2 102 #define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE 103 /* 0: means nocompress, 1: best speed, ... 9: best compress ratio */ 104 #define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1 105 /* 0: means nocompress, 1: best speed, ... 20: best compress ratio */ 106 #define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1 107 108 /* Background transfer rate for postcopy, 0 means unlimited, note 109 * that page requests can still exceed this limit. 110 */ 111 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0 112 113 /* 114 * Parameters for self_announce_delay giving a stream of RARP/ARP 115 * packets after migration. 116 */ 117 #define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50 118 #define DEFAULT_MIGRATE_ANNOUNCE_MAX 550 119 #define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5 120 #define DEFAULT_MIGRATE_ANNOUNCE_STEP 100 121 122 static NotifierList migration_state_notifiers = 123 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers); 124 125 /* Messages sent on the return path from destination to source */ 126 enum mig_rp_message_type { 127 MIG_RP_MSG_INVALID = 0, /* Must be 0 */ 128 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */ 129 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */ 130 131 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */ 132 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */ 133 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */ 134 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */ 135 136 MIG_RP_MSG_MAX 137 }; 138 139 /* Migration capabilities set */ 140 struct MigrateCapsSet { 141 int size; /* Capability set size */ 142 MigrationCapability caps[]; /* Variadic array of capabilities */ 143 }; 144 typedef struct MigrateCapsSet MigrateCapsSet; 145 146 /* Define and initialize MigrateCapsSet */ 147 #define INITIALIZE_MIGRATE_CAPS_SET(_name, ...) \ 148 MigrateCapsSet _name = { \ 149 .size = sizeof((int []) { __VA_ARGS__ }) / sizeof(int), \ 150 .caps = { __VA_ARGS__ } \ 151 } 152 153 /* Background-snapshot compatibility check list */ 154 static const 155 INITIALIZE_MIGRATE_CAPS_SET(check_caps_background_snapshot, 156 MIGRATION_CAPABILITY_POSTCOPY_RAM, 157 MIGRATION_CAPABILITY_DIRTY_BITMAPS, 158 MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME, 159 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE, 160 MIGRATION_CAPABILITY_RETURN_PATH, 161 MIGRATION_CAPABILITY_MULTIFD, 162 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER, 163 MIGRATION_CAPABILITY_AUTO_CONVERGE, 164 MIGRATION_CAPABILITY_RELEASE_RAM, 165 MIGRATION_CAPABILITY_RDMA_PIN_ALL, 166 MIGRATION_CAPABILITY_COMPRESS, 167 MIGRATION_CAPABILITY_XBZRLE, 168 MIGRATION_CAPABILITY_X_COLO, 169 MIGRATION_CAPABILITY_VALIDATE_UUID, 170 MIGRATION_CAPABILITY_ZERO_COPY_SEND); 171 172 /* When we add fault tolerance, we could have several 173 migrations at once. For now we don't need to add 174 dynamic creation of migration */ 175 176 static MigrationState *current_migration; 177 static MigrationIncomingState *current_incoming; 178 179 static GSList *migration_blockers; 180 181 static bool migration_object_check(MigrationState *ms, Error **errp); 182 static int migration_maybe_pause(MigrationState *s, 183 int *current_active_state, 184 int new_state); 185 static void migrate_fd_cancel(MigrationState *s); 186 187 static bool migration_needs_multiple_sockets(void) 188 { 189 return migrate_multifd() || migrate_postcopy_preempt(); 190 } 191 192 static bool uri_supports_multi_channels(const char *uri) 193 { 194 return strstart(uri, "tcp:", NULL) || strstart(uri, "unix:", NULL) || 195 strstart(uri, "vsock:", NULL); 196 } 197 198 static bool 199 migration_channels_and_uri_compatible(const char *uri, Error **errp) 200 { 201 if (migration_needs_multiple_sockets() && 202 !uri_supports_multi_channels(uri)) { 203 error_setg(errp, "Migration requires multi-channel URIs (e.g. tcp)"); 204 return false; 205 } 206 207 return true; 208 } 209 210 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp) 211 { 212 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp; 213 214 return (a > b) - (a < b); 215 } 216 217 void migration_object_init(void) 218 { 219 /* This can only be called once. */ 220 assert(!current_migration); 221 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION)); 222 223 /* 224 * Init the migrate incoming object as well no matter whether 225 * we'll use it or not. 226 */ 227 assert(!current_incoming); 228 current_incoming = g_new0(MigrationIncomingState, 1); 229 current_incoming->state = MIGRATION_STATUS_NONE; 230 current_incoming->postcopy_remote_fds = 231 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD)); 232 qemu_mutex_init(¤t_incoming->rp_mutex); 233 qemu_mutex_init(¤t_incoming->postcopy_prio_thread_mutex); 234 qemu_event_init(¤t_incoming->main_thread_load_event, false); 235 qemu_sem_init(¤t_incoming->postcopy_pause_sem_dst, 0); 236 qemu_sem_init(¤t_incoming->postcopy_pause_sem_fault, 0); 237 qemu_sem_init(¤t_incoming->postcopy_pause_sem_fast_load, 0); 238 qemu_sem_init(¤t_incoming->postcopy_qemufile_dst_done, 0); 239 240 qemu_mutex_init(¤t_incoming->page_request_mutex); 241 current_incoming->page_requested = g_tree_new(page_request_addr_cmp); 242 243 migration_object_check(current_migration, &error_fatal); 244 245 blk_mig_init(); 246 ram_mig_init(); 247 dirty_bitmap_mig_init(); 248 } 249 250 void migration_cancel(const Error *error) 251 { 252 if (error) { 253 migrate_set_error(current_migration, error); 254 } 255 migrate_fd_cancel(current_migration); 256 } 257 258 void migration_shutdown(void) 259 { 260 /* 261 * When the QEMU main thread exit, the COLO thread 262 * may wait a semaphore. So, we should wakeup the 263 * COLO thread before migration shutdown. 264 */ 265 colo_shutdown(); 266 /* 267 * Cancel the current migration - that will (eventually) 268 * stop the migration using this structure 269 */ 270 migration_cancel(NULL); 271 object_unref(OBJECT(current_migration)); 272 273 /* 274 * Cancel outgoing migration of dirty bitmaps. It should 275 * at least unref used block nodes. 276 */ 277 dirty_bitmap_mig_cancel_outgoing(); 278 279 /* 280 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps 281 * are non-critical data, and their loss never considered as 282 * something serious. 283 */ 284 dirty_bitmap_mig_cancel_incoming(); 285 } 286 287 /* For outgoing */ 288 MigrationState *migrate_get_current(void) 289 { 290 /* This can only be called after the object created. */ 291 assert(current_migration); 292 return current_migration; 293 } 294 295 MigrationIncomingState *migration_incoming_get_current(void) 296 { 297 assert(current_incoming); 298 return current_incoming; 299 } 300 301 void migration_incoming_transport_cleanup(MigrationIncomingState *mis) 302 { 303 if (mis->socket_address_list) { 304 qapi_free_SocketAddressList(mis->socket_address_list); 305 mis->socket_address_list = NULL; 306 } 307 308 if (mis->transport_cleanup) { 309 mis->transport_cleanup(mis->transport_data); 310 mis->transport_data = mis->transport_cleanup = NULL; 311 } 312 } 313 314 void migration_incoming_state_destroy(void) 315 { 316 struct MigrationIncomingState *mis = migration_incoming_get_current(); 317 318 multifd_load_cleanup(); 319 320 if (mis->to_src_file) { 321 /* Tell source that we are done */ 322 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0); 323 qemu_fclose(mis->to_src_file); 324 mis->to_src_file = NULL; 325 } 326 327 if (mis->from_src_file) { 328 migration_ioc_unregister_yank_from_file(mis->from_src_file); 329 qemu_fclose(mis->from_src_file); 330 mis->from_src_file = NULL; 331 } 332 if (mis->postcopy_remote_fds) { 333 g_array_free(mis->postcopy_remote_fds, TRUE); 334 mis->postcopy_remote_fds = NULL; 335 } 336 337 migration_incoming_transport_cleanup(mis); 338 qemu_event_reset(&mis->main_thread_load_event); 339 340 if (mis->page_requested) { 341 g_tree_destroy(mis->page_requested); 342 mis->page_requested = NULL; 343 } 344 345 if (mis->postcopy_qemufile_dst) { 346 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst); 347 qemu_fclose(mis->postcopy_qemufile_dst); 348 mis->postcopy_qemufile_dst = NULL; 349 } 350 351 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 352 } 353 354 static void migrate_generate_event(int new_state) 355 { 356 if (migrate_events()) { 357 qapi_event_send_migration(new_state); 358 } 359 } 360 361 /* 362 * Send a message on the return channel back to the source 363 * of the migration. 364 */ 365 static int migrate_send_rp_message(MigrationIncomingState *mis, 366 enum mig_rp_message_type message_type, 367 uint16_t len, void *data) 368 { 369 int ret = 0; 370 371 trace_migrate_send_rp_message((int)message_type, len); 372 QEMU_LOCK_GUARD(&mis->rp_mutex); 373 374 /* 375 * It's possible that the file handle got lost due to network 376 * failures. 377 */ 378 if (!mis->to_src_file) { 379 ret = -EIO; 380 return ret; 381 } 382 383 qemu_put_be16(mis->to_src_file, (unsigned int)message_type); 384 qemu_put_be16(mis->to_src_file, len); 385 qemu_put_buffer(mis->to_src_file, data, len); 386 qemu_fflush(mis->to_src_file); 387 388 /* It's possible that qemu file got error during sending */ 389 ret = qemu_file_get_error(mis->to_src_file); 390 391 return ret; 392 } 393 394 /* Request one page from the source VM at the given start address. 395 * rb: the RAMBlock to request the page in 396 * Start: Address offset within the RB 397 * Len: Length in bytes required - must be a multiple of pagesize 398 */ 399 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis, 400 RAMBlock *rb, ram_addr_t start) 401 { 402 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */ 403 size_t msglen = 12; /* start + len */ 404 size_t len = qemu_ram_pagesize(rb); 405 enum mig_rp_message_type msg_type; 406 const char *rbname; 407 int rbname_len; 408 409 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start); 410 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len); 411 412 /* 413 * We maintain the last ramblock that we requested for page. Note that we 414 * don't need locking because this function will only be called within the 415 * postcopy ram fault thread. 416 */ 417 if (rb != mis->last_rb) { 418 mis->last_rb = rb; 419 420 rbname = qemu_ram_get_idstr(rb); 421 rbname_len = strlen(rbname); 422 423 assert(rbname_len < 256); 424 425 bufc[msglen++] = rbname_len; 426 memcpy(bufc + msglen, rbname, rbname_len); 427 msglen += rbname_len; 428 msg_type = MIG_RP_MSG_REQ_PAGES_ID; 429 } else { 430 msg_type = MIG_RP_MSG_REQ_PAGES; 431 } 432 433 return migrate_send_rp_message(mis, msg_type, msglen, bufc); 434 } 435 436 int migrate_send_rp_req_pages(MigrationIncomingState *mis, 437 RAMBlock *rb, ram_addr_t start, uint64_t haddr) 438 { 439 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb)); 440 bool received = false; 441 442 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) { 443 received = ramblock_recv_bitmap_test_byte_offset(rb, start); 444 if (!received && !g_tree_lookup(mis->page_requested, aligned)) { 445 /* 446 * The page has not been received, and it's not yet in the page 447 * request list. Queue it. Set the value of element to 1, so that 448 * things like g_tree_lookup() will return TRUE (1) when found. 449 */ 450 g_tree_insert(mis->page_requested, aligned, (gpointer)1); 451 mis->page_requested_count++; 452 trace_postcopy_page_req_add(aligned, mis->page_requested_count); 453 } 454 } 455 456 /* 457 * If the page is there, skip sending the message. We don't even need the 458 * lock because as long as the page arrived, it'll be there forever. 459 */ 460 if (received) { 461 return 0; 462 } 463 464 return migrate_send_rp_message_req_pages(mis, rb, start); 465 } 466 467 static bool migration_colo_enabled; 468 bool migration_incoming_colo_enabled(void) 469 { 470 return migration_colo_enabled; 471 } 472 473 void migration_incoming_disable_colo(void) 474 { 475 ram_block_discard_disable(false); 476 migration_colo_enabled = false; 477 } 478 479 int migration_incoming_enable_colo(void) 480 { 481 if (ram_block_discard_disable(true)) { 482 error_report("COLO: cannot disable RAM discard"); 483 return -EBUSY; 484 } 485 migration_colo_enabled = true; 486 return 0; 487 } 488 489 void migrate_add_address(SocketAddress *address) 490 { 491 MigrationIncomingState *mis = migration_incoming_get_current(); 492 493 QAPI_LIST_PREPEND(mis->socket_address_list, 494 QAPI_CLONE(SocketAddress, address)); 495 } 496 497 static void qemu_start_incoming_migration(const char *uri, Error **errp) 498 { 499 const char *p = NULL; 500 501 /* URI is not suitable for migration? */ 502 if (!migration_channels_and_uri_compatible(uri, errp)) { 503 return; 504 } 505 506 qapi_event_send_migration(MIGRATION_STATUS_SETUP); 507 if (strstart(uri, "tcp:", &p) || 508 strstart(uri, "unix:", NULL) || 509 strstart(uri, "vsock:", NULL)) { 510 socket_start_incoming_migration(p ? p : uri, errp); 511 #ifdef CONFIG_RDMA 512 } else if (strstart(uri, "rdma:", &p)) { 513 rdma_start_incoming_migration(p, errp); 514 #endif 515 } else if (strstart(uri, "exec:", &p)) { 516 exec_start_incoming_migration(p, errp); 517 } else if (strstart(uri, "fd:", &p)) { 518 fd_start_incoming_migration(p, errp); 519 } else { 520 error_setg(errp, "unknown migration protocol: %s", uri); 521 } 522 } 523 524 static void process_incoming_migration_bh(void *opaque) 525 { 526 Error *local_err = NULL; 527 MigrationIncomingState *mis = opaque; 528 529 /* If capability late_block_activate is set: 530 * Only fire up the block code now if we're going to restart the 531 * VM, else 'cont' will do it. 532 * This causes file locking to happen; so we don't want it to happen 533 * unless we really are starting the VM. 534 */ 535 if (!migrate_late_block_activate() || 536 (autostart && (!global_state_received() || 537 global_state_get_runstate() == RUN_STATE_RUNNING))) { 538 /* Make sure all file formats throw away their mutable metadata. 539 * If we get an error here, just don't restart the VM yet. */ 540 bdrv_activate_all(&local_err); 541 if (local_err) { 542 error_report_err(local_err); 543 local_err = NULL; 544 autostart = false; 545 } 546 } 547 548 /* 549 * This must happen after all error conditions are dealt with and 550 * we're sure the VM is going to be running on this host. 551 */ 552 qemu_announce_self(&mis->announce_timer, migrate_announce_params()); 553 554 multifd_load_shutdown(); 555 556 dirty_bitmap_mig_before_vm_start(); 557 558 if (!global_state_received() || 559 global_state_get_runstate() == RUN_STATE_RUNNING) { 560 if (autostart) { 561 vm_start(); 562 } else { 563 runstate_set(RUN_STATE_PAUSED); 564 } 565 } else if (migration_incoming_colo_enabled()) { 566 migration_incoming_disable_colo(); 567 vm_start(); 568 } else { 569 runstate_set(global_state_get_runstate()); 570 } 571 /* 572 * This must happen after any state changes since as soon as an external 573 * observer sees this event they might start to prod at the VM assuming 574 * it's ready to use. 575 */ 576 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE, 577 MIGRATION_STATUS_COMPLETED); 578 qemu_bh_delete(mis->bh); 579 migration_incoming_state_destroy(); 580 } 581 582 static void coroutine_fn 583 process_incoming_migration_co(void *opaque) 584 { 585 MigrationIncomingState *mis = migration_incoming_get_current(); 586 PostcopyState ps; 587 int ret; 588 Error *local_err = NULL; 589 590 assert(mis->from_src_file); 591 mis->migration_incoming_co = qemu_coroutine_self(); 592 mis->largest_page_size = qemu_ram_pagesize_largest(); 593 postcopy_state_set(POSTCOPY_INCOMING_NONE); 594 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE, 595 MIGRATION_STATUS_ACTIVE); 596 ret = qemu_loadvm_state(mis->from_src_file); 597 598 ps = postcopy_state_get(); 599 trace_process_incoming_migration_co_end(ret, ps); 600 if (ps != POSTCOPY_INCOMING_NONE) { 601 if (ps == POSTCOPY_INCOMING_ADVISE) { 602 /* 603 * Where a migration had postcopy enabled (and thus went to advise) 604 * but managed to complete within the precopy period, we can use 605 * the normal exit. 606 */ 607 postcopy_ram_incoming_cleanup(mis); 608 } else if (ret >= 0) { 609 /* 610 * Postcopy was started, cleanup should happen at the end of the 611 * postcopy thread. 612 */ 613 trace_process_incoming_migration_co_postcopy_end_main(); 614 return; 615 } 616 /* Else if something went wrong then just fall out of the normal exit */ 617 } 618 619 /* we get COLO info, and know if we are in COLO mode */ 620 if (!ret && migration_incoming_colo_enabled()) { 621 /* Make sure all file formats throw away their mutable metadata */ 622 bdrv_activate_all(&local_err); 623 if (local_err) { 624 error_report_err(local_err); 625 goto fail; 626 } 627 628 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming", 629 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE); 630 mis->have_colo_incoming_thread = true; 631 qemu_coroutine_yield(); 632 633 qemu_mutex_unlock_iothread(); 634 /* Wait checkpoint incoming thread exit before free resource */ 635 qemu_thread_join(&mis->colo_incoming_thread); 636 qemu_mutex_lock_iothread(); 637 /* We hold the global iothread lock, so it is safe here */ 638 colo_release_ram_cache(); 639 } 640 641 if (ret < 0) { 642 error_report("load of migration failed: %s", strerror(-ret)); 643 goto fail; 644 } 645 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis); 646 qemu_bh_schedule(mis->bh); 647 mis->migration_incoming_co = NULL; 648 return; 649 fail: 650 local_err = NULL; 651 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE, 652 MIGRATION_STATUS_FAILED); 653 qemu_fclose(mis->from_src_file); 654 655 multifd_load_cleanup(); 656 657 exit(EXIT_FAILURE); 658 } 659 660 /** 661 * migration_incoming_setup: Setup incoming migration 662 * @f: file for main migration channel 663 * @errp: where to put errors 664 * 665 * Returns: %true on success, %false on error. 666 */ 667 static bool migration_incoming_setup(QEMUFile *f, Error **errp) 668 { 669 MigrationIncomingState *mis = migration_incoming_get_current(); 670 671 if (!mis->from_src_file) { 672 mis->from_src_file = f; 673 } 674 qemu_file_set_blocking(f, false); 675 return true; 676 } 677 678 void migration_incoming_process(void) 679 { 680 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL); 681 qemu_coroutine_enter(co); 682 } 683 684 /* Returns true if recovered from a paused migration, otherwise false */ 685 static bool postcopy_try_recover(void) 686 { 687 MigrationIncomingState *mis = migration_incoming_get_current(); 688 689 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) { 690 /* Resumed from a paused postcopy migration */ 691 692 /* This should be set already in migration_incoming_setup() */ 693 assert(mis->from_src_file); 694 /* Postcopy has standalone thread to do vm load */ 695 qemu_file_set_blocking(mis->from_src_file, true); 696 697 /* Re-configure the return path */ 698 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file); 699 700 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED, 701 MIGRATION_STATUS_POSTCOPY_RECOVER); 702 703 /* 704 * Here, we only wake up the main loading thread (while the 705 * rest threads will still be waiting), so that we can receive 706 * commands from source now, and answer it if needed. The 707 * rest threads will be woken up afterwards until we are sure 708 * that source is ready to reply to page requests. 709 */ 710 qemu_sem_post(&mis->postcopy_pause_sem_dst); 711 return true; 712 } 713 714 return false; 715 } 716 717 void migration_fd_process_incoming(QEMUFile *f, Error **errp) 718 { 719 if (!migration_incoming_setup(f, errp)) { 720 return; 721 } 722 if (postcopy_try_recover()) { 723 return; 724 } 725 migration_incoming_process(); 726 } 727 728 /* 729 * Returns true when we want to start a new incoming migration process, 730 * false otherwise. 731 */ 732 static bool migration_should_start_incoming(bool main_channel) 733 { 734 /* Multifd doesn't start unless all channels are established */ 735 if (migrate_multifd()) { 736 return migration_has_all_channels(); 737 } 738 739 /* Preempt channel only starts when the main channel is created */ 740 if (migrate_postcopy_preempt()) { 741 return main_channel; 742 } 743 744 /* 745 * For all the rest types of migration, we should only reach here when 746 * it's the main channel that's being created, and we should always 747 * proceed with this channel. 748 */ 749 assert(main_channel); 750 return true; 751 } 752 753 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp) 754 { 755 MigrationIncomingState *mis = migration_incoming_get_current(); 756 Error *local_err = NULL; 757 QEMUFile *f; 758 bool default_channel = true; 759 uint32_t channel_magic = 0; 760 int ret = 0; 761 762 if (migrate_multifd() && !migrate_postcopy_ram() && 763 qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) { 764 /* 765 * With multiple channels, it is possible that we receive channels 766 * out of order on destination side, causing incorrect mapping of 767 * source channels on destination side. Check channel MAGIC to 768 * decide type of channel. Please note this is best effort, postcopy 769 * preempt channel does not send any magic number so avoid it for 770 * postcopy live migration. Also tls live migration already does 771 * tls handshake while initializing main channel so with tls this 772 * issue is not possible. 773 */ 774 ret = migration_channel_read_peek(ioc, (void *)&channel_magic, 775 sizeof(channel_magic), &local_err); 776 777 if (ret != 0) { 778 error_propagate(errp, local_err); 779 return; 780 } 781 782 default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC)); 783 } else { 784 default_channel = !mis->from_src_file; 785 } 786 787 if (multifd_load_setup(errp) != 0) { 788 error_setg(errp, "Failed to setup multifd channels"); 789 return; 790 } 791 792 if (default_channel) { 793 f = qemu_file_new_input(ioc); 794 795 if (!migration_incoming_setup(f, errp)) { 796 return; 797 } 798 } else { 799 /* Multiple connections */ 800 assert(migration_needs_multiple_sockets()); 801 if (migrate_multifd()) { 802 multifd_recv_new_channel(ioc, &local_err); 803 } else { 804 assert(migrate_postcopy_preempt()); 805 f = qemu_file_new_input(ioc); 806 postcopy_preempt_new_channel(mis, f); 807 } 808 if (local_err) { 809 error_propagate(errp, local_err); 810 return; 811 } 812 } 813 814 if (migration_should_start_incoming(default_channel)) { 815 /* If it's a recovery, we're done */ 816 if (postcopy_try_recover()) { 817 return; 818 } 819 migration_incoming_process(); 820 } 821 } 822 823 /** 824 * @migration_has_all_channels: We have received all channels that we need 825 * 826 * Returns true when we have got connections to all the channels that 827 * we need for migration. 828 */ 829 bool migration_has_all_channels(void) 830 { 831 MigrationIncomingState *mis = migration_incoming_get_current(); 832 833 if (!mis->from_src_file) { 834 return false; 835 } 836 837 if (migrate_multifd()) { 838 return multifd_recv_all_channels_created(); 839 } 840 841 if (migrate_postcopy_preempt()) { 842 return mis->postcopy_qemufile_dst != NULL; 843 } 844 845 return true; 846 } 847 848 /* 849 * Send a 'SHUT' message on the return channel with the given value 850 * to indicate that we've finished with the RP. Non-0 value indicates 851 * error. 852 */ 853 void migrate_send_rp_shut(MigrationIncomingState *mis, 854 uint32_t value) 855 { 856 uint32_t buf; 857 858 buf = cpu_to_be32(value); 859 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf); 860 } 861 862 /* 863 * Send a 'PONG' message on the return channel with the given value 864 * (normally in response to a 'PING') 865 */ 866 void migrate_send_rp_pong(MigrationIncomingState *mis, 867 uint32_t value) 868 { 869 uint32_t buf; 870 871 buf = cpu_to_be32(value); 872 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf); 873 } 874 875 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis, 876 char *block_name) 877 { 878 char buf[512]; 879 int len; 880 int64_t res; 881 882 /* 883 * First, we send the header part. It contains only the len of 884 * idstr, and the idstr itself. 885 */ 886 len = strlen(block_name); 887 buf[0] = len; 888 memcpy(buf + 1, block_name, len); 889 890 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) { 891 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery", 892 __func__); 893 return; 894 } 895 896 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf); 897 898 /* 899 * Next, we dump the received bitmap to the stream. 900 * 901 * TODO: currently we are safe since we are the only one that is 902 * using the to_src_file handle (fault thread is still paused), 903 * and it's ok even not taking the mutex. However the best way is 904 * to take the lock before sending the message header, and release 905 * the lock after sending the bitmap. 906 */ 907 qemu_mutex_lock(&mis->rp_mutex); 908 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name); 909 qemu_mutex_unlock(&mis->rp_mutex); 910 911 trace_migrate_send_rp_recv_bitmap(block_name, res); 912 } 913 914 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value) 915 { 916 uint32_t buf; 917 918 buf = cpu_to_be32(value); 919 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf); 920 } 921 922 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp) 923 { 924 MigrationCapabilityStatusList *head = NULL, **tail = &head; 925 MigrationCapabilityStatus *caps; 926 MigrationState *s = migrate_get_current(); 927 int i; 928 929 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) { 930 #ifndef CONFIG_LIVE_BLOCK_MIGRATION 931 if (i == MIGRATION_CAPABILITY_BLOCK) { 932 continue; 933 } 934 #endif 935 caps = g_malloc0(sizeof(*caps)); 936 caps->capability = i; 937 caps->state = s->capabilities[i]; 938 QAPI_LIST_APPEND(tail, caps); 939 } 940 941 return head; 942 } 943 944 MigrationParameters *qmp_query_migrate_parameters(Error **errp) 945 { 946 MigrationParameters *params; 947 MigrationState *s = migrate_get_current(); 948 949 /* TODO use QAPI_CLONE() instead of duplicating it inline */ 950 params = g_malloc0(sizeof(*params)); 951 params->has_compress_level = true; 952 params->compress_level = s->parameters.compress_level; 953 params->has_compress_threads = true; 954 params->compress_threads = s->parameters.compress_threads; 955 params->has_compress_wait_thread = true; 956 params->compress_wait_thread = s->parameters.compress_wait_thread; 957 params->has_decompress_threads = true; 958 params->decompress_threads = s->parameters.decompress_threads; 959 params->has_throttle_trigger_threshold = true; 960 params->throttle_trigger_threshold = s->parameters.throttle_trigger_threshold; 961 params->has_cpu_throttle_initial = true; 962 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial; 963 params->has_cpu_throttle_increment = true; 964 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment; 965 params->has_cpu_throttle_tailslow = true; 966 params->cpu_throttle_tailslow = s->parameters.cpu_throttle_tailslow; 967 params->tls_creds = g_strdup(s->parameters.tls_creds); 968 params->tls_hostname = g_strdup(s->parameters.tls_hostname); 969 params->tls_authz = g_strdup(s->parameters.tls_authz ? 970 s->parameters.tls_authz : ""); 971 params->has_max_bandwidth = true; 972 params->max_bandwidth = s->parameters.max_bandwidth; 973 params->has_downtime_limit = true; 974 params->downtime_limit = s->parameters.downtime_limit; 975 params->has_x_checkpoint_delay = true; 976 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay; 977 params->has_block_incremental = true; 978 params->block_incremental = s->parameters.block_incremental; 979 params->has_multifd_channels = true; 980 params->multifd_channels = s->parameters.multifd_channels; 981 params->has_multifd_compression = true; 982 params->multifd_compression = s->parameters.multifd_compression; 983 params->has_multifd_zlib_level = true; 984 params->multifd_zlib_level = s->parameters.multifd_zlib_level; 985 params->has_multifd_zstd_level = true; 986 params->multifd_zstd_level = s->parameters.multifd_zstd_level; 987 params->has_xbzrle_cache_size = true; 988 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size; 989 params->has_max_postcopy_bandwidth = true; 990 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth; 991 params->has_max_cpu_throttle = true; 992 params->max_cpu_throttle = s->parameters.max_cpu_throttle; 993 params->has_announce_initial = true; 994 params->announce_initial = s->parameters.announce_initial; 995 params->has_announce_max = true; 996 params->announce_max = s->parameters.announce_max; 997 params->has_announce_rounds = true; 998 params->announce_rounds = s->parameters.announce_rounds; 999 params->has_announce_step = true; 1000 params->announce_step = s->parameters.announce_step; 1001 1002 if (s->parameters.has_block_bitmap_mapping) { 1003 params->has_block_bitmap_mapping = true; 1004 params->block_bitmap_mapping = 1005 QAPI_CLONE(BitmapMigrationNodeAliasList, 1006 s->parameters.block_bitmap_mapping); 1007 } 1008 1009 return params; 1010 } 1011 1012 AnnounceParameters *migrate_announce_params(void) 1013 { 1014 static AnnounceParameters ap; 1015 1016 MigrationState *s = migrate_get_current(); 1017 1018 ap.initial = s->parameters.announce_initial; 1019 ap.max = s->parameters.announce_max; 1020 ap.rounds = s->parameters.announce_rounds; 1021 ap.step = s->parameters.announce_step; 1022 1023 return ≈ 1024 } 1025 1026 /* 1027 * Return true if we're already in the middle of a migration 1028 * (i.e. any of the active or setup states) 1029 */ 1030 bool migration_is_setup_or_active(int state) 1031 { 1032 switch (state) { 1033 case MIGRATION_STATUS_ACTIVE: 1034 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1035 case MIGRATION_STATUS_POSTCOPY_PAUSED: 1036 case MIGRATION_STATUS_POSTCOPY_RECOVER: 1037 case MIGRATION_STATUS_SETUP: 1038 case MIGRATION_STATUS_PRE_SWITCHOVER: 1039 case MIGRATION_STATUS_DEVICE: 1040 case MIGRATION_STATUS_WAIT_UNPLUG: 1041 case MIGRATION_STATUS_COLO: 1042 return true; 1043 1044 default: 1045 return false; 1046 1047 } 1048 } 1049 1050 bool migration_is_running(int state) 1051 { 1052 switch (state) { 1053 case MIGRATION_STATUS_ACTIVE: 1054 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1055 case MIGRATION_STATUS_POSTCOPY_PAUSED: 1056 case MIGRATION_STATUS_POSTCOPY_RECOVER: 1057 case MIGRATION_STATUS_SETUP: 1058 case MIGRATION_STATUS_PRE_SWITCHOVER: 1059 case MIGRATION_STATUS_DEVICE: 1060 case MIGRATION_STATUS_WAIT_UNPLUG: 1061 case MIGRATION_STATUS_CANCELLING: 1062 return true; 1063 1064 default: 1065 return false; 1066 1067 } 1068 } 1069 1070 static bool migrate_show_downtime(MigrationState *s) 1071 { 1072 return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy(); 1073 } 1074 1075 static void populate_time_info(MigrationInfo *info, MigrationState *s) 1076 { 1077 info->has_status = true; 1078 info->has_setup_time = true; 1079 info->setup_time = s->setup_time; 1080 1081 if (s->state == MIGRATION_STATUS_COMPLETED) { 1082 info->has_total_time = true; 1083 info->total_time = s->total_time; 1084 } else { 1085 info->has_total_time = true; 1086 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - 1087 s->start_time; 1088 } 1089 1090 if (migrate_show_downtime(s)) { 1091 info->has_downtime = true; 1092 info->downtime = s->downtime; 1093 } else { 1094 info->has_expected_downtime = true; 1095 info->expected_downtime = s->expected_downtime; 1096 } 1097 } 1098 1099 static void populate_ram_info(MigrationInfo *info, MigrationState *s) 1100 { 1101 size_t page_size = qemu_target_page_size(); 1102 1103 info->ram = g_malloc0(sizeof(*info->ram)); 1104 info->ram->transferred = stat64_get(&ram_counters.transferred); 1105 info->ram->total = ram_bytes_total(); 1106 info->ram->duplicate = stat64_get(&ram_counters.zero_pages); 1107 /* legacy value. It is not used anymore */ 1108 info->ram->skipped = 0; 1109 info->ram->normal = stat64_get(&ram_counters.normal_pages); 1110 info->ram->normal_bytes = info->ram->normal * page_size; 1111 info->ram->mbps = s->mbps; 1112 info->ram->dirty_sync_count = 1113 stat64_get(&ram_counters.dirty_sync_count); 1114 info->ram->dirty_sync_missed_zero_copy = 1115 stat64_get(&ram_counters.dirty_sync_missed_zero_copy); 1116 info->ram->postcopy_requests = 1117 stat64_get(&ram_counters.postcopy_requests); 1118 info->ram->page_size = page_size; 1119 info->ram->multifd_bytes = stat64_get(&ram_counters.multifd_bytes); 1120 info->ram->pages_per_second = s->pages_per_second; 1121 info->ram->precopy_bytes = stat64_get(&ram_counters.precopy_bytes); 1122 info->ram->downtime_bytes = stat64_get(&ram_counters.downtime_bytes); 1123 info->ram->postcopy_bytes = stat64_get(&ram_counters.postcopy_bytes); 1124 1125 if (migrate_use_xbzrle()) { 1126 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache)); 1127 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size(); 1128 info->xbzrle_cache->bytes = xbzrle_counters.bytes; 1129 info->xbzrle_cache->pages = xbzrle_counters.pages; 1130 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss; 1131 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate; 1132 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate; 1133 info->xbzrle_cache->overflow = xbzrle_counters.overflow; 1134 } 1135 1136 if (migrate_compress()) { 1137 info->compression = g_malloc0(sizeof(*info->compression)); 1138 info->compression->pages = compression_counters.pages; 1139 info->compression->busy = compression_counters.busy; 1140 info->compression->busy_rate = compression_counters.busy_rate; 1141 info->compression->compressed_size = 1142 compression_counters.compressed_size; 1143 info->compression->compression_rate = 1144 compression_counters.compression_rate; 1145 } 1146 1147 if (cpu_throttle_active()) { 1148 info->has_cpu_throttle_percentage = true; 1149 info->cpu_throttle_percentage = cpu_throttle_get_percentage(); 1150 } 1151 1152 if (s->state != MIGRATION_STATUS_COMPLETED) { 1153 info->ram->remaining = ram_bytes_remaining(); 1154 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate; 1155 } 1156 } 1157 1158 static void populate_disk_info(MigrationInfo *info) 1159 { 1160 if (blk_mig_active()) { 1161 info->disk = g_malloc0(sizeof(*info->disk)); 1162 info->disk->transferred = blk_mig_bytes_transferred(); 1163 info->disk->remaining = blk_mig_bytes_remaining(); 1164 info->disk->total = blk_mig_bytes_total(); 1165 } 1166 } 1167 1168 static void fill_source_migration_info(MigrationInfo *info) 1169 { 1170 MigrationState *s = migrate_get_current(); 1171 int state = qatomic_read(&s->state); 1172 GSList *cur_blocker = migration_blockers; 1173 1174 info->blocked_reasons = NULL; 1175 1176 /* 1177 * There are two types of reasons a migration might be blocked; 1178 * a) devices marked in VMState as non-migratable, and 1179 * b) Explicit migration blockers 1180 * We need to add both of them here. 1181 */ 1182 qemu_savevm_non_migratable_list(&info->blocked_reasons); 1183 1184 while (cur_blocker) { 1185 QAPI_LIST_PREPEND(info->blocked_reasons, 1186 g_strdup(error_get_pretty(cur_blocker->data))); 1187 cur_blocker = g_slist_next(cur_blocker); 1188 } 1189 info->has_blocked_reasons = info->blocked_reasons != NULL; 1190 1191 switch (state) { 1192 case MIGRATION_STATUS_NONE: 1193 /* no migration has happened ever */ 1194 /* do not overwrite destination migration status */ 1195 return; 1196 case MIGRATION_STATUS_SETUP: 1197 info->has_status = true; 1198 info->has_total_time = false; 1199 break; 1200 case MIGRATION_STATUS_ACTIVE: 1201 case MIGRATION_STATUS_CANCELLING: 1202 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1203 case MIGRATION_STATUS_PRE_SWITCHOVER: 1204 case MIGRATION_STATUS_DEVICE: 1205 case MIGRATION_STATUS_POSTCOPY_PAUSED: 1206 case MIGRATION_STATUS_POSTCOPY_RECOVER: 1207 /* TODO add some postcopy stats */ 1208 populate_time_info(info, s); 1209 populate_ram_info(info, s); 1210 populate_disk_info(info); 1211 populate_vfio_info(info); 1212 break; 1213 case MIGRATION_STATUS_COLO: 1214 info->has_status = true; 1215 /* TODO: display COLO specific information (checkpoint info etc.) */ 1216 break; 1217 case MIGRATION_STATUS_COMPLETED: 1218 populate_time_info(info, s); 1219 populate_ram_info(info, s); 1220 populate_vfio_info(info); 1221 break; 1222 case MIGRATION_STATUS_FAILED: 1223 info->has_status = true; 1224 if (s->error) { 1225 info->error_desc = g_strdup(error_get_pretty(s->error)); 1226 } 1227 break; 1228 case MIGRATION_STATUS_CANCELLED: 1229 info->has_status = true; 1230 break; 1231 case MIGRATION_STATUS_WAIT_UNPLUG: 1232 info->has_status = true; 1233 break; 1234 } 1235 info->status = state; 1236 } 1237 1238 typedef enum WriteTrackingSupport { 1239 WT_SUPPORT_UNKNOWN = 0, 1240 WT_SUPPORT_ABSENT, 1241 WT_SUPPORT_AVAILABLE, 1242 WT_SUPPORT_COMPATIBLE 1243 } WriteTrackingSupport; 1244 1245 static 1246 WriteTrackingSupport migrate_query_write_tracking(void) 1247 { 1248 /* Check if kernel supports required UFFD features */ 1249 if (!ram_write_tracking_available()) { 1250 return WT_SUPPORT_ABSENT; 1251 } 1252 /* 1253 * Check if current memory configuration is 1254 * compatible with required UFFD features. 1255 */ 1256 if (!ram_write_tracking_compatible()) { 1257 return WT_SUPPORT_AVAILABLE; 1258 } 1259 1260 return WT_SUPPORT_COMPATIBLE; 1261 } 1262 1263 /** 1264 * @migration_caps_check - check capability compatibility 1265 * 1266 * @old_caps: old capability list 1267 * @new_caps: new capability list 1268 * @errp: set *errp if the check failed, with reason 1269 * 1270 * Returns true if check passed, otherwise false. 1271 */ 1272 static bool migrate_caps_check(bool *old_caps, bool *new_caps, Error **errp) 1273 { 1274 MigrationIncomingState *mis = migration_incoming_get_current(); 1275 1276 #ifndef CONFIG_LIVE_BLOCK_MIGRATION 1277 if (new_caps[MIGRATION_CAPABILITY_BLOCK]) { 1278 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) " 1279 "block migration"); 1280 error_append_hint(errp, "Use drive_mirror+NBD instead.\n"); 1281 return false; 1282 } 1283 #endif 1284 1285 #ifndef CONFIG_REPLICATION 1286 if (new_caps[MIGRATION_CAPABILITY_X_COLO]) { 1287 error_setg(errp, "QEMU compiled without replication module" 1288 " can't enable COLO"); 1289 error_append_hint(errp, "Please enable replication before COLO.\n"); 1290 return false; 1291 } 1292 #endif 1293 1294 if (new_caps[MIGRATION_CAPABILITY_POSTCOPY_RAM]) { 1295 /* This check is reasonably expensive, so only when it's being 1296 * set the first time, also it's only the destination that needs 1297 * special support. 1298 */ 1299 if (!old_caps[MIGRATION_CAPABILITY_POSTCOPY_RAM] && 1300 runstate_check(RUN_STATE_INMIGRATE) && 1301 !postcopy_ram_supported_by_host(mis)) { 1302 /* postcopy_ram_supported_by_host will have emitted a more 1303 * detailed message 1304 */ 1305 error_setg(errp, "Postcopy is not supported"); 1306 return false; 1307 } 1308 1309 if (new_caps[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) { 1310 error_setg(errp, "Postcopy is not compatible with ignore-shared"); 1311 return false; 1312 } 1313 } 1314 1315 if (new_caps[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) { 1316 WriteTrackingSupport wt_support; 1317 int idx; 1318 /* 1319 * Check if 'background-snapshot' capability is supported by 1320 * host kernel and compatible with guest memory configuration. 1321 */ 1322 wt_support = migrate_query_write_tracking(); 1323 if (wt_support < WT_SUPPORT_AVAILABLE) { 1324 error_setg(errp, "Background-snapshot is not supported by host kernel"); 1325 return false; 1326 } 1327 if (wt_support < WT_SUPPORT_COMPATIBLE) { 1328 error_setg(errp, "Background-snapshot is not compatible " 1329 "with guest memory configuration"); 1330 return false; 1331 } 1332 1333 /* 1334 * Check if there are any migration capabilities 1335 * incompatible with 'background-snapshot'. 1336 */ 1337 for (idx = 0; idx < check_caps_background_snapshot.size; idx++) { 1338 int incomp_cap = check_caps_background_snapshot.caps[idx]; 1339 if (new_caps[incomp_cap]) { 1340 error_setg(errp, 1341 "Background-snapshot is not compatible with %s", 1342 MigrationCapability_str(incomp_cap)); 1343 return false; 1344 } 1345 } 1346 } 1347 1348 #ifdef CONFIG_LINUX 1349 if (new_caps[MIGRATION_CAPABILITY_ZERO_COPY_SEND] && 1350 (!new_caps[MIGRATION_CAPABILITY_MULTIFD] || 1351 new_caps[MIGRATION_CAPABILITY_COMPRESS] || 1352 new_caps[MIGRATION_CAPABILITY_XBZRLE] || 1353 migrate_multifd_compression() || 1354 migrate_use_tls())) { 1355 error_setg(errp, 1356 "Zero copy only available for non-compressed non-TLS multifd migration"); 1357 return false; 1358 } 1359 #else 1360 if (new_caps[MIGRATION_CAPABILITY_ZERO_COPY_SEND]) { 1361 error_setg(errp, 1362 "Zero copy currently only available on Linux"); 1363 return false; 1364 } 1365 #endif 1366 1367 if (new_caps[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT]) { 1368 if (!new_caps[MIGRATION_CAPABILITY_POSTCOPY_RAM]) { 1369 error_setg(errp, "Postcopy preempt requires postcopy-ram"); 1370 return false; 1371 } 1372 1373 /* 1374 * Preempt mode requires urgent pages to be sent in separate 1375 * channel, OTOH compression logic will disorder all pages into 1376 * different compression channels, which is not compatible with the 1377 * preempt assumptions on channel assignments. 1378 */ 1379 if (new_caps[MIGRATION_CAPABILITY_COMPRESS]) { 1380 error_setg(errp, "Postcopy preempt not compatible with compress"); 1381 return false; 1382 } 1383 } 1384 1385 if (new_caps[MIGRATION_CAPABILITY_MULTIFD]) { 1386 if (new_caps[MIGRATION_CAPABILITY_COMPRESS]) { 1387 error_setg(errp, "Multifd is not compatible with compress"); 1388 return false; 1389 } 1390 } 1391 1392 return true; 1393 } 1394 1395 static void fill_destination_migration_info(MigrationInfo *info) 1396 { 1397 MigrationIncomingState *mis = migration_incoming_get_current(); 1398 1399 if (mis->socket_address_list) { 1400 info->has_socket_address = true; 1401 info->socket_address = 1402 QAPI_CLONE(SocketAddressList, mis->socket_address_list); 1403 } 1404 1405 switch (mis->state) { 1406 case MIGRATION_STATUS_NONE: 1407 return; 1408 case MIGRATION_STATUS_SETUP: 1409 case MIGRATION_STATUS_CANCELLING: 1410 case MIGRATION_STATUS_CANCELLED: 1411 case MIGRATION_STATUS_ACTIVE: 1412 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1413 case MIGRATION_STATUS_POSTCOPY_PAUSED: 1414 case MIGRATION_STATUS_POSTCOPY_RECOVER: 1415 case MIGRATION_STATUS_FAILED: 1416 case MIGRATION_STATUS_COLO: 1417 info->has_status = true; 1418 break; 1419 case MIGRATION_STATUS_COMPLETED: 1420 info->has_status = true; 1421 fill_destination_postcopy_migration_info(info); 1422 break; 1423 } 1424 info->status = mis->state; 1425 } 1426 1427 MigrationInfo *qmp_query_migrate(Error **errp) 1428 { 1429 MigrationInfo *info = g_malloc0(sizeof(*info)); 1430 1431 fill_destination_migration_info(info); 1432 fill_source_migration_info(info); 1433 1434 return info; 1435 } 1436 1437 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params, 1438 Error **errp) 1439 { 1440 MigrationState *s = migrate_get_current(); 1441 MigrationCapabilityStatusList *cap; 1442 bool new_caps[MIGRATION_CAPABILITY__MAX]; 1443 1444 if (migration_is_running(s->state)) { 1445 error_setg(errp, QERR_MIGRATION_ACTIVE); 1446 return; 1447 } 1448 1449 memcpy(new_caps, s->capabilities, sizeof(new_caps)); 1450 for (cap = params; cap; cap = cap->next) { 1451 new_caps[cap->value->capability] = cap->value->state; 1452 } 1453 1454 if (!migrate_caps_check(s->capabilities, new_caps, errp)) { 1455 return; 1456 } 1457 1458 for (cap = params; cap; cap = cap->next) { 1459 s->capabilities[cap->value->capability] = cap->value->state; 1460 } 1461 } 1462 1463 /* 1464 * Check whether the parameters are valid. Error will be put into errp 1465 * (if provided). Return true if valid, otherwise false. 1466 */ 1467 static bool migrate_params_check(MigrationParameters *params, Error **errp) 1468 { 1469 if (params->has_compress_level && 1470 (params->compress_level > 9)) { 1471 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level", 1472 "a value between 0 and 9"); 1473 return false; 1474 } 1475 1476 if (params->has_compress_threads && (params->compress_threads < 1)) { 1477 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1478 "compress_threads", 1479 "a value between 1 and 255"); 1480 return false; 1481 } 1482 1483 if (params->has_decompress_threads && (params->decompress_threads < 1)) { 1484 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1485 "decompress_threads", 1486 "a value between 1 and 255"); 1487 return false; 1488 } 1489 1490 if (params->has_throttle_trigger_threshold && 1491 (params->throttle_trigger_threshold < 1 || 1492 params->throttle_trigger_threshold > 100)) { 1493 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1494 "throttle_trigger_threshold", 1495 "an integer in the range of 1 to 100"); 1496 return false; 1497 } 1498 1499 if (params->has_cpu_throttle_initial && 1500 (params->cpu_throttle_initial < 1 || 1501 params->cpu_throttle_initial > 99)) { 1502 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1503 "cpu_throttle_initial", 1504 "an integer in the range of 1 to 99"); 1505 return false; 1506 } 1507 1508 if (params->has_cpu_throttle_increment && 1509 (params->cpu_throttle_increment < 1 || 1510 params->cpu_throttle_increment > 99)) { 1511 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1512 "cpu_throttle_increment", 1513 "an integer in the range of 1 to 99"); 1514 return false; 1515 } 1516 1517 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) { 1518 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1519 "max_bandwidth", 1520 "an integer in the range of 0 to "stringify(SIZE_MAX) 1521 " bytes/second"); 1522 return false; 1523 } 1524 1525 if (params->has_downtime_limit && 1526 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) { 1527 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1528 "downtime_limit", 1529 "an integer in the range of 0 to " 1530 stringify(MAX_MIGRATE_DOWNTIME)" ms"); 1531 return false; 1532 } 1533 1534 /* x_checkpoint_delay is now always positive */ 1535 1536 if (params->has_multifd_channels && (params->multifd_channels < 1)) { 1537 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1538 "multifd_channels", 1539 "a value between 1 and 255"); 1540 return false; 1541 } 1542 1543 if (params->has_multifd_zlib_level && 1544 (params->multifd_zlib_level > 9)) { 1545 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level", 1546 "a value between 0 and 9"); 1547 return false; 1548 } 1549 1550 if (params->has_multifd_zstd_level && 1551 (params->multifd_zstd_level > 20)) { 1552 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level", 1553 "a value between 0 and 20"); 1554 return false; 1555 } 1556 1557 if (params->has_xbzrle_cache_size && 1558 (params->xbzrle_cache_size < qemu_target_page_size() || 1559 !is_power_of_2(params->xbzrle_cache_size))) { 1560 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1561 "xbzrle_cache_size", 1562 "a power of two no less than the target page size"); 1563 return false; 1564 } 1565 1566 if (params->has_max_cpu_throttle && 1567 (params->max_cpu_throttle < params->cpu_throttle_initial || 1568 params->max_cpu_throttle > 99)) { 1569 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1570 "max_cpu_throttle", 1571 "an integer in the range of cpu_throttle_initial to 99"); 1572 return false; 1573 } 1574 1575 if (params->has_announce_initial && 1576 params->announce_initial > 100000) { 1577 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1578 "announce_initial", 1579 "a value between 0 and 100000"); 1580 return false; 1581 } 1582 if (params->has_announce_max && 1583 params->announce_max > 100000) { 1584 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1585 "announce_max", 1586 "a value between 0 and 100000"); 1587 return false; 1588 } 1589 if (params->has_announce_rounds && 1590 params->announce_rounds > 1000) { 1591 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1592 "announce_rounds", 1593 "a value between 0 and 1000"); 1594 return false; 1595 } 1596 if (params->has_announce_step && 1597 (params->announce_step < 1 || 1598 params->announce_step > 10000)) { 1599 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 1600 "announce_step", 1601 "a value between 0 and 10000"); 1602 return false; 1603 } 1604 1605 if (params->has_block_bitmap_mapping && 1606 !check_dirty_bitmap_mig_alias_map(params->block_bitmap_mapping, errp)) { 1607 error_prepend(errp, "Invalid mapping given for block-bitmap-mapping: "); 1608 return false; 1609 } 1610 1611 #ifdef CONFIG_LINUX 1612 if (migrate_use_zero_copy_send() && 1613 ((params->has_multifd_compression && params->multifd_compression) || 1614 (params->tls_creds && *params->tls_creds))) { 1615 error_setg(errp, 1616 "Zero copy only available for non-compressed non-TLS multifd migration"); 1617 return false; 1618 } 1619 #endif 1620 1621 return true; 1622 } 1623 1624 static void migrate_params_test_apply(MigrateSetParameters *params, 1625 MigrationParameters *dest) 1626 { 1627 *dest = migrate_get_current()->parameters; 1628 1629 /* TODO use QAPI_CLONE() instead of duplicating it inline */ 1630 1631 if (params->has_compress_level) { 1632 dest->compress_level = params->compress_level; 1633 } 1634 1635 if (params->has_compress_threads) { 1636 dest->compress_threads = params->compress_threads; 1637 } 1638 1639 if (params->has_compress_wait_thread) { 1640 dest->compress_wait_thread = params->compress_wait_thread; 1641 } 1642 1643 if (params->has_decompress_threads) { 1644 dest->decompress_threads = params->decompress_threads; 1645 } 1646 1647 if (params->has_throttle_trigger_threshold) { 1648 dest->throttle_trigger_threshold = params->throttle_trigger_threshold; 1649 } 1650 1651 if (params->has_cpu_throttle_initial) { 1652 dest->cpu_throttle_initial = params->cpu_throttle_initial; 1653 } 1654 1655 if (params->has_cpu_throttle_increment) { 1656 dest->cpu_throttle_increment = params->cpu_throttle_increment; 1657 } 1658 1659 if (params->has_cpu_throttle_tailslow) { 1660 dest->cpu_throttle_tailslow = params->cpu_throttle_tailslow; 1661 } 1662 1663 if (params->tls_creds) { 1664 assert(params->tls_creds->type == QTYPE_QSTRING); 1665 dest->tls_creds = params->tls_creds->u.s; 1666 } 1667 1668 if (params->tls_hostname) { 1669 assert(params->tls_hostname->type == QTYPE_QSTRING); 1670 dest->tls_hostname = params->tls_hostname->u.s; 1671 } 1672 1673 if (params->has_max_bandwidth) { 1674 dest->max_bandwidth = params->max_bandwidth; 1675 } 1676 1677 if (params->has_downtime_limit) { 1678 dest->downtime_limit = params->downtime_limit; 1679 } 1680 1681 if (params->has_x_checkpoint_delay) { 1682 dest->x_checkpoint_delay = params->x_checkpoint_delay; 1683 } 1684 1685 if (params->has_block_incremental) { 1686 dest->block_incremental = params->block_incremental; 1687 } 1688 if (params->has_multifd_channels) { 1689 dest->multifd_channels = params->multifd_channels; 1690 } 1691 if (params->has_multifd_compression) { 1692 dest->multifd_compression = params->multifd_compression; 1693 } 1694 if (params->has_xbzrle_cache_size) { 1695 dest->xbzrle_cache_size = params->xbzrle_cache_size; 1696 } 1697 if (params->has_max_postcopy_bandwidth) { 1698 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth; 1699 } 1700 if (params->has_max_cpu_throttle) { 1701 dest->max_cpu_throttle = params->max_cpu_throttle; 1702 } 1703 if (params->has_announce_initial) { 1704 dest->announce_initial = params->announce_initial; 1705 } 1706 if (params->has_announce_max) { 1707 dest->announce_max = params->announce_max; 1708 } 1709 if (params->has_announce_rounds) { 1710 dest->announce_rounds = params->announce_rounds; 1711 } 1712 if (params->has_announce_step) { 1713 dest->announce_step = params->announce_step; 1714 } 1715 1716 if (params->has_block_bitmap_mapping) { 1717 dest->has_block_bitmap_mapping = true; 1718 dest->block_bitmap_mapping = params->block_bitmap_mapping; 1719 } 1720 } 1721 1722 static void migrate_params_apply(MigrateSetParameters *params, Error **errp) 1723 { 1724 MigrationState *s = migrate_get_current(); 1725 1726 /* TODO use QAPI_CLONE() instead of duplicating it inline */ 1727 1728 if (params->has_compress_level) { 1729 s->parameters.compress_level = params->compress_level; 1730 } 1731 1732 if (params->has_compress_threads) { 1733 s->parameters.compress_threads = params->compress_threads; 1734 } 1735 1736 if (params->has_compress_wait_thread) { 1737 s->parameters.compress_wait_thread = params->compress_wait_thread; 1738 } 1739 1740 if (params->has_decompress_threads) { 1741 s->parameters.decompress_threads = params->decompress_threads; 1742 } 1743 1744 if (params->has_throttle_trigger_threshold) { 1745 s->parameters.throttle_trigger_threshold = params->throttle_trigger_threshold; 1746 } 1747 1748 if (params->has_cpu_throttle_initial) { 1749 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial; 1750 } 1751 1752 if (params->has_cpu_throttle_increment) { 1753 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment; 1754 } 1755 1756 if (params->has_cpu_throttle_tailslow) { 1757 s->parameters.cpu_throttle_tailslow = params->cpu_throttle_tailslow; 1758 } 1759 1760 if (params->tls_creds) { 1761 g_free(s->parameters.tls_creds); 1762 assert(params->tls_creds->type == QTYPE_QSTRING); 1763 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s); 1764 } 1765 1766 if (params->tls_hostname) { 1767 g_free(s->parameters.tls_hostname); 1768 assert(params->tls_hostname->type == QTYPE_QSTRING); 1769 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s); 1770 } 1771 1772 if (params->tls_authz) { 1773 g_free(s->parameters.tls_authz); 1774 assert(params->tls_authz->type == QTYPE_QSTRING); 1775 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s); 1776 } 1777 1778 if (params->has_max_bandwidth) { 1779 s->parameters.max_bandwidth = params->max_bandwidth; 1780 if (s->to_dst_file && !migration_in_postcopy()) { 1781 qemu_file_set_rate_limit(s->to_dst_file, 1782 s->parameters.max_bandwidth / XFER_LIMIT_RATIO); 1783 } 1784 } 1785 1786 if (params->has_downtime_limit) { 1787 s->parameters.downtime_limit = params->downtime_limit; 1788 } 1789 1790 if (params->has_x_checkpoint_delay) { 1791 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay; 1792 if (migration_in_colo_state()) { 1793 colo_checkpoint_notify(s); 1794 } 1795 } 1796 1797 if (params->has_block_incremental) { 1798 s->parameters.block_incremental = params->block_incremental; 1799 } 1800 if (params->has_multifd_channels) { 1801 s->parameters.multifd_channels = params->multifd_channels; 1802 } 1803 if (params->has_multifd_compression) { 1804 s->parameters.multifd_compression = params->multifd_compression; 1805 } 1806 if (params->has_xbzrle_cache_size) { 1807 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size; 1808 xbzrle_cache_resize(params->xbzrle_cache_size, errp); 1809 } 1810 if (params->has_max_postcopy_bandwidth) { 1811 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth; 1812 if (s->to_dst_file && migration_in_postcopy()) { 1813 qemu_file_set_rate_limit(s->to_dst_file, 1814 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO); 1815 } 1816 } 1817 if (params->has_max_cpu_throttle) { 1818 s->parameters.max_cpu_throttle = params->max_cpu_throttle; 1819 } 1820 if (params->has_announce_initial) { 1821 s->parameters.announce_initial = params->announce_initial; 1822 } 1823 if (params->has_announce_max) { 1824 s->parameters.announce_max = params->announce_max; 1825 } 1826 if (params->has_announce_rounds) { 1827 s->parameters.announce_rounds = params->announce_rounds; 1828 } 1829 if (params->has_announce_step) { 1830 s->parameters.announce_step = params->announce_step; 1831 } 1832 1833 if (params->has_block_bitmap_mapping) { 1834 qapi_free_BitmapMigrationNodeAliasList( 1835 s->parameters.block_bitmap_mapping); 1836 1837 s->parameters.has_block_bitmap_mapping = true; 1838 s->parameters.block_bitmap_mapping = 1839 QAPI_CLONE(BitmapMigrationNodeAliasList, 1840 params->block_bitmap_mapping); 1841 } 1842 } 1843 1844 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp) 1845 { 1846 MigrationParameters tmp; 1847 1848 /* TODO Rewrite "" to null instead */ 1849 if (params->tls_creds 1850 && params->tls_creds->type == QTYPE_QNULL) { 1851 qobject_unref(params->tls_creds->u.n); 1852 params->tls_creds->type = QTYPE_QSTRING; 1853 params->tls_creds->u.s = strdup(""); 1854 } 1855 /* TODO Rewrite "" to null instead */ 1856 if (params->tls_hostname 1857 && params->tls_hostname->type == QTYPE_QNULL) { 1858 qobject_unref(params->tls_hostname->u.n); 1859 params->tls_hostname->type = QTYPE_QSTRING; 1860 params->tls_hostname->u.s = strdup(""); 1861 } 1862 1863 migrate_params_test_apply(params, &tmp); 1864 1865 if (!migrate_params_check(&tmp, errp)) { 1866 /* Invalid parameter */ 1867 return; 1868 } 1869 1870 migrate_params_apply(params, errp); 1871 } 1872 1873 1874 void qmp_migrate_start_postcopy(Error **errp) 1875 { 1876 MigrationState *s = migrate_get_current(); 1877 1878 if (!migrate_postcopy()) { 1879 error_setg(errp, "Enable postcopy with migrate_set_capability before" 1880 " the start of migration"); 1881 return; 1882 } 1883 1884 if (s->state == MIGRATION_STATUS_NONE) { 1885 error_setg(errp, "Postcopy must be started after migration has been" 1886 " started"); 1887 return; 1888 } 1889 /* 1890 * we don't error if migration has finished since that would be racy 1891 * with issuing this command. 1892 */ 1893 qatomic_set(&s->start_postcopy, true); 1894 } 1895 1896 /* shared migration helpers */ 1897 1898 void migrate_set_state(int *state, int old_state, int new_state) 1899 { 1900 assert(new_state < MIGRATION_STATUS__MAX); 1901 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) { 1902 trace_migrate_set_state(MigrationStatus_str(new_state)); 1903 migrate_generate_event(new_state); 1904 } 1905 } 1906 1907 static bool migrate_cap_set(int cap, bool value, Error **errp) 1908 { 1909 MigrationState *s = migrate_get_current(); 1910 bool new_caps[MIGRATION_CAPABILITY__MAX]; 1911 1912 if (migration_is_running(s->state)) { 1913 error_setg(errp, QERR_MIGRATION_ACTIVE); 1914 return false; 1915 } 1916 1917 memcpy(new_caps, s->capabilities, sizeof(new_caps)); 1918 new_caps[cap] = value; 1919 1920 if (!migrate_caps_check(s->capabilities, new_caps, errp)) { 1921 return false; 1922 } 1923 s->capabilities[cap] = value; 1924 return true; 1925 } 1926 1927 static void migrate_set_block_incremental(MigrationState *s, bool value) 1928 { 1929 s->parameters.block_incremental = value; 1930 } 1931 1932 static void block_cleanup_parameters(MigrationState *s) 1933 { 1934 if (s->must_remove_block_options) { 1935 /* setting to false can never fail */ 1936 migrate_cap_set(MIGRATION_CAPABILITY_BLOCK, false, &error_abort); 1937 migrate_set_block_incremental(s, false); 1938 s->must_remove_block_options = false; 1939 } 1940 } 1941 1942 static void migrate_fd_cleanup(MigrationState *s) 1943 { 1944 qemu_bh_delete(s->cleanup_bh); 1945 s->cleanup_bh = NULL; 1946 1947 g_free(s->hostname); 1948 s->hostname = NULL; 1949 json_writer_free(s->vmdesc); 1950 s->vmdesc = NULL; 1951 1952 qemu_savevm_state_cleanup(); 1953 1954 if (s->to_dst_file) { 1955 QEMUFile *tmp; 1956 1957 trace_migrate_fd_cleanup(); 1958 qemu_mutex_unlock_iothread(); 1959 if (s->migration_thread_running) { 1960 qemu_thread_join(&s->thread); 1961 s->migration_thread_running = false; 1962 } 1963 qemu_mutex_lock_iothread(); 1964 1965 multifd_save_cleanup(); 1966 qemu_mutex_lock(&s->qemu_file_lock); 1967 tmp = s->to_dst_file; 1968 s->to_dst_file = NULL; 1969 qemu_mutex_unlock(&s->qemu_file_lock); 1970 /* 1971 * Close the file handle without the lock to make sure the 1972 * critical section won't block for long. 1973 */ 1974 migration_ioc_unregister_yank_from_file(tmp); 1975 qemu_fclose(tmp); 1976 } 1977 1978 if (s->postcopy_qemufile_src) { 1979 migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src); 1980 qemu_fclose(s->postcopy_qemufile_src); 1981 s->postcopy_qemufile_src = NULL; 1982 } 1983 1984 assert(!migration_is_active(s)); 1985 1986 if (s->state == MIGRATION_STATUS_CANCELLING) { 1987 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING, 1988 MIGRATION_STATUS_CANCELLED); 1989 } 1990 1991 if (s->error) { 1992 /* It is used on info migrate. We can't free it */ 1993 error_report_err(error_copy(s->error)); 1994 } 1995 notifier_list_notify(&migration_state_notifiers, s); 1996 block_cleanup_parameters(s); 1997 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 1998 } 1999 2000 static void migrate_fd_cleanup_schedule(MigrationState *s) 2001 { 2002 /* 2003 * Ref the state for bh, because it may be called when 2004 * there're already no other refs 2005 */ 2006 object_ref(OBJECT(s)); 2007 qemu_bh_schedule(s->cleanup_bh); 2008 } 2009 2010 static void migrate_fd_cleanup_bh(void *opaque) 2011 { 2012 MigrationState *s = opaque; 2013 migrate_fd_cleanup(s); 2014 object_unref(OBJECT(s)); 2015 } 2016 2017 void migrate_set_error(MigrationState *s, const Error *error) 2018 { 2019 QEMU_LOCK_GUARD(&s->error_mutex); 2020 if (!s->error) { 2021 s->error = error_copy(error); 2022 } 2023 } 2024 2025 static void migrate_error_free(MigrationState *s) 2026 { 2027 QEMU_LOCK_GUARD(&s->error_mutex); 2028 if (s->error) { 2029 error_free(s->error); 2030 s->error = NULL; 2031 } 2032 } 2033 2034 void migrate_fd_error(MigrationState *s, const Error *error) 2035 { 2036 trace_migrate_fd_error(error_get_pretty(error)); 2037 assert(s->to_dst_file == NULL); 2038 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 2039 MIGRATION_STATUS_FAILED); 2040 migrate_set_error(s, error); 2041 } 2042 2043 static void migrate_fd_cancel(MigrationState *s) 2044 { 2045 int old_state ; 2046 QEMUFile *f = migrate_get_current()->to_dst_file; 2047 trace_migrate_fd_cancel(); 2048 2049 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) { 2050 if (s->rp_state.from_dst_file) { 2051 /* shutdown the rp socket, so causing the rp thread to shutdown */ 2052 qemu_file_shutdown(s->rp_state.from_dst_file); 2053 } 2054 } 2055 2056 do { 2057 old_state = s->state; 2058 if (!migration_is_running(old_state)) { 2059 break; 2060 } 2061 /* If the migration is paused, kick it out of the pause */ 2062 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) { 2063 qemu_sem_post(&s->pause_sem); 2064 } 2065 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING); 2066 } while (s->state != MIGRATION_STATUS_CANCELLING); 2067 2068 /* 2069 * If we're unlucky the migration code might be stuck somewhere in a 2070 * send/write while the network has failed and is waiting to timeout; 2071 * if we've got shutdown(2) available then we can force it to quit. 2072 * The outgoing qemu file gets closed in migrate_fd_cleanup that is 2073 * called in a bh, so there is no race against this cancel. 2074 */ 2075 if (s->state == MIGRATION_STATUS_CANCELLING && f) { 2076 qemu_file_shutdown(f); 2077 } 2078 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) { 2079 Error *local_err = NULL; 2080 2081 bdrv_activate_all(&local_err); 2082 if (local_err) { 2083 error_report_err(local_err); 2084 } else { 2085 s->block_inactive = false; 2086 } 2087 } 2088 } 2089 2090 void add_migration_state_change_notifier(Notifier *notify) 2091 { 2092 notifier_list_add(&migration_state_notifiers, notify); 2093 } 2094 2095 void remove_migration_state_change_notifier(Notifier *notify) 2096 { 2097 notifier_remove(notify); 2098 } 2099 2100 bool migration_in_setup(MigrationState *s) 2101 { 2102 return s->state == MIGRATION_STATUS_SETUP; 2103 } 2104 2105 bool migration_has_finished(MigrationState *s) 2106 { 2107 return s->state == MIGRATION_STATUS_COMPLETED; 2108 } 2109 2110 bool migration_has_failed(MigrationState *s) 2111 { 2112 return (s->state == MIGRATION_STATUS_CANCELLED || 2113 s->state == MIGRATION_STATUS_FAILED); 2114 } 2115 2116 bool migration_in_postcopy(void) 2117 { 2118 MigrationState *s = migrate_get_current(); 2119 2120 switch (s->state) { 2121 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 2122 case MIGRATION_STATUS_POSTCOPY_PAUSED: 2123 case MIGRATION_STATUS_POSTCOPY_RECOVER: 2124 return true; 2125 default: 2126 return false; 2127 } 2128 } 2129 2130 bool migration_in_postcopy_after_devices(MigrationState *s) 2131 { 2132 return migration_in_postcopy() && s->postcopy_after_devices; 2133 } 2134 2135 bool migration_in_incoming_postcopy(void) 2136 { 2137 PostcopyState ps = postcopy_state_get(); 2138 2139 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END; 2140 } 2141 2142 bool migration_incoming_postcopy_advised(void) 2143 { 2144 PostcopyState ps = postcopy_state_get(); 2145 2146 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END; 2147 } 2148 2149 bool migration_in_bg_snapshot(void) 2150 { 2151 MigrationState *s = migrate_get_current(); 2152 2153 return migrate_background_snapshot() && 2154 migration_is_setup_or_active(s->state); 2155 } 2156 2157 bool migration_is_idle(void) 2158 { 2159 MigrationState *s = current_migration; 2160 2161 if (!s) { 2162 return true; 2163 } 2164 2165 switch (s->state) { 2166 case MIGRATION_STATUS_NONE: 2167 case MIGRATION_STATUS_CANCELLED: 2168 case MIGRATION_STATUS_COMPLETED: 2169 case MIGRATION_STATUS_FAILED: 2170 return true; 2171 case MIGRATION_STATUS_SETUP: 2172 case MIGRATION_STATUS_CANCELLING: 2173 case MIGRATION_STATUS_ACTIVE: 2174 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 2175 case MIGRATION_STATUS_COLO: 2176 case MIGRATION_STATUS_PRE_SWITCHOVER: 2177 case MIGRATION_STATUS_DEVICE: 2178 case MIGRATION_STATUS_WAIT_UNPLUG: 2179 return false; 2180 case MIGRATION_STATUS__MAX: 2181 g_assert_not_reached(); 2182 } 2183 2184 return false; 2185 } 2186 2187 bool migration_is_active(MigrationState *s) 2188 { 2189 return (s->state == MIGRATION_STATUS_ACTIVE || 2190 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE); 2191 } 2192 2193 void migrate_init(MigrationState *s) 2194 { 2195 /* 2196 * Reinitialise all migration state, except 2197 * parameters/capabilities that the user set, and 2198 * locks. 2199 */ 2200 s->cleanup_bh = 0; 2201 s->vm_start_bh = 0; 2202 s->to_dst_file = NULL; 2203 s->state = MIGRATION_STATUS_NONE; 2204 s->rp_state.from_dst_file = NULL; 2205 s->rp_state.error = false; 2206 s->mbps = 0.0; 2207 s->pages_per_second = 0.0; 2208 s->downtime = 0; 2209 s->expected_downtime = 0; 2210 s->setup_time = 0; 2211 s->start_postcopy = false; 2212 s->postcopy_after_devices = false; 2213 s->migration_thread_running = false; 2214 error_free(s->error); 2215 s->error = NULL; 2216 s->hostname = NULL; 2217 2218 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP); 2219 2220 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2221 s->total_time = 0; 2222 s->vm_was_running = false; 2223 s->iteration_initial_bytes = 0; 2224 s->threshold_size = 0; 2225 } 2226 2227 int migrate_add_blocker_internal(Error *reason, Error **errp) 2228 { 2229 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */ 2230 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) { 2231 error_propagate_prepend(errp, error_copy(reason), 2232 "disallowing migration blocker " 2233 "(migration/snapshot in progress) for: "); 2234 return -EBUSY; 2235 } 2236 2237 migration_blockers = g_slist_prepend(migration_blockers, reason); 2238 return 0; 2239 } 2240 2241 int migrate_add_blocker(Error *reason, Error **errp) 2242 { 2243 if (only_migratable) { 2244 error_propagate_prepend(errp, error_copy(reason), 2245 "disallowing migration blocker " 2246 "(--only-migratable) for: "); 2247 return -EACCES; 2248 } 2249 2250 return migrate_add_blocker_internal(reason, errp); 2251 } 2252 2253 void migrate_del_blocker(Error *reason) 2254 { 2255 migration_blockers = g_slist_remove(migration_blockers, reason); 2256 } 2257 2258 void qmp_migrate_incoming(const char *uri, Error **errp) 2259 { 2260 Error *local_err = NULL; 2261 static bool once = true; 2262 2263 if (!once) { 2264 error_setg(errp, "The incoming migration has already been started"); 2265 return; 2266 } 2267 if (!runstate_check(RUN_STATE_INMIGRATE)) { 2268 error_setg(errp, "'-incoming' was not specified on the command line"); 2269 return; 2270 } 2271 2272 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) { 2273 return; 2274 } 2275 2276 qemu_start_incoming_migration(uri, &local_err); 2277 2278 if (local_err) { 2279 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 2280 error_propagate(errp, local_err); 2281 return; 2282 } 2283 2284 once = false; 2285 } 2286 2287 void qmp_migrate_recover(const char *uri, Error **errp) 2288 { 2289 MigrationIncomingState *mis = migration_incoming_get_current(); 2290 2291 /* 2292 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by 2293 * callers (no one should ignore a recover failure); if there is, it's a 2294 * programming error. 2295 */ 2296 assert(errp); 2297 2298 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) { 2299 error_setg(errp, "Migrate recover can only be run " 2300 "when postcopy is paused."); 2301 return; 2302 } 2303 2304 /* If there's an existing transport, release it */ 2305 migration_incoming_transport_cleanup(mis); 2306 2307 /* 2308 * Note that this call will never start a real migration; it will 2309 * only re-setup the migration stream and poke existing migration 2310 * to continue using that newly established channel. 2311 */ 2312 qemu_start_incoming_migration(uri, errp); 2313 } 2314 2315 void qmp_migrate_pause(Error **errp) 2316 { 2317 MigrationState *ms = migrate_get_current(); 2318 MigrationIncomingState *mis = migration_incoming_get_current(); 2319 int ret; 2320 2321 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 2322 /* Source side, during postcopy */ 2323 qemu_mutex_lock(&ms->qemu_file_lock); 2324 ret = qemu_file_shutdown(ms->to_dst_file); 2325 qemu_mutex_unlock(&ms->qemu_file_lock); 2326 if (ret) { 2327 error_setg(errp, "Failed to pause source migration"); 2328 } 2329 return; 2330 } 2331 2332 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 2333 ret = qemu_file_shutdown(mis->from_src_file); 2334 if (ret) { 2335 error_setg(errp, "Failed to pause destination migration"); 2336 } 2337 return; 2338 } 2339 2340 error_setg(errp, "migrate-pause is currently only supported " 2341 "during postcopy-active state"); 2342 } 2343 2344 bool migration_is_blocked(Error **errp) 2345 { 2346 if (qemu_savevm_state_blocked(errp)) { 2347 return true; 2348 } 2349 2350 if (migration_blockers) { 2351 error_propagate(errp, error_copy(migration_blockers->data)); 2352 return true; 2353 } 2354 2355 return false; 2356 } 2357 2358 /* Returns true if continue to migrate, or false if error detected */ 2359 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc, 2360 bool resume, Error **errp) 2361 { 2362 Error *local_err = NULL; 2363 2364 if (resume) { 2365 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) { 2366 error_setg(errp, "Cannot resume if there is no " 2367 "paused migration"); 2368 return false; 2369 } 2370 2371 /* 2372 * Postcopy recovery won't work well with release-ram 2373 * capability since release-ram will drop the page buffer as 2374 * long as the page is put into the send buffer. So if there 2375 * is a network failure happened, any page buffers that have 2376 * not yet reached the destination VM but have already been 2377 * sent from the source VM will be lost forever. Let's refuse 2378 * the client from resuming such a postcopy migration. 2379 * Luckily release-ram was designed to only be used when src 2380 * and destination VMs are on the same host, so it should be 2381 * fine. 2382 */ 2383 if (migrate_release_ram()) { 2384 error_setg(errp, "Postcopy recovery cannot work " 2385 "when release-ram capability is set"); 2386 return false; 2387 } 2388 2389 /* This is a resume, skip init status */ 2390 return true; 2391 } 2392 2393 if (migration_is_running(s->state)) { 2394 error_setg(errp, QERR_MIGRATION_ACTIVE); 2395 return false; 2396 } 2397 2398 if (runstate_check(RUN_STATE_INMIGRATE)) { 2399 error_setg(errp, "Guest is waiting for an incoming migration"); 2400 return false; 2401 } 2402 2403 if (runstate_check(RUN_STATE_POSTMIGRATE)) { 2404 error_setg(errp, "Can't migrate the vm that was paused due to " 2405 "previous migration"); 2406 return false; 2407 } 2408 2409 if (migration_is_blocked(errp)) { 2410 return false; 2411 } 2412 2413 if (blk || blk_inc) { 2414 if (migrate_colo()) { 2415 error_setg(errp, "No disk migration is required in COLO mode"); 2416 return false; 2417 } 2418 if (migrate_use_block() || migrate_use_block_incremental()) { 2419 error_setg(errp, "Command options are incompatible with " 2420 "current migration capabilities"); 2421 return false; 2422 } 2423 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK, true, &local_err)) { 2424 error_propagate(errp, local_err); 2425 return false; 2426 } 2427 s->must_remove_block_options = true; 2428 } 2429 2430 if (blk_inc) { 2431 migrate_set_block_incremental(s, true); 2432 } 2433 2434 migrate_init(s); 2435 /* 2436 * set ram_counters compression_counters memory to zero for a 2437 * new migration 2438 */ 2439 memset(&ram_counters, 0, sizeof(ram_counters)); 2440 memset(&compression_counters, 0, sizeof(compression_counters)); 2441 2442 return true; 2443 } 2444 2445 void qmp_migrate(const char *uri, bool has_blk, bool blk, 2446 bool has_inc, bool inc, bool has_detach, bool detach, 2447 bool has_resume, bool resume, Error **errp) 2448 { 2449 Error *local_err = NULL; 2450 MigrationState *s = migrate_get_current(); 2451 const char *p = NULL; 2452 2453 /* URI is not suitable for migration? */ 2454 if (!migration_channels_and_uri_compatible(uri, errp)) { 2455 return; 2456 } 2457 2458 if (!migrate_prepare(s, has_blk && blk, has_inc && inc, 2459 has_resume && resume, errp)) { 2460 /* Error detected, put into errp */ 2461 return; 2462 } 2463 2464 if (!(has_resume && resume)) { 2465 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) { 2466 return; 2467 } 2468 } 2469 2470 if (strstart(uri, "tcp:", &p) || 2471 strstart(uri, "unix:", NULL) || 2472 strstart(uri, "vsock:", NULL)) { 2473 socket_start_outgoing_migration(s, p ? p : uri, &local_err); 2474 #ifdef CONFIG_RDMA 2475 } else if (strstart(uri, "rdma:", &p)) { 2476 rdma_start_outgoing_migration(s, p, &local_err); 2477 #endif 2478 } else if (strstart(uri, "exec:", &p)) { 2479 exec_start_outgoing_migration(s, p, &local_err); 2480 } else if (strstart(uri, "fd:", &p)) { 2481 fd_start_outgoing_migration(s, p, &local_err); 2482 } else { 2483 if (!(has_resume && resume)) { 2484 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 2485 } 2486 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri", 2487 "a valid migration protocol"); 2488 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 2489 MIGRATION_STATUS_FAILED); 2490 block_cleanup_parameters(s); 2491 return; 2492 } 2493 2494 if (local_err) { 2495 if (!(has_resume && resume)) { 2496 yank_unregister_instance(MIGRATION_YANK_INSTANCE); 2497 } 2498 migrate_fd_error(s, local_err); 2499 error_propagate(errp, local_err); 2500 return; 2501 } 2502 } 2503 2504 void qmp_migrate_cancel(Error **errp) 2505 { 2506 migration_cancel(NULL); 2507 } 2508 2509 void qmp_migrate_continue(MigrationStatus state, Error **errp) 2510 { 2511 MigrationState *s = migrate_get_current(); 2512 if (s->state != state) { 2513 error_setg(errp, "Migration not in expected state: %s", 2514 MigrationStatus_str(s->state)); 2515 return; 2516 } 2517 qemu_sem_post(&s->pause_sem); 2518 } 2519 2520 bool migrate_postcopy(void) 2521 { 2522 return migrate_postcopy_ram() || migrate_dirty_bitmaps(); 2523 } 2524 2525 int migrate_compress_level(void) 2526 { 2527 MigrationState *s; 2528 2529 s = migrate_get_current(); 2530 2531 return s->parameters.compress_level; 2532 } 2533 2534 int migrate_compress_threads(void) 2535 { 2536 MigrationState *s; 2537 2538 s = migrate_get_current(); 2539 2540 return s->parameters.compress_threads; 2541 } 2542 2543 int migrate_compress_wait_thread(void) 2544 { 2545 MigrationState *s; 2546 2547 s = migrate_get_current(); 2548 2549 return s->parameters.compress_wait_thread; 2550 } 2551 2552 int migrate_decompress_threads(void) 2553 { 2554 MigrationState *s; 2555 2556 s = migrate_get_current(); 2557 2558 return s->parameters.decompress_threads; 2559 } 2560 2561 int migrate_multifd_channels(void) 2562 { 2563 MigrationState *s; 2564 2565 s = migrate_get_current(); 2566 2567 return s->parameters.multifd_channels; 2568 } 2569 2570 MultiFDCompression migrate_multifd_compression(void) 2571 { 2572 MigrationState *s; 2573 2574 s = migrate_get_current(); 2575 2576 assert(s->parameters.multifd_compression < MULTIFD_COMPRESSION__MAX); 2577 return s->parameters.multifd_compression; 2578 } 2579 2580 int migrate_multifd_zlib_level(void) 2581 { 2582 MigrationState *s; 2583 2584 s = migrate_get_current(); 2585 2586 return s->parameters.multifd_zlib_level; 2587 } 2588 2589 int migrate_multifd_zstd_level(void) 2590 { 2591 MigrationState *s; 2592 2593 s = migrate_get_current(); 2594 2595 return s->parameters.multifd_zstd_level; 2596 } 2597 2598 #ifdef CONFIG_LINUX 2599 bool migrate_use_zero_copy_send(void) 2600 { 2601 MigrationState *s; 2602 2603 s = migrate_get_current(); 2604 2605 return s->capabilities[MIGRATION_CAPABILITY_ZERO_COPY_SEND]; 2606 } 2607 #endif 2608 2609 int migrate_use_tls(void) 2610 { 2611 MigrationState *s; 2612 2613 s = migrate_get_current(); 2614 2615 return s->parameters.tls_creds && *s->parameters.tls_creds; 2616 } 2617 2618 int migrate_use_xbzrle(void) 2619 { 2620 MigrationState *s; 2621 2622 s = migrate_get_current(); 2623 2624 return s->capabilities[MIGRATION_CAPABILITY_XBZRLE]; 2625 } 2626 2627 uint64_t migrate_xbzrle_cache_size(void) 2628 { 2629 MigrationState *s; 2630 2631 s = migrate_get_current(); 2632 2633 return s->parameters.xbzrle_cache_size; 2634 } 2635 2636 static int64_t migrate_max_postcopy_bandwidth(void) 2637 { 2638 MigrationState *s; 2639 2640 s = migrate_get_current(); 2641 2642 return s->parameters.max_postcopy_bandwidth; 2643 } 2644 2645 bool migrate_use_block(void) 2646 { 2647 MigrationState *s; 2648 2649 s = migrate_get_current(); 2650 2651 return s->capabilities[MIGRATION_CAPABILITY_BLOCK]; 2652 } 2653 2654 bool migrate_use_return_path(void) 2655 { 2656 MigrationState *s; 2657 2658 s = migrate_get_current(); 2659 2660 return s->capabilities[MIGRATION_CAPABILITY_RETURN_PATH]; 2661 } 2662 2663 bool migrate_use_block_incremental(void) 2664 { 2665 MigrationState *s; 2666 2667 s = migrate_get_current(); 2668 2669 return s->parameters.block_incremental; 2670 } 2671 2672 /* migration thread support */ 2673 /* 2674 * Something bad happened to the RP stream, mark an error 2675 * The caller shall print or trace something to indicate why 2676 */ 2677 static void mark_source_rp_bad(MigrationState *s) 2678 { 2679 s->rp_state.error = true; 2680 } 2681 2682 static struct rp_cmd_args { 2683 ssize_t len; /* -1 = variable */ 2684 const char *name; 2685 } rp_cmd_args[] = { 2686 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" }, 2687 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" }, 2688 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" }, 2689 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" }, 2690 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" }, 2691 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" }, 2692 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" }, 2693 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" }, 2694 }; 2695 2696 /* 2697 * Process a request for pages received on the return path, 2698 * We're allowed to send more than requested (e.g. to round to our page size) 2699 * and we don't need to send pages that have already been sent. 2700 */ 2701 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname, 2702 ram_addr_t start, size_t len) 2703 { 2704 long our_host_ps = qemu_real_host_page_size(); 2705 2706 trace_migrate_handle_rp_req_pages(rbname, start, len); 2707 2708 /* 2709 * Since we currently insist on matching page sizes, just sanity check 2710 * we're being asked for whole host pages. 2711 */ 2712 if (!QEMU_IS_ALIGNED(start, our_host_ps) || 2713 !QEMU_IS_ALIGNED(len, our_host_ps)) { 2714 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT 2715 " len: %zd", __func__, start, len); 2716 mark_source_rp_bad(ms); 2717 return; 2718 } 2719 2720 if (ram_save_queue_pages(rbname, start, len)) { 2721 mark_source_rp_bad(ms); 2722 } 2723 } 2724 2725 /* Return true to retry, false to quit */ 2726 static bool postcopy_pause_return_path_thread(MigrationState *s) 2727 { 2728 trace_postcopy_pause_return_path(); 2729 2730 qemu_sem_wait(&s->postcopy_pause_rp_sem); 2731 2732 trace_postcopy_pause_return_path_continued(); 2733 2734 return true; 2735 } 2736 2737 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name) 2738 { 2739 RAMBlock *block = qemu_ram_block_by_name(block_name); 2740 2741 if (!block) { 2742 error_report("%s: invalid block name '%s'", __func__, block_name); 2743 return -EINVAL; 2744 } 2745 2746 /* Fetch the received bitmap and refresh the dirty bitmap */ 2747 return ram_dirty_bitmap_reload(s, block); 2748 } 2749 2750 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value) 2751 { 2752 trace_source_return_path_thread_resume_ack(value); 2753 2754 if (value != MIGRATION_RESUME_ACK_VALUE) { 2755 error_report("%s: illegal resume_ack value %"PRIu32, 2756 __func__, value); 2757 return -1; 2758 } 2759 2760 /* Now both sides are active. */ 2761 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER, 2762 MIGRATION_STATUS_POSTCOPY_ACTIVE); 2763 2764 /* Notify send thread that time to continue send pages */ 2765 qemu_sem_post(&s->rp_state.rp_sem); 2766 2767 return 0; 2768 } 2769 2770 /* 2771 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if 2772 * existed) in a safe way. 2773 */ 2774 static void migration_release_dst_files(MigrationState *ms) 2775 { 2776 QEMUFile *file; 2777 2778 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) { 2779 /* 2780 * Reset the from_dst_file pointer first before releasing it, as we 2781 * can't block within lock section 2782 */ 2783 file = ms->rp_state.from_dst_file; 2784 ms->rp_state.from_dst_file = NULL; 2785 } 2786 2787 /* 2788 * Do the same to postcopy fast path socket too if there is. No 2789 * locking needed because this qemufile should only be managed by 2790 * return path thread. 2791 */ 2792 if (ms->postcopy_qemufile_src) { 2793 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src); 2794 qemu_file_shutdown(ms->postcopy_qemufile_src); 2795 qemu_fclose(ms->postcopy_qemufile_src); 2796 ms->postcopy_qemufile_src = NULL; 2797 } 2798 2799 qemu_fclose(file); 2800 } 2801 2802 /* 2803 * Handles messages sent on the return path towards the source VM 2804 * 2805 */ 2806 static void *source_return_path_thread(void *opaque) 2807 { 2808 MigrationState *ms = opaque; 2809 QEMUFile *rp = ms->rp_state.from_dst_file; 2810 uint16_t header_len, header_type; 2811 uint8_t buf[512]; 2812 uint32_t tmp32, sibling_error; 2813 ram_addr_t start = 0; /* =0 to silence warning */ 2814 size_t len = 0, expected_len; 2815 int res; 2816 2817 trace_source_return_path_thread_entry(); 2818 rcu_register_thread(); 2819 2820 retry: 2821 while (!ms->rp_state.error && !qemu_file_get_error(rp) && 2822 migration_is_setup_or_active(ms->state)) { 2823 trace_source_return_path_thread_loop_top(); 2824 header_type = qemu_get_be16(rp); 2825 header_len = qemu_get_be16(rp); 2826 2827 if (qemu_file_get_error(rp)) { 2828 mark_source_rp_bad(ms); 2829 goto out; 2830 } 2831 2832 if (header_type >= MIG_RP_MSG_MAX || 2833 header_type == MIG_RP_MSG_INVALID) { 2834 error_report("RP: Received invalid message 0x%04x length 0x%04x", 2835 header_type, header_len); 2836 mark_source_rp_bad(ms); 2837 goto out; 2838 } 2839 2840 if ((rp_cmd_args[header_type].len != -1 && 2841 header_len != rp_cmd_args[header_type].len) || 2842 header_len > sizeof(buf)) { 2843 error_report("RP: Received '%s' message (0x%04x) with" 2844 "incorrect length %d expecting %zu", 2845 rp_cmd_args[header_type].name, header_type, header_len, 2846 (size_t)rp_cmd_args[header_type].len); 2847 mark_source_rp_bad(ms); 2848 goto out; 2849 } 2850 2851 /* We know we've got a valid header by this point */ 2852 res = qemu_get_buffer(rp, buf, header_len); 2853 if (res != header_len) { 2854 error_report("RP: Failed reading data for message 0x%04x" 2855 " read %d expected %d", 2856 header_type, res, header_len); 2857 mark_source_rp_bad(ms); 2858 goto out; 2859 } 2860 2861 /* OK, we have the message and the data */ 2862 switch (header_type) { 2863 case MIG_RP_MSG_SHUT: 2864 sibling_error = ldl_be_p(buf); 2865 trace_source_return_path_thread_shut(sibling_error); 2866 if (sibling_error) { 2867 error_report("RP: Sibling indicated error %d", sibling_error); 2868 mark_source_rp_bad(ms); 2869 } 2870 /* 2871 * We'll let the main thread deal with closing the RP 2872 * we could do a shutdown(2) on it, but we're the only user 2873 * anyway, so there's nothing gained. 2874 */ 2875 goto out; 2876 2877 case MIG_RP_MSG_PONG: 2878 tmp32 = ldl_be_p(buf); 2879 trace_source_return_path_thread_pong(tmp32); 2880 qemu_sem_post(&ms->rp_state.rp_pong_acks); 2881 break; 2882 2883 case MIG_RP_MSG_REQ_PAGES: 2884 start = ldq_be_p(buf); 2885 len = ldl_be_p(buf + 8); 2886 migrate_handle_rp_req_pages(ms, NULL, start, len); 2887 break; 2888 2889 case MIG_RP_MSG_REQ_PAGES_ID: 2890 expected_len = 12 + 1; /* header + termination */ 2891 2892 if (header_len >= expected_len) { 2893 start = ldq_be_p(buf); 2894 len = ldl_be_p(buf + 8); 2895 /* Now we expect an idstr */ 2896 tmp32 = buf[12]; /* Length of the following idstr */ 2897 buf[13 + tmp32] = '\0'; 2898 expected_len += tmp32; 2899 } 2900 if (header_len != expected_len) { 2901 error_report("RP: Req_Page_id with length %d expecting %zd", 2902 header_len, expected_len); 2903 mark_source_rp_bad(ms); 2904 goto out; 2905 } 2906 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len); 2907 break; 2908 2909 case MIG_RP_MSG_RECV_BITMAP: 2910 if (header_len < 1) { 2911 error_report("%s: missing block name", __func__); 2912 mark_source_rp_bad(ms); 2913 goto out; 2914 } 2915 /* Format: len (1B) + idstr (<255B). This ends the idstr. */ 2916 buf[buf[0] + 1] = '\0'; 2917 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) { 2918 mark_source_rp_bad(ms); 2919 goto out; 2920 } 2921 break; 2922 2923 case MIG_RP_MSG_RESUME_ACK: 2924 tmp32 = ldl_be_p(buf); 2925 if (migrate_handle_rp_resume_ack(ms, tmp32)) { 2926 mark_source_rp_bad(ms); 2927 goto out; 2928 } 2929 break; 2930 2931 default: 2932 break; 2933 } 2934 } 2935 2936 out: 2937 res = qemu_file_get_error(rp); 2938 if (res) { 2939 if (res && migration_in_postcopy()) { 2940 /* 2941 * Maybe there is something we can do: it looks like a 2942 * network down issue, and we pause for a recovery. 2943 */ 2944 migration_release_dst_files(ms); 2945 rp = NULL; 2946 if (postcopy_pause_return_path_thread(ms)) { 2947 /* 2948 * Reload rp, reset the rest. Referencing it is safe since 2949 * it's reset only by us above, or when migration completes 2950 */ 2951 rp = ms->rp_state.from_dst_file; 2952 ms->rp_state.error = false; 2953 goto retry; 2954 } 2955 } 2956 2957 trace_source_return_path_thread_bad_end(); 2958 mark_source_rp_bad(ms); 2959 } 2960 2961 trace_source_return_path_thread_end(); 2962 migration_release_dst_files(ms); 2963 rcu_unregister_thread(); 2964 return NULL; 2965 } 2966 2967 static int open_return_path_on_source(MigrationState *ms, 2968 bool create_thread) 2969 { 2970 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file); 2971 if (!ms->rp_state.from_dst_file) { 2972 return -1; 2973 } 2974 2975 trace_open_return_path_on_source(); 2976 2977 if (!create_thread) { 2978 /* We're done */ 2979 return 0; 2980 } 2981 2982 qemu_thread_create(&ms->rp_state.rp_thread, "return path", 2983 source_return_path_thread, ms, QEMU_THREAD_JOINABLE); 2984 ms->rp_state.rp_thread_created = true; 2985 2986 trace_open_return_path_on_source_continue(); 2987 2988 return 0; 2989 } 2990 2991 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */ 2992 static int await_return_path_close_on_source(MigrationState *ms) 2993 { 2994 /* 2995 * If this is a normal exit then the destination will send a SHUT and the 2996 * rp_thread will exit, however if there's an error we need to cause 2997 * it to exit. 2998 */ 2999 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) { 3000 /* 3001 * shutdown(2), if we have it, will cause it to unblock if it's stuck 3002 * waiting for the destination. 3003 */ 3004 qemu_file_shutdown(ms->rp_state.from_dst_file); 3005 mark_source_rp_bad(ms); 3006 } 3007 trace_await_return_path_close_on_source_joining(); 3008 qemu_thread_join(&ms->rp_state.rp_thread); 3009 ms->rp_state.rp_thread_created = false; 3010 trace_await_return_path_close_on_source_close(); 3011 return ms->rp_state.error; 3012 } 3013 3014 static inline void 3015 migration_wait_main_channel(MigrationState *ms) 3016 { 3017 /* Wait until one PONG message received */ 3018 qemu_sem_wait(&ms->rp_state.rp_pong_acks); 3019 } 3020 3021 /* 3022 * Switch from normal iteration to postcopy 3023 * Returns non-0 on error 3024 */ 3025 static int postcopy_start(MigrationState *ms) 3026 { 3027 int ret; 3028 QIOChannelBuffer *bioc; 3029 QEMUFile *fb; 3030 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 3031 int64_t bandwidth = migrate_max_postcopy_bandwidth(); 3032 bool restart_block = false; 3033 int cur_state = MIGRATION_STATUS_ACTIVE; 3034 3035 if (migrate_postcopy_preempt()) { 3036 migration_wait_main_channel(ms); 3037 if (postcopy_preempt_establish_channel(ms)) { 3038 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED); 3039 return -1; 3040 } 3041 } 3042 3043 if (!migrate_pause_before_switchover()) { 3044 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE, 3045 MIGRATION_STATUS_POSTCOPY_ACTIVE); 3046 } 3047 3048 trace_postcopy_start(); 3049 qemu_mutex_lock_iothread(); 3050 trace_postcopy_start_set_run(); 3051 3052 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL); 3053 global_state_store(); 3054 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE); 3055 if (ret < 0) { 3056 goto fail; 3057 } 3058 3059 ret = migration_maybe_pause(ms, &cur_state, 3060 MIGRATION_STATUS_POSTCOPY_ACTIVE); 3061 if (ret < 0) { 3062 goto fail; 3063 } 3064 3065 ret = bdrv_inactivate_all(); 3066 if (ret < 0) { 3067 goto fail; 3068 } 3069 restart_block = true; 3070 3071 /* 3072 * Cause any non-postcopiable, but iterative devices to 3073 * send out their final data. 3074 */ 3075 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false); 3076 3077 /* 3078 * in Finish migrate and with the io-lock held everything should 3079 * be quiet, but we've potentially still got dirty pages and we 3080 * need to tell the destination to throw any pages it's already received 3081 * that are dirty 3082 */ 3083 if (migrate_postcopy_ram()) { 3084 ram_postcopy_send_discard_bitmap(ms); 3085 } 3086 3087 /* 3088 * send rest of state - note things that are doing postcopy 3089 * will notice we're in POSTCOPY_ACTIVE and not actually 3090 * wrap their state up here 3091 */ 3092 /* 0 max-postcopy-bandwidth means unlimited */ 3093 if (!bandwidth) { 3094 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX); 3095 } else { 3096 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO); 3097 } 3098 if (migrate_postcopy_ram()) { 3099 /* Ping just for debugging, helps line traces up */ 3100 qemu_savevm_send_ping(ms->to_dst_file, 2); 3101 } 3102 3103 /* 3104 * While loading the device state we may trigger page transfer 3105 * requests and the fd must be free to process those, and thus 3106 * the destination must read the whole device state off the fd before 3107 * it starts processing it. Unfortunately the ad-hoc migration format 3108 * doesn't allow the destination to know the size to read without fully 3109 * parsing it through each devices load-state code (especially the open 3110 * coded devices that use get/put). 3111 * So we wrap the device state up in a package with a length at the start; 3112 * to do this we use a qemu_buf to hold the whole of the device state. 3113 */ 3114 bioc = qio_channel_buffer_new(4096); 3115 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer"); 3116 fb = qemu_file_new_output(QIO_CHANNEL(bioc)); 3117 object_unref(OBJECT(bioc)); 3118 3119 /* 3120 * Make sure the receiver can get incoming pages before we send the rest 3121 * of the state 3122 */ 3123 qemu_savevm_send_postcopy_listen(fb); 3124 3125 qemu_savevm_state_complete_precopy(fb, false, false); 3126 if (migrate_postcopy_ram()) { 3127 qemu_savevm_send_ping(fb, 3); 3128 } 3129 3130 qemu_savevm_send_postcopy_run(fb); 3131 3132 /* <><> end of stuff going into the package */ 3133 3134 /* Last point of recovery; as soon as we send the package the destination 3135 * can open devices and potentially start running. 3136 * Lets just check again we've not got any errors. 3137 */ 3138 ret = qemu_file_get_error(ms->to_dst_file); 3139 if (ret) { 3140 error_report("postcopy_start: Migration stream errored (pre package)"); 3141 goto fail_closefb; 3142 } 3143 3144 restart_block = false; 3145 3146 /* Now send that blob */ 3147 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) { 3148 goto fail_closefb; 3149 } 3150 qemu_fclose(fb); 3151 3152 /* Send a notify to give a chance for anything that needs to happen 3153 * at the transition to postcopy and after the device state; in particular 3154 * spice needs to trigger a transition now 3155 */ 3156 ms->postcopy_after_devices = true; 3157 notifier_list_notify(&migration_state_notifiers, ms); 3158 3159 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop; 3160 3161 qemu_mutex_unlock_iothread(); 3162 3163 if (migrate_postcopy_ram()) { 3164 /* 3165 * Although this ping is just for debug, it could potentially be 3166 * used for getting a better measurement of downtime at the source. 3167 */ 3168 qemu_savevm_send_ping(ms->to_dst_file, 4); 3169 } 3170 3171 if (migrate_release_ram()) { 3172 ram_postcopy_migrated_memory_release(ms); 3173 } 3174 3175 ret = qemu_file_get_error(ms->to_dst_file); 3176 if (ret) { 3177 error_report("postcopy_start: Migration stream errored"); 3178 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE, 3179 MIGRATION_STATUS_FAILED); 3180 } 3181 3182 trace_postcopy_preempt_enabled(migrate_postcopy_preempt()); 3183 3184 return ret; 3185 3186 fail_closefb: 3187 qemu_fclose(fb); 3188 fail: 3189 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE, 3190 MIGRATION_STATUS_FAILED); 3191 if (restart_block) { 3192 /* A failure happened early enough that we know the destination hasn't 3193 * accessed block devices, so we're safe to recover. 3194 */ 3195 Error *local_err = NULL; 3196 3197 bdrv_activate_all(&local_err); 3198 if (local_err) { 3199 error_report_err(local_err); 3200 } 3201 } 3202 qemu_mutex_unlock_iothread(); 3203 return -1; 3204 } 3205 3206 /** 3207 * migration_maybe_pause: Pause if required to by 3208 * migrate_pause_before_switchover called with the iothread locked 3209 * Returns: 0 on success 3210 */ 3211 static int migration_maybe_pause(MigrationState *s, 3212 int *current_active_state, 3213 int new_state) 3214 { 3215 if (!migrate_pause_before_switchover()) { 3216 return 0; 3217 } 3218 3219 /* Since leaving this state is not atomic with posting the semaphore 3220 * it's possible that someone could have issued multiple migrate_continue 3221 * and the semaphore is incorrectly positive at this point; 3222 * the docs say it's undefined to reinit a semaphore that's already 3223 * init'd, so use timedwait to eat up any existing posts. 3224 */ 3225 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) { 3226 /* This block intentionally left blank */ 3227 } 3228 3229 /* 3230 * If the migration is cancelled when it is in the completion phase, 3231 * the migration state is set to MIGRATION_STATUS_CANCELLING. 3232 * So we don't need to wait a semaphore, otherwise we would always 3233 * wait for the 'pause_sem' semaphore. 3234 */ 3235 if (s->state != MIGRATION_STATUS_CANCELLING) { 3236 qemu_mutex_unlock_iothread(); 3237 migrate_set_state(&s->state, *current_active_state, 3238 MIGRATION_STATUS_PRE_SWITCHOVER); 3239 qemu_sem_wait(&s->pause_sem); 3240 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER, 3241 new_state); 3242 *current_active_state = new_state; 3243 qemu_mutex_lock_iothread(); 3244 } 3245 3246 return s->state == new_state ? 0 : -EINVAL; 3247 } 3248 3249 /** 3250 * migration_completion: Used by migration_thread when there's not much left. 3251 * The caller 'breaks' the loop when this returns. 3252 * 3253 * @s: Current migration state 3254 */ 3255 static void migration_completion(MigrationState *s) 3256 { 3257 int ret; 3258 int current_active_state = s->state; 3259 3260 if (s->state == MIGRATION_STATUS_ACTIVE) { 3261 qemu_mutex_lock_iothread(); 3262 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 3263 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL); 3264 s->vm_was_running = runstate_is_running(); 3265 ret = global_state_store(); 3266 3267 if (!ret) { 3268 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE); 3269 trace_migration_completion_vm_stop(ret); 3270 if (ret >= 0) { 3271 ret = migration_maybe_pause(s, ¤t_active_state, 3272 MIGRATION_STATUS_DEVICE); 3273 } 3274 if (ret >= 0) { 3275 s->block_inactive = !migrate_colo(); 3276 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX); 3277 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false, 3278 s->block_inactive); 3279 } 3280 } 3281 qemu_mutex_unlock_iothread(); 3282 3283 if (ret < 0) { 3284 goto fail; 3285 } 3286 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 3287 trace_migration_completion_postcopy_end(); 3288 3289 qemu_mutex_lock_iothread(); 3290 qemu_savevm_state_complete_postcopy(s->to_dst_file); 3291 qemu_mutex_unlock_iothread(); 3292 3293 /* 3294 * Shutdown the postcopy fast path thread. This is only needed 3295 * when dest QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need 3296 * this. 3297 */ 3298 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) { 3299 postcopy_preempt_shutdown_file(s); 3300 } 3301 3302 trace_migration_completion_postcopy_end_after_complete(); 3303 } else { 3304 goto fail; 3305 } 3306 3307 /* 3308 * If rp was opened we must clean up the thread before 3309 * cleaning everything else up (since if there are no failures 3310 * it will wait for the destination to send it's status in 3311 * a SHUT command). 3312 */ 3313 if (s->rp_state.rp_thread_created) { 3314 int rp_error; 3315 trace_migration_return_path_end_before(); 3316 rp_error = await_return_path_close_on_source(s); 3317 trace_migration_return_path_end_after(rp_error); 3318 if (rp_error) { 3319 goto fail_invalidate; 3320 } 3321 } 3322 3323 if (qemu_file_get_error(s->to_dst_file)) { 3324 trace_migration_completion_file_err(); 3325 goto fail_invalidate; 3326 } 3327 3328 if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) { 3329 /* COLO does not support postcopy */ 3330 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE, 3331 MIGRATION_STATUS_COLO); 3332 } else { 3333 migrate_set_state(&s->state, current_active_state, 3334 MIGRATION_STATUS_COMPLETED); 3335 } 3336 3337 return; 3338 3339 fail_invalidate: 3340 /* If not doing postcopy, vm_start() will be called: let's regain 3341 * control on images. 3342 */ 3343 if (s->state == MIGRATION_STATUS_ACTIVE || 3344 s->state == MIGRATION_STATUS_DEVICE) { 3345 Error *local_err = NULL; 3346 3347 qemu_mutex_lock_iothread(); 3348 bdrv_activate_all(&local_err); 3349 if (local_err) { 3350 error_report_err(local_err); 3351 s->block_inactive = true; 3352 } else { 3353 s->block_inactive = false; 3354 } 3355 qemu_mutex_unlock_iothread(); 3356 } 3357 3358 fail: 3359 migrate_set_state(&s->state, current_active_state, 3360 MIGRATION_STATUS_FAILED); 3361 } 3362 3363 /** 3364 * bg_migration_completion: Used by bg_migration_thread when after all the 3365 * RAM has been saved. The caller 'breaks' the loop when this returns. 3366 * 3367 * @s: Current migration state 3368 */ 3369 static void bg_migration_completion(MigrationState *s) 3370 { 3371 int current_active_state = s->state; 3372 3373 /* 3374 * Stop tracking RAM writes - un-protect memory, un-register UFFD 3375 * memory ranges, flush kernel wait queues and wake up threads 3376 * waiting for write fault to be resolved. 3377 */ 3378 ram_write_tracking_stop(); 3379 3380 if (s->state == MIGRATION_STATUS_ACTIVE) { 3381 /* 3382 * By this moment we have RAM content saved into the migration stream. 3383 * The next step is to flush the non-RAM content (device state) 3384 * right after the ram content. The device state has been stored into 3385 * the temporary buffer before RAM saving started. 3386 */ 3387 qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage); 3388 qemu_fflush(s->to_dst_file); 3389 } else if (s->state == MIGRATION_STATUS_CANCELLING) { 3390 goto fail; 3391 } 3392 3393 if (qemu_file_get_error(s->to_dst_file)) { 3394 trace_migration_completion_file_err(); 3395 goto fail; 3396 } 3397 3398 migrate_set_state(&s->state, current_active_state, 3399 MIGRATION_STATUS_COMPLETED); 3400 return; 3401 3402 fail: 3403 migrate_set_state(&s->state, current_active_state, 3404 MIGRATION_STATUS_FAILED); 3405 } 3406 3407 typedef enum MigThrError { 3408 /* No error detected */ 3409 MIG_THR_ERR_NONE = 0, 3410 /* Detected error, but resumed successfully */ 3411 MIG_THR_ERR_RECOVERED = 1, 3412 /* Detected fatal error, need to exit */ 3413 MIG_THR_ERR_FATAL = 2, 3414 } MigThrError; 3415 3416 static int postcopy_resume_handshake(MigrationState *s) 3417 { 3418 qemu_savevm_send_postcopy_resume(s->to_dst_file); 3419 3420 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) { 3421 qemu_sem_wait(&s->rp_state.rp_sem); 3422 } 3423 3424 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 3425 return 0; 3426 } 3427 3428 return -1; 3429 } 3430 3431 /* Return zero if success, or <0 for error */ 3432 static int postcopy_do_resume(MigrationState *s) 3433 { 3434 int ret; 3435 3436 /* 3437 * Call all the resume_prepare() hooks, so that modules can be 3438 * ready for the migration resume. 3439 */ 3440 ret = qemu_savevm_state_resume_prepare(s); 3441 if (ret) { 3442 error_report("%s: resume_prepare() failure detected: %d", 3443 __func__, ret); 3444 return ret; 3445 } 3446 3447 /* 3448 * If preempt is enabled, re-establish the preempt channel. Note that 3449 * we do it after resume prepare to make sure the main channel will be 3450 * created before the preempt channel. E.g. with weak network, the 3451 * dest QEMU may get messed up with the preempt and main channels on 3452 * the order of connection setup. This guarantees the correct order. 3453 */ 3454 ret = postcopy_preempt_establish_channel(s); 3455 if (ret) { 3456 error_report("%s: postcopy_preempt_establish_channel(): %d", 3457 __func__, ret); 3458 return ret; 3459 } 3460 3461 /* 3462 * Last handshake with destination on the resume (destination will 3463 * switch to postcopy-active afterwards) 3464 */ 3465 ret = postcopy_resume_handshake(s); 3466 if (ret) { 3467 error_report("%s: handshake failed: %d", __func__, ret); 3468 return ret; 3469 } 3470 3471 return 0; 3472 } 3473 3474 /* 3475 * We don't return until we are in a safe state to continue current 3476 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or 3477 * MIG_THR_ERR_FATAL if unrecovery failure happened. 3478 */ 3479 static MigThrError postcopy_pause(MigrationState *s) 3480 { 3481 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE); 3482 3483 while (true) { 3484 QEMUFile *file; 3485 3486 /* 3487 * Current channel is possibly broken. Release it. Note that this is 3488 * guaranteed even without lock because to_dst_file should only be 3489 * modified by the migration thread. That also guarantees that the 3490 * unregister of yank is safe too without the lock. It should be safe 3491 * even to be within the qemu_file_lock, but we didn't do that to avoid 3492 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make 3493 * the qemu_file_lock critical section as small as possible. 3494 */ 3495 assert(s->to_dst_file); 3496 migration_ioc_unregister_yank_from_file(s->to_dst_file); 3497 qemu_mutex_lock(&s->qemu_file_lock); 3498 file = s->to_dst_file; 3499 s->to_dst_file = NULL; 3500 qemu_mutex_unlock(&s->qemu_file_lock); 3501 3502 qemu_file_shutdown(file); 3503 qemu_fclose(file); 3504 3505 migrate_set_state(&s->state, s->state, 3506 MIGRATION_STATUS_POSTCOPY_PAUSED); 3507 3508 error_report("Detected IO failure for postcopy. " 3509 "Migration paused."); 3510 3511 /* 3512 * We wait until things fixed up. Then someone will setup the 3513 * status back for us. 3514 */ 3515 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) { 3516 qemu_sem_wait(&s->postcopy_pause_sem); 3517 } 3518 3519 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) { 3520 /* Woken up by a recover procedure. Give it a shot */ 3521 3522 /* 3523 * Firstly, let's wake up the return path now, with a new 3524 * return path channel. 3525 */ 3526 qemu_sem_post(&s->postcopy_pause_rp_sem); 3527 3528 /* Do the resume logic */ 3529 if (postcopy_do_resume(s) == 0) { 3530 /* Let's continue! */ 3531 trace_postcopy_pause_continued(); 3532 return MIG_THR_ERR_RECOVERED; 3533 } else { 3534 /* 3535 * Something wrong happened during the recovery, let's 3536 * pause again. Pause is always better than throwing 3537 * data away. 3538 */ 3539 continue; 3540 } 3541 } else { 3542 /* This is not right... Time to quit. */ 3543 return MIG_THR_ERR_FATAL; 3544 } 3545 } 3546 } 3547 3548 static MigThrError migration_detect_error(MigrationState *s) 3549 { 3550 int ret; 3551 int state = s->state; 3552 Error *local_error = NULL; 3553 3554 if (state == MIGRATION_STATUS_CANCELLING || 3555 state == MIGRATION_STATUS_CANCELLED) { 3556 /* End the migration, but don't set the state to failed */ 3557 return MIG_THR_ERR_FATAL; 3558 } 3559 3560 /* 3561 * Try to detect any file errors. Note that postcopy_qemufile_src will 3562 * be NULL when postcopy preempt is not enabled. 3563 */ 3564 ret = qemu_file_get_error_obj_any(s->to_dst_file, 3565 s->postcopy_qemufile_src, 3566 &local_error); 3567 if (!ret) { 3568 /* Everything is fine */ 3569 assert(!local_error); 3570 return MIG_THR_ERR_NONE; 3571 } 3572 3573 if (local_error) { 3574 migrate_set_error(s, local_error); 3575 error_free(local_error); 3576 } 3577 3578 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) { 3579 /* 3580 * For postcopy, we allow the network to be down for a 3581 * while. After that, it can be continued by a 3582 * recovery phase. 3583 */ 3584 return postcopy_pause(s); 3585 } else { 3586 /* 3587 * For precopy (or postcopy with error outside IO), we fail 3588 * with no time. 3589 */ 3590 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED); 3591 trace_migration_thread_file_err(); 3592 3593 /* Time to stop the migration, now. */ 3594 return MIG_THR_ERR_FATAL; 3595 } 3596 } 3597 3598 /* How many bytes have we transferred since the beginning of the migration */ 3599 static uint64_t migration_total_bytes(MigrationState *s) 3600 { 3601 return qemu_file_total_transferred(s->to_dst_file) + 3602 stat64_get(&ram_counters.multifd_bytes); 3603 } 3604 3605 static void migration_calculate_complete(MigrationState *s) 3606 { 3607 uint64_t bytes = migration_total_bytes(s); 3608 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 3609 int64_t transfer_time; 3610 3611 s->total_time = end_time - s->start_time; 3612 if (!s->downtime) { 3613 /* 3614 * It's still not set, so we are precopy migration. For 3615 * postcopy, downtime is calculated during postcopy_start(). 3616 */ 3617 s->downtime = end_time - s->downtime_start; 3618 } 3619 3620 transfer_time = s->total_time - s->setup_time; 3621 if (transfer_time) { 3622 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000; 3623 } 3624 } 3625 3626 static void update_iteration_initial_status(MigrationState *s) 3627 { 3628 /* 3629 * Update these three fields at the same time to avoid mismatch info lead 3630 * wrong speed calculation. 3631 */ 3632 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 3633 s->iteration_initial_bytes = migration_total_bytes(s); 3634 s->iteration_initial_pages = ram_get_total_transferred_pages(); 3635 } 3636 3637 static void migration_update_counters(MigrationState *s, 3638 int64_t current_time) 3639 { 3640 uint64_t transferred, transferred_pages, time_spent; 3641 uint64_t current_bytes; /* bytes transferred since the beginning */ 3642 double bandwidth; 3643 3644 if (current_time < s->iteration_start_time + BUFFER_DELAY) { 3645 return; 3646 } 3647 3648 current_bytes = migration_total_bytes(s); 3649 transferred = current_bytes - s->iteration_initial_bytes; 3650 time_spent = current_time - s->iteration_start_time; 3651 bandwidth = (double)transferred / time_spent; 3652 s->threshold_size = bandwidth * s->parameters.downtime_limit; 3653 3654 s->mbps = (((double) transferred * 8.0) / 3655 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0; 3656 3657 transferred_pages = ram_get_total_transferred_pages() - 3658 s->iteration_initial_pages; 3659 s->pages_per_second = (double) transferred_pages / 3660 (((double) time_spent / 1000.0)); 3661 3662 /* 3663 * if we haven't sent anything, we don't want to 3664 * recalculate. 10000 is a small enough number for our purposes 3665 */ 3666 if (ram_counters.dirty_pages_rate && transferred > 10000) { 3667 s->expected_downtime = ram_counters.remaining / bandwidth; 3668 } 3669 3670 qemu_file_reset_rate_limit(s->to_dst_file); 3671 3672 update_iteration_initial_status(s); 3673 3674 trace_migrate_transferred(transferred, time_spent, 3675 bandwidth, s->threshold_size); 3676 } 3677 3678 /* Migration thread iteration status */ 3679 typedef enum { 3680 MIG_ITERATE_RESUME, /* Resume current iteration */ 3681 MIG_ITERATE_SKIP, /* Skip current iteration */ 3682 MIG_ITERATE_BREAK, /* Break the loop */ 3683 } MigIterateState; 3684 3685 /* 3686 * Return true if continue to the next iteration directly, false 3687 * otherwise. 3688 */ 3689 static MigIterateState migration_iteration_run(MigrationState *s) 3690 { 3691 uint64_t must_precopy, can_postcopy; 3692 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE; 3693 3694 qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy); 3695 uint64_t pending_size = must_precopy + can_postcopy; 3696 3697 trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy); 3698 3699 if (must_precopy <= s->threshold_size) { 3700 qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy); 3701 pending_size = must_precopy + can_postcopy; 3702 trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy); 3703 } 3704 3705 if (!pending_size || pending_size < s->threshold_size) { 3706 trace_migration_thread_low_pending(pending_size); 3707 migration_completion(s); 3708 return MIG_ITERATE_BREAK; 3709 } 3710 3711 /* Still a significant amount to transfer */ 3712 if (!in_postcopy && must_precopy <= s->threshold_size && 3713 qatomic_read(&s->start_postcopy)) { 3714 if (postcopy_start(s)) { 3715 error_report("%s: postcopy failed to start", __func__); 3716 } 3717 return MIG_ITERATE_SKIP; 3718 } 3719 3720 /* Just another iteration step */ 3721 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy); 3722 return MIG_ITERATE_RESUME; 3723 } 3724 3725 static void migration_iteration_finish(MigrationState *s) 3726 { 3727 /* If we enabled cpu throttling for auto-converge, turn it off. */ 3728 cpu_throttle_stop(); 3729 3730 qemu_mutex_lock_iothread(); 3731 switch (s->state) { 3732 case MIGRATION_STATUS_COMPLETED: 3733 migration_calculate_complete(s); 3734 runstate_set(RUN_STATE_POSTMIGRATE); 3735 break; 3736 case MIGRATION_STATUS_COLO: 3737 if (!migrate_colo()) { 3738 error_report("%s: critical error: calling COLO code without " 3739 "COLO enabled", __func__); 3740 } 3741 migrate_start_colo_process(s); 3742 s->vm_was_running = true; 3743 /* Fallthrough */ 3744 case MIGRATION_STATUS_FAILED: 3745 case MIGRATION_STATUS_CANCELLED: 3746 case MIGRATION_STATUS_CANCELLING: 3747 if (s->vm_was_running) { 3748 if (!runstate_check(RUN_STATE_SHUTDOWN)) { 3749 vm_start(); 3750 } 3751 } else { 3752 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) { 3753 runstate_set(RUN_STATE_POSTMIGRATE); 3754 } 3755 } 3756 break; 3757 3758 default: 3759 /* Should not reach here, but if so, forgive the VM. */ 3760 error_report("%s: Unknown ending state %d", __func__, s->state); 3761 break; 3762 } 3763 migrate_fd_cleanup_schedule(s); 3764 qemu_mutex_unlock_iothread(); 3765 } 3766 3767 static void bg_migration_iteration_finish(MigrationState *s) 3768 { 3769 qemu_mutex_lock_iothread(); 3770 switch (s->state) { 3771 case MIGRATION_STATUS_COMPLETED: 3772 migration_calculate_complete(s); 3773 break; 3774 3775 case MIGRATION_STATUS_ACTIVE: 3776 case MIGRATION_STATUS_FAILED: 3777 case MIGRATION_STATUS_CANCELLED: 3778 case MIGRATION_STATUS_CANCELLING: 3779 break; 3780 3781 default: 3782 /* Should not reach here, but if so, forgive the VM. */ 3783 error_report("%s: Unknown ending state %d", __func__, s->state); 3784 break; 3785 } 3786 3787 migrate_fd_cleanup_schedule(s); 3788 qemu_mutex_unlock_iothread(); 3789 } 3790 3791 /* 3792 * Return true if continue to the next iteration directly, false 3793 * otherwise. 3794 */ 3795 static MigIterateState bg_migration_iteration_run(MigrationState *s) 3796 { 3797 int res; 3798 3799 res = qemu_savevm_state_iterate(s->to_dst_file, false); 3800 if (res > 0) { 3801 bg_migration_completion(s); 3802 return MIG_ITERATE_BREAK; 3803 } 3804 3805 return MIG_ITERATE_RESUME; 3806 } 3807 3808 void migration_make_urgent_request(void) 3809 { 3810 qemu_sem_post(&migrate_get_current()->rate_limit_sem); 3811 } 3812 3813 void migration_consume_urgent_request(void) 3814 { 3815 qemu_sem_wait(&migrate_get_current()->rate_limit_sem); 3816 } 3817 3818 /* Returns true if the rate limiting was broken by an urgent request */ 3819 bool migration_rate_limit(void) 3820 { 3821 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 3822 MigrationState *s = migrate_get_current(); 3823 3824 bool urgent = false; 3825 migration_update_counters(s, now); 3826 if (qemu_file_rate_limit(s->to_dst_file)) { 3827 3828 if (qemu_file_get_error(s->to_dst_file)) { 3829 return false; 3830 } 3831 /* 3832 * Wait for a delay to do rate limiting OR 3833 * something urgent to post the semaphore. 3834 */ 3835 int ms = s->iteration_start_time + BUFFER_DELAY - now; 3836 trace_migration_rate_limit_pre(ms); 3837 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) { 3838 /* 3839 * We were woken by one or more urgent things but 3840 * the timedwait will have consumed one of them. 3841 * The service routine for the urgent wake will dec 3842 * the semaphore itself for each item it consumes, 3843 * so add this one we just eat back. 3844 */ 3845 qemu_sem_post(&s->rate_limit_sem); 3846 urgent = true; 3847 } 3848 trace_migration_rate_limit_post(urgent); 3849 } 3850 return urgent; 3851 } 3852 3853 /* 3854 * if failover devices are present, wait they are completely 3855 * unplugged 3856 */ 3857 3858 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state, 3859 int new_state) 3860 { 3861 if (qemu_savevm_state_guest_unplug_pending()) { 3862 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG); 3863 3864 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG && 3865 qemu_savevm_state_guest_unplug_pending()) { 3866 qemu_sem_timedwait(&s->wait_unplug_sem, 250); 3867 } 3868 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) { 3869 int timeout = 120; /* 30 seconds */ 3870 /* 3871 * migration has been canceled 3872 * but as we have started an unplug we must wait the end 3873 * to be able to plug back the card 3874 */ 3875 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) { 3876 qemu_sem_timedwait(&s->wait_unplug_sem, 250); 3877 } 3878 if (qemu_savevm_state_guest_unplug_pending() && 3879 !qtest_enabled()) { 3880 warn_report("migration: partially unplugged device on " 3881 "failure"); 3882 } 3883 } 3884 3885 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state); 3886 } else { 3887 migrate_set_state(&s->state, old_state, new_state); 3888 } 3889 } 3890 3891 /* 3892 * Master migration thread on the source VM. 3893 * It drives the migration and pumps the data down the outgoing channel. 3894 */ 3895 static void *migration_thread(void *opaque) 3896 { 3897 MigrationState *s = opaque; 3898 MigrationThread *thread = NULL; 3899 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST); 3900 MigThrError thr_error; 3901 bool urgent = false; 3902 3903 thread = MigrationThreadAdd("live_migration", qemu_get_thread_id()); 3904 3905 rcu_register_thread(); 3906 3907 object_ref(OBJECT(s)); 3908 update_iteration_initial_status(s); 3909 3910 qemu_savevm_state_header(s->to_dst_file); 3911 3912 /* 3913 * If we opened the return path, we need to make sure dst has it 3914 * opened as well. 3915 */ 3916 if (s->rp_state.rp_thread_created) { 3917 /* Now tell the dest that it should open its end so it can reply */ 3918 qemu_savevm_send_open_return_path(s->to_dst_file); 3919 3920 /* And do a ping that will make stuff easier to debug */ 3921 qemu_savevm_send_ping(s->to_dst_file, 1); 3922 } 3923 3924 if (migrate_postcopy()) { 3925 /* 3926 * Tell the destination that we *might* want to do postcopy later; 3927 * if the other end can't do postcopy it should fail now, nice and 3928 * early. 3929 */ 3930 qemu_savevm_send_postcopy_advise(s->to_dst_file); 3931 } 3932 3933 if (migrate_colo()) { 3934 /* Notify migration destination that we enable COLO */ 3935 qemu_savevm_send_colo_enable(s->to_dst_file); 3936 } 3937 3938 qemu_savevm_state_setup(s->to_dst_file); 3939 3940 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP, 3941 MIGRATION_STATUS_ACTIVE); 3942 3943 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start; 3944 3945 trace_migration_thread_setup_complete(); 3946 3947 while (migration_is_active(s)) { 3948 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) { 3949 MigIterateState iter_state = migration_iteration_run(s); 3950 if (iter_state == MIG_ITERATE_SKIP) { 3951 continue; 3952 } else if (iter_state == MIG_ITERATE_BREAK) { 3953 break; 3954 } 3955 } 3956 3957 /* 3958 * Try to detect any kind of failures, and see whether we 3959 * should stop the migration now. 3960 */ 3961 thr_error = migration_detect_error(s); 3962 if (thr_error == MIG_THR_ERR_FATAL) { 3963 /* Stop migration */ 3964 break; 3965 } else if (thr_error == MIG_THR_ERR_RECOVERED) { 3966 /* 3967 * Just recovered from a e.g. network failure, reset all 3968 * the local variables. This is important to avoid 3969 * breaking transferred_bytes and bandwidth calculation 3970 */ 3971 update_iteration_initial_status(s); 3972 } 3973 3974 urgent = migration_rate_limit(); 3975 } 3976 3977 trace_migration_thread_after_loop(); 3978 migration_iteration_finish(s); 3979 object_unref(OBJECT(s)); 3980 rcu_unregister_thread(); 3981 MigrationThreadDel(thread); 3982 return NULL; 3983 } 3984 3985 static void bg_migration_vm_start_bh(void *opaque) 3986 { 3987 MigrationState *s = opaque; 3988 3989 qemu_bh_delete(s->vm_start_bh); 3990 s->vm_start_bh = NULL; 3991 3992 vm_start(); 3993 s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start; 3994 } 3995 3996 /** 3997 * Background snapshot thread, based on live migration code. 3998 * This is an alternative implementation of live migration mechanism 3999 * introduced specifically to support background snapshots. 4000 * 4001 * It takes advantage of userfault_fd write protection mechanism introduced 4002 * in v5.7 kernel. Compared to existing dirty page logging migration much 4003 * lesser stream traffic is produced resulting in smaller snapshot images, 4004 * simply cause of no page duplicates can get into the stream. 4005 * 4006 * Another key point is that generated vmstate stream reflects machine state 4007 * 'frozen' at the beginning of snapshot creation compared to dirty page logging 4008 * mechanism, which effectively results in that saved snapshot is the state of VM 4009 * at the end of the process. 4010 */ 4011 static void *bg_migration_thread(void *opaque) 4012 { 4013 MigrationState *s = opaque; 4014 int64_t setup_start; 4015 MigThrError thr_error; 4016 QEMUFile *fb; 4017 bool early_fail = true; 4018 4019 rcu_register_thread(); 4020 object_ref(OBJECT(s)); 4021 4022 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX); 4023 4024 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST); 4025 /* 4026 * We want to save vmstate for the moment when migration has been 4027 * initiated but also we want to save RAM content while VM is running. 4028 * The RAM content should appear first in the vmstate. So, we first 4029 * stash the non-RAM part of the vmstate to the temporary buffer, 4030 * then write RAM part of the vmstate to the migration stream 4031 * with vCPUs running and, finally, write stashed non-RAM part of 4032 * the vmstate from the buffer to the migration stream. 4033 */ 4034 s->bioc = qio_channel_buffer_new(512 * 1024); 4035 qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer"); 4036 fb = qemu_file_new_output(QIO_CHANNEL(s->bioc)); 4037 object_unref(OBJECT(s->bioc)); 4038 4039 update_iteration_initial_status(s); 4040 4041 /* 4042 * Prepare for tracking memory writes with UFFD-WP - populate 4043 * RAM pages before protecting. 4044 */ 4045 #ifdef __linux__ 4046 ram_write_tracking_prepare(); 4047 #endif 4048 4049 qemu_savevm_state_header(s->to_dst_file); 4050 qemu_savevm_state_setup(s->to_dst_file); 4051 4052 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP, 4053 MIGRATION_STATUS_ACTIVE); 4054 4055 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start; 4056 4057 trace_migration_thread_setup_complete(); 4058 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 4059 4060 qemu_mutex_lock_iothread(); 4061 4062 /* 4063 * If VM is currently in suspended state, then, to make a valid runstate 4064 * transition in vm_stop_force_state() we need to wakeup it up. 4065 */ 4066 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL); 4067 s->vm_was_running = runstate_is_running(); 4068 4069 if (global_state_store()) { 4070 goto fail; 4071 } 4072 /* Forcibly stop VM before saving state of vCPUs and devices */ 4073 if (vm_stop_force_state(RUN_STATE_PAUSED)) { 4074 goto fail; 4075 } 4076 /* 4077 * Put vCPUs in sync with shadow context structures, then 4078 * save their state to channel-buffer along with devices. 4079 */ 4080 cpu_synchronize_all_states(); 4081 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) { 4082 goto fail; 4083 } 4084 /* 4085 * Since we are going to get non-iterable state data directly 4086 * from s->bioc->data, explicit flush is needed here. 4087 */ 4088 qemu_fflush(fb); 4089 4090 /* Now initialize UFFD context and start tracking RAM writes */ 4091 if (ram_write_tracking_start()) { 4092 goto fail; 4093 } 4094 early_fail = false; 4095 4096 /* 4097 * Start VM from BH handler to avoid write-fault lock here. 4098 * UFFD-WP protection for the whole RAM is already enabled so 4099 * calling VM state change notifiers from vm_start() would initiate 4100 * writes to virtio VQs memory which is in write-protected region. 4101 */ 4102 s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s); 4103 qemu_bh_schedule(s->vm_start_bh); 4104 4105 qemu_mutex_unlock_iothread(); 4106 4107 while (migration_is_active(s)) { 4108 MigIterateState iter_state = bg_migration_iteration_run(s); 4109 if (iter_state == MIG_ITERATE_SKIP) { 4110 continue; 4111 } else if (iter_state == MIG_ITERATE_BREAK) { 4112 break; 4113 } 4114 4115 /* 4116 * Try to detect any kind of failures, and see whether we 4117 * should stop the migration now. 4118 */ 4119 thr_error = migration_detect_error(s); 4120 if (thr_error == MIG_THR_ERR_FATAL) { 4121 /* Stop migration */ 4122 break; 4123 } 4124 4125 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME)); 4126 } 4127 4128 trace_migration_thread_after_loop(); 4129 4130 fail: 4131 if (early_fail) { 4132 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE, 4133 MIGRATION_STATUS_FAILED); 4134 qemu_mutex_unlock_iothread(); 4135 } 4136 4137 bg_migration_iteration_finish(s); 4138 4139 qemu_fclose(fb); 4140 object_unref(OBJECT(s)); 4141 rcu_unregister_thread(); 4142 4143 return NULL; 4144 } 4145 4146 void migrate_fd_connect(MigrationState *s, Error *error_in) 4147 { 4148 Error *local_err = NULL; 4149 int64_t rate_limit; 4150 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED; 4151 4152 /* 4153 * If there's a previous error, free it and prepare for another one. 4154 * Meanwhile if migration completes successfully, there won't have an error 4155 * dumped when calling migrate_fd_cleanup(). 4156 */ 4157 migrate_error_free(s); 4158 4159 s->expected_downtime = s->parameters.downtime_limit; 4160 if (resume) { 4161 assert(s->cleanup_bh); 4162 } else { 4163 assert(!s->cleanup_bh); 4164 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s); 4165 } 4166 if (error_in) { 4167 migrate_fd_error(s, error_in); 4168 if (resume) { 4169 /* 4170 * Don't do cleanup for resume if channel is invalid, but only dump 4171 * the error. We wait for another channel connect from the user. 4172 * The error_report still gives HMP user a hint on what failed. 4173 * It's normally done in migrate_fd_cleanup(), but call it here 4174 * explicitly. 4175 */ 4176 error_report_err(error_copy(s->error)); 4177 } else { 4178 migrate_fd_cleanup(s); 4179 } 4180 return; 4181 } 4182 4183 if (resume) { 4184 /* This is a resumed migration */ 4185 rate_limit = s->parameters.max_postcopy_bandwidth / 4186 XFER_LIMIT_RATIO; 4187 } else { 4188 /* This is a fresh new migration */ 4189 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO; 4190 4191 /* Notify before starting migration thread */ 4192 notifier_list_notify(&migration_state_notifiers, s); 4193 } 4194 4195 qemu_file_set_rate_limit(s->to_dst_file, rate_limit); 4196 qemu_file_set_blocking(s->to_dst_file, true); 4197 4198 /* 4199 * Open the return path. For postcopy, it is used exclusively. For 4200 * precopy, only if user specified "return-path" capability would 4201 * QEMU uses the return path. 4202 */ 4203 if (migrate_postcopy_ram() || migrate_use_return_path()) { 4204 if (open_return_path_on_source(s, !resume)) { 4205 error_report("Unable to open return-path for postcopy"); 4206 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED); 4207 migrate_fd_cleanup(s); 4208 return; 4209 } 4210 } 4211 4212 /* 4213 * This needs to be done before resuming a postcopy. Note: for newer 4214 * QEMUs we will delay the channel creation until postcopy_start(), to 4215 * avoid disorder of channel creations. 4216 */ 4217 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) { 4218 postcopy_preempt_setup(s); 4219 } 4220 4221 if (resume) { 4222 /* Wakeup the main migration thread to do the recovery */ 4223 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED, 4224 MIGRATION_STATUS_POSTCOPY_RECOVER); 4225 qemu_sem_post(&s->postcopy_pause_sem); 4226 return; 4227 } 4228 4229 if (multifd_save_setup(&local_err) != 0) { 4230 error_report_err(local_err); 4231 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 4232 MIGRATION_STATUS_FAILED); 4233 migrate_fd_cleanup(s); 4234 return; 4235 } 4236 4237 if (migrate_background_snapshot()) { 4238 qemu_thread_create(&s->thread, "bg_snapshot", 4239 bg_migration_thread, s, QEMU_THREAD_JOINABLE); 4240 } else { 4241 qemu_thread_create(&s->thread, "live_migration", 4242 migration_thread, s, QEMU_THREAD_JOINABLE); 4243 } 4244 s->migration_thread_running = true; 4245 } 4246 4247 #define DEFINE_PROP_MIG_CAP(name, x) \ 4248 DEFINE_PROP_BOOL(name, MigrationState, capabilities[x], false) 4249 4250 static Property migration_properties[] = { 4251 DEFINE_PROP_BOOL("store-global-state", MigrationState, 4252 store_global_state, true), 4253 DEFINE_PROP_BOOL("send-configuration", MigrationState, 4254 send_configuration, true), 4255 DEFINE_PROP_BOOL("send-section-footer", MigrationState, 4256 send_section_footer, true), 4257 DEFINE_PROP_BOOL("decompress-error-check", MigrationState, 4258 decompress_error_check, true), 4259 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState, 4260 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT), 4261 DEFINE_PROP_BOOL("x-preempt-pre-7-2", MigrationState, 4262 preempt_pre_7_2, false), 4263 4264 /* Migration parameters */ 4265 DEFINE_PROP_UINT8("x-compress-level", MigrationState, 4266 parameters.compress_level, 4267 DEFAULT_MIGRATE_COMPRESS_LEVEL), 4268 DEFINE_PROP_UINT8("x-compress-threads", MigrationState, 4269 parameters.compress_threads, 4270 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT), 4271 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState, 4272 parameters.compress_wait_thread, true), 4273 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState, 4274 parameters.decompress_threads, 4275 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT), 4276 DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState, 4277 parameters.throttle_trigger_threshold, 4278 DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD), 4279 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState, 4280 parameters.cpu_throttle_initial, 4281 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL), 4282 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState, 4283 parameters.cpu_throttle_increment, 4284 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT), 4285 DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState, 4286 parameters.cpu_throttle_tailslow, false), 4287 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState, 4288 parameters.max_bandwidth, MAX_THROTTLE), 4289 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState, 4290 parameters.downtime_limit, 4291 DEFAULT_MIGRATE_SET_DOWNTIME), 4292 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState, 4293 parameters.x_checkpoint_delay, 4294 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY), 4295 DEFINE_PROP_UINT8("multifd-channels", MigrationState, 4296 parameters.multifd_channels, 4297 DEFAULT_MIGRATE_MULTIFD_CHANNELS), 4298 DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState, 4299 parameters.multifd_compression, 4300 DEFAULT_MIGRATE_MULTIFD_COMPRESSION), 4301 DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState, 4302 parameters.multifd_zlib_level, 4303 DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL), 4304 DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState, 4305 parameters.multifd_zstd_level, 4306 DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL), 4307 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState, 4308 parameters.xbzrle_cache_size, 4309 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE), 4310 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState, 4311 parameters.max_postcopy_bandwidth, 4312 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH), 4313 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState, 4314 parameters.max_cpu_throttle, 4315 DEFAULT_MIGRATE_MAX_CPU_THROTTLE), 4316 DEFINE_PROP_SIZE("announce-initial", MigrationState, 4317 parameters.announce_initial, 4318 DEFAULT_MIGRATE_ANNOUNCE_INITIAL), 4319 DEFINE_PROP_SIZE("announce-max", MigrationState, 4320 parameters.announce_max, 4321 DEFAULT_MIGRATE_ANNOUNCE_MAX), 4322 DEFINE_PROP_SIZE("announce-rounds", MigrationState, 4323 parameters.announce_rounds, 4324 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS), 4325 DEFINE_PROP_SIZE("announce-step", MigrationState, 4326 parameters.announce_step, 4327 DEFAULT_MIGRATE_ANNOUNCE_STEP), 4328 DEFINE_PROP_STRING("tls-creds", MigrationState, parameters.tls_creds), 4329 DEFINE_PROP_STRING("tls-hostname", MigrationState, parameters.tls_hostname), 4330 DEFINE_PROP_STRING("tls-authz", MigrationState, parameters.tls_authz), 4331 4332 /* Migration capabilities */ 4333 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE), 4334 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL), 4335 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE), 4336 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS), 4337 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS), 4338 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS), 4339 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM), 4340 DEFINE_PROP_MIG_CAP("x-postcopy-preempt", 4341 MIGRATION_CAPABILITY_POSTCOPY_PREEMPT), 4342 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO), 4343 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM), 4344 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK), 4345 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH), 4346 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD), 4347 DEFINE_PROP_MIG_CAP("x-background-snapshot", 4348 MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT), 4349 #ifdef CONFIG_LINUX 4350 DEFINE_PROP_MIG_CAP("x-zero-copy-send", 4351 MIGRATION_CAPABILITY_ZERO_COPY_SEND), 4352 #endif 4353 4354 DEFINE_PROP_END_OF_LIST(), 4355 }; 4356 4357 static void migration_class_init(ObjectClass *klass, void *data) 4358 { 4359 DeviceClass *dc = DEVICE_CLASS(klass); 4360 4361 dc->user_creatable = false; 4362 device_class_set_props(dc, migration_properties); 4363 } 4364 4365 static void migration_instance_finalize(Object *obj) 4366 { 4367 MigrationState *ms = MIGRATION_OBJ(obj); 4368 4369 qemu_mutex_destroy(&ms->error_mutex); 4370 qemu_mutex_destroy(&ms->qemu_file_lock); 4371 qemu_sem_destroy(&ms->wait_unplug_sem); 4372 qemu_sem_destroy(&ms->rate_limit_sem); 4373 qemu_sem_destroy(&ms->pause_sem); 4374 qemu_sem_destroy(&ms->postcopy_pause_sem); 4375 qemu_sem_destroy(&ms->postcopy_pause_rp_sem); 4376 qemu_sem_destroy(&ms->rp_state.rp_sem); 4377 qemu_sem_destroy(&ms->rp_state.rp_pong_acks); 4378 qemu_sem_destroy(&ms->postcopy_qemufile_src_sem); 4379 error_free(ms->error); 4380 } 4381 4382 static void migration_instance_init(Object *obj) 4383 { 4384 MigrationState *ms = MIGRATION_OBJ(obj); 4385 MigrationParameters *params = &ms->parameters; 4386 4387 ms->state = MIGRATION_STATUS_NONE; 4388 ms->mbps = -1; 4389 ms->pages_per_second = -1; 4390 qemu_sem_init(&ms->pause_sem, 0); 4391 qemu_mutex_init(&ms->error_mutex); 4392 4393 params->tls_hostname = g_strdup(""); 4394 params->tls_creds = g_strdup(""); 4395 4396 /* Set has_* up only for parameter checks */ 4397 params->has_compress_level = true; 4398 params->has_compress_threads = true; 4399 params->has_compress_wait_thread = true; 4400 params->has_decompress_threads = true; 4401 params->has_throttle_trigger_threshold = true; 4402 params->has_cpu_throttle_initial = true; 4403 params->has_cpu_throttle_increment = true; 4404 params->has_cpu_throttle_tailslow = true; 4405 params->has_max_bandwidth = true; 4406 params->has_downtime_limit = true; 4407 params->has_x_checkpoint_delay = true; 4408 params->has_block_incremental = true; 4409 params->has_multifd_channels = true; 4410 params->has_multifd_compression = true; 4411 params->has_multifd_zlib_level = true; 4412 params->has_multifd_zstd_level = true; 4413 params->has_xbzrle_cache_size = true; 4414 params->has_max_postcopy_bandwidth = true; 4415 params->has_max_cpu_throttle = true; 4416 params->has_announce_initial = true; 4417 params->has_announce_max = true; 4418 params->has_announce_rounds = true; 4419 params->has_announce_step = true; 4420 4421 qemu_sem_init(&ms->postcopy_pause_sem, 0); 4422 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0); 4423 qemu_sem_init(&ms->rp_state.rp_sem, 0); 4424 qemu_sem_init(&ms->rp_state.rp_pong_acks, 0); 4425 qemu_sem_init(&ms->rate_limit_sem, 0); 4426 qemu_sem_init(&ms->wait_unplug_sem, 0); 4427 qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0); 4428 qemu_mutex_init(&ms->qemu_file_lock); 4429 } 4430 4431 /* 4432 * Return true if check pass, false otherwise. Error will be put 4433 * inside errp if provided. 4434 */ 4435 static bool migration_object_check(MigrationState *ms, Error **errp) 4436 { 4437 /* Assuming all off */ 4438 bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 }; 4439 4440 if (!migrate_params_check(&ms->parameters, errp)) { 4441 return false; 4442 } 4443 4444 return migrate_caps_check(old_caps, ms->capabilities, errp); 4445 } 4446 4447 static const TypeInfo migration_type = { 4448 .name = TYPE_MIGRATION, 4449 /* 4450 * NOTE: TYPE_MIGRATION is not really a device, as the object is 4451 * not created using qdev_new(), it is not attached to the qdev 4452 * device tree, and it is never realized. 4453 * 4454 * TODO: Make this TYPE_OBJECT once QOM provides something like 4455 * TYPE_DEVICE's "-global" properties. 4456 */ 4457 .parent = TYPE_DEVICE, 4458 .class_init = migration_class_init, 4459 .class_size = sizeof(MigrationClass), 4460 .instance_size = sizeof(MigrationState), 4461 .instance_init = migration_instance_init, 4462 .instance_finalize = migration_instance_finalize, 4463 }; 4464 4465 static void register_migration_types(void) 4466 { 4467 type_register_static(&migration_type); 4468 } 4469 4470 type_init(register_migration_types); 4471