target/ppc: Fix lxv/stxv MSR facility check
[qemu/ar7.git] / migration / migration.c
blobab21de2cadbf19067aa798de2441a447afe946d7
1 /*
2 * QEMU live migration
4 * Copyright IBM, Corp. 2008
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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.
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"
72 static NotifierList migration_state_notifiers =
73 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
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 ) */
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 */
87 MIG_RP_MSG_MAX
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 */
94 static MigrationState *current_migration;
95 static MigrationIncomingState *current_incoming;
97 static GSList *migration_blockers[MIG_MODE__MAX];
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);
106 static void migration_downtime_start(MigrationState *s)
108 trace_vmstate_downtime_checkpoint("src-downtime-start");
109 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
112 static void migration_downtime_end(MigrationState *s)
114 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
117 * If downtime already set, should mean that postcopy already set it,
118 * then that should be the real downtime already.
120 if (!s->downtime) {
121 s->downtime = now - s->downtime_start;
124 trace_vmstate_downtime_checkpoint("src-downtime-end");
127 static bool migration_needs_multiple_sockets(void)
129 return migrate_multifd() || migrate_postcopy_preempt();
132 static bool transport_supports_multi_channels(MigrationAddress *addr)
134 if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
135 SocketAddress *saddr = &addr->u.socket;
137 return saddr->type == SOCKET_ADDRESS_TYPE_INET ||
138 saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
139 saddr->type == SOCKET_ADDRESS_TYPE_VSOCK;
142 return false;
145 static bool
146 migration_channels_and_transport_compatible(MigrationAddress *addr,
147 Error **errp)
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;
155 return true;
158 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
160 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
162 return (a > b) - (a < b);
165 int migration_stop_vm(RunState state)
167 int ret = vm_stop_force_state(state);
169 trace_vmstate_downtime_checkpoint("src-vm-stopped");
171 return ret;
174 void migration_object_init(void)
176 /* This can only be called once. */
177 assert(!current_migration);
178 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
181 * Init the migrate incoming object as well no matter whether
182 * we'll use it or not.
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(&current_incoming->rp_mutex);
190 qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
191 qemu_event_init(&current_incoming->main_thread_load_event, false);
192 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
193 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
194 qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
195 qemu_sem_init(&current_incoming->postcopy_qemufile_dst_done, 0);
197 qemu_mutex_init(&current_incoming->page_request_mutex);
198 qemu_cond_init(&current_incoming->page_request_cond);
199 current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
201 migration_object_check(current_migration, &error_fatal);
203 blk_mig_init();
204 ram_mig_init();
205 dirty_bitmap_mig_init();
208 typedef struct {
209 QEMUBH *bh;
210 QEMUBHFunc *cb;
211 void *opaque;
212 } MigrationBH;
214 static void migration_bh_dispatch_bh(void *opaque)
216 MigrationState *s = migrate_get_current();
217 MigrationBH *migbh = opaque;
219 /* cleanup this BH */
220 qemu_bh_delete(migbh->bh);
221 migbh->bh = NULL;
223 /* dispatch the other one */
224 migbh->cb(migbh->opaque);
225 object_unref(OBJECT(s));
227 g_free(migbh);
230 void migration_bh_schedule(QEMUBHFunc *cb, void *opaque)
232 MigrationState *s = migrate_get_current();
233 MigrationBH *migbh = g_new0(MigrationBH, 1);
234 QEMUBH *bh = qemu_bh_new(migration_bh_dispatch_bh, migbh);
236 /* Store these to dispatch when the BH runs */
237 migbh->bh = bh;
238 migbh->cb = cb;
239 migbh->opaque = opaque;
242 * Ref the state for bh, because it may be called when
243 * there're already no other refs
245 object_ref(OBJECT(s));
246 qemu_bh_schedule(bh);
249 void migration_cancel(const Error *error)
251 if (error) {
252 migrate_set_error(current_migration, error);
254 if (migrate_dirty_limit()) {
255 qmp_cancel_vcpu_dirty_limit(false, -1, NULL);
257 migrate_fd_cancel(current_migration);
260 void migration_shutdown(void)
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.
267 colo_shutdown();
269 * Cancel the current migration - that will (eventually)
270 * stop the migration using this structure
272 migration_cancel(NULL);
273 object_unref(OBJECT(current_migration));
276 * Cancel outgoing migration of dirty bitmaps. It should
277 * at least unref used block nodes.
279 dirty_bitmap_mig_cancel_outgoing();
282 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
283 * are non-critical data, and their loss never considered as
284 * something serious.
286 dirty_bitmap_mig_cancel_incoming();
289 /* For outgoing */
290 MigrationState *migrate_get_current(void)
292 /* This can only be called after the object created. */
293 assert(current_migration);
294 return current_migration;
297 MigrationIncomingState *migration_incoming_get_current(void)
299 assert(current_incoming);
300 return current_incoming;
303 void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
305 if (mis->socket_address_list) {
306 qapi_free_SocketAddressList(mis->socket_address_list);
307 mis->socket_address_list = NULL;
310 if (mis->transport_cleanup) {
311 mis->transport_cleanup(mis->transport_data);
312 mis->transport_data = mis->transport_cleanup = NULL;
316 void migration_incoming_state_destroy(void)
318 struct MigrationIncomingState *mis = migration_incoming_get_current();
320 multifd_recv_cleanup();
321 compress_threads_load_cleanup();
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;
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;
335 if (mis->postcopy_remote_fds) {
336 g_array_free(mis->postcopy_remote_fds, TRUE);
337 mis->postcopy_remote_fds = NULL;
340 migration_incoming_transport_cleanup(mis);
341 qemu_event_reset(&mis->main_thread_load_event);
343 if (mis->page_requested) {
344 g_tree_destroy(mis->page_requested);
345 mis->page_requested = NULL;
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;
354 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
357 static void migrate_generate_event(int new_state)
359 if (migrate_events()) {
360 qapi_event_send_migration(new_state);
365 * Send a message on the return channel back to the source
366 * of the migration.
368 static int migrate_send_rp_message(MigrationIncomingState *mis,
369 enum mig_rp_message_type message_type,
370 uint16_t len, void *data)
372 int ret = 0;
374 trace_migrate_send_rp_message((int)message_type, len);
375 QEMU_LOCK_GUARD(&mis->rp_mutex);
378 * It's possible that the file handle got lost due to network
379 * failures.
381 if (!mis->to_src_file) {
382 ret = -EIO;
383 return ret;
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);
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
397 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
398 RAMBlock *rb, ram_addr_t start)
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;
407 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
408 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
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.
415 if (rb != mis->last_rb) {
416 mis->last_rb = rb;
418 rbname = qemu_ram_get_idstr(rb);
419 rbname_len = strlen(rbname);
421 assert(rbname_len < 256);
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;
431 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
434 int migrate_send_rp_req_pages(MigrationIncomingState *mis,
435 RAMBlock *rb, ram_addr_t start, uint64_t haddr)
437 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
438 bool received = false;
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)) {
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.
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);
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.
458 if (received) {
459 return 0;
462 return migrate_send_rp_message_req_pages(mis, rb, start);
465 static bool migration_colo_enabled;
466 bool migration_incoming_colo_enabled(void)
468 return migration_colo_enabled;
471 void migration_incoming_disable_colo(void)
473 ram_block_discard_disable(false);
474 migration_colo_enabled = false;
477 int migration_incoming_enable_colo(void)
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
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;
491 if (ram_block_discard_disable(true)) {
492 error_report("COLO: cannot disable RAM discard");
493 return -EBUSY;
495 migration_colo_enabled = true;
496 return 0;
499 void migrate_add_address(SocketAddress *address)
501 MigrationIncomingState *mis = migration_incoming_get_current();
503 QAPI_LIST_PREPEND(mis->socket_address_list,
504 QAPI_CLONE(SocketAddress, address));
507 bool migrate_uri_parse(const char *uri, MigrationChannel **channel,
508 Error **errp)
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;
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;
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;
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;
551 } else {
552 error_setg(errp, "unknown migration protocol: %s", uri);
553 return false;
556 val->channel_type = MIGRATION_CHANNEL_TYPE_MAIN;
557 val->addr = g_steal_pointer(&addr);
558 *channel = g_steal_pointer(&val);
559 return true;
562 static void qemu_start_incoming_migration(const char *uri, bool has_channels,
563 MigrationChannelList *channels,
564 Error **errp)
566 g_autoptr(MigrationChannel) channel = NULL;
567 MigrationAddress *addr = NULL;
568 MigrationIncomingState *mis = migration_incoming_get_current();
571 * Having preliminary checks for uri and channel
573 if (!uri == !channels) {
574 error_setg(errp, "need either 'uri' or 'channels' argument");
575 return;
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;
584 addr = channels->value->addr;
587 if (uri) {
588 /* caller uses the old URI syntax */
589 if (!migrate_uri_parse(uri, &channel, errp)) {
590 return;
592 addr = channel->addr;
595 /* transport mechanism not suitable for migration? */
596 if (!migration_channels_and_transport_compatible(addr, errp)) {
597 return;
600 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
601 MIGRATION_STATUS_SETUP);
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);
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;
618 if (migrate_xbzrle()) {
619 error_setg(errp, "RDMA and XBZRLE can't be used together");
620 return;
622 if (migrate_multifd()) {
623 error_setg(errp, "RDMA and multifd can't be used together");
624 return;
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);
637 static void process_incoming_migration_bh(void *opaque)
639 Error *local_err = NULL;
640 MigrationIncomingState *mis = opaque;
642 trace_vmstate_downtime_checkpoint("dst-precopy-bh-enter");
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.
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;
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.
667 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
669 trace_vmstate_downtime_checkpoint("dst-precopy-bh-announced");
671 multifd_recv_shutdown();
673 dirty_bitmap_mig_before_vm_start();
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);
682 } else if (migration_incoming_colo_enabled()) {
683 migration_incoming_disable_colo();
684 vm_start();
685 } else {
686 runstate_set(global_state_get_runstate());
688 trace_vmstate_downtime_checkpoint("dst-precopy-bh-vm-started");
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.
694 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
695 MIGRATION_STATUS_COMPLETED);
696 migration_incoming_state_destroy();
699 static void coroutine_fn
700 process_incoming_migration_co(void *opaque)
702 MigrationIncomingState *mis = migration_incoming_get_current();
703 PostcopyState ps;
704 int ret;
706 assert(mis->from_src_file);
708 if (compress_threads_load_setup(mis->from_src_file)) {
709 error_report("Failed to setup decompress threads");
710 goto fail;
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);
718 mis->loadvm_co = qemu_coroutine_self();
719 ret = qemu_loadvm_state(mis->from_src_file);
720 mis->loadvm_co = NULL;
722 trace_vmstate_downtime_checkpoint("dst-precopy-loadvm-completed");
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) {
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.
733 postcopy_ram_incoming_cleanup(mis);
734 } else if (ret >= 0) {
736 * Postcopy was started, cleanup should happen at the end of the
737 * postcopy thread.
739 trace_process_incoming_migration_co_postcopy_end_main();
740 return;
742 /* Else if something went wrong then just fall out of the normal exit */
745 if (ret < 0) {
746 MigrationState *s = migrate_get_current();
748 if (migrate_has_error(s)) {
749 WITH_QEMU_LOCK_GUARD(&s->error_mutex) {
750 error_report_err(s->error);
753 error_report("load of migration failed: %s", strerror(-ret));
754 goto fail;
757 if (colo_incoming_co() < 0) {
758 goto fail;
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);
768 multifd_recv_cleanup();
769 compress_threads_load_cleanup();
771 exit(EXIT_FAILURE);
775 * migration_incoming_setup: Setup incoming migration
776 * @f: file for main migration channel
778 static void migration_incoming_setup(QEMUFile *f)
780 MigrationIncomingState *mis = migration_incoming_get_current();
782 if (!mis->from_src_file) {
783 mis->from_src_file = f;
785 qemu_file_set_blocking(f, false);
788 void migration_incoming_process(void)
790 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
791 qemu_coroutine_enter(co);
794 /* Returns true if recovered from a paused migration, otherwise false */
795 static bool postcopy_try_recover(void)
797 MigrationIncomingState *mis = migration_incoming_get_current();
799 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
800 /* Resumed from a paused postcopy migration */
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);
807 /* Re-configure the return path */
808 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
810 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
811 MIGRATION_STATUS_POSTCOPY_RECOVER);
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.
820 qemu_sem_post(&mis->postcopy_pause_sem_dst);
821 return true;
824 return false;
827 void migration_fd_process_incoming(QEMUFile *f)
829 migration_incoming_setup(f);
830 if (postcopy_try_recover()) {
831 return;
833 migration_incoming_process();
837 * Returns true when we want to start a new incoming migration process,
838 * false otherwise.
840 static bool migration_should_start_incoming(bool main_channel)
842 /* Multifd doesn't start unless all channels are established */
843 if (migrate_multifd()) {
844 return migration_has_all_channels();
847 /* Preempt channel only starts when the main channel is created */
848 if (migrate_postcopy_preempt()) {
849 return main_channel;
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.
857 assert(main_channel);
858 return true;
861 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
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;
870 if (migrate_multifd() && !migrate_postcopy_ram() &&
871 qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) {
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.
882 ret = migration_channel_read_peek(ioc, (void *)&channel_magic,
883 sizeof(channel_magic), errp);
885 if (ret != 0) {
886 return;
889 default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC));
890 } else {
891 default_channel = !mis->from_src_file;
894 if (multifd_recv_setup(errp) != 0) {
895 return;
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);
911 if (local_err) {
912 error_propagate(errp, local_err);
913 return;
917 if (migration_should_start_incoming(default_channel)) {
918 /* If it's a recovery, we're done */
919 if (postcopy_try_recover()) {
920 return;
922 migration_incoming_process();
927 * @migration_has_all_channels: We have received all channels that we need
929 * Returns true when we have got connections to all the channels that
930 * we need for migration.
932 bool migration_has_all_channels(void)
934 MigrationIncomingState *mis = migration_incoming_get_current();
936 if (!mis->from_src_file) {
937 return false;
940 if (migrate_multifd()) {
941 return multifd_recv_all_channels_created();
944 if (migrate_postcopy_preempt()) {
945 return mis->postcopy_qemufile_dst != NULL;
948 return true;
951 int migrate_send_rp_switchover_ack(MigrationIncomingState *mis)
953 return migrate_send_rp_message(mis, MIG_RP_MSG_SWITCHOVER_ACK, 0, NULL);
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.
961 void migrate_send_rp_shut(MigrationIncomingState *mis,
962 uint32_t value)
964 uint32_t buf;
966 buf = cpu_to_be32(value);
967 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
971 * Send a 'PONG' message on the return channel with the given value
972 * (normally in response to a 'PING')
974 void migrate_send_rp_pong(MigrationIncomingState *mis,
975 uint32_t value)
977 uint32_t buf;
979 buf = cpu_to_be32(value);
980 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
983 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
984 char *block_name)
986 char buf[512];
987 int len;
988 int64_t res;
991 * First, we send the header part. It contains only the len of
992 * idstr, and the idstr itself.
994 len = strlen(block_name);
995 buf[0] = len;
996 memcpy(buf + 1, block_name, len);
998 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
999 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
1000 __func__);
1001 return;
1004 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
1007 * Next, we dump the received bitmap to the stream.
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.
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);
1019 trace_migrate_send_rp_recv_bitmap(block_name, res);
1022 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
1024 uint32_t buf;
1026 buf = cpu_to_be32(value);
1027 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
1031 * Return true if we're already in the middle of a migration
1032 * (i.e. any of the active or setup states)
1034 bool migration_is_setup_or_active(int state)
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;
1048 default:
1049 return false;
1054 bool migration_is_running(int state)
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;
1068 default:
1069 return false;
1074 static bool migrate_show_downtime(MigrationState *s)
1076 return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy();
1079 static void populate_time_info(MigrationInfo *info, MigrationState *s)
1081 info->has_status = true;
1082 info->has_setup_time = true;
1083 info->setup_time = s->setup_time;
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;
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;
1103 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
1105 size_t page_size = qemu_target_page_size();
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);
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;
1140 populate_compress(info);
1142 if (cpu_throttle_active()) {
1143 info->has_cpu_throttle_percentage = true;
1144 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
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);
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();
1158 info->has_dirty_limit_ring_full_time = true;
1159 info->dirty_limit_ring_full_time = dirtylimit_ring_full_time();
1163 static void populate_disk_info(MigrationInfo *info)
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();
1173 static void fill_source_migration_info(MigrationInfo *info)
1175 MigrationState *s = migrate_get_current();
1176 int state = qatomic_read(&s->state);
1177 GSList *cur_blocker = migration_blockers[migrate_mode()];
1179 info->blocked_reasons = NULL;
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.
1187 qemu_savevm_non_migratable_list(&info->blocked_reasons);
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);
1194 info->has_blocked_reasons = info->blocked_reasons != NULL;
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;
1237 info->status = state;
1239 QEMU_LOCK_GUARD(&s->error_mutex);
1240 if (s->error) {
1241 info->error_desc = g_strdup(error_get_pretty(s->error));
1245 static void fill_destination_migration_info(MigrationInfo *info)
1247 MigrationIncomingState *mis = migration_incoming_get_current();
1249 if (mis->socket_address_list) {
1250 info->has_socket_address = true;
1251 info->socket_address =
1252 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
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;
1274 info->status = mis->state;
1277 MigrationInfo *qmp_query_migrate(Error **errp)
1279 MigrationInfo *info = g_malloc0(sizeof(*info));
1281 fill_destination_migration_info(info);
1282 fill_source_migration_info(info);
1284 return info;
1287 void qmp_migrate_start_postcopy(Error **errp)
1289 MigrationState *s = migrate_get_current();
1291 if (!migrate_postcopy()) {
1292 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1293 " the start of migration");
1294 return;
1297 if (s->state == MIGRATION_STATUS_NONE) {
1298 error_setg(errp, "Postcopy must be started after migration has been"
1299 " started");
1300 return;
1303 * we don't error if migration has finished since that would be racy
1304 * with issuing this command.
1306 qatomic_set(&s->start_postcopy, true);
1309 /* shared migration helpers */
1311 void migrate_set_state(int *state, int old_state, int new_state)
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);
1320 static void migrate_fd_cleanup(MigrationState *s)
1322 g_free(s->hostname);
1323 s->hostname = NULL;
1324 json_writer_free(s->vmdesc);
1325 s->vmdesc = NULL;
1327 qemu_savevm_state_cleanup();
1329 if (s->to_dst_file) {
1330 QEMUFile *tmp;
1332 trace_migrate_fd_cleanup();
1333 bql_unlock();
1334 if (s->migration_thread_running) {
1335 qemu_thread_join(&s->thread);
1336 s->migration_thread_running = false;
1338 bql_lock();
1340 multifd_send_shutdown();
1341 qemu_mutex_lock(&s->qemu_file_lock);
1342 tmp = s->to_dst_file;
1343 s->to_dst_file = NULL;
1344 qemu_mutex_unlock(&s->qemu_file_lock);
1346 * Close the file handle without the lock to make sure the
1347 * critical section won't block for long.
1349 migration_ioc_unregister_yank_from_file(tmp);
1350 qemu_fclose(tmp);
1354 * We already cleaned up to_dst_file, so errors from the return
1355 * path might be due to that, ignore them.
1357 close_return_path_on_source(s);
1359 assert(!migration_is_active(s));
1361 if (s->state == MIGRATION_STATUS_CANCELLING) {
1362 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1363 MIGRATION_STATUS_CANCELLED);
1366 if (s->error) {
1367 /* It is used on info migrate. We can't free it */
1368 error_report_err(error_copy(s->error));
1370 migration_call_notifiers(s);
1371 block_cleanup_parameters();
1372 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1375 static void migrate_fd_cleanup_bh(void *opaque)
1377 migrate_fd_cleanup(opaque);
1380 void migrate_set_error(MigrationState *s, const Error *error)
1382 QEMU_LOCK_GUARD(&s->error_mutex);
1383 if (!s->error) {
1384 s->error = error_copy(error);
1388 bool migrate_has_error(MigrationState *s)
1390 /* The lock is not helpful here, but still follow the rule */
1391 QEMU_LOCK_GUARD(&s->error_mutex);
1392 return qatomic_read(&s->error);
1395 static void migrate_error_free(MigrationState *s)
1397 QEMU_LOCK_GUARD(&s->error_mutex);
1398 if (s->error) {
1399 error_free(s->error);
1400 s->error = NULL;
1404 static void migrate_fd_error(MigrationState *s, const Error *error)
1406 trace_migrate_fd_error(error_get_pretty(error));
1407 assert(s->to_dst_file == NULL);
1408 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1409 MIGRATION_STATUS_FAILED);
1410 migrate_set_error(s, error);
1413 static void migrate_fd_cancel(MigrationState *s)
1415 int old_state ;
1417 trace_migrate_fd_cancel();
1419 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1420 if (s->rp_state.from_dst_file) {
1421 /* shutdown the rp socket, so causing the rp thread to shutdown */
1422 qemu_file_shutdown(s->rp_state.from_dst_file);
1426 do {
1427 old_state = s->state;
1428 if (!migration_is_running(old_state)) {
1429 break;
1431 /* If the migration is paused, kick it out of the pause */
1432 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1433 qemu_sem_post(&s->pause_sem);
1435 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1436 } while (s->state != MIGRATION_STATUS_CANCELLING);
1439 * If we're unlucky the migration code might be stuck somewhere in a
1440 * send/write while the network has failed and is waiting to timeout;
1441 * if we've got shutdown(2) available then we can force it to quit.
1443 if (s->state == MIGRATION_STATUS_CANCELLING) {
1444 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1445 if (s->to_dst_file) {
1446 qemu_file_shutdown(s->to_dst_file);
1450 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1451 Error *local_err = NULL;
1453 bdrv_activate_all(&local_err);
1454 if (local_err) {
1455 error_report_err(local_err);
1456 } else {
1457 s->block_inactive = false;
1462 void migration_add_notifier(Notifier *notify,
1463 void (*func)(Notifier *notifier, void *data))
1465 notify->notify = func;
1466 notifier_list_add(&migration_state_notifiers, notify);
1469 void migration_remove_notifier(Notifier *notify)
1471 if (notify->notify) {
1472 notifier_remove(notify);
1473 notify->notify = NULL;
1477 void migration_call_notifiers(MigrationState *s)
1479 notifier_list_notify(&migration_state_notifiers, s);
1482 bool migration_in_setup(MigrationState *s)
1484 return s->state == MIGRATION_STATUS_SETUP;
1487 bool migration_has_finished(MigrationState *s)
1489 return s->state == MIGRATION_STATUS_COMPLETED;
1492 bool migration_has_failed(MigrationState *s)
1494 return (s->state == MIGRATION_STATUS_CANCELLED ||
1495 s->state == MIGRATION_STATUS_FAILED);
1498 bool migration_in_postcopy(void)
1500 MigrationState *s = migrate_get_current();
1502 switch (s->state) {
1503 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1504 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1505 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1506 return true;
1507 default:
1508 return false;
1512 bool migration_postcopy_is_alive(int state)
1514 switch (state) {
1515 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1516 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1517 return true;
1518 default:
1519 return false;
1523 bool migration_in_postcopy_after_devices(MigrationState *s)
1525 return migration_in_postcopy() && s->postcopy_after_devices;
1528 bool migration_in_incoming_postcopy(void)
1530 PostcopyState ps = postcopy_state_get();
1532 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
1535 bool migration_incoming_postcopy_advised(void)
1537 PostcopyState ps = postcopy_state_get();
1539 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
1542 bool migration_in_bg_snapshot(void)
1544 MigrationState *s = migrate_get_current();
1546 return migrate_background_snapshot() &&
1547 migration_is_setup_or_active(s->state);
1550 bool migration_is_idle(void)
1552 MigrationState *s = current_migration;
1554 if (!s) {
1555 return true;
1558 switch (s->state) {
1559 case MIGRATION_STATUS_NONE:
1560 case MIGRATION_STATUS_CANCELLED:
1561 case MIGRATION_STATUS_COMPLETED:
1562 case MIGRATION_STATUS_FAILED:
1563 return true;
1564 case MIGRATION_STATUS_SETUP:
1565 case MIGRATION_STATUS_CANCELLING:
1566 case MIGRATION_STATUS_ACTIVE:
1567 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1568 case MIGRATION_STATUS_COLO:
1569 case MIGRATION_STATUS_PRE_SWITCHOVER:
1570 case MIGRATION_STATUS_DEVICE:
1571 case MIGRATION_STATUS_WAIT_UNPLUG:
1572 return false;
1573 case MIGRATION_STATUS__MAX:
1574 g_assert_not_reached();
1577 return false;
1580 bool migration_is_active(MigrationState *s)
1582 return (s->state == MIGRATION_STATUS_ACTIVE ||
1583 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1586 int migrate_init(MigrationState *s, Error **errp)
1588 int ret;
1590 ret = qemu_savevm_state_prepare(errp);
1591 if (ret) {
1592 return ret;
1596 * Reinitialise all migration state, except
1597 * parameters/capabilities that the user set, and
1598 * locks.
1600 s->to_dst_file = NULL;
1601 s->state = MIGRATION_STATUS_NONE;
1602 s->rp_state.from_dst_file = NULL;
1603 s->mbps = 0.0;
1604 s->pages_per_second = 0.0;
1605 s->downtime = 0;
1606 s->expected_downtime = 0;
1607 s->setup_time = 0;
1608 s->start_postcopy = false;
1609 s->postcopy_after_devices = false;
1610 s->migration_thread_running = false;
1611 error_free(s->error);
1612 s->error = NULL;
1613 s->vmdesc = NULL;
1615 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1617 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1618 s->total_time = 0;
1619 s->vm_old_state = -1;
1620 s->iteration_initial_bytes = 0;
1621 s->threshold_size = 0;
1622 s->switchover_acked = false;
1623 s->rdma_migration = false;
1625 * set mig_stats memory to zero for a new migration
1627 memset(&mig_stats, 0, sizeof(mig_stats));
1628 migration_reset_vfio_bytes_transferred();
1630 return 0;
1633 static bool is_busy(Error **reasonp, Error **errp)
1635 ERRP_GUARD();
1637 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1638 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
1639 error_propagate_prepend(errp, *reasonp,
1640 "disallowing migration blocker "
1641 "(migration/snapshot in progress) for: ");
1642 *reasonp = NULL;
1643 return true;
1645 return false;
1648 static bool is_only_migratable(Error **reasonp, Error **errp, int modes)
1650 ERRP_GUARD();
1652 if (only_migratable && (modes & BIT(MIG_MODE_NORMAL))) {
1653 error_propagate_prepend(errp, *reasonp,
1654 "disallowing migration blocker "
1655 "(--only-migratable) for: ");
1656 *reasonp = NULL;
1657 return true;
1659 return false;
1662 static int get_modes(MigMode mode, va_list ap)
1664 int modes = 0;
1666 while (mode != -1 && mode != MIG_MODE_ALL) {
1667 assert(mode >= MIG_MODE_NORMAL && mode < MIG_MODE__MAX);
1668 modes |= BIT(mode);
1669 mode = va_arg(ap, MigMode);
1671 if (mode == MIG_MODE_ALL) {
1672 modes = BIT(MIG_MODE__MAX) - 1;
1674 return modes;
1677 static int add_blockers(Error **reasonp, Error **errp, int modes)
1679 for (MigMode mode = 0; mode < MIG_MODE__MAX; mode++) {
1680 if (modes & BIT(mode)) {
1681 migration_blockers[mode] = g_slist_prepend(migration_blockers[mode],
1682 *reasonp);
1685 return 0;
1688 int migrate_add_blocker(Error **reasonp, Error **errp)
1690 return migrate_add_blocker_modes(reasonp, errp, MIG_MODE_ALL);
1693 int migrate_add_blocker_normal(Error **reasonp, Error **errp)
1695 return migrate_add_blocker_modes(reasonp, errp, MIG_MODE_NORMAL, -1);
1698 int migrate_add_blocker_modes(Error **reasonp, Error **errp, MigMode mode, ...)
1700 int modes;
1701 va_list ap;
1703 va_start(ap, mode);
1704 modes = get_modes(mode, ap);
1705 va_end(ap);
1707 if (is_only_migratable(reasonp, errp, modes)) {
1708 return -EACCES;
1709 } else if (is_busy(reasonp, errp)) {
1710 return -EBUSY;
1712 return add_blockers(reasonp, errp, modes);
1715 int migrate_add_blocker_internal(Error **reasonp, Error **errp)
1717 int modes = BIT(MIG_MODE__MAX) - 1;
1719 if (is_busy(reasonp, errp)) {
1720 return -EBUSY;
1722 return add_blockers(reasonp, errp, modes);
1725 void migrate_del_blocker(Error **reasonp)
1727 if (*reasonp) {
1728 for (MigMode mode = 0; mode < MIG_MODE__MAX; mode++) {
1729 migration_blockers[mode] = g_slist_remove(migration_blockers[mode],
1730 *reasonp);
1732 error_free(*reasonp);
1733 *reasonp = NULL;
1737 void qmp_migrate_incoming(const char *uri, bool has_channels,
1738 MigrationChannelList *channels, Error **errp)
1740 Error *local_err = NULL;
1741 static bool once = true;
1743 if (!once) {
1744 error_setg(errp, "The incoming migration has already been started");
1745 return;
1747 if (!runstate_check(RUN_STATE_INMIGRATE)) {
1748 error_setg(errp, "'-incoming' was not specified on the command line");
1749 return;
1752 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1753 return;
1756 qemu_start_incoming_migration(uri, has_channels, channels, &local_err);
1758 if (local_err) {
1759 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1760 error_propagate(errp, local_err);
1761 return;
1764 once = false;
1767 void qmp_migrate_recover(const char *uri, Error **errp)
1769 MigrationIncomingState *mis = migration_incoming_get_current();
1772 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1773 * callers (no one should ignore a recover failure); if there is, it's a
1774 * programming error.
1776 assert(errp);
1778 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1779 error_setg(errp, "Migrate recover can only be run "
1780 "when postcopy is paused.");
1781 return;
1784 /* If there's an existing transport, release it */
1785 migration_incoming_transport_cleanup(mis);
1788 * Note that this call will never start a real migration; it will
1789 * only re-setup the migration stream and poke existing migration
1790 * to continue using that newly established channel.
1792 qemu_start_incoming_migration(uri, false, NULL, errp);
1795 void qmp_migrate_pause(Error **errp)
1797 MigrationState *ms = migrate_get_current();
1798 MigrationIncomingState *mis = migration_incoming_get_current();
1799 int ret = 0;
1801 if (migration_postcopy_is_alive(ms->state)) {
1802 /* Source side, during postcopy */
1803 Error *error = NULL;
1805 /* Tell the core migration that we're pausing */
1806 error_setg(&error, "Postcopy migration is paused by the user");
1807 migrate_set_error(ms, error);
1808 error_free(error);
1810 qemu_mutex_lock(&ms->qemu_file_lock);
1811 if (ms->to_dst_file) {
1812 ret = qemu_file_shutdown(ms->to_dst_file);
1814 qemu_mutex_unlock(&ms->qemu_file_lock);
1815 if (ret) {
1816 error_setg(errp, "Failed to pause source migration");
1820 * Kick the migration thread out of any waiting windows (on behalf
1821 * of the rp thread).
1823 migration_rp_kick(ms);
1825 return;
1828 if (migration_postcopy_is_alive(mis->state)) {
1829 ret = qemu_file_shutdown(mis->from_src_file);
1830 if (ret) {
1831 error_setg(errp, "Failed to pause destination migration");
1833 return;
1836 error_setg(errp, "migrate-pause is currently only supported "
1837 "during postcopy-active or postcopy-recover state");
1840 bool migration_is_blocked(Error **errp)
1842 GSList *blockers = migration_blockers[migrate_mode()];
1844 if (qemu_savevm_state_blocked(errp)) {
1845 return true;
1848 if (blockers) {
1849 error_propagate(errp, error_copy(blockers->data));
1850 return true;
1853 return false;
1856 /* Returns true if continue to migrate, or false if error detected */
1857 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1858 bool resume, Error **errp)
1860 if (blk_inc) {
1861 warn_report("parameter 'inc' is deprecated;"
1862 " use blockdev-mirror with NBD instead");
1865 if (blk) {
1866 warn_report("parameter 'blk' is deprecated;"
1867 " use blockdev-mirror with NBD instead");
1870 if (resume) {
1871 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1872 error_setg(errp, "Cannot resume if there is no "
1873 "paused migration");
1874 return false;
1878 * Postcopy recovery won't work well with release-ram
1879 * capability since release-ram will drop the page buffer as
1880 * long as the page is put into the send buffer. So if there
1881 * is a network failure happened, any page buffers that have
1882 * not yet reached the destination VM but have already been
1883 * sent from the source VM will be lost forever. Let's refuse
1884 * the client from resuming such a postcopy migration.
1885 * Luckily release-ram was designed to only be used when src
1886 * and destination VMs are on the same host, so it should be
1887 * fine.
1889 if (migrate_release_ram()) {
1890 error_setg(errp, "Postcopy recovery cannot work "
1891 "when release-ram capability is set");
1892 return false;
1895 /* This is a resume, skip init status */
1896 return true;
1899 if (migration_is_running(s->state)) {
1900 error_setg(errp, QERR_MIGRATION_ACTIVE);
1901 return false;
1904 if (runstate_check(RUN_STATE_INMIGRATE)) {
1905 error_setg(errp, "Guest is waiting for an incoming migration");
1906 return false;
1909 if (runstate_check(RUN_STATE_POSTMIGRATE)) {
1910 error_setg(errp, "Can't migrate the vm that was paused due to "
1911 "previous migration");
1912 return false;
1915 if (kvm_hwpoisoned_mem()) {
1916 error_setg(errp, "Can't migrate this vm with hardware poisoned memory, "
1917 "please reboot the vm and try again");
1918 return false;
1921 if (migration_is_blocked(errp)) {
1922 return false;
1925 if (blk || blk_inc) {
1926 if (migrate_colo()) {
1927 error_setg(errp, "No disk migration is required in COLO mode");
1928 return false;
1930 if (migrate_block() || migrate_block_incremental()) {
1931 error_setg(errp, "Command options are incompatible with "
1932 "current migration capabilities");
1933 return false;
1935 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK, true, errp)) {
1936 return false;
1938 s->must_remove_block_options = true;
1941 if (blk_inc) {
1942 migrate_set_block_incremental(true);
1945 if (migrate_init(s, errp)) {
1946 return false;
1949 return true;
1952 void qmp_migrate(const char *uri, bool has_channels,
1953 MigrationChannelList *channels, bool has_blk, bool blk,
1954 bool has_inc, bool inc, bool has_detach, bool detach,
1955 bool has_resume, bool resume, Error **errp)
1957 bool resume_requested;
1958 Error *local_err = NULL;
1959 MigrationState *s = migrate_get_current();
1960 g_autoptr(MigrationChannel) channel = NULL;
1961 MigrationAddress *addr = NULL;
1964 * Having preliminary checks for uri and channel
1966 if (!uri == !channels) {
1967 error_setg(errp, "need either 'uri' or 'channels' argument");
1968 return;
1971 if (channels) {
1972 /* To verify that Migrate channel list has only item */
1973 if (channels->next) {
1974 error_setg(errp, "Channel list has more than one entries");
1975 return;
1977 addr = channels->value->addr;
1980 if (uri) {
1981 /* caller uses the old URI syntax */
1982 if (!migrate_uri_parse(uri, &channel, errp)) {
1983 return;
1985 addr = channel->addr;
1988 /* transport mechanism not suitable for migration? */
1989 if (!migration_channels_and_transport_compatible(addr, errp)) {
1990 return;
1993 resume_requested = has_resume && resume;
1994 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1995 resume_requested, errp)) {
1996 /* Error detected, put into errp */
1997 return;
2000 if (!resume_requested) {
2001 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2002 return;
2006 if (addr->transport == MIGRATION_ADDRESS_TYPE_SOCKET) {
2007 SocketAddress *saddr = &addr->u.socket;
2008 if (saddr->type == SOCKET_ADDRESS_TYPE_INET ||
2009 saddr->type == SOCKET_ADDRESS_TYPE_UNIX ||
2010 saddr->type == SOCKET_ADDRESS_TYPE_VSOCK) {
2011 socket_start_outgoing_migration(s, saddr, &local_err);
2012 } else if (saddr->type == SOCKET_ADDRESS_TYPE_FD) {
2013 fd_start_outgoing_migration(s, saddr->u.fd.str, &local_err);
2015 #ifdef CONFIG_RDMA
2016 } else if (addr->transport == MIGRATION_ADDRESS_TYPE_RDMA) {
2017 rdma_start_outgoing_migration(s, &addr->u.rdma, &local_err);
2018 #endif
2019 } else if (addr->transport == MIGRATION_ADDRESS_TYPE_EXEC) {
2020 exec_start_outgoing_migration(s, addr->u.exec.args, &local_err);
2021 } else if (addr->transport == MIGRATION_ADDRESS_TYPE_FILE) {
2022 file_start_outgoing_migration(s, &addr->u.file, &local_err);
2023 } else {
2024 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "uri",
2025 "a valid migration protocol");
2026 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2027 MIGRATION_STATUS_FAILED);
2028 block_cleanup_parameters();
2031 if (local_err) {
2032 if (!resume_requested) {
2033 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2035 migrate_fd_error(s, local_err);
2036 error_propagate(errp, local_err);
2037 return;
2041 void qmp_migrate_cancel(Error **errp)
2043 migration_cancel(NULL);
2046 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2048 MigrationState *s = migrate_get_current();
2049 if (s->state != state) {
2050 error_setg(errp, "Migration not in expected state: %s",
2051 MigrationStatus_str(s->state));
2052 return;
2054 qemu_sem_post(&s->pause_sem);
2057 int migration_rp_wait(MigrationState *s)
2059 /* If migration has failure already, ignore the wait */
2060 if (migrate_has_error(s)) {
2061 return -1;
2064 qemu_sem_wait(&s->rp_state.rp_sem);
2066 /* After wait, double check that there's no failure */
2067 if (migrate_has_error(s)) {
2068 return -1;
2071 return 0;
2074 void migration_rp_kick(MigrationState *s)
2076 qemu_sem_post(&s->rp_state.rp_sem);
2079 static struct rp_cmd_args {
2080 ssize_t len; /* -1 = variable */
2081 const char *name;
2082 } rp_cmd_args[] = {
2083 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2084 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2085 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2086 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2087 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2088 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2089 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2090 [MIG_RP_MSG_SWITCHOVER_ACK] = { .len = 0, .name = "SWITCHOVER_ACK" },
2091 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2095 * Process a request for pages received on the return path,
2096 * We're allowed to send more than requested (e.g. to round to our page size)
2097 * and we don't need to send pages that have already been sent.
2099 static void
2100 migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2101 ram_addr_t start, size_t len, Error **errp)
2103 long our_host_ps = qemu_real_host_page_size();
2105 trace_migrate_handle_rp_req_pages(rbname, start, len);
2108 * Since we currently insist on matching page sizes, just sanity check
2109 * we're being asked for whole host pages.
2111 if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2112 !QEMU_IS_ALIGNED(len, our_host_ps)) {
2113 error_setg(errp, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
2114 RAM_ADDR_FMT " len: %zd", start, len);
2115 return;
2118 ram_save_queue_pages(rbname, start, len, errp);
2121 static bool migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name,
2122 Error **errp)
2124 RAMBlock *block = qemu_ram_block_by_name(block_name);
2126 if (!block) {
2127 error_setg(errp, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
2128 block_name);
2129 return false;
2132 /* Fetch the received bitmap and refresh the dirty bitmap */
2133 return ram_dirty_bitmap_reload(s, block, errp);
2136 static bool migrate_handle_rp_resume_ack(MigrationState *s,
2137 uint32_t value, Error **errp)
2139 trace_source_return_path_thread_resume_ack(value);
2141 if (value != MIGRATION_RESUME_ACK_VALUE) {
2142 error_setg(errp, "illegal resume_ack value %"PRIu32, value);
2143 return false;
2146 /* Now both sides are active. */
2147 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2148 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2150 /* Notify send thread that time to continue send pages */
2151 migration_rp_kick(s);
2153 return true;
2157 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2158 * existed) in a safe way.
2160 static void migration_release_dst_files(MigrationState *ms)
2162 QEMUFile *file;
2164 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2166 * Reset the from_dst_file pointer first before releasing it, as we
2167 * can't block within lock section
2169 file = ms->rp_state.from_dst_file;
2170 ms->rp_state.from_dst_file = NULL;
2174 * Do the same to postcopy fast path socket too if there is. No
2175 * locking needed because this qemufile should only be managed by
2176 * return path thread.
2178 if (ms->postcopy_qemufile_src) {
2179 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
2180 qemu_file_shutdown(ms->postcopy_qemufile_src);
2181 qemu_fclose(ms->postcopy_qemufile_src);
2182 ms->postcopy_qemufile_src = NULL;
2185 qemu_fclose(file);
2189 * Handles messages sent on the return path towards the source VM
2192 static void *source_return_path_thread(void *opaque)
2194 MigrationState *ms = opaque;
2195 QEMUFile *rp = ms->rp_state.from_dst_file;
2196 uint16_t header_len, header_type;
2197 uint8_t buf[512];
2198 uint32_t tmp32, sibling_error;
2199 ram_addr_t start = 0; /* =0 to silence warning */
2200 size_t len = 0, expected_len;
2201 Error *err = NULL;
2202 int res;
2204 trace_source_return_path_thread_entry();
2205 rcu_register_thread();
2207 while (migration_is_setup_or_active(ms->state)) {
2208 trace_source_return_path_thread_loop_top();
2210 header_type = qemu_get_be16(rp);
2211 header_len = qemu_get_be16(rp);
2213 if (qemu_file_get_error(rp)) {
2214 qemu_file_get_error_obj(rp, &err);
2215 goto out;
2218 if (header_type >= MIG_RP_MSG_MAX ||
2219 header_type == MIG_RP_MSG_INVALID) {
2220 error_setg(&err, "Received invalid message 0x%04x length 0x%04x",
2221 header_type, header_len);
2222 goto out;
2225 if ((rp_cmd_args[header_type].len != -1 &&
2226 header_len != rp_cmd_args[header_type].len) ||
2227 header_len > sizeof(buf)) {
2228 error_setg(&err, "Received '%s' message (0x%04x) with"
2229 "incorrect length %d expecting %zu",
2230 rp_cmd_args[header_type].name, header_type, header_len,
2231 (size_t)rp_cmd_args[header_type].len);
2232 goto out;
2235 /* We know we've got a valid header by this point */
2236 res = qemu_get_buffer(rp, buf, header_len);
2237 if (res != header_len) {
2238 error_setg(&err, "Failed reading data for message 0x%04x"
2239 " read %d expected %d",
2240 header_type, res, header_len);
2241 goto out;
2244 /* OK, we have the message and the data */
2245 switch (header_type) {
2246 case MIG_RP_MSG_SHUT:
2247 sibling_error = ldl_be_p(buf);
2248 trace_source_return_path_thread_shut(sibling_error);
2249 if (sibling_error) {
2250 error_setg(&err, "Sibling indicated error %d", sibling_error);
2253 * We'll let the main thread deal with closing the RP
2254 * we could do a shutdown(2) on it, but we're the only user
2255 * anyway, so there's nothing gained.
2257 goto out;
2259 case MIG_RP_MSG_PONG:
2260 tmp32 = ldl_be_p(buf);
2261 trace_source_return_path_thread_pong(tmp32);
2262 qemu_sem_post(&ms->rp_state.rp_pong_acks);
2263 break;
2265 case MIG_RP_MSG_REQ_PAGES:
2266 start = ldq_be_p(buf);
2267 len = ldl_be_p(buf + 8);
2268 migrate_handle_rp_req_pages(ms, NULL, start, len, &err);
2269 if (err) {
2270 goto out;
2272 break;
2274 case MIG_RP_MSG_REQ_PAGES_ID:
2275 expected_len = 12 + 1; /* header + termination */
2277 if (header_len >= expected_len) {
2278 start = ldq_be_p(buf);
2279 len = ldl_be_p(buf + 8);
2280 /* Now we expect an idstr */
2281 tmp32 = buf[12]; /* Length of the following idstr */
2282 buf[13 + tmp32] = '\0';
2283 expected_len += tmp32;
2285 if (header_len != expected_len) {
2286 error_setg(&err, "Req_Page_id with length %d expecting %zd",
2287 header_len, expected_len);
2288 goto out;
2290 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len,
2291 &err);
2292 if (err) {
2293 goto out;
2295 break;
2297 case MIG_RP_MSG_RECV_BITMAP:
2298 if (header_len < 1) {
2299 error_setg(&err, "MIG_RP_MSG_RECV_BITMAP missing block name");
2300 goto out;
2302 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2303 buf[buf[0] + 1] = '\0';
2304 if (!migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1), &err)) {
2305 goto out;
2307 break;
2309 case MIG_RP_MSG_RESUME_ACK:
2310 tmp32 = ldl_be_p(buf);
2311 if (!migrate_handle_rp_resume_ack(ms, tmp32, &err)) {
2312 goto out;
2314 break;
2316 case MIG_RP_MSG_SWITCHOVER_ACK:
2317 ms->switchover_acked = true;
2318 trace_source_return_path_thread_switchover_acked();
2319 break;
2321 default:
2322 break;
2326 out:
2327 if (err) {
2328 migrate_set_error(ms, err);
2329 error_free(err);
2330 trace_source_return_path_thread_bad_end();
2333 if (ms->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2335 * this will be extremely unlikely: that we got yet another network
2336 * issue during recovering of the 1st network failure.. during this
2337 * period the main migration thread can be waiting on rp_sem for
2338 * this thread to sync with the other side.
2340 * When this happens, explicitly kick the migration thread out of
2341 * RECOVER stage and back to PAUSED, so the admin can try
2342 * everything again.
2344 migration_rp_kick(ms);
2347 trace_source_return_path_thread_end();
2348 rcu_unregister_thread();
2350 return NULL;
2353 static int open_return_path_on_source(MigrationState *ms)
2355 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2356 if (!ms->rp_state.from_dst_file) {
2357 return -1;
2360 trace_open_return_path_on_source();
2362 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2363 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2364 ms->rp_state.rp_thread_created = true;
2366 trace_open_return_path_on_source_continue();
2368 return 0;
2371 /* Return true if error detected, or false otherwise */
2372 static bool close_return_path_on_source(MigrationState *ms)
2374 if (!ms->rp_state.rp_thread_created) {
2375 return false;
2378 trace_migration_return_path_end_before();
2381 * If this is a normal exit then the destination will send a SHUT
2382 * and the rp_thread will exit, however if there's an error we
2383 * need to cause it to exit. shutdown(2), if we have it, will
2384 * cause it to unblock if it's stuck waiting for the destination.
2386 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2387 if (ms->to_dst_file && ms->rp_state.from_dst_file &&
2388 qemu_file_get_error(ms->to_dst_file)) {
2389 qemu_file_shutdown(ms->rp_state.from_dst_file);
2393 qemu_thread_join(&ms->rp_state.rp_thread);
2394 ms->rp_state.rp_thread_created = false;
2395 migration_release_dst_files(ms);
2396 trace_migration_return_path_end_after();
2398 /* Return path will persist the error in MigrationState when quit */
2399 return migrate_has_error(ms);
2402 static inline void
2403 migration_wait_main_channel(MigrationState *ms)
2405 /* Wait until one PONG message received */
2406 qemu_sem_wait(&ms->rp_state.rp_pong_acks);
2410 * Switch from normal iteration to postcopy
2411 * Returns non-0 on error
2413 static int postcopy_start(MigrationState *ms, Error **errp)
2415 int ret;
2416 QIOChannelBuffer *bioc;
2417 QEMUFile *fb;
2418 uint64_t bandwidth = migrate_max_postcopy_bandwidth();
2419 bool restart_block = false;
2420 int cur_state = MIGRATION_STATUS_ACTIVE;
2422 if (migrate_postcopy_preempt()) {
2423 migration_wait_main_channel(ms);
2424 if (postcopy_preempt_establish_channel(ms)) {
2425 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
2426 return -1;
2430 if (!migrate_pause_before_switchover()) {
2431 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2432 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2435 trace_postcopy_start();
2436 bql_lock();
2437 trace_postcopy_start_set_run();
2439 migration_downtime_start(ms);
2441 global_state_store();
2442 ret = migration_stop_vm(RUN_STATE_FINISH_MIGRATE);
2443 if (ret < 0) {
2444 goto fail;
2447 ret = migration_maybe_pause(ms, &cur_state,
2448 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2449 if (ret < 0) {
2450 goto fail;
2453 ret = bdrv_inactivate_all();
2454 if (ret < 0) {
2455 goto fail;
2457 restart_block = true;
2460 * Cause any non-postcopiable, but iterative devices to
2461 * send out their final data.
2463 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2466 * in Finish migrate and with the io-lock held everything should
2467 * be quiet, but we've potentially still got dirty pages and we
2468 * need to tell the destination to throw any pages it's already received
2469 * that are dirty
2471 if (migrate_postcopy_ram()) {
2472 ram_postcopy_send_discard_bitmap(ms);
2476 * send rest of state - note things that are doing postcopy
2477 * will notice we're in POSTCOPY_ACTIVE and not actually
2478 * wrap their state up here
2480 migration_rate_set(bandwidth);
2481 if (migrate_postcopy_ram()) {
2482 /* Ping just for debugging, helps line traces up */
2483 qemu_savevm_send_ping(ms->to_dst_file, 2);
2487 * While loading the device state we may trigger page transfer
2488 * requests and the fd must be free to process those, and thus
2489 * the destination must read the whole device state off the fd before
2490 * it starts processing it. Unfortunately the ad-hoc migration format
2491 * doesn't allow the destination to know the size to read without fully
2492 * parsing it through each devices load-state code (especially the open
2493 * coded devices that use get/put).
2494 * So we wrap the device state up in a package with a length at the start;
2495 * to do this we use a qemu_buf to hold the whole of the device state.
2497 bioc = qio_channel_buffer_new(4096);
2498 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2499 fb = qemu_file_new_output(QIO_CHANNEL(bioc));
2500 object_unref(OBJECT(bioc));
2503 * Make sure the receiver can get incoming pages before we send the rest
2504 * of the state
2506 qemu_savevm_send_postcopy_listen(fb);
2508 qemu_savevm_state_complete_precopy(fb, false, false);
2509 if (migrate_postcopy_ram()) {
2510 qemu_savevm_send_ping(fb, 3);
2513 qemu_savevm_send_postcopy_run(fb);
2515 /* <><> end of stuff going into the package */
2517 /* Last point of recovery; as soon as we send the package the destination
2518 * can open devices and potentially start running.
2519 * Lets just check again we've not got any errors.
2521 ret = qemu_file_get_error(ms->to_dst_file);
2522 if (ret) {
2523 error_setg(errp, "postcopy_start: Migration stream errored (pre package)");
2524 goto fail_closefb;
2527 restart_block = false;
2529 /* Now send that blob */
2530 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2531 goto fail_closefb;
2533 qemu_fclose(fb);
2535 /* Send a notify to give a chance for anything that needs to happen
2536 * at the transition to postcopy and after the device state; in particular
2537 * spice needs to trigger a transition now
2539 ms->postcopy_after_devices = true;
2540 migration_call_notifiers(ms);
2542 migration_downtime_end(ms);
2544 bql_unlock();
2546 if (migrate_postcopy_ram()) {
2548 * Although this ping is just for debug, it could potentially be
2549 * used for getting a better measurement of downtime at the source.
2551 qemu_savevm_send_ping(ms->to_dst_file, 4);
2554 if (migrate_release_ram()) {
2555 ram_postcopy_migrated_memory_release(ms);
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);
2565 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2567 return ret;
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.
2578 Error *local_err = NULL;
2580 bdrv_activate_all(&local_err);
2581 if (local_err) {
2582 error_report_err(local_err);
2585 bql_unlock();
2586 return -1;
2590 * migration_maybe_pause: Pause if required to by
2591 * migrate_pause_before_switchover called with the BQL locked
2592 * Returns: 0 on success
2594 static int migration_maybe_pause(MigrationState *s,
2595 int *current_active_state,
2596 int new_state)
2598 if (!migrate_pause_before_switchover()) {
2599 return 0;
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.
2608 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2609 /* This block intentionally left blank */
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.
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();
2629 return s->state == new_state ? 0 : -EINVAL;
2632 static int migration_completion_precopy(MigrationState *s,
2633 int *current_active_state)
2635 int ret;
2637 bql_lock();
2638 migration_downtime_start(s);
2640 s->vm_old_state = runstate_get();
2641 global_state_store();
2643 ret = migration_stop_vm(RUN_STATE_FINISH_MIGRATE);
2644 trace_migration_completion_vm_stop(ret);
2645 if (ret < 0) {
2646 goto out_unlock;
2649 ret = migration_maybe_pause(s, current_active_state,
2650 MIGRATION_STATUS_DEVICE);
2651 if (ret < 0) {
2652 goto out_unlock;
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.
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;
2668 static void migration_completion_postcopy(MigrationState *s)
2670 trace_migration_completion_postcopy_end();
2672 bql_lock();
2673 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2674 bql_unlock();
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.
2680 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
2681 postcopy_preempt_shutdown_file(s);
2684 trace_migration_completion_postcopy_end_after_complete();
2687 static void migration_completion_failed(MigrationState *s,
2688 int current_active_state)
2690 if (s->block_inactive && (s->state == MIGRATION_STATUS_ACTIVE ||
2691 s->state == MIGRATION_STATUS_DEVICE)) {
2693 * If not doing postcopy, vm_start() will be called: let's
2694 * regain control on images.
2696 Error *local_err = NULL;
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;
2705 bql_unlock();
2708 migrate_set_state(&s->state, current_active_state,
2709 MIGRATION_STATUS_FAILED);
2713 * migration_completion: Used by migration_thread when there's not much left.
2714 * The caller 'breaks' the loop when this returns.
2716 * @s: Current migration state
2718 static void migration_completion(MigrationState *s)
2720 int ret = 0;
2721 int current_active_state = s->state;
2723 if (s->state == MIGRATION_STATUS_ACTIVE) {
2724 ret = migration_completion_precopy(s, &current_active_state);
2725 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2726 migration_completion_postcopy(s);
2727 } else {
2728 ret = -1;
2731 if (ret < 0) {
2732 goto fail;
2735 if (close_return_path_on_source(s)) {
2736 goto fail;
2739 if (qemu_file_get_error(s->to_dst_file)) {
2740 trace_migration_completion_file_err();
2741 goto fail;
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);
2753 return;
2755 fail:
2756 migration_completion_failed(s, current_active_state);
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.
2763 * @s: Current migration state
2765 static void bg_migration_completion(MigrationState *s)
2767 int current_active_state = s->state;
2769 if (s->state == MIGRATION_STATUS_ACTIVE) {
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.
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;
2782 if (qemu_file_get_error(s->to_dst_file)) {
2783 trace_migration_completion_file_err();
2784 goto fail;
2787 migrate_set_state(&s->state, current_active_state,
2788 MIGRATION_STATUS_COMPLETED);
2789 return;
2791 fail:
2792 migrate_set_state(&s->state, current_active_state,
2793 MIGRATION_STATUS_FAILED);
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;
2805 static int postcopy_resume_handshake(MigrationState *s)
2807 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2809 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2810 if (migration_rp_wait(s)) {
2811 return -1;
2815 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2816 return 0;
2819 return -1;
2822 /* Return zero if success, or <0 for error */
2823 static int postcopy_do_resume(MigrationState *s)
2825 int ret;
2828 * Call all the resume_prepare() hooks, so that modules can be
2829 * ready for the migration resume.
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;
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.
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;
2853 * Last handshake with destination on the resume (destination will
2854 * switch to postcopy-active afterwards)
2856 ret = postcopy_resume_handshake(s);
2857 if (ret) {
2858 error_report("%s: handshake failed: %d", __func__, ret);
2859 return ret;
2862 return 0;
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.
2870 static MigThrError postcopy_pause(MigrationState *s)
2872 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2874 while (true) {
2875 QEMUFile *file;
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.
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);
2893 qemu_file_shutdown(file);
2894 qemu_fclose(file);
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.
2901 close_return_path_on_source(s);
2903 migrate_set_state(&s->state, s->state,
2904 MIGRATION_STATUS_POSTCOPY_PAUSED);
2906 error_report("Detected IO failure for postcopy. "
2907 "Migration paused.");
2910 * We wait until things fixed up. Then someone will setup the
2911 * status back for us.
2913 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2914 qemu_sem_wait(&s->postcopy_pause_sem);
2917 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2918 /* Woken up by a recover procedure. Give it a shot */
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 {
2927 * Something wrong happened during the recovery, let's
2928 * pause again. Pause is always better than throwing
2929 * data away.
2931 continue;
2933 } else {
2934 /* This is not right... Time to quit. */
2935 return MIG_THR_ERR_FATAL;
2940 static MigThrError migration_detect_error(MigrationState *s)
2942 int ret;
2943 int state = s->state;
2944 Error *local_error = NULL;
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;
2953 * Try to detect any file errors. Note that postcopy_qemufile_src will
2954 * be NULL when postcopy preempt is not enabled.
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;
2965 if (local_error) {
2966 migrate_set_error(s, local_error);
2967 error_free(local_error);
2970 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
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.
2976 return postcopy_pause(s);
2977 } else {
2979 * For precopy (or postcopy with error outside IO), we fail
2980 * with no time.
2982 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
2983 trace_migration_thread_file_err();
2985 /* Time to stop the migration, now. */
2986 return MIG_THR_ERR_FATAL;
2990 static void migration_calculate_complete(MigrationState *s)
2992 uint64_t bytes = migration_transferred_bytes();
2993 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2994 int64_t transfer_time;
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;
3004 static void update_iteration_initial_status(MigrationState *s)
3007 * Update these three fields at the same time to avoid mismatch info lead
3008 * wrong speed calculation.
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();
3015 static void migration_update_counters(MigrationState *s,
3016 int64_t current_time)
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;
3025 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3026 return;
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;
3035 if (switchover_bw) {
3037 * If the user specified a switchover bandwidth, let's trust the
3038 * user so that can be more accurate than what we estimated.
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;
3046 s->threshold_size = expected_bw_per_ms * migrate_downtime_limit();
3048 s->mbps = (((double) transferred * 8.0) /
3049 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
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));
3057 * if we haven't sent anything, we don't want to
3058 * recalculate. 10000 is a small enough number for our purposes
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;
3066 migration_rate_reset();
3068 update_iteration_initial_status(s);
3070 trace_migrate_transferred(transferred, time_spent,
3071 /* Both in unit bytes/ms */
3072 bandwidth, switchover_bw / 1000,
3073 s->threshold_size);
3076 static bool migration_can_switchover(MigrationState *s)
3078 if (!migrate_switchover_ack()) {
3079 return true;
3082 /* No reason to wait for switchover ACK if VM is stopped */
3083 if (!runstate_is_running()) {
3084 return true;
3087 return s->switchover_acked;
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;
3098 * Return true if continue to the next iteration directly, false
3099 * otherwise.
3101 static MigIterateState migration_iteration_run(MigrationState *s)
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);
3108 qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
3109 uint64_t pending_size = must_precopy + can_postcopy;
3111 trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
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);
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;
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);
3132 return MIG_ITERATE_SKIP;
3135 /* Just another iteration step */
3136 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3137 return MIG_ITERATE_RESUME;
3140 static void migration_iteration_finish(MigrationState *s)
3142 /* If we enabled cpu throttling for auto-converge, turn it off. */
3143 cpu_throttle_stop();
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();
3163 } else {
3164 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3165 runstate_set(s->vm_old_state);
3168 break;
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;
3176 migration_bh_schedule(migrate_fd_cleanup_bh, s);
3177 bql_unlock();
3180 static void bg_migration_iteration_finish(MigrationState *s)
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.
3187 ram_write_tracking_stop();
3189 bql_lock();
3190 switch (s->state) {
3191 case MIGRATION_STATUS_COMPLETED:
3192 migration_calculate_complete(s);
3193 break;
3195 case MIGRATION_STATUS_ACTIVE:
3196 case MIGRATION_STATUS_FAILED:
3197 case MIGRATION_STATUS_CANCELLED:
3198 case MIGRATION_STATUS_CANCELLING:
3199 break;
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;
3207 migration_bh_schedule(migrate_fd_cleanup_bh, s);
3208 bql_unlock();
3212 * Return true if continue to the next iteration directly, false
3213 * otherwise.
3215 static MigIterateState bg_migration_iteration_run(MigrationState *s)
3217 int res;
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;
3225 return MIG_ITERATE_RESUME;
3228 void migration_make_urgent_request(void)
3230 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3233 void migration_consume_urgent_request(void)
3235 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3238 /* Returns true if the rate limiting was broken by an urgent request */
3239 bool migration_rate_limit(void)
3241 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3242 MigrationState *s = migrate_get_current();
3244 bool urgent = false;
3245 migration_update_counters(s, now);
3246 if (migration_rate_exceeded(s->to_dst_file)) {
3248 if (qemu_file_get_error(s->to_dst_file)) {
3249 return false;
3252 * Wait for a delay to do rate limiting OR
3253 * something urgent to post the semaphore.
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) {
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.
3265 qemu_sem_post(&s->rate_limit_sem);
3266 urgent = true;
3268 trace_migration_rate_limit_post(urgent);
3270 return urgent;
3274 * if failover devices are present, wait they are completely
3275 * unplugged
3278 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3279 int new_state)
3281 if (qemu_savevm_state_guest_unplug_pending()) {
3282 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3284 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3285 qemu_savevm_state_guest_unplug_pending()) {
3286 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3288 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3289 int timeout = 120; /* 30 seconds */
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
3295 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3296 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3298 if (qemu_savevm_state_guest_unplug_pending() &&
3299 !qtest_enabled()) {
3300 warn_report("migration: partially unplugged device on "
3301 "failure");
3305 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3306 } else {
3307 migrate_set_state(&s->state, old_state, new_state);
3312 * Master migration thread on the source VM.
3313 * It drives the migration and pumps the data down the outgoing channel.
3315 static void *migration_thread(void *opaque)
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;
3323 thread = migration_threads_add("live_migration", qemu_get_thread_id());
3325 rcu_register_thread();
3327 object_ref(OBJECT(s));
3328 update_iteration_initial_status(s);
3330 if (!multifd_send_setup()) {
3331 goto out;
3334 bql_lock();
3335 qemu_savevm_state_header(s->to_dst_file);
3336 bql_unlock();
3339 * If we opened the return path, we need to make sure dst has it
3340 * opened as well.
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);
3346 /* And do a ping that will make stuff easier to debug */
3347 qemu_savevm_send_ping(s->to_dst_file, 1);
3350 if (migrate_postcopy()) {
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.
3356 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3359 if (migrate_colo()) {
3360 /* Notify migration destination that we enable COLO */
3361 qemu_savevm_send_colo_enable(s->to_dst_file);
3364 bql_lock();
3365 qemu_savevm_state_setup(s->to_dst_file);
3366 bql_unlock();
3368 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3369 MIGRATION_STATUS_ACTIVE);
3371 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3373 trace_migration_thread_setup_complete();
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;
3386 * Try to detect any kind of failures, and see whether we
3387 * should stop the migration now.
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) {
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
3399 update_iteration_initial_status(s);
3402 urgent = migration_rate_limit();
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;
3414 static void bg_migration_vm_start_bh(void *opaque)
3416 MigrationState *s = opaque;
3418 vm_resume(s->vm_old_state);
3419 migration_downtime_end(s);
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.
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.
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.
3437 static void *bg_migration_thread(void *opaque)
3439 MigrationState *s = opaque;
3440 int64_t setup_start;
3441 MigThrError thr_error;
3442 QEMUFile *fb;
3443 bool early_fail = true;
3445 rcu_register_thread();
3446 object_ref(OBJECT(s));
3448 migration_rate_set(RATE_LIMIT_DISABLED);
3450 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
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.
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));
3465 update_iteration_initial_status(s);
3468 * Prepare for tracking memory writes with UFFD-WP - populate
3469 * RAM pages before protecting.
3471 #ifdef __linux__
3472 ram_write_tracking_prepare();
3473 #endif
3475 bql_lock();
3476 qemu_savevm_state_header(s->to_dst_file);
3477 qemu_savevm_state_setup(s->to_dst_file);
3478 bql_unlock();
3480 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3481 MIGRATION_STATUS_ACTIVE);
3483 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3485 trace_migration_thread_setup_complete();
3486 migration_downtime_start(s);
3488 bql_lock();
3490 s->vm_old_state = runstate_get();
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;
3498 * Put vCPUs in sync with shadow context structures, then
3499 * save their state to channel-buffer along with devices.
3501 cpu_synchronize_all_states();
3502 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
3503 goto fail;
3506 * Since we are going to get non-iterable state data directly
3507 * from s->bioc->data, explicit flush is needed here.
3509 qemu_fflush(fb);
3511 /* Now initialize UFFD context and start tracking RAM writes */
3512 if (ram_write_tracking_start()) {
3513 goto fail;
3515 early_fail = false;
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.
3523 migration_bh_schedule(bg_migration_vm_start_bh, s);
3524 bql_unlock();
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;
3535 * Try to detect any kind of failures, and see whether we
3536 * should stop the migration now.
3538 thr_error = migration_detect_error(s);
3539 if (thr_error == MIG_THR_ERR_FATAL) {
3540 /* Stop migration */
3541 break;
3544 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
3547 trace_migration_thread_after_loop();
3549 fail:
3550 if (early_fail) {
3551 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3552 MIGRATION_STATUS_FAILED);
3553 bql_unlock();
3556 bg_migration_iteration_finish(s);
3558 qemu_fclose(fb);
3559 object_unref(OBJECT(s));
3560 rcu_unregister_thread();
3562 return NULL;
3565 void migrate_fd_connect(MigrationState *s, Error *error_in)
3567 Error *local_err = NULL;
3568 uint64_t rate_limit;
3569 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
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().
3576 migrate_error_free(s);
3578 s->expected_downtime = migrate_downtime_limit();
3579 if (error_in) {
3580 migrate_fd_error(s, error_in);
3581 if (resume) {
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.
3589 error_report_err(error_copy(s->error));
3590 } else {
3591 migrate_fd_cleanup(s);
3593 return;
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();
3603 /* Notify before starting migration thread */
3604 migration_call_notifiers(s);
3607 migration_rate_set(rate_limit);
3608 qemu_file_set_blocking(s->to_dst_file, true);
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.
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;
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.
3631 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
3632 postcopy_preempt_setup(s);
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;
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);
3650 s->migration_thread_running = true;
3653 static void migration_class_init(ObjectClass *klass, void *data)
3655 DeviceClass *dc = DEVICE_CLASS(klass);
3657 dc->user_creatable = false;
3658 device_class_set_props(dc, migration_properties);
3661 static void migration_instance_finalize(Object *obj)
3663 MigrationState *ms = MIGRATION_OBJ(obj);
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);
3677 static void migration_instance_init(Object *obj)
3679 MigrationState *ms = MIGRATION_OBJ(obj);
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);
3687 migrate_params_init(&ms->parameters);
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);
3699 * Return true if check pass, false otherwise. Error will be put
3700 * inside errp if provided.
3702 static bool migration_object_check(MigrationState *ms, Error **errp)
3704 /* Assuming all off */
3705 bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
3707 if (!migrate_params_check(&ms->parameters, errp)) {
3708 return false;
3711 return migrate_caps_check(old_caps, ms->capabilities, errp);
3714 static const TypeInfo migration_type = {
3715 .name = TYPE_MIGRATION,
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.
3721 * TODO: Make this TYPE_OBJECT once QOM provides something like
3722 * TYPE_DEVICE's "-global" properties.
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,
3732 static void register_migration_types(void)
3734 type_register_static(&migration_type);
3737 type_init(register_migration_types);