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 "migration/blocker.h" 20 #include "exec.h" 21 #include "fd.h" 22 #include "socket.h" 23 #include "rdma.h" 24 #include "ram.h" 25 #include "migration/global_state.h" 26 #include "migration/misc.h" 27 #include "migration.h" 28 #include "savevm.h" 29 #include "qemu-file-channel.h" 30 #include "qemu-file.h" 31 #include "migration/vmstate.h" 32 #include "block/block.h" 33 #include "qapi/error.h" 34 #include "qapi/qapi-commands-migration.h" 35 #include "qapi/qapi-events-migration.h" 36 #include "qapi/qmp/qerror.h" 37 #include "qapi/qmp/qnull.h" 38 #include "qemu/rcu.h" 39 #include "block.h" 40 #include "postcopy-ram.h" 41 #include "qemu/thread.h" 42 #include "trace.h" 43 #include "exec/target_page.h" 44 #include "io/channel-buffer.h" 45 #include "migration/colo.h" 46 #include "hw/boards.h" 47 #include "monitor/monitor.h" 48 49 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */ 50 51 /* Amount of time to allocate to each "chunk" of bandwidth-throttled 52 * data. */ 53 #define BUFFER_DELAY 100 54 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY) 55 56 /* Time in milliseconds we are allowed to stop the source, 57 * for sending the last part */ 58 #define DEFAULT_MIGRATE_SET_DOWNTIME 300 59 60 /* Maximum migrate downtime set to 2000 seconds */ 61 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000 62 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000) 63 64 /* Default compression thread count */ 65 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8 66 /* Default decompression thread count, usually decompression is at 67 * least 4 times as fast as compression.*/ 68 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2 69 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */ 70 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1 71 /* Define default autoconverge cpu throttle migration parameters */ 72 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20 73 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10 74 75 /* Migration XBZRLE default cache size */ 76 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024) 77 78 /* The delay time (in ms) between two COLO checkpoints 79 * Note: Please change this default value to 10000 when we support hybrid mode. 80 */ 81 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200 82 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2 83 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16 84 85 static NotifierList migration_state_notifiers = 86 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers); 87 88 static bool deferred_incoming; 89 90 /* Messages sent on the return path from destination to source */ 91 enum mig_rp_message_type { 92 MIG_RP_MSG_INVALID = 0, /* Must be 0 */ 93 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */ 94 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */ 95 96 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */ 97 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */ 98 99 MIG_RP_MSG_MAX 100 }; 101 102 /* When we add fault tolerance, we could have several 103 migrations at once. For now we don't need to add 104 dynamic creation of migration */ 105 106 static MigrationState *current_migration; 107 108 static bool migration_object_check(MigrationState *ms, Error **errp); 109 static int migration_maybe_pause(MigrationState *s, 110 int *current_active_state, 111 int new_state); 112 113 void migration_object_init(void) 114 { 115 MachineState *ms = MACHINE(qdev_get_machine()); 116 Error *err = NULL; 117 118 /* This can only be called once. */ 119 assert(!current_migration); 120 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION)); 121 122 if (!migration_object_check(current_migration, &err)) { 123 error_report_err(err); 124 exit(1); 125 } 126 127 /* 128 * We cannot really do this in migration_instance_init() since at 129 * that time global properties are not yet applied, then this 130 * value will be definitely replaced by something else. 131 */ 132 if (ms->enforce_config_section) { 133 current_migration->send_configuration = true; 134 } 135 } 136 137 void migration_object_finalize(void) 138 { 139 object_unref(OBJECT(current_migration)); 140 } 141 142 /* For outgoing */ 143 MigrationState *migrate_get_current(void) 144 { 145 /* This can only be called after the object created. */ 146 assert(current_migration); 147 return current_migration; 148 } 149 150 MigrationIncomingState *migration_incoming_get_current(void) 151 { 152 static bool once; 153 static MigrationIncomingState mis_current; 154 155 if (!once) { 156 mis_current.state = MIGRATION_STATUS_NONE; 157 memset(&mis_current, 0, sizeof(MigrationIncomingState)); 158 mis_current.postcopy_remote_fds = g_array_new(FALSE, TRUE, 159 sizeof(struct PostCopyFD)); 160 qemu_mutex_init(&mis_current.rp_mutex); 161 qemu_event_init(&mis_current.main_thread_load_event, false); 162 163 init_dirty_bitmap_incoming_migration(); 164 165 once = true; 166 } 167 return &mis_current; 168 } 169 170 void migration_incoming_state_destroy(void) 171 { 172 struct MigrationIncomingState *mis = migration_incoming_get_current(); 173 174 if (mis->to_src_file) { 175 /* Tell source that we are done */ 176 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0); 177 qemu_fclose(mis->to_src_file); 178 mis->to_src_file = NULL; 179 } 180 181 if (mis->from_src_file) { 182 qemu_fclose(mis->from_src_file); 183 mis->from_src_file = NULL; 184 } 185 if (mis->postcopy_remote_fds) { 186 g_array_free(mis->postcopy_remote_fds, TRUE); 187 mis->postcopy_remote_fds = NULL; 188 } 189 190 qemu_event_reset(&mis->main_thread_load_event); 191 } 192 193 static void migrate_generate_event(int new_state) 194 { 195 if (migrate_use_events()) { 196 qapi_event_send_migration(new_state, &error_abort); 197 } 198 } 199 200 /* 201 * Called on -incoming with a defer: uri. 202 * The migration can be started later after any parameters have been 203 * changed. 204 */ 205 static void deferred_incoming_migration(Error **errp) 206 { 207 if (deferred_incoming) { 208 error_setg(errp, "Incoming migration already deferred"); 209 } 210 deferred_incoming = true; 211 } 212 213 /* 214 * Send a message on the return channel back to the source 215 * of the migration. 216 */ 217 static int migrate_send_rp_message(MigrationIncomingState *mis, 218 enum mig_rp_message_type message_type, 219 uint16_t len, void *data) 220 { 221 int ret = 0; 222 223 trace_migrate_send_rp_message((int)message_type, len); 224 qemu_mutex_lock(&mis->rp_mutex); 225 226 /* 227 * It's possible that the file handle got lost due to network 228 * failures. 229 */ 230 if (!mis->to_src_file) { 231 ret = -EIO; 232 goto error; 233 } 234 235 qemu_put_be16(mis->to_src_file, (unsigned int)message_type); 236 qemu_put_be16(mis->to_src_file, len); 237 qemu_put_buffer(mis->to_src_file, data, len); 238 qemu_fflush(mis->to_src_file); 239 240 /* It's possible that qemu file got error during sending */ 241 ret = qemu_file_get_error(mis->to_src_file); 242 243 error: 244 qemu_mutex_unlock(&mis->rp_mutex); 245 return ret; 246 } 247 248 /* Request a range of pages from the source VM at the given 249 * start address. 250 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same 251 * as the last request (a name must have been given previously) 252 * Start: Address offset within the RB 253 * Len: Length in bytes required - must be a multiple of pagesize 254 */ 255 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname, 256 ram_addr_t start, size_t len) 257 { 258 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */ 259 size_t msglen = 12; /* start + len */ 260 enum mig_rp_message_type msg_type; 261 262 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start); 263 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len); 264 265 if (rbname) { 266 int rbname_len = strlen(rbname); 267 assert(rbname_len < 256); 268 269 bufc[msglen++] = rbname_len; 270 memcpy(bufc + msglen, rbname, rbname_len); 271 msglen += rbname_len; 272 msg_type = MIG_RP_MSG_REQ_PAGES_ID; 273 } else { 274 msg_type = MIG_RP_MSG_REQ_PAGES; 275 } 276 277 return migrate_send_rp_message(mis, msg_type, msglen, bufc); 278 } 279 280 void qemu_start_incoming_migration(const char *uri, Error **errp) 281 { 282 const char *p; 283 284 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort); 285 if (!strcmp(uri, "defer")) { 286 deferred_incoming_migration(errp); 287 } else if (strstart(uri, "tcp:", &p)) { 288 tcp_start_incoming_migration(p, errp); 289 #ifdef CONFIG_RDMA 290 } else if (strstart(uri, "rdma:", &p)) { 291 rdma_start_incoming_migration(p, errp); 292 #endif 293 } else if (strstart(uri, "exec:", &p)) { 294 exec_start_incoming_migration(p, errp); 295 } else if (strstart(uri, "unix:", &p)) { 296 unix_start_incoming_migration(p, errp); 297 } else if (strstart(uri, "fd:", &p)) { 298 fd_start_incoming_migration(p, errp); 299 } else { 300 error_setg(errp, "unknown migration protocol: %s", uri); 301 } 302 } 303 304 static void process_incoming_migration_bh(void *opaque) 305 { 306 Error *local_err = NULL; 307 MigrationIncomingState *mis = opaque; 308 309 /* Make sure all file formats flush their mutable metadata. 310 * If we get an error here, just don't restart the VM yet. */ 311 bdrv_invalidate_cache_all(&local_err); 312 if (local_err) { 313 error_report_err(local_err); 314 local_err = NULL; 315 autostart = false; 316 } 317 318 /* 319 * This must happen after all error conditions are dealt with and 320 * we're sure the VM is going to be running on this host. 321 */ 322 qemu_announce_self(); 323 324 if (multifd_load_cleanup(&local_err) != 0) { 325 error_report_err(local_err); 326 autostart = false; 327 } 328 /* If global state section was not received or we are in running 329 state, we need to obey autostart. Any other state is set with 330 runstate_set. */ 331 332 dirty_bitmap_mig_before_vm_start(); 333 334 if (!global_state_received() || 335 global_state_get_runstate() == RUN_STATE_RUNNING) { 336 if (autostart) { 337 vm_start(); 338 } else { 339 runstate_set(RUN_STATE_PAUSED); 340 } 341 } else { 342 runstate_set(global_state_get_runstate()); 343 } 344 /* 345 * This must happen after any state changes since as soon as an external 346 * observer sees this event they might start to prod at the VM assuming 347 * it's ready to use. 348 */ 349 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE, 350 MIGRATION_STATUS_COMPLETED); 351 qemu_bh_delete(mis->bh); 352 migration_incoming_state_destroy(); 353 } 354 355 static void process_incoming_migration_co(void *opaque) 356 { 357 MigrationIncomingState *mis = migration_incoming_get_current(); 358 PostcopyState ps; 359 int ret; 360 361 assert(mis->from_src_file); 362 mis->largest_page_size = qemu_ram_pagesize_largest(); 363 postcopy_state_set(POSTCOPY_INCOMING_NONE); 364 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE, 365 MIGRATION_STATUS_ACTIVE); 366 ret = qemu_loadvm_state(mis->from_src_file); 367 368 ps = postcopy_state_get(); 369 trace_process_incoming_migration_co_end(ret, ps); 370 if (ps != POSTCOPY_INCOMING_NONE) { 371 if (ps == POSTCOPY_INCOMING_ADVISE) { 372 /* 373 * Where a migration had postcopy enabled (and thus went to advise) 374 * but managed to complete within the precopy period, we can use 375 * the normal exit. 376 */ 377 postcopy_ram_incoming_cleanup(mis); 378 } else if (ret >= 0) { 379 /* 380 * Postcopy was started, cleanup should happen at the end of the 381 * postcopy thread. 382 */ 383 trace_process_incoming_migration_co_postcopy_end_main(); 384 return; 385 } 386 /* Else if something went wrong then just fall out of the normal exit */ 387 } 388 389 /* we get COLO info, and know if we are in COLO mode */ 390 if (!ret && migration_incoming_enable_colo()) { 391 mis->migration_incoming_co = qemu_coroutine_self(); 392 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming", 393 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE); 394 mis->have_colo_incoming_thread = true; 395 qemu_coroutine_yield(); 396 397 /* Wait checkpoint incoming thread exit before free resource */ 398 qemu_thread_join(&mis->colo_incoming_thread); 399 } 400 401 if (ret < 0) { 402 Error *local_err = NULL; 403 404 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE, 405 MIGRATION_STATUS_FAILED); 406 error_report("load of migration failed: %s", strerror(-ret)); 407 qemu_fclose(mis->from_src_file); 408 if (multifd_load_cleanup(&local_err) != 0) { 409 error_report_err(local_err); 410 } 411 exit(EXIT_FAILURE); 412 } 413 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis); 414 qemu_bh_schedule(mis->bh); 415 } 416 417 static void migration_incoming_setup(QEMUFile *f) 418 { 419 MigrationIncomingState *mis = migration_incoming_get_current(); 420 421 if (multifd_load_setup() != 0) { 422 /* We haven't been able to create multifd threads 423 nothing better to do */ 424 exit(EXIT_FAILURE); 425 } 426 427 if (!mis->from_src_file) { 428 mis->from_src_file = f; 429 } 430 qemu_file_set_blocking(f, false); 431 } 432 433 static void migration_incoming_process(void) 434 { 435 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL); 436 qemu_coroutine_enter(co); 437 } 438 439 void migration_fd_process_incoming(QEMUFile *f) 440 { 441 migration_incoming_setup(f); 442 migration_incoming_process(); 443 } 444 445 void migration_ioc_process_incoming(QIOChannel *ioc) 446 { 447 MigrationIncomingState *mis = migration_incoming_get_current(); 448 449 if (!mis->from_src_file) { 450 QEMUFile *f = qemu_fopen_channel_input(ioc); 451 migration_fd_process_incoming(f); 452 } 453 /* We still only have a single channel. Nothing to do here yet */ 454 } 455 456 /** 457 * @migration_has_all_channels: We have received all channels that we need 458 * 459 * Returns true when we have got connections to all the channels that 460 * we need for migration. 461 */ 462 bool migration_has_all_channels(void) 463 { 464 return true; 465 } 466 467 /* 468 * Send a 'SHUT' message on the return channel with the given value 469 * to indicate that we've finished with the RP. Non-0 value indicates 470 * error. 471 */ 472 void migrate_send_rp_shut(MigrationIncomingState *mis, 473 uint32_t value) 474 { 475 uint32_t buf; 476 477 buf = cpu_to_be32(value); 478 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf); 479 } 480 481 /* 482 * Send a 'PONG' message on the return channel with the given value 483 * (normally in response to a 'PING') 484 */ 485 void migrate_send_rp_pong(MigrationIncomingState *mis, 486 uint32_t value) 487 { 488 uint32_t buf; 489 490 buf = cpu_to_be32(value); 491 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf); 492 } 493 494 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp) 495 { 496 MigrationCapabilityStatusList *head = NULL; 497 MigrationCapabilityStatusList *caps; 498 MigrationState *s = migrate_get_current(); 499 int i; 500 501 caps = NULL; /* silence compiler warning */ 502 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) { 503 #ifndef CONFIG_LIVE_BLOCK_MIGRATION 504 if (i == MIGRATION_CAPABILITY_BLOCK) { 505 continue; 506 } 507 #endif 508 if (head == NULL) { 509 head = g_malloc0(sizeof(*caps)); 510 caps = head; 511 } else { 512 caps->next = g_malloc0(sizeof(*caps)); 513 caps = caps->next; 514 } 515 caps->value = 516 g_malloc(sizeof(*caps->value)); 517 caps->value->capability = i; 518 caps->value->state = s->enabled_capabilities[i]; 519 } 520 521 return head; 522 } 523 524 MigrationParameters *qmp_query_migrate_parameters(Error **errp) 525 { 526 MigrationParameters *params; 527 MigrationState *s = migrate_get_current(); 528 529 /* TODO use QAPI_CLONE() instead of duplicating it inline */ 530 params = g_malloc0(sizeof(*params)); 531 params->has_compress_level = true; 532 params->compress_level = s->parameters.compress_level; 533 params->has_compress_threads = true; 534 params->compress_threads = s->parameters.compress_threads; 535 params->has_decompress_threads = true; 536 params->decompress_threads = s->parameters.decompress_threads; 537 params->has_cpu_throttle_initial = true; 538 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial; 539 params->has_cpu_throttle_increment = true; 540 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment; 541 params->has_tls_creds = true; 542 params->tls_creds = g_strdup(s->parameters.tls_creds); 543 params->has_tls_hostname = true; 544 params->tls_hostname = g_strdup(s->parameters.tls_hostname); 545 params->has_max_bandwidth = true; 546 params->max_bandwidth = s->parameters.max_bandwidth; 547 params->has_downtime_limit = true; 548 params->downtime_limit = s->parameters.downtime_limit; 549 params->has_x_checkpoint_delay = true; 550 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay; 551 params->has_block_incremental = true; 552 params->block_incremental = s->parameters.block_incremental; 553 params->has_x_multifd_channels = true; 554 params->x_multifd_channels = s->parameters.x_multifd_channels; 555 params->has_x_multifd_page_count = true; 556 params->x_multifd_page_count = s->parameters.x_multifd_page_count; 557 params->has_xbzrle_cache_size = true; 558 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size; 559 560 return params; 561 } 562 563 /* 564 * Return true if we're already in the middle of a migration 565 * (i.e. any of the active or setup states) 566 */ 567 static bool migration_is_setup_or_active(int state) 568 { 569 switch (state) { 570 case MIGRATION_STATUS_ACTIVE: 571 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 572 case MIGRATION_STATUS_SETUP: 573 case MIGRATION_STATUS_PRE_SWITCHOVER: 574 case MIGRATION_STATUS_DEVICE: 575 return true; 576 577 default: 578 return false; 579 580 } 581 } 582 583 static void populate_ram_info(MigrationInfo *info, MigrationState *s) 584 { 585 info->has_ram = true; 586 info->ram = g_malloc0(sizeof(*info->ram)); 587 info->ram->transferred = ram_counters.transferred; 588 info->ram->total = ram_bytes_total(); 589 info->ram->duplicate = ram_counters.duplicate; 590 /* legacy value. It is not used anymore */ 591 info->ram->skipped = 0; 592 info->ram->normal = ram_counters.normal; 593 info->ram->normal_bytes = ram_counters.normal * 594 qemu_target_page_size(); 595 info->ram->mbps = s->mbps; 596 info->ram->dirty_sync_count = ram_counters.dirty_sync_count; 597 info->ram->postcopy_requests = ram_counters.postcopy_requests; 598 info->ram->page_size = qemu_target_page_size(); 599 600 if (migrate_use_xbzrle()) { 601 info->has_xbzrle_cache = true; 602 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache)); 603 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size(); 604 info->xbzrle_cache->bytes = xbzrle_counters.bytes; 605 info->xbzrle_cache->pages = xbzrle_counters.pages; 606 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss; 607 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate; 608 info->xbzrle_cache->overflow = xbzrle_counters.overflow; 609 } 610 611 if (cpu_throttle_active()) { 612 info->has_cpu_throttle_percentage = true; 613 info->cpu_throttle_percentage = cpu_throttle_get_percentage(); 614 } 615 616 if (s->state != MIGRATION_STATUS_COMPLETED) { 617 info->ram->remaining = ram_bytes_remaining(); 618 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate; 619 } 620 } 621 622 static void populate_disk_info(MigrationInfo *info) 623 { 624 if (blk_mig_active()) { 625 info->has_disk = true; 626 info->disk = g_malloc0(sizeof(*info->disk)); 627 info->disk->transferred = blk_mig_bytes_transferred(); 628 info->disk->remaining = blk_mig_bytes_remaining(); 629 info->disk->total = blk_mig_bytes_total(); 630 } 631 } 632 633 static void fill_source_migration_info(MigrationInfo *info) 634 { 635 MigrationState *s = migrate_get_current(); 636 637 switch (s->state) { 638 case MIGRATION_STATUS_NONE: 639 /* no migration has happened ever */ 640 /* do not overwrite destination migration status */ 641 return; 642 break; 643 case MIGRATION_STATUS_SETUP: 644 info->has_status = true; 645 info->has_total_time = false; 646 break; 647 case MIGRATION_STATUS_ACTIVE: 648 case MIGRATION_STATUS_CANCELLING: 649 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 650 case MIGRATION_STATUS_PRE_SWITCHOVER: 651 case MIGRATION_STATUS_DEVICE: 652 /* TODO add some postcopy stats */ 653 info->has_status = true; 654 info->has_total_time = true; 655 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) 656 - s->start_time; 657 info->has_expected_downtime = true; 658 info->expected_downtime = s->expected_downtime; 659 info->has_setup_time = true; 660 info->setup_time = s->setup_time; 661 662 populate_ram_info(info, s); 663 populate_disk_info(info); 664 break; 665 case MIGRATION_STATUS_COLO: 666 info->has_status = true; 667 /* TODO: display COLO specific information (checkpoint info etc.) */ 668 break; 669 case MIGRATION_STATUS_COMPLETED: 670 info->has_status = true; 671 info->has_total_time = true; 672 info->total_time = s->total_time; 673 info->has_downtime = true; 674 info->downtime = s->downtime; 675 info->has_setup_time = true; 676 info->setup_time = s->setup_time; 677 678 populate_ram_info(info, s); 679 break; 680 case MIGRATION_STATUS_FAILED: 681 info->has_status = true; 682 if (s->error) { 683 info->has_error_desc = true; 684 info->error_desc = g_strdup(error_get_pretty(s->error)); 685 } 686 break; 687 case MIGRATION_STATUS_CANCELLED: 688 info->has_status = true; 689 break; 690 } 691 info->status = s->state; 692 } 693 694 /** 695 * @migration_caps_check - check capability validity 696 * 697 * @cap_list: old capability list, array of bool 698 * @params: new capabilities to be applied soon 699 * @errp: set *errp if the check failed, with reason 700 * 701 * Returns true if check passed, otherwise false. 702 */ 703 static bool migrate_caps_check(bool *cap_list, 704 MigrationCapabilityStatusList *params, 705 Error **errp) 706 { 707 MigrationCapabilityStatusList *cap; 708 bool old_postcopy_cap; 709 MigrationIncomingState *mis = migration_incoming_get_current(); 710 711 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]; 712 713 for (cap = params; cap; cap = cap->next) { 714 cap_list[cap->value->capability] = cap->value->state; 715 } 716 717 #ifndef CONFIG_LIVE_BLOCK_MIGRATION 718 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) { 719 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) " 720 "block migration"); 721 error_append_hint(errp, "Use drive_mirror+NBD instead.\n"); 722 return false; 723 } 724 #endif 725 726 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) { 727 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) { 728 /* The decompression threads asynchronously write into RAM 729 * rather than use the atomic copies needed to avoid 730 * userfaulting. It should be possible to fix the decompression 731 * threads for compatibility in future. 732 */ 733 error_setg(errp, "Postcopy is not currently compatible " 734 "with compression"); 735 return false; 736 } 737 738 /* This check is reasonably expensive, so only when it's being 739 * set the first time, also it's only the destination that needs 740 * special support. 741 */ 742 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) && 743 !postcopy_ram_supported_by_host(mis)) { 744 /* postcopy_ram_supported_by_host will have emitted a more 745 * detailed message 746 */ 747 error_setg(errp, "Postcopy is not supported"); 748 return false; 749 } 750 } 751 752 return true; 753 } 754 755 static void fill_destination_migration_info(MigrationInfo *info) 756 { 757 MigrationIncomingState *mis = migration_incoming_get_current(); 758 759 switch (mis->state) { 760 case MIGRATION_STATUS_NONE: 761 return; 762 break; 763 case MIGRATION_STATUS_SETUP: 764 case MIGRATION_STATUS_CANCELLING: 765 case MIGRATION_STATUS_CANCELLED: 766 case MIGRATION_STATUS_ACTIVE: 767 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 768 case MIGRATION_STATUS_FAILED: 769 case MIGRATION_STATUS_COLO: 770 info->has_status = true; 771 break; 772 case MIGRATION_STATUS_COMPLETED: 773 info->has_status = true; 774 fill_destination_postcopy_migration_info(info); 775 break; 776 } 777 info->status = mis->state; 778 } 779 780 MigrationInfo *qmp_query_migrate(Error **errp) 781 { 782 MigrationInfo *info = g_malloc0(sizeof(*info)); 783 784 fill_destination_migration_info(info); 785 fill_source_migration_info(info); 786 787 return info; 788 } 789 790 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params, 791 Error **errp) 792 { 793 MigrationState *s = migrate_get_current(); 794 MigrationCapabilityStatusList *cap; 795 bool cap_list[MIGRATION_CAPABILITY__MAX]; 796 797 if (migration_is_setup_or_active(s->state)) { 798 error_setg(errp, QERR_MIGRATION_ACTIVE); 799 return; 800 } 801 802 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list)); 803 if (!migrate_caps_check(cap_list, params, errp)) { 804 return; 805 } 806 807 for (cap = params; cap; cap = cap->next) { 808 s->enabled_capabilities[cap->value->capability] = cap->value->state; 809 } 810 } 811 812 /* 813 * Check whether the parameters are valid. Error will be put into errp 814 * (if provided). Return true if valid, otherwise false. 815 */ 816 static bool migrate_params_check(MigrationParameters *params, Error **errp) 817 { 818 if (params->has_compress_level && 819 (params->compress_level > 9)) { 820 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level", 821 "is invalid, it should be in the range of 0 to 9"); 822 return false; 823 } 824 825 if (params->has_compress_threads && (params->compress_threads < 1)) { 826 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 827 "compress_threads", 828 "is invalid, it should be in the range of 1 to 255"); 829 return false; 830 } 831 832 if (params->has_decompress_threads && (params->decompress_threads < 1)) { 833 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 834 "decompress_threads", 835 "is invalid, it should be in the range of 1 to 255"); 836 return false; 837 } 838 839 if (params->has_cpu_throttle_initial && 840 (params->cpu_throttle_initial < 1 || 841 params->cpu_throttle_initial > 99)) { 842 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 843 "cpu_throttle_initial", 844 "an integer in the range of 1 to 99"); 845 return false; 846 } 847 848 if (params->has_cpu_throttle_increment && 849 (params->cpu_throttle_increment < 1 || 850 params->cpu_throttle_increment > 99)) { 851 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 852 "cpu_throttle_increment", 853 "an integer in the range of 1 to 99"); 854 return false; 855 } 856 857 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) { 858 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the" 859 " range of 0 to %zu bytes/second", SIZE_MAX); 860 return false; 861 } 862 863 if (params->has_downtime_limit && 864 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) { 865 error_setg(errp, "Parameter 'downtime_limit' expects an integer in " 866 "the range of 0 to %d milliseconds", 867 MAX_MIGRATE_DOWNTIME); 868 return false; 869 } 870 871 /* x_checkpoint_delay is now always positive */ 872 873 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) { 874 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 875 "multifd_channels", 876 "is invalid, it should be in the range of 1 to 255"); 877 return false; 878 } 879 if (params->has_x_multifd_page_count && 880 (params->x_multifd_page_count < 1 || 881 params->x_multifd_page_count > 10000)) { 882 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 883 "multifd_page_count", 884 "is invalid, it should be in the range of 1 to 10000"); 885 return false; 886 } 887 888 if (params->has_xbzrle_cache_size && 889 (params->xbzrle_cache_size < qemu_target_page_size() || 890 !is_power_of_2(params->xbzrle_cache_size))) { 891 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, 892 "xbzrle_cache_size", 893 "is invalid, it should be bigger than target page size" 894 " and a power of two"); 895 return false; 896 } 897 898 return true; 899 } 900 901 static void migrate_params_test_apply(MigrateSetParameters *params, 902 MigrationParameters *dest) 903 { 904 *dest = migrate_get_current()->parameters; 905 906 /* TODO use QAPI_CLONE() instead of duplicating it inline */ 907 908 if (params->has_compress_level) { 909 dest->compress_level = params->compress_level; 910 } 911 912 if (params->has_compress_threads) { 913 dest->compress_threads = params->compress_threads; 914 } 915 916 if (params->has_decompress_threads) { 917 dest->decompress_threads = params->decompress_threads; 918 } 919 920 if (params->has_cpu_throttle_initial) { 921 dest->cpu_throttle_initial = params->cpu_throttle_initial; 922 } 923 924 if (params->has_cpu_throttle_increment) { 925 dest->cpu_throttle_increment = params->cpu_throttle_increment; 926 } 927 928 if (params->has_tls_creds) { 929 assert(params->tls_creds->type == QTYPE_QSTRING); 930 dest->tls_creds = g_strdup(params->tls_creds->u.s); 931 } 932 933 if (params->has_tls_hostname) { 934 assert(params->tls_hostname->type == QTYPE_QSTRING); 935 dest->tls_hostname = g_strdup(params->tls_hostname->u.s); 936 } 937 938 if (params->has_max_bandwidth) { 939 dest->max_bandwidth = params->max_bandwidth; 940 } 941 942 if (params->has_downtime_limit) { 943 dest->downtime_limit = params->downtime_limit; 944 } 945 946 if (params->has_x_checkpoint_delay) { 947 dest->x_checkpoint_delay = params->x_checkpoint_delay; 948 } 949 950 if (params->has_block_incremental) { 951 dest->block_incremental = params->block_incremental; 952 } 953 if (params->has_x_multifd_channels) { 954 dest->x_multifd_channels = params->x_multifd_channels; 955 } 956 if (params->has_x_multifd_page_count) { 957 dest->x_multifd_page_count = params->x_multifd_page_count; 958 } 959 if (params->has_xbzrle_cache_size) { 960 dest->xbzrle_cache_size = params->xbzrle_cache_size; 961 } 962 } 963 964 static void migrate_params_apply(MigrateSetParameters *params, Error **errp) 965 { 966 MigrationState *s = migrate_get_current(); 967 968 /* TODO use QAPI_CLONE() instead of duplicating it inline */ 969 970 if (params->has_compress_level) { 971 s->parameters.compress_level = params->compress_level; 972 } 973 974 if (params->has_compress_threads) { 975 s->parameters.compress_threads = params->compress_threads; 976 } 977 978 if (params->has_decompress_threads) { 979 s->parameters.decompress_threads = params->decompress_threads; 980 } 981 982 if (params->has_cpu_throttle_initial) { 983 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial; 984 } 985 986 if (params->has_cpu_throttle_increment) { 987 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment; 988 } 989 990 if (params->has_tls_creds) { 991 g_free(s->parameters.tls_creds); 992 assert(params->tls_creds->type == QTYPE_QSTRING); 993 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s); 994 } 995 996 if (params->has_tls_hostname) { 997 g_free(s->parameters.tls_hostname); 998 assert(params->tls_hostname->type == QTYPE_QSTRING); 999 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s); 1000 } 1001 1002 if (params->has_max_bandwidth) { 1003 s->parameters.max_bandwidth = params->max_bandwidth; 1004 if (s->to_dst_file) { 1005 qemu_file_set_rate_limit(s->to_dst_file, 1006 s->parameters.max_bandwidth / XFER_LIMIT_RATIO); 1007 } 1008 } 1009 1010 if (params->has_downtime_limit) { 1011 s->parameters.downtime_limit = params->downtime_limit; 1012 } 1013 1014 if (params->has_x_checkpoint_delay) { 1015 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay; 1016 if (migration_in_colo_state()) { 1017 colo_checkpoint_notify(s); 1018 } 1019 } 1020 1021 if (params->has_block_incremental) { 1022 s->parameters.block_incremental = params->block_incremental; 1023 } 1024 if (params->has_x_multifd_channels) { 1025 s->parameters.x_multifd_channels = params->x_multifd_channels; 1026 } 1027 if (params->has_x_multifd_page_count) { 1028 s->parameters.x_multifd_page_count = params->x_multifd_page_count; 1029 } 1030 if (params->has_xbzrle_cache_size) { 1031 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size; 1032 xbzrle_cache_resize(params->xbzrle_cache_size, errp); 1033 } 1034 } 1035 1036 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp) 1037 { 1038 MigrationParameters tmp; 1039 1040 /* TODO Rewrite "" to null instead */ 1041 if (params->has_tls_creds 1042 && params->tls_creds->type == QTYPE_QNULL) { 1043 qobject_unref(params->tls_creds->u.n); 1044 params->tls_creds->type = QTYPE_QSTRING; 1045 params->tls_creds->u.s = strdup(""); 1046 } 1047 /* TODO Rewrite "" to null instead */ 1048 if (params->has_tls_hostname 1049 && params->tls_hostname->type == QTYPE_QNULL) { 1050 qobject_unref(params->tls_hostname->u.n); 1051 params->tls_hostname->type = QTYPE_QSTRING; 1052 params->tls_hostname->u.s = strdup(""); 1053 } 1054 1055 migrate_params_test_apply(params, &tmp); 1056 1057 if (!migrate_params_check(&tmp, errp)) { 1058 /* Invalid parameter */ 1059 return; 1060 } 1061 1062 migrate_params_apply(params, errp); 1063 } 1064 1065 1066 void qmp_migrate_start_postcopy(Error **errp) 1067 { 1068 MigrationState *s = migrate_get_current(); 1069 1070 if (!migrate_postcopy()) { 1071 error_setg(errp, "Enable postcopy with migrate_set_capability before" 1072 " the start of migration"); 1073 return; 1074 } 1075 1076 if (s->state == MIGRATION_STATUS_NONE) { 1077 error_setg(errp, "Postcopy must be started after migration has been" 1078 " started"); 1079 return; 1080 } 1081 /* 1082 * we don't error if migration has finished since that would be racy 1083 * with issuing this command. 1084 */ 1085 atomic_set(&s->start_postcopy, true); 1086 } 1087 1088 /* shared migration helpers */ 1089 1090 void migrate_set_state(int *state, int old_state, int new_state) 1091 { 1092 assert(new_state < MIGRATION_STATUS__MAX); 1093 if (atomic_cmpxchg(state, old_state, new_state) == old_state) { 1094 trace_migrate_set_state(MigrationStatus_str(new_state)); 1095 migrate_generate_event(new_state); 1096 } 1097 } 1098 1099 static MigrationCapabilityStatusList *migrate_cap_add( 1100 MigrationCapabilityStatusList *list, 1101 MigrationCapability index, 1102 bool state) 1103 { 1104 MigrationCapabilityStatusList *cap; 1105 1106 cap = g_new0(MigrationCapabilityStatusList, 1); 1107 cap->value = g_new0(MigrationCapabilityStatus, 1); 1108 cap->value->capability = index; 1109 cap->value->state = state; 1110 cap->next = list; 1111 1112 return cap; 1113 } 1114 1115 void migrate_set_block_enabled(bool value, Error **errp) 1116 { 1117 MigrationCapabilityStatusList *cap; 1118 1119 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value); 1120 qmp_migrate_set_capabilities(cap, errp); 1121 qapi_free_MigrationCapabilityStatusList(cap); 1122 } 1123 1124 static void migrate_set_block_incremental(MigrationState *s, bool value) 1125 { 1126 s->parameters.block_incremental = value; 1127 } 1128 1129 static void block_cleanup_parameters(MigrationState *s) 1130 { 1131 if (s->must_remove_block_options) { 1132 /* setting to false can never fail */ 1133 migrate_set_block_enabled(false, &error_abort); 1134 migrate_set_block_incremental(s, false); 1135 s->must_remove_block_options = false; 1136 } 1137 } 1138 1139 static void migrate_fd_cleanup(void *opaque) 1140 { 1141 MigrationState *s = opaque; 1142 1143 qemu_bh_delete(s->cleanup_bh); 1144 s->cleanup_bh = NULL; 1145 1146 qemu_savevm_state_cleanup(); 1147 1148 if (s->to_dst_file) { 1149 Error *local_err = NULL; 1150 1151 trace_migrate_fd_cleanup(); 1152 qemu_mutex_unlock_iothread(); 1153 if (s->migration_thread_running) { 1154 qemu_thread_join(&s->thread); 1155 s->migration_thread_running = false; 1156 } 1157 qemu_mutex_lock_iothread(); 1158 1159 if (multifd_save_cleanup(&local_err) != 0) { 1160 error_report_err(local_err); 1161 } 1162 qemu_fclose(s->to_dst_file); 1163 s->to_dst_file = NULL; 1164 } 1165 1166 assert((s->state != MIGRATION_STATUS_ACTIVE) && 1167 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE)); 1168 1169 if (s->state == MIGRATION_STATUS_CANCELLING) { 1170 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING, 1171 MIGRATION_STATUS_CANCELLED); 1172 } 1173 1174 if (s->error) { 1175 /* It is used on info migrate. We can't free it */ 1176 error_report_err(error_copy(s->error)); 1177 } 1178 notifier_list_notify(&migration_state_notifiers, s); 1179 block_cleanup_parameters(s); 1180 } 1181 1182 void migrate_set_error(MigrationState *s, const Error *error) 1183 { 1184 qemu_mutex_lock(&s->error_mutex); 1185 if (!s->error) { 1186 s->error = error_copy(error); 1187 } 1188 qemu_mutex_unlock(&s->error_mutex); 1189 } 1190 1191 void migrate_fd_error(MigrationState *s, const Error *error) 1192 { 1193 trace_migrate_fd_error(error_get_pretty(error)); 1194 assert(s->to_dst_file == NULL); 1195 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 1196 MIGRATION_STATUS_FAILED); 1197 migrate_set_error(s, error); 1198 } 1199 1200 static void migrate_fd_cancel(MigrationState *s) 1201 { 1202 int old_state ; 1203 QEMUFile *f = migrate_get_current()->to_dst_file; 1204 trace_migrate_fd_cancel(); 1205 1206 if (s->rp_state.from_dst_file) { 1207 /* shutdown the rp socket, so causing the rp thread to shutdown */ 1208 qemu_file_shutdown(s->rp_state.from_dst_file); 1209 } 1210 1211 do { 1212 old_state = s->state; 1213 if (!migration_is_setup_or_active(old_state)) { 1214 break; 1215 } 1216 /* If the migration is paused, kick it out of the pause */ 1217 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) { 1218 qemu_sem_post(&s->pause_sem); 1219 } 1220 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING); 1221 } while (s->state != MIGRATION_STATUS_CANCELLING); 1222 1223 /* 1224 * If we're unlucky the migration code might be stuck somewhere in a 1225 * send/write while the network has failed and is waiting to timeout; 1226 * if we've got shutdown(2) available then we can force it to quit. 1227 * The outgoing qemu file gets closed in migrate_fd_cleanup that is 1228 * called in a bh, so there is no race against this cancel. 1229 */ 1230 if (s->state == MIGRATION_STATUS_CANCELLING && f) { 1231 qemu_file_shutdown(f); 1232 } 1233 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) { 1234 Error *local_err = NULL; 1235 1236 bdrv_invalidate_cache_all(&local_err); 1237 if (local_err) { 1238 error_report_err(local_err); 1239 } else { 1240 s->block_inactive = false; 1241 } 1242 } 1243 } 1244 1245 void add_migration_state_change_notifier(Notifier *notify) 1246 { 1247 notifier_list_add(&migration_state_notifiers, notify); 1248 } 1249 1250 void remove_migration_state_change_notifier(Notifier *notify) 1251 { 1252 notifier_remove(notify); 1253 } 1254 1255 bool migration_in_setup(MigrationState *s) 1256 { 1257 return s->state == MIGRATION_STATUS_SETUP; 1258 } 1259 1260 bool migration_has_finished(MigrationState *s) 1261 { 1262 return s->state == MIGRATION_STATUS_COMPLETED; 1263 } 1264 1265 bool migration_has_failed(MigrationState *s) 1266 { 1267 return (s->state == MIGRATION_STATUS_CANCELLED || 1268 s->state == MIGRATION_STATUS_FAILED); 1269 } 1270 1271 bool migration_in_postcopy(void) 1272 { 1273 MigrationState *s = migrate_get_current(); 1274 1275 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE); 1276 } 1277 1278 bool migration_in_postcopy_after_devices(MigrationState *s) 1279 { 1280 return migration_in_postcopy() && s->postcopy_after_devices; 1281 } 1282 1283 bool migration_is_idle(void) 1284 { 1285 MigrationState *s = migrate_get_current(); 1286 1287 switch (s->state) { 1288 case MIGRATION_STATUS_NONE: 1289 case MIGRATION_STATUS_CANCELLED: 1290 case MIGRATION_STATUS_COMPLETED: 1291 case MIGRATION_STATUS_FAILED: 1292 return true; 1293 case MIGRATION_STATUS_SETUP: 1294 case MIGRATION_STATUS_CANCELLING: 1295 case MIGRATION_STATUS_ACTIVE: 1296 case MIGRATION_STATUS_POSTCOPY_ACTIVE: 1297 case MIGRATION_STATUS_COLO: 1298 case MIGRATION_STATUS_PRE_SWITCHOVER: 1299 case MIGRATION_STATUS_DEVICE: 1300 return false; 1301 case MIGRATION_STATUS__MAX: 1302 g_assert_not_reached(); 1303 } 1304 1305 return false; 1306 } 1307 1308 void migrate_init(MigrationState *s) 1309 { 1310 /* 1311 * Reinitialise all migration state, except 1312 * parameters/capabilities that the user set, and 1313 * locks. 1314 */ 1315 s->bytes_xfer = 0; 1316 s->xfer_limit = 0; 1317 s->cleanup_bh = 0; 1318 s->to_dst_file = NULL; 1319 s->state = MIGRATION_STATUS_NONE; 1320 s->rp_state.from_dst_file = NULL; 1321 s->rp_state.error = false; 1322 s->mbps = 0.0; 1323 s->downtime = 0; 1324 s->expected_downtime = 0; 1325 s->setup_time = 0; 1326 s->start_postcopy = false; 1327 s->postcopy_after_devices = false; 1328 s->migration_thread_running = false; 1329 error_free(s->error); 1330 s->error = NULL; 1331 1332 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP); 1333 1334 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 1335 s->total_time = 0; 1336 s->vm_was_running = false; 1337 s->iteration_initial_bytes = 0; 1338 s->threshold_size = 0; 1339 } 1340 1341 static GSList *migration_blockers; 1342 1343 int migrate_add_blocker(Error *reason, Error **errp) 1344 { 1345 if (migrate_get_current()->only_migratable) { 1346 error_propagate(errp, error_copy(reason)); 1347 error_prepend(errp, "disallowing migration blocker " 1348 "(--only_migratable) for: "); 1349 return -EACCES; 1350 } 1351 1352 if (migration_is_idle()) { 1353 migration_blockers = g_slist_prepend(migration_blockers, reason); 1354 return 0; 1355 } 1356 1357 error_propagate(errp, error_copy(reason)); 1358 error_prepend(errp, "disallowing migration blocker (migration in " 1359 "progress) for: "); 1360 return -EBUSY; 1361 } 1362 1363 void migrate_del_blocker(Error *reason) 1364 { 1365 migration_blockers = g_slist_remove(migration_blockers, reason); 1366 } 1367 1368 void qmp_migrate_incoming(const char *uri, Error **errp) 1369 { 1370 Error *local_err = NULL; 1371 static bool once = true; 1372 1373 if (!deferred_incoming) { 1374 error_setg(errp, "For use with '-incoming defer'"); 1375 return; 1376 } 1377 if (!once) { 1378 error_setg(errp, "The incoming migration has already been started"); 1379 } 1380 1381 qemu_start_incoming_migration(uri, &local_err); 1382 1383 if (local_err) { 1384 error_propagate(errp, local_err); 1385 return; 1386 } 1387 1388 once = false; 1389 } 1390 1391 bool migration_is_blocked(Error **errp) 1392 { 1393 if (qemu_savevm_state_blocked(errp)) { 1394 return true; 1395 } 1396 1397 if (migration_blockers) { 1398 error_propagate(errp, error_copy(migration_blockers->data)); 1399 return true; 1400 } 1401 1402 return false; 1403 } 1404 1405 void qmp_migrate(const char *uri, bool has_blk, bool blk, 1406 bool has_inc, bool inc, bool has_detach, bool detach, 1407 Error **errp) 1408 { 1409 Error *local_err = NULL; 1410 MigrationState *s = migrate_get_current(); 1411 const char *p; 1412 1413 if (migration_is_setup_or_active(s->state) || 1414 s->state == MIGRATION_STATUS_CANCELLING || 1415 s->state == MIGRATION_STATUS_COLO) { 1416 error_setg(errp, QERR_MIGRATION_ACTIVE); 1417 return; 1418 } 1419 if (runstate_check(RUN_STATE_INMIGRATE)) { 1420 error_setg(errp, "Guest is waiting for an incoming migration"); 1421 return; 1422 } 1423 1424 if (migration_is_blocked(errp)) { 1425 return; 1426 } 1427 1428 if ((has_blk && blk) || (has_inc && inc)) { 1429 if (migrate_use_block() || migrate_use_block_incremental()) { 1430 error_setg(errp, "Command options are incompatible with " 1431 "current migration capabilities"); 1432 return; 1433 } 1434 migrate_set_block_enabled(true, &local_err); 1435 if (local_err) { 1436 error_propagate(errp, local_err); 1437 return; 1438 } 1439 s->must_remove_block_options = true; 1440 } 1441 1442 if (has_inc && inc) { 1443 migrate_set_block_incremental(s, true); 1444 } 1445 1446 migrate_init(s); 1447 1448 if (strstart(uri, "tcp:", &p)) { 1449 tcp_start_outgoing_migration(s, p, &local_err); 1450 #ifdef CONFIG_RDMA 1451 } else if (strstart(uri, "rdma:", &p)) { 1452 rdma_start_outgoing_migration(s, p, &local_err); 1453 #endif 1454 } else if (strstart(uri, "exec:", &p)) { 1455 exec_start_outgoing_migration(s, p, &local_err); 1456 } else if (strstart(uri, "unix:", &p)) { 1457 unix_start_outgoing_migration(s, p, &local_err); 1458 } else if (strstart(uri, "fd:", &p)) { 1459 fd_start_outgoing_migration(s, p, &local_err); 1460 } else { 1461 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri", 1462 "a valid migration protocol"); 1463 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 1464 MIGRATION_STATUS_FAILED); 1465 block_cleanup_parameters(s); 1466 return; 1467 } 1468 1469 if (local_err) { 1470 migrate_fd_error(s, local_err); 1471 error_propagate(errp, local_err); 1472 return; 1473 } 1474 } 1475 1476 void qmp_migrate_cancel(Error **errp) 1477 { 1478 migrate_fd_cancel(migrate_get_current()); 1479 } 1480 1481 void qmp_migrate_continue(MigrationStatus state, Error **errp) 1482 { 1483 MigrationState *s = migrate_get_current(); 1484 if (s->state != state) { 1485 error_setg(errp, "Migration not in expected state: %s", 1486 MigrationStatus_str(s->state)); 1487 return; 1488 } 1489 qemu_sem_post(&s->pause_sem); 1490 } 1491 1492 void qmp_migrate_set_cache_size(int64_t value, Error **errp) 1493 { 1494 MigrateSetParameters p = { 1495 .has_xbzrle_cache_size = true, 1496 .xbzrle_cache_size = value, 1497 }; 1498 1499 qmp_migrate_set_parameters(&p, errp); 1500 } 1501 1502 int64_t qmp_query_migrate_cache_size(Error **errp) 1503 { 1504 return migrate_xbzrle_cache_size(); 1505 } 1506 1507 void qmp_migrate_set_speed(int64_t value, Error **errp) 1508 { 1509 MigrateSetParameters p = { 1510 .has_max_bandwidth = true, 1511 .max_bandwidth = value, 1512 }; 1513 1514 qmp_migrate_set_parameters(&p, errp); 1515 } 1516 1517 void qmp_migrate_set_downtime(double value, Error **errp) 1518 { 1519 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) { 1520 error_setg(errp, "Parameter 'downtime_limit' expects an integer in " 1521 "the range of 0 to %d seconds", 1522 MAX_MIGRATE_DOWNTIME_SECONDS); 1523 return; 1524 } 1525 1526 value *= 1000; /* Convert to milliseconds */ 1527 value = MAX(0, MIN(INT64_MAX, value)); 1528 1529 MigrateSetParameters p = { 1530 .has_downtime_limit = true, 1531 .downtime_limit = value, 1532 }; 1533 1534 qmp_migrate_set_parameters(&p, errp); 1535 } 1536 1537 bool migrate_release_ram(void) 1538 { 1539 MigrationState *s; 1540 1541 s = migrate_get_current(); 1542 1543 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM]; 1544 } 1545 1546 bool migrate_postcopy_ram(void) 1547 { 1548 MigrationState *s; 1549 1550 s = migrate_get_current(); 1551 1552 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM]; 1553 } 1554 1555 bool migrate_postcopy(void) 1556 { 1557 return migrate_postcopy_ram() || migrate_dirty_bitmaps(); 1558 } 1559 1560 bool migrate_auto_converge(void) 1561 { 1562 MigrationState *s; 1563 1564 s = migrate_get_current(); 1565 1566 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE]; 1567 } 1568 1569 bool migrate_zero_blocks(void) 1570 { 1571 MigrationState *s; 1572 1573 s = migrate_get_current(); 1574 1575 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS]; 1576 } 1577 1578 bool migrate_postcopy_blocktime(void) 1579 { 1580 MigrationState *s; 1581 1582 s = migrate_get_current(); 1583 1584 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME]; 1585 } 1586 1587 bool migrate_use_compression(void) 1588 { 1589 MigrationState *s; 1590 1591 s = migrate_get_current(); 1592 1593 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS]; 1594 } 1595 1596 int migrate_compress_level(void) 1597 { 1598 MigrationState *s; 1599 1600 s = migrate_get_current(); 1601 1602 return s->parameters.compress_level; 1603 } 1604 1605 int migrate_compress_threads(void) 1606 { 1607 MigrationState *s; 1608 1609 s = migrate_get_current(); 1610 1611 return s->parameters.compress_threads; 1612 } 1613 1614 int migrate_decompress_threads(void) 1615 { 1616 MigrationState *s; 1617 1618 s = migrate_get_current(); 1619 1620 return s->parameters.decompress_threads; 1621 } 1622 1623 bool migrate_dirty_bitmaps(void) 1624 { 1625 MigrationState *s; 1626 1627 s = migrate_get_current(); 1628 1629 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS]; 1630 } 1631 1632 bool migrate_use_events(void) 1633 { 1634 MigrationState *s; 1635 1636 s = migrate_get_current(); 1637 1638 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS]; 1639 } 1640 1641 bool migrate_use_multifd(void) 1642 { 1643 MigrationState *s; 1644 1645 s = migrate_get_current(); 1646 1647 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD]; 1648 } 1649 1650 bool migrate_pause_before_switchover(void) 1651 { 1652 MigrationState *s; 1653 1654 s = migrate_get_current(); 1655 1656 return s->enabled_capabilities[ 1657 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER]; 1658 } 1659 1660 int migrate_multifd_channels(void) 1661 { 1662 MigrationState *s; 1663 1664 s = migrate_get_current(); 1665 1666 return s->parameters.x_multifd_channels; 1667 } 1668 1669 int migrate_multifd_page_count(void) 1670 { 1671 MigrationState *s; 1672 1673 s = migrate_get_current(); 1674 1675 return s->parameters.x_multifd_page_count; 1676 } 1677 1678 int migrate_use_xbzrle(void) 1679 { 1680 MigrationState *s; 1681 1682 s = migrate_get_current(); 1683 1684 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE]; 1685 } 1686 1687 int64_t migrate_xbzrle_cache_size(void) 1688 { 1689 MigrationState *s; 1690 1691 s = migrate_get_current(); 1692 1693 return s->parameters.xbzrle_cache_size; 1694 } 1695 1696 bool migrate_use_block(void) 1697 { 1698 MigrationState *s; 1699 1700 s = migrate_get_current(); 1701 1702 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK]; 1703 } 1704 1705 bool migrate_use_return_path(void) 1706 { 1707 MigrationState *s; 1708 1709 s = migrate_get_current(); 1710 1711 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH]; 1712 } 1713 1714 bool migrate_use_block_incremental(void) 1715 { 1716 MigrationState *s; 1717 1718 s = migrate_get_current(); 1719 1720 return s->parameters.block_incremental; 1721 } 1722 1723 /* migration thread support */ 1724 /* 1725 * Something bad happened to the RP stream, mark an error 1726 * The caller shall print or trace something to indicate why 1727 */ 1728 static void mark_source_rp_bad(MigrationState *s) 1729 { 1730 s->rp_state.error = true; 1731 } 1732 1733 static struct rp_cmd_args { 1734 ssize_t len; /* -1 = variable */ 1735 const char *name; 1736 } rp_cmd_args[] = { 1737 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" }, 1738 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" }, 1739 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" }, 1740 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" }, 1741 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" }, 1742 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" }, 1743 }; 1744 1745 /* 1746 * Process a request for pages received on the return path, 1747 * We're allowed to send more than requested (e.g. to round to our page size) 1748 * and we don't need to send pages that have already been sent. 1749 */ 1750 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname, 1751 ram_addr_t start, size_t len) 1752 { 1753 long our_host_ps = getpagesize(); 1754 1755 trace_migrate_handle_rp_req_pages(rbname, start, len); 1756 1757 /* 1758 * Since we currently insist on matching page sizes, just sanity check 1759 * we're being asked for whole host pages. 1760 */ 1761 if (start & (our_host_ps-1) || 1762 (len & (our_host_ps-1))) { 1763 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT 1764 " len: %zd", __func__, start, len); 1765 mark_source_rp_bad(ms); 1766 return; 1767 } 1768 1769 if (ram_save_queue_pages(rbname, start, len)) { 1770 mark_source_rp_bad(ms); 1771 } 1772 } 1773 1774 /* 1775 * Handles messages sent on the return path towards the source VM 1776 * 1777 */ 1778 static void *source_return_path_thread(void *opaque) 1779 { 1780 MigrationState *ms = opaque; 1781 QEMUFile *rp = ms->rp_state.from_dst_file; 1782 uint16_t header_len, header_type; 1783 uint8_t buf[512]; 1784 uint32_t tmp32, sibling_error; 1785 ram_addr_t start = 0; /* =0 to silence warning */ 1786 size_t len = 0, expected_len; 1787 int res; 1788 1789 trace_source_return_path_thread_entry(); 1790 while (!ms->rp_state.error && !qemu_file_get_error(rp) && 1791 migration_is_setup_or_active(ms->state)) { 1792 trace_source_return_path_thread_loop_top(); 1793 header_type = qemu_get_be16(rp); 1794 header_len = qemu_get_be16(rp); 1795 1796 if (qemu_file_get_error(rp)) { 1797 mark_source_rp_bad(ms); 1798 goto out; 1799 } 1800 1801 if (header_type >= MIG_RP_MSG_MAX || 1802 header_type == MIG_RP_MSG_INVALID) { 1803 error_report("RP: Received invalid message 0x%04x length 0x%04x", 1804 header_type, header_len); 1805 mark_source_rp_bad(ms); 1806 goto out; 1807 } 1808 1809 if ((rp_cmd_args[header_type].len != -1 && 1810 header_len != rp_cmd_args[header_type].len) || 1811 header_len > sizeof(buf)) { 1812 error_report("RP: Received '%s' message (0x%04x) with" 1813 "incorrect length %d expecting %zu", 1814 rp_cmd_args[header_type].name, header_type, header_len, 1815 (size_t)rp_cmd_args[header_type].len); 1816 mark_source_rp_bad(ms); 1817 goto out; 1818 } 1819 1820 /* We know we've got a valid header by this point */ 1821 res = qemu_get_buffer(rp, buf, header_len); 1822 if (res != header_len) { 1823 error_report("RP: Failed reading data for message 0x%04x" 1824 " read %d expected %d", 1825 header_type, res, header_len); 1826 mark_source_rp_bad(ms); 1827 goto out; 1828 } 1829 1830 /* OK, we have the message and the data */ 1831 switch (header_type) { 1832 case MIG_RP_MSG_SHUT: 1833 sibling_error = ldl_be_p(buf); 1834 trace_source_return_path_thread_shut(sibling_error); 1835 if (sibling_error) { 1836 error_report("RP: Sibling indicated error %d", sibling_error); 1837 mark_source_rp_bad(ms); 1838 } 1839 /* 1840 * We'll let the main thread deal with closing the RP 1841 * we could do a shutdown(2) on it, but we're the only user 1842 * anyway, so there's nothing gained. 1843 */ 1844 goto out; 1845 1846 case MIG_RP_MSG_PONG: 1847 tmp32 = ldl_be_p(buf); 1848 trace_source_return_path_thread_pong(tmp32); 1849 break; 1850 1851 case MIG_RP_MSG_REQ_PAGES: 1852 start = ldq_be_p(buf); 1853 len = ldl_be_p(buf + 8); 1854 migrate_handle_rp_req_pages(ms, NULL, start, len); 1855 break; 1856 1857 case MIG_RP_MSG_REQ_PAGES_ID: 1858 expected_len = 12 + 1; /* header + termination */ 1859 1860 if (header_len >= expected_len) { 1861 start = ldq_be_p(buf); 1862 len = ldl_be_p(buf + 8); 1863 /* Now we expect an idstr */ 1864 tmp32 = buf[12]; /* Length of the following idstr */ 1865 buf[13 + tmp32] = '\0'; 1866 expected_len += tmp32; 1867 } 1868 if (header_len != expected_len) { 1869 error_report("RP: Req_Page_id with length %d expecting %zd", 1870 header_len, expected_len); 1871 mark_source_rp_bad(ms); 1872 goto out; 1873 } 1874 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len); 1875 break; 1876 1877 default: 1878 break; 1879 } 1880 } 1881 if (qemu_file_get_error(rp)) { 1882 trace_source_return_path_thread_bad_end(); 1883 mark_source_rp_bad(ms); 1884 } 1885 1886 trace_source_return_path_thread_end(); 1887 out: 1888 ms->rp_state.from_dst_file = NULL; 1889 qemu_fclose(rp); 1890 return NULL; 1891 } 1892 1893 static int open_return_path_on_source(MigrationState *ms) 1894 { 1895 1896 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file); 1897 if (!ms->rp_state.from_dst_file) { 1898 return -1; 1899 } 1900 1901 trace_open_return_path_on_source(); 1902 qemu_thread_create(&ms->rp_state.rp_thread, "return path", 1903 source_return_path_thread, ms, QEMU_THREAD_JOINABLE); 1904 1905 trace_open_return_path_on_source_continue(); 1906 1907 return 0; 1908 } 1909 1910 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */ 1911 static int await_return_path_close_on_source(MigrationState *ms) 1912 { 1913 /* 1914 * If this is a normal exit then the destination will send a SHUT and the 1915 * rp_thread will exit, however if there's an error we need to cause 1916 * it to exit. 1917 */ 1918 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) { 1919 /* 1920 * shutdown(2), if we have it, will cause it to unblock if it's stuck 1921 * waiting for the destination. 1922 */ 1923 qemu_file_shutdown(ms->rp_state.from_dst_file); 1924 mark_source_rp_bad(ms); 1925 } 1926 trace_await_return_path_close_on_source_joining(); 1927 qemu_thread_join(&ms->rp_state.rp_thread); 1928 trace_await_return_path_close_on_source_close(); 1929 return ms->rp_state.error; 1930 } 1931 1932 /* 1933 * Switch from normal iteration to postcopy 1934 * Returns non-0 on error 1935 */ 1936 static int postcopy_start(MigrationState *ms) 1937 { 1938 int ret; 1939 QIOChannelBuffer *bioc; 1940 QEMUFile *fb; 1941 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 1942 bool restart_block = false; 1943 int cur_state = MIGRATION_STATUS_ACTIVE; 1944 if (!migrate_pause_before_switchover()) { 1945 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE, 1946 MIGRATION_STATUS_POSTCOPY_ACTIVE); 1947 } 1948 1949 trace_postcopy_start(); 1950 qemu_mutex_lock_iothread(); 1951 trace_postcopy_start_set_run(); 1952 1953 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER); 1954 global_state_store(); 1955 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE); 1956 if (ret < 0) { 1957 goto fail; 1958 } 1959 1960 ret = migration_maybe_pause(ms, &cur_state, 1961 MIGRATION_STATUS_POSTCOPY_ACTIVE); 1962 if (ret < 0) { 1963 goto fail; 1964 } 1965 1966 ret = bdrv_inactivate_all(); 1967 if (ret < 0) { 1968 goto fail; 1969 } 1970 restart_block = true; 1971 1972 /* 1973 * Cause any non-postcopiable, but iterative devices to 1974 * send out their final data. 1975 */ 1976 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false); 1977 1978 /* 1979 * in Finish migrate and with the io-lock held everything should 1980 * be quiet, but we've potentially still got dirty pages and we 1981 * need to tell the destination to throw any pages it's already received 1982 * that are dirty 1983 */ 1984 if (migrate_postcopy_ram()) { 1985 if (ram_postcopy_send_discard_bitmap(ms)) { 1986 error_report("postcopy send discard bitmap failed"); 1987 goto fail; 1988 } 1989 } 1990 1991 /* 1992 * send rest of state - note things that are doing postcopy 1993 * will notice we're in POSTCOPY_ACTIVE and not actually 1994 * wrap their state up here 1995 */ 1996 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX); 1997 if (migrate_postcopy_ram()) { 1998 /* Ping just for debugging, helps line traces up */ 1999 qemu_savevm_send_ping(ms->to_dst_file, 2); 2000 } 2001 2002 /* 2003 * While loading the device state we may trigger page transfer 2004 * requests and the fd must be free to process those, and thus 2005 * the destination must read the whole device state off the fd before 2006 * it starts processing it. Unfortunately the ad-hoc migration format 2007 * doesn't allow the destination to know the size to read without fully 2008 * parsing it through each devices load-state code (especially the open 2009 * coded devices that use get/put). 2010 * So we wrap the device state up in a package with a length at the start; 2011 * to do this we use a qemu_buf to hold the whole of the device state. 2012 */ 2013 bioc = qio_channel_buffer_new(4096); 2014 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer"); 2015 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc)); 2016 object_unref(OBJECT(bioc)); 2017 2018 /* 2019 * Make sure the receiver can get incoming pages before we send the rest 2020 * of the state 2021 */ 2022 qemu_savevm_send_postcopy_listen(fb); 2023 2024 qemu_savevm_state_complete_precopy(fb, false, false); 2025 if (migrate_postcopy_ram()) { 2026 qemu_savevm_send_ping(fb, 3); 2027 } 2028 2029 qemu_savevm_send_postcopy_run(fb); 2030 2031 /* <><> end of stuff going into the package */ 2032 2033 /* Last point of recovery; as soon as we send the package the destination 2034 * can open devices and potentially start running. 2035 * Lets just check again we've not got any errors. 2036 */ 2037 ret = qemu_file_get_error(ms->to_dst_file); 2038 if (ret) { 2039 error_report("postcopy_start: Migration stream errored (pre package)"); 2040 goto fail_closefb; 2041 } 2042 2043 restart_block = false; 2044 2045 /* Now send that blob */ 2046 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) { 2047 goto fail_closefb; 2048 } 2049 qemu_fclose(fb); 2050 2051 /* Send a notify to give a chance for anything that needs to happen 2052 * at the transition to postcopy and after the device state; in particular 2053 * spice needs to trigger a transition now 2054 */ 2055 ms->postcopy_after_devices = true; 2056 notifier_list_notify(&migration_state_notifiers, ms); 2057 2058 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop; 2059 2060 qemu_mutex_unlock_iothread(); 2061 2062 if (migrate_postcopy_ram()) { 2063 /* 2064 * Although this ping is just for debug, it could potentially be 2065 * used for getting a better measurement of downtime at the source. 2066 */ 2067 qemu_savevm_send_ping(ms->to_dst_file, 4); 2068 } 2069 2070 if (migrate_release_ram()) { 2071 ram_postcopy_migrated_memory_release(ms); 2072 } 2073 2074 ret = qemu_file_get_error(ms->to_dst_file); 2075 if (ret) { 2076 error_report("postcopy_start: Migration stream errored"); 2077 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE, 2078 MIGRATION_STATUS_FAILED); 2079 } 2080 2081 return ret; 2082 2083 fail_closefb: 2084 qemu_fclose(fb); 2085 fail: 2086 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE, 2087 MIGRATION_STATUS_FAILED); 2088 if (restart_block) { 2089 /* A failure happened early enough that we know the destination hasn't 2090 * accessed block devices, so we're safe to recover. 2091 */ 2092 Error *local_err = NULL; 2093 2094 bdrv_invalidate_cache_all(&local_err); 2095 if (local_err) { 2096 error_report_err(local_err); 2097 } 2098 } 2099 qemu_mutex_unlock_iothread(); 2100 return -1; 2101 } 2102 2103 /** 2104 * migration_maybe_pause: Pause if required to by 2105 * migrate_pause_before_switchover called with the iothread locked 2106 * Returns: 0 on success 2107 */ 2108 static int migration_maybe_pause(MigrationState *s, 2109 int *current_active_state, 2110 int new_state) 2111 { 2112 if (!migrate_pause_before_switchover()) { 2113 return 0; 2114 } 2115 2116 /* Since leaving this state is not atomic with posting the semaphore 2117 * it's possible that someone could have issued multiple migrate_continue 2118 * and the semaphore is incorrectly positive at this point; 2119 * the docs say it's undefined to reinit a semaphore that's already 2120 * init'd, so use timedwait to eat up any existing posts. 2121 */ 2122 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) { 2123 /* This block intentionally left blank */ 2124 } 2125 2126 qemu_mutex_unlock_iothread(); 2127 migrate_set_state(&s->state, *current_active_state, 2128 MIGRATION_STATUS_PRE_SWITCHOVER); 2129 qemu_sem_wait(&s->pause_sem); 2130 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER, 2131 new_state); 2132 *current_active_state = new_state; 2133 qemu_mutex_lock_iothread(); 2134 2135 return s->state == new_state ? 0 : -EINVAL; 2136 } 2137 2138 /** 2139 * migration_completion: Used by migration_thread when there's not much left. 2140 * The caller 'breaks' the loop when this returns. 2141 * 2142 * @s: Current migration state 2143 */ 2144 static void migration_completion(MigrationState *s) 2145 { 2146 int ret; 2147 int current_active_state = s->state; 2148 2149 if (s->state == MIGRATION_STATUS_ACTIVE) { 2150 qemu_mutex_lock_iothread(); 2151 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2152 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER); 2153 s->vm_was_running = runstate_is_running(); 2154 ret = global_state_store(); 2155 2156 if (!ret) { 2157 bool inactivate = !migrate_colo_enabled(); 2158 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE); 2159 if (ret >= 0) { 2160 ret = migration_maybe_pause(s, ¤t_active_state, 2161 MIGRATION_STATUS_DEVICE); 2162 } 2163 if (ret >= 0) { 2164 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX); 2165 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false, 2166 inactivate); 2167 } 2168 if (inactivate && ret >= 0) { 2169 s->block_inactive = true; 2170 } 2171 } 2172 qemu_mutex_unlock_iothread(); 2173 2174 if (ret < 0) { 2175 goto fail; 2176 } 2177 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 2178 trace_migration_completion_postcopy_end(); 2179 2180 qemu_savevm_state_complete_postcopy(s->to_dst_file); 2181 trace_migration_completion_postcopy_end_after_complete(); 2182 } 2183 2184 /* 2185 * If rp was opened we must clean up the thread before 2186 * cleaning everything else up (since if there are no failures 2187 * it will wait for the destination to send it's status in 2188 * a SHUT command). 2189 */ 2190 if (s->rp_state.from_dst_file) { 2191 int rp_error; 2192 trace_migration_return_path_end_before(); 2193 rp_error = await_return_path_close_on_source(s); 2194 trace_migration_return_path_end_after(rp_error); 2195 if (rp_error) { 2196 goto fail_invalidate; 2197 } 2198 } 2199 2200 if (qemu_file_get_error(s->to_dst_file)) { 2201 trace_migration_completion_file_err(); 2202 goto fail_invalidate; 2203 } 2204 2205 if (!migrate_colo_enabled()) { 2206 migrate_set_state(&s->state, current_active_state, 2207 MIGRATION_STATUS_COMPLETED); 2208 } 2209 2210 return; 2211 2212 fail_invalidate: 2213 /* If not doing postcopy, vm_start() will be called: let's regain 2214 * control on images. 2215 */ 2216 if (s->state == MIGRATION_STATUS_ACTIVE || 2217 s->state == MIGRATION_STATUS_DEVICE) { 2218 Error *local_err = NULL; 2219 2220 qemu_mutex_lock_iothread(); 2221 bdrv_invalidate_cache_all(&local_err); 2222 if (local_err) { 2223 error_report_err(local_err); 2224 } else { 2225 s->block_inactive = false; 2226 } 2227 qemu_mutex_unlock_iothread(); 2228 } 2229 2230 fail: 2231 migrate_set_state(&s->state, current_active_state, 2232 MIGRATION_STATUS_FAILED); 2233 } 2234 2235 bool migrate_colo_enabled(void) 2236 { 2237 MigrationState *s = migrate_get_current(); 2238 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO]; 2239 } 2240 2241 static void migration_calculate_complete(MigrationState *s) 2242 { 2243 uint64_t bytes = qemu_ftell(s->to_dst_file); 2244 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2245 2246 s->total_time = end_time - s->start_time; 2247 if (!s->downtime) { 2248 /* 2249 * It's still not set, so we are precopy migration. For 2250 * postcopy, downtime is calculated during postcopy_start(). 2251 */ 2252 s->downtime = end_time - s->downtime_start; 2253 } 2254 2255 if (s->total_time) { 2256 s->mbps = ((double) bytes * 8.0) / s->total_time / 1000; 2257 } 2258 } 2259 2260 static void migration_update_counters(MigrationState *s, 2261 int64_t current_time) 2262 { 2263 uint64_t transferred, time_spent; 2264 double bandwidth; 2265 2266 if (current_time < s->iteration_start_time + BUFFER_DELAY) { 2267 return; 2268 } 2269 2270 transferred = qemu_ftell(s->to_dst_file) - s->iteration_initial_bytes; 2271 time_spent = current_time - s->iteration_start_time; 2272 bandwidth = (double)transferred / time_spent; 2273 s->threshold_size = bandwidth * s->parameters.downtime_limit; 2274 2275 s->mbps = (((double) transferred * 8.0) / 2276 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0; 2277 2278 /* 2279 * if we haven't sent anything, we don't want to 2280 * recalculate. 10000 is a small enough number for our purposes 2281 */ 2282 if (ram_counters.dirty_pages_rate && transferred > 10000) { 2283 s->expected_downtime = ram_counters.dirty_pages_rate * 2284 qemu_target_page_size() / bandwidth; 2285 } 2286 2287 qemu_file_reset_rate_limit(s->to_dst_file); 2288 2289 s->iteration_start_time = current_time; 2290 s->iteration_initial_bytes = qemu_ftell(s->to_dst_file); 2291 2292 trace_migrate_transferred(transferred, time_spent, 2293 bandwidth, s->threshold_size); 2294 } 2295 2296 /* Migration thread iteration status */ 2297 typedef enum { 2298 MIG_ITERATE_RESUME, /* Resume current iteration */ 2299 MIG_ITERATE_SKIP, /* Skip current iteration */ 2300 MIG_ITERATE_BREAK, /* Break the loop */ 2301 } MigIterateState; 2302 2303 /* 2304 * Return true if continue to the next iteration directly, false 2305 * otherwise. 2306 */ 2307 static MigIterateState migration_iteration_run(MigrationState *s) 2308 { 2309 uint64_t pending_size, pend_pre, pend_compat, pend_post; 2310 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE; 2311 2312 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre, 2313 &pend_compat, &pend_post); 2314 pending_size = pend_pre + pend_compat + pend_post; 2315 2316 trace_migrate_pending(pending_size, s->threshold_size, 2317 pend_pre, pend_compat, pend_post); 2318 2319 if (pending_size && pending_size >= s->threshold_size) { 2320 /* Still a significant amount to transfer */ 2321 if (migrate_postcopy() && !in_postcopy && 2322 pend_pre <= s->threshold_size && 2323 atomic_read(&s->start_postcopy)) { 2324 if (postcopy_start(s)) { 2325 error_report("%s: postcopy failed to start", __func__); 2326 } 2327 return MIG_ITERATE_SKIP; 2328 } 2329 /* Just another iteration step */ 2330 qemu_savevm_state_iterate(s->to_dst_file, 2331 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE); 2332 } else { 2333 trace_migration_thread_low_pending(pending_size); 2334 migration_completion(s); 2335 return MIG_ITERATE_BREAK; 2336 } 2337 2338 return MIG_ITERATE_RESUME; 2339 } 2340 2341 static void migration_iteration_finish(MigrationState *s) 2342 { 2343 /* If we enabled cpu throttling for auto-converge, turn it off. */ 2344 cpu_throttle_stop(); 2345 2346 qemu_mutex_lock_iothread(); 2347 switch (s->state) { 2348 case MIGRATION_STATUS_COMPLETED: 2349 migration_calculate_complete(s); 2350 runstate_set(RUN_STATE_POSTMIGRATE); 2351 break; 2352 2353 case MIGRATION_STATUS_ACTIVE: 2354 /* 2355 * We should really assert here, but since it's during 2356 * migration, let's try to reduce the usage of assertions. 2357 */ 2358 if (!migrate_colo_enabled()) { 2359 error_report("%s: critical error: calling COLO code without " 2360 "COLO enabled", __func__); 2361 } 2362 migrate_start_colo_process(s); 2363 /* 2364 * Fixme: we will run VM in COLO no matter its old running state. 2365 * After exited COLO, we will keep running. 2366 */ 2367 s->vm_was_running = true; 2368 /* Fallthrough */ 2369 case MIGRATION_STATUS_FAILED: 2370 case MIGRATION_STATUS_CANCELLED: 2371 if (s->vm_was_running) { 2372 vm_start(); 2373 } else { 2374 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) { 2375 runstate_set(RUN_STATE_POSTMIGRATE); 2376 } 2377 } 2378 break; 2379 2380 default: 2381 /* Should not reach here, but if so, forgive the VM. */ 2382 error_report("%s: Unknown ending state %d", __func__, s->state); 2383 break; 2384 } 2385 qemu_bh_schedule(s->cleanup_bh); 2386 qemu_mutex_unlock_iothread(); 2387 } 2388 2389 /* 2390 * Master migration thread on the source VM. 2391 * It drives the migration and pumps the data down the outgoing channel. 2392 */ 2393 static void *migration_thread(void *opaque) 2394 { 2395 MigrationState *s = opaque; 2396 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST); 2397 2398 rcu_register_thread(); 2399 2400 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2401 2402 qemu_savevm_state_header(s->to_dst_file); 2403 2404 /* 2405 * If we opened the return path, we need to make sure dst has it 2406 * opened as well. 2407 */ 2408 if (s->rp_state.from_dst_file) { 2409 /* Now tell the dest that it should open its end so it can reply */ 2410 qemu_savevm_send_open_return_path(s->to_dst_file); 2411 2412 /* And do a ping that will make stuff easier to debug */ 2413 qemu_savevm_send_ping(s->to_dst_file, 1); 2414 } 2415 2416 if (migrate_postcopy()) { 2417 /* 2418 * Tell the destination that we *might* want to do postcopy later; 2419 * if the other end can't do postcopy it should fail now, nice and 2420 * early. 2421 */ 2422 qemu_savevm_send_postcopy_advise(s->to_dst_file); 2423 } 2424 2425 qemu_savevm_state_setup(s->to_dst_file); 2426 2427 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start; 2428 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 2429 MIGRATION_STATUS_ACTIVE); 2430 2431 trace_migration_thread_setup_complete(); 2432 2433 while (s->state == MIGRATION_STATUS_ACTIVE || 2434 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) { 2435 int64_t current_time; 2436 2437 if (!qemu_file_rate_limit(s->to_dst_file)) { 2438 MigIterateState iter_state = migration_iteration_run(s); 2439 if (iter_state == MIG_ITERATE_SKIP) { 2440 continue; 2441 } else if (iter_state == MIG_ITERATE_BREAK) { 2442 break; 2443 } 2444 } 2445 2446 if (qemu_file_get_error(s->to_dst_file)) { 2447 if (migration_is_setup_or_active(s->state)) { 2448 migrate_set_state(&s->state, s->state, 2449 MIGRATION_STATUS_FAILED); 2450 } 2451 trace_migration_thread_file_err(); 2452 break; 2453 } 2454 2455 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME); 2456 2457 migration_update_counters(s, current_time); 2458 2459 if (qemu_file_rate_limit(s->to_dst_file)) { 2460 /* usleep expects microseconds */ 2461 g_usleep((s->iteration_start_time + BUFFER_DELAY - 2462 current_time) * 1000); 2463 } 2464 } 2465 2466 trace_migration_thread_after_loop(); 2467 migration_iteration_finish(s); 2468 rcu_unregister_thread(); 2469 return NULL; 2470 } 2471 2472 void migrate_fd_connect(MigrationState *s, Error *error_in) 2473 { 2474 s->expected_downtime = s->parameters.downtime_limit; 2475 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s); 2476 if (error_in) { 2477 migrate_fd_error(s, error_in); 2478 migrate_fd_cleanup(s); 2479 return; 2480 } 2481 2482 qemu_file_set_blocking(s->to_dst_file, true); 2483 qemu_file_set_rate_limit(s->to_dst_file, 2484 s->parameters.max_bandwidth / XFER_LIMIT_RATIO); 2485 2486 /* Notify before starting migration thread */ 2487 notifier_list_notify(&migration_state_notifiers, s); 2488 2489 /* 2490 * Open the return path. For postcopy, it is used exclusively. For 2491 * precopy, only if user specified "return-path" capability would 2492 * QEMU uses the return path. 2493 */ 2494 if (migrate_postcopy_ram() || migrate_use_return_path()) { 2495 if (open_return_path_on_source(s)) { 2496 error_report("Unable to open return-path for postcopy"); 2497 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 2498 MIGRATION_STATUS_FAILED); 2499 migrate_fd_cleanup(s); 2500 return; 2501 } 2502 } 2503 2504 if (multifd_save_setup() != 0) { 2505 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP, 2506 MIGRATION_STATUS_FAILED); 2507 migrate_fd_cleanup(s); 2508 return; 2509 } 2510 qemu_thread_create(&s->thread, "live_migration", migration_thread, s, 2511 QEMU_THREAD_JOINABLE); 2512 s->migration_thread_running = true; 2513 } 2514 2515 void migration_global_dump(Monitor *mon) 2516 { 2517 MigrationState *ms = migrate_get_current(); 2518 2519 monitor_printf(mon, "globals:\n"); 2520 monitor_printf(mon, "store-global-state: %s\n", 2521 ms->store_global_state ? "on" : "off"); 2522 monitor_printf(mon, "only-migratable: %s\n", 2523 ms->only_migratable ? "on" : "off"); 2524 monitor_printf(mon, "send-configuration: %s\n", 2525 ms->send_configuration ? "on" : "off"); 2526 monitor_printf(mon, "send-section-footer: %s\n", 2527 ms->send_section_footer ? "on" : "off"); 2528 } 2529 2530 #define DEFINE_PROP_MIG_CAP(name, x) \ 2531 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false) 2532 2533 static Property migration_properties[] = { 2534 DEFINE_PROP_BOOL("store-global-state", MigrationState, 2535 store_global_state, true), 2536 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false), 2537 DEFINE_PROP_BOOL("send-configuration", MigrationState, 2538 send_configuration, true), 2539 DEFINE_PROP_BOOL("send-section-footer", MigrationState, 2540 send_section_footer, true), 2541 2542 /* Migration parameters */ 2543 DEFINE_PROP_UINT8("x-compress-level", MigrationState, 2544 parameters.compress_level, 2545 DEFAULT_MIGRATE_COMPRESS_LEVEL), 2546 DEFINE_PROP_UINT8("x-compress-threads", MigrationState, 2547 parameters.compress_threads, 2548 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT), 2549 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState, 2550 parameters.decompress_threads, 2551 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT), 2552 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState, 2553 parameters.cpu_throttle_initial, 2554 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL), 2555 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState, 2556 parameters.cpu_throttle_increment, 2557 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT), 2558 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState, 2559 parameters.max_bandwidth, MAX_THROTTLE), 2560 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState, 2561 parameters.downtime_limit, 2562 DEFAULT_MIGRATE_SET_DOWNTIME), 2563 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState, 2564 parameters.x_checkpoint_delay, 2565 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY), 2566 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState, 2567 parameters.x_multifd_channels, 2568 DEFAULT_MIGRATE_MULTIFD_CHANNELS), 2569 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState, 2570 parameters.x_multifd_page_count, 2571 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT), 2572 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState, 2573 parameters.xbzrle_cache_size, 2574 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE), 2575 2576 /* Migration capabilities */ 2577 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE), 2578 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL), 2579 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE), 2580 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS), 2581 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS), 2582 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS), 2583 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM), 2584 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO), 2585 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM), 2586 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK), 2587 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH), 2588 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD), 2589 2590 DEFINE_PROP_END_OF_LIST(), 2591 }; 2592 2593 static void migration_class_init(ObjectClass *klass, void *data) 2594 { 2595 DeviceClass *dc = DEVICE_CLASS(klass); 2596 2597 dc->user_creatable = false; 2598 dc->props = migration_properties; 2599 } 2600 2601 static void migration_instance_finalize(Object *obj) 2602 { 2603 MigrationState *ms = MIGRATION_OBJ(obj); 2604 MigrationParameters *params = &ms->parameters; 2605 2606 qemu_mutex_destroy(&ms->error_mutex); 2607 g_free(params->tls_hostname); 2608 g_free(params->tls_creds); 2609 qemu_sem_destroy(&ms->pause_sem); 2610 error_free(ms->error); 2611 } 2612 2613 static void migration_instance_init(Object *obj) 2614 { 2615 MigrationState *ms = MIGRATION_OBJ(obj); 2616 MigrationParameters *params = &ms->parameters; 2617 2618 ms->state = MIGRATION_STATUS_NONE; 2619 ms->mbps = -1; 2620 qemu_sem_init(&ms->pause_sem, 0); 2621 qemu_mutex_init(&ms->error_mutex); 2622 2623 params->tls_hostname = g_strdup(""); 2624 params->tls_creds = g_strdup(""); 2625 2626 /* Set has_* up only for parameter checks */ 2627 params->has_compress_level = true; 2628 params->has_compress_threads = true; 2629 params->has_decompress_threads = true; 2630 params->has_cpu_throttle_initial = true; 2631 params->has_cpu_throttle_increment = true; 2632 params->has_max_bandwidth = true; 2633 params->has_downtime_limit = true; 2634 params->has_x_checkpoint_delay = true; 2635 params->has_block_incremental = true; 2636 params->has_x_multifd_channels = true; 2637 params->has_x_multifd_page_count = true; 2638 params->has_xbzrle_cache_size = true; 2639 } 2640 2641 /* 2642 * Return true if check pass, false otherwise. Error will be put 2643 * inside errp if provided. 2644 */ 2645 static bool migration_object_check(MigrationState *ms, Error **errp) 2646 { 2647 MigrationCapabilityStatusList *head = NULL; 2648 /* Assuming all off */ 2649 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret; 2650 int i; 2651 2652 if (!migrate_params_check(&ms->parameters, errp)) { 2653 return false; 2654 } 2655 2656 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) { 2657 if (ms->enabled_capabilities[i]) { 2658 head = migrate_cap_add(head, i, true); 2659 } 2660 } 2661 2662 ret = migrate_caps_check(cap_list, head, errp); 2663 2664 /* It works with head == NULL */ 2665 qapi_free_MigrationCapabilityStatusList(head); 2666 2667 return ret; 2668 } 2669 2670 static const TypeInfo migration_type = { 2671 .name = TYPE_MIGRATION, 2672 /* 2673 * NOTE: TYPE_MIGRATION is not really a device, as the object is 2674 * not created using qdev_create(), it is not attached to the qdev 2675 * device tree, and it is never realized. 2676 * 2677 * TODO: Make this TYPE_OBJECT once QOM provides something like 2678 * TYPE_DEVICE's "-global" properties. 2679 */ 2680 .parent = TYPE_DEVICE, 2681 .class_init = migration_class_init, 2682 .class_size = sizeof(MigrationClass), 2683 .instance_size = sizeof(MigrationState), 2684 .instance_init = migration_instance_init, 2685 .instance_finalize = migration_instance_finalize, 2686 }; 2687 2688 static void register_migration_types(void) 2689 { 2690 type_register_static(&migration_type); 2691 } 2692 2693 type_init(register_migration_types); 2694