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