4 * Copyright IBM, Corp. 2008
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"
25 #include "sysemu/runstate.h"
26 #include "sysemu/sysemu.h"
27 #include "sysemu/cpu-throttle.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"
36 #include "qemu-file.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"
50 #include "postcopy-ram.h"
51 #include "qemu/thread.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"
62 #include "threadinfo.h"
63 #include "qemu/yank.h"
64 #include "sysemu/cpus.h"
65 #include "yank_functions.h"
66 #include "sysemu/qtest.h"
68 #include "sysemu/dirtylimit.h"
69 #include "qemu/sockets.h"
71 static NotifierList migration_state_notifiers
=
72 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
74 /* Messages sent on the return path from destination to source */
75 enum mig_rp_message_type
{
76 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
77 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
78 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
80 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
81 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
82 MIG_RP_MSG_RECV_BITMAP
, /* send recved_bitmap back to source */
83 MIG_RP_MSG_RESUME_ACK
, /* tell source that we are ready to resume */
84 MIG_RP_MSG_SWITCHOVER_ACK
, /* Tell source it's OK to do switchover */
89 /* When we add fault tolerance, we could have several
90 migrations at once. For now we don't need to add
91 dynamic creation of migration */
93 static MigrationState
*current_migration
;
94 static MigrationIncomingState
*current_incoming
;
96 static GSList
*migration_blockers
[MIG_MODE__MAX
];
98 static bool migration_object_check(MigrationState
*ms
, Error
**errp
);
99 static int migration_maybe_pause(MigrationState
*s
,
100 int *current_active_state
,
102 static void migrate_fd_cancel(MigrationState
*s
);
103 static bool close_return_path_on_source(MigrationState
*s
);
105 static void migration_downtime_start(MigrationState
*s
)
107 trace_vmstate_downtime_checkpoint("src-downtime-start");
108 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
111 static void migration_downtime_end(MigrationState
*s
)
113 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
116 * If downtime already set, should mean that postcopy already set it,
117 * then that should be the real downtime already.
120 s
->downtime
= now
- s
->downtime_start
;
123 trace_vmstate_downtime_checkpoint("src-downtime-end");
126 static bool migration_needs_multiple_sockets(void)
128 return migrate_multifd() || migrate_postcopy_preempt();
131 static bool transport_supports_multi_channels(SocketAddress
*saddr
)
133 return saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
134 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
135 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
;
139 migration_channels_and_transport_compatible(MigrationAddress
*addr
,
142 if (migration_needs_multiple_sockets() &&
143 (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) &&
144 !transport_supports_multi_channels(&addr
->u
.socket
)) {
145 error_setg(errp
, "Migration requires multi-channel URIs (e.g. tcp)");
152 static gint
page_request_addr_cmp(gconstpointer ap
, gconstpointer bp
)
154 uintptr_t a
= (uintptr_t) ap
, b
= (uintptr_t) bp
;
156 return (a
> b
) - (a
< b
);
159 int migration_stop_vm(RunState state
)
161 int ret
= vm_stop_force_state(state
);
163 trace_vmstate_downtime_checkpoint("src-vm-stopped");
168 void migration_object_init(void)
170 /* This can only be called once. */
171 assert(!current_migration
);
172 current_migration
= MIGRATION_OBJ(object_new(TYPE_MIGRATION
));
175 * Init the migrate incoming object as well no matter whether
176 * we'll use it or not.
178 assert(!current_incoming
);
179 current_incoming
= g_new0(MigrationIncomingState
, 1);
180 current_incoming
->state
= MIGRATION_STATUS_NONE
;
181 current_incoming
->postcopy_remote_fds
=
182 g_array_new(FALSE
, TRUE
, sizeof(struct PostCopyFD
));
183 qemu_mutex_init(¤t_incoming
->rp_mutex
);
184 qemu_mutex_init(¤t_incoming
->postcopy_prio_thread_mutex
);
185 qemu_event_init(¤t_incoming
->main_thread_load_event
, false);
186 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_dst
, 0);
187 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fault
, 0);
188 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fast_load
, 0);
189 qemu_sem_init(¤t_incoming
->postcopy_qemufile_dst_done
, 0);
191 qemu_mutex_init(¤t_incoming
->page_request_mutex
);
192 qemu_cond_init(¤t_incoming
->page_request_cond
);
193 current_incoming
->page_requested
= g_tree_new(page_request_addr_cmp
);
195 migration_object_check(current_migration
, &error_fatal
);
199 dirty_bitmap_mig_init();
202 void migration_cancel(const Error
*error
)
205 migrate_set_error(current_migration
, error
);
207 if (migrate_dirty_limit()) {
208 qmp_cancel_vcpu_dirty_limit(false, -1, NULL
);
210 migrate_fd_cancel(current_migration
);
213 void migration_shutdown(void)
216 * When the QEMU main thread exit, the COLO thread
217 * may wait a semaphore. So, we should wakeup the
218 * COLO thread before migration shutdown.
222 * Cancel the current migration - that will (eventually)
223 * stop the migration using this structure
225 migration_cancel(NULL
);
226 object_unref(OBJECT(current_migration
));
229 * Cancel outgoing migration of dirty bitmaps. It should
230 * at least unref used block nodes.
232 dirty_bitmap_mig_cancel_outgoing();
235 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
236 * are non-critical data, and their loss never considered as
239 dirty_bitmap_mig_cancel_incoming();
243 MigrationState
*migrate_get_current(void)
245 /* This can only be called after the object created. */
246 assert(current_migration
);
247 return current_migration
;
250 MigrationIncomingState
*migration_incoming_get_current(void)
252 assert(current_incoming
);
253 return current_incoming
;
256 void migration_incoming_transport_cleanup(MigrationIncomingState
*mis
)
258 if (mis
->socket_address_list
) {
259 qapi_free_SocketAddressList(mis
->socket_address_list
);
260 mis
->socket_address_list
= NULL
;
263 if (mis
->transport_cleanup
) {
264 mis
->transport_cleanup(mis
->transport_data
);
265 mis
->transport_data
= mis
->transport_cleanup
= NULL
;
269 void migration_incoming_state_destroy(void)
271 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
273 multifd_load_cleanup();
274 compress_threads_load_cleanup();
276 if (mis
->to_src_file
) {
277 /* Tell source that we are done */
278 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
279 qemu_fclose(mis
->to_src_file
);
280 mis
->to_src_file
= NULL
;
283 if (mis
->from_src_file
) {
284 migration_ioc_unregister_yank_from_file(mis
->from_src_file
);
285 qemu_fclose(mis
->from_src_file
);
286 mis
->from_src_file
= NULL
;
288 if (mis
->postcopy_remote_fds
) {
289 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
290 mis
->postcopy_remote_fds
= NULL
;
293 migration_incoming_transport_cleanup(mis
);
294 qemu_event_reset(&mis
->main_thread_load_event
);
296 if (mis
->page_requested
) {
297 g_tree_destroy(mis
->page_requested
);
298 mis
->page_requested
= NULL
;
301 if (mis
->postcopy_qemufile_dst
) {
302 migration_ioc_unregister_yank_from_file(mis
->postcopy_qemufile_dst
);
303 qemu_fclose(mis
->postcopy_qemufile_dst
);
304 mis
->postcopy_qemufile_dst
= NULL
;
307 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
310 static void migrate_generate_event(int new_state
)
312 if (migrate_events()) {
313 qapi_event_send_migration(new_state
);
318 * Send a message on the return channel back to the source
321 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
322 enum mig_rp_message_type message_type
,
323 uint16_t len
, void *data
)
327 trace_migrate_send_rp_message((int)message_type
, len
);
328 QEMU_LOCK_GUARD(&mis
->rp_mutex
);
331 * It's possible that the file handle got lost due to network
334 if (!mis
->to_src_file
) {
339 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
340 qemu_put_be16(mis
->to_src_file
, len
);
341 qemu_put_buffer(mis
->to_src_file
, data
, len
);
342 return qemu_fflush(mis
->to_src_file
);
345 /* Request one page from the source VM at the given start address.
346 * rb: the RAMBlock to request the page in
347 * Start: Address offset within the RB
348 * Len: Length in bytes required - must be a multiple of pagesize
350 int migrate_send_rp_message_req_pages(MigrationIncomingState
*mis
,
351 RAMBlock
*rb
, ram_addr_t start
)
353 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
354 size_t msglen
= 12; /* start + len */
355 size_t len
= qemu_ram_pagesize(rb
);
356 enum mig_rp_message_type msg_type
;
360 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
361 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
364 * We maintain the last ramblock that we requested for page. Note that we
365 * don't need locking because this function will only be called within the
366 * postcopy ram fault thread.
368 if (rb
!= mis
->last_rb
) {
371 rbname
= qemu_ram_get_idstr(rb
);
372 rbname_len
= strlen(rbname
);
374 assert(rbname_len
< 256);
376 bufc
[msglen
++] = rbname_len
;
377 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
378 msglen
+= rbname_len
;
379 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
381 msg_type
= MIG_RP_MSG_REQ_PAGES
;
384 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
387 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
,
388 RAMBlock
*rb
, ram_addr_t start
, uint64_t haddr
)
390 void *aligned
= (void *)(uintptr_t)ROUND_DOWN(haddr
, qemu_ram_pagesize(rb
));
391 bool received
= false;
393 WITH_QEMU_LOCK_GUARD(&mis
->page_request_mutex
) {
394 received
= ramblock_recv_bitmap_test_byte_offset(rb
, start
);
395 if (!received
&& !g_tree_lookup(mis
->page_requested
, aligned
)) {
397 * The page has not been received, and it's not yet in the page
398 * request list. Queue it. Set the value of element to 1, so that
399 * things like g_tree_lookup() will return TRUE (1) when found.
401 g_tree_insert(mis
->page_requested
, aligned
, (gpointer
)1);
402 qatomic_inc(&mis
->page_requested_count
);
403 trace_postcopy_page_req_add(aligned
, mis
->page_requested_count
);
408 * If the page is there, skip sending the message. We don't even need the
409 * lock because as long as the page arrived, it'll be there forever.
415 return migrate_send_rp_message_req_pages(mis
, rb
, start
);
418 static bool migration_colo_enabled
;
419 bool migration_incoming_colo_enabled(void)
421 return migration_colo_enabled
;
424 void migration_incoming_disable_colo(void)
426 ram_block_discard_disable(false);
427 migration_colo_enabled
= false;
430 int migration_incoming_enable_colo(void)
432 #ifndef CONFIG_REPLICATION
433 error_report("ENABLE_COLO command come in migration stream, but COLO "
434 "module is not built in");
438 if (!migrate_colo()) {
439 error_report("ENABLE_COLO command come in migration stream, but c-colo "
440 "capability is not set");
444 if (ram_block_discard_disable(true)) {
445 error_report("COLO: cannot disable RAM discard");
448 migration_colo_enabled
= true;
452 void migrate_add_address(SocketAddress
*address
)
454 MigrationIncomingState
*mis
= migration_incoming_get_current();
456 QAPI_LIST_PREPEND(mis
->socket_address_list
,
457 QAPI_CLONE(SocketAddress
, address
));
460 bool migrate_uri_parse(const char *uri
, MigrationChannel
**channel
,
463 g_autoptr(MigrationChannel
) val
= g_new0(MigrationChannel
, 1);
464 g_autoptr(MigrationAddress
) addr
= g_new0(MigrationAddress
, 1);
465 InetSocketAddress
*isock
= &addr
->u
.rdma
;
466 strList
**tail
= &addr
->u
.exec
.args
;
468 if (strstart(uri
, "exec:", NULL
)) {
469 addr
->transport
= MIGRATION_ADDRESS_TYPE_EXEC
;
471 QAPI_LIST_APPEND(tail
, g_strdup(exec_get_cmd_path()));
472 QAPI_LIST_APPEND(tail
, g_strdup("/c"));
474 QAPI_LIST_APPEND(tail
, g_strdup("/bin/sh"));
475 QAPI_LIST_APPEND(tail
, g_strdup("-c"));
477 QAPI_LIST_APPEND(tail
, g_strdup(uri
+ strlen("exec:")));
478 } else if (strstart(uri
, "rdma:", NULL
)) {
479 if (inet_parse(isock
, uri
+ strlen("rdma:"), errp
)) {
480 qapi_free_InetSocketAddress(isock
);
483 addr
->transport
= MIGRATION_ADDRESS_TYPE_RDMA
;
484 } else if (strstart(uri
, "tcp:", NULL
) ||
485 strstart(uri
, "unix:", NULL
) ||
486 strstart(uri
, "vsock:", NULL
) ||
487 strstart(uri
, "fd:", NULL
)) {
488 addr
->transport
= MIGRATION_ADDRESS_TYPE_SOCKET
;
489 SocketAddress
*saddr
= socket_parse(uri
, errp
);
493 addr
->u
.socket
.type
= saddr
->type
;
494 addr
->u
.socket
.u
= saddr
->u
;
495 /* Don't free the objects inside; their ownership moved to "addr" */
497 } else if (strstart(uri
, "file:", NULL
)) {
498 addr
->transport
= MIGRATION_ADDRESS_TYPE_FILE
;
499 addr
->u
.file
.filename
= g_strdup(uri
+ strlen("file:"));
500 if (file_parse_offset(addr
->u
.file
.filename
, &addr
->u
.file
.offset
,
505 error_setg(errp
, "unknown migration protocol: %s", uri
);
509 val
->channel_type
= MIGRATION_CHANNEL_TYPE_MAIN
;
510 val
->addr
= g_steal_pointer(&addr
);
511 *channel
= g_steal_pointer(&val
);
515 static void qemu_start_incoming_migration(const char *uri
, bool has_channels
,
516 MigrationChannelList
*channels
,
519 g_autoptr(MigrationChannel
) channel
= NULL
;
520 MigrationAddress
*addr
= NULL
;
521 MigrationIncomingState
*mis
= migration_incoming_get_current();
524 * Having preliminary checks for uri and channel
526 if (uri
&& has_channels
) {
527 error_setg(errp
, "'uri' and 'channels' arguments are mutually "
528 "exclusive; exactly one of the two should be present in "
529 "'migrate-incoming' qmp command ");
531 } else if (channels
) {
532 /* To verify that Migrate channel list has only item */
533 if (channels
->next
) {
534 error_setg(errp
, "Channel list has more than one entries");
537 addr
= channels
->value
->addr
;
539 /* caller uses the old URI syntax */
540 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
543 addr
= channel
->addr
;
545 error_setg(errp
, "neither 'uri' or 'channels' argument are "
546 "specified in 'migrate-incoming' qmp command ");
550 /* transport mechanism not suitable for migration? */
551 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
555 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
556 MIGRATION_STATUS_SETUP
);
558 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
559 SocketAddress
*saddr
= &addr
->u
.socket
;
560 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
561 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
562 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
563 socket_start_incoming_migration(saddr
, errp
);
564 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
565 fd_start_incoming_migration(saddr
->u
.fd
.str
, errp
);
568 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
569 if (migrate_compress()) {
570 error_setg(errp
, "RDMA and compression can't be used together");
573 if (migrate_xbzrle()) {
574 error_setg(errp
, "RDMA and XBZRLE can't be used together");
577 if (migrate_multifd()) {
578 error_setg(errp
, "RDMA and multifd can't be used together");
581 rdma_start_incoming_migration(&addr
->u
.rdma
, errp
);
583 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
584 exec_start_incoming_migration(addr
->u
.exec
.args
, errp
);
585 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
586 file_start_incoming_migration(&addr
->u
.file
, errp
);
588 error_setg(errp
, "unknown migration protocol: %s", uri
);
592 static void process_incoming_migration_bh(void *opaque
)
594 Error
*local_err
= NULL
;
595 MigrationIncomingState
*mis
= opaque
;
597 trace_vmstate_downtime_checkpoint("dst-precopy-bh-enter");
599 /* If capability late_block_activate is set:
600 * Only fire up the block code now if we're going to restart the
601 * VM, else 'cont' will do it.
602 * This causes file locking to happen; so we don't want it to happen
603 * unless we really are starting the VM.
605 if (!migrate_late_block_activate() ||
606 (autostart
&& (!global_state_received() ||
607 global_state_get_runstate() == RUN_STATE_RUNNING
))) {
608 /* Make sure all file formats throw away their mutable metadata.
609 * If we get an error here, just don't restart the VM yet. */
610 bdrv_activate_all(&local_err
);
612 error_report_err(local_err
);
619 * This must happen after all error conditions are dealt with and
620 * we're sure the VM is going to be running on this host.
622 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
624 trace_vmstate_downtime_checkpoint("dst-precopy-bh-announced");
626 multifd_load_shutdown();
628 dirty_bitmap_mig_before_vm_start();
630 if (!global_state_received() ||
631 global_state_get_runstate() == RUN_STATE_RUNNING
) {
635 runstate_set(RUN_STATE_PAUSED
);
637 } else if (migration_incoming_colo_enabled()) {
638 migration_incoming_disable_colo();
641 runstate_set(global_state_get_runstate());
643 trace_vmstate_downtime_checkpoint("dst-precopy-bh-vm-started");
645 * This must happen after any state changes since as soon as an external
646 * observer sees this event they might start to prod at the VM assuming
649 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
650 MIGRATION_STATUS_COMPLETED
);
651 qemu_bh_delete(mis
->bh
);
652 migration_incoming_state_destroy();
655 static void coroutine_fn
656 process_incoming_migration_co(void *opaque
)
658 MigrationIncomingState
*mis
= migration_incoming_get_current();
662 assert(mis
->from_src_file
);
664 if (compress_threads_load_setup(mis
->from_src_file
)) {
665 error_report("Failed to setup decompress threads");
669 mis
->largest_page_size
= qemu_ram_pagesize_largest();
670 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
671 migrate_set_state(&mis
->state
, MIGRATION_STATUS_SETUP
,
672 MIGRATION_STATUS_ACTIVE
);
674 mis
->loadvm_co
= qemu_coroutine_self();
675 ret
= qemu_loadvm_state(mis
->from_src_file
);
676 mis
->loadvm_co
= NULL
;
678 trace_vmstate_downtime_checkpoint("dst-precopy-loadvm-completed");
680 ps
= postcopy_state_get();
681 trace_process_incoming_migration_co_end(ret
, ps
);
682 if (ps
!= POSTCOPY_INCOMING_NONE
) {
683 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
685 * Where a migration had postcopy enabled (and thus went to advise)
686 * but managed to complete within the precopy period, we can use
689 postcopy_ram_incoming_cleanup(mis
);
690 } else if (ret
>= 0) {
692 * Postcopy was started, cleanup should happen at the end of the
695 trace_process_incoming_migration_co_postcopy_end_main();
698 /* Else if something went wrong then just fall out of the normal exit */
702 error_report("load of migration failed: %s", strerror(-ret
));
706 if (colo_incoming_co() < 0) {
710 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
711 qemu_bh_schedule(mis
->bh
);
714 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
715 MIGRATION_STATUS_FAILED
);
716 qemu_fclose(mis
->from_src_file
);
718 multifd_load_cleanup();
719 compress_threads_load_cleanup();
725 * migration_incoming_setup: Setup incoming migration
726 * @f: file for main migration channel
727 * @errp: where to put errors
729 * Returns: %true on success, %false on error.
731 static bool migration_incoming_setup(QEMUFile
*f
, Error
**errp
)
733 MigrationIncomingState
*mis
= migration_incoming_get_current();
735 if (!mis
->from_src_file
) {
736 mis
->from_src_file
= f
;
738 qemu_file_set_blocking(f
, false);
742 void migration_incoming_process(void)
744 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
745 qemu_coroutine_enter(co
);
748 /* Returns true if recovered from a paused migration, otherwise false */
749 static bool postcopy_try_recover(void)
751 MigrationIncomingState
*mis
= migration_incoming_get_current();
753 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
754 /* Resumed from a paused postcopy migration */
756 /* This should be set already in migration_incoming_setup() */
757 assert(mis
->from_src_file
);
758 /* Postcopy has standalone thread to do vm load */
759 qemu_file_set_blocking(mis
->from_src_file
, true);
761 /* Re-configure the return path */
762 mis
->to_src_file
= qemu_file_get_return_path(mis
->from_src_file
);
764 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
765 MIGRATION_STATUS_POSTCOPY_RECOVER
);
768 * Here, we only wake up the main loading thread (while the
769 * rest threads will still be waiting), so that we can receive
770 * commands from source now, and answer it if needed. The
771 * rest threads will be woken up afterwards until we are sure
772 * that source is ready to reply to page requests.
774 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
781 void migration_fd_process_incoming(QEMUFile
*f
, Error
**errp
)
783 if (!migration_incoming_setup(f
, errp
)) {
786 if (postcopy_try_recover()) {
789 migration_incoming_process();
793 * Returns true when we want to start a new incoming migration process,
796 static bool migration_should_start_incoming(bool main_channel
)
798 /* Multifd doesn't start unless all channels are established */
799 if (migrate_multifd()) {
800 return migration_has_all_channels();
803 /* Preempt channel only starts when the main channel is created */
804 if (migrate_postcopy_preempt()) {
809 * For all the rest types of migration, we should only reach here when
810 * it's the main channel that's being created, and we should always
811 * proceed with this channel.
813 assert(main_channel
);
817 void migration_ioc_process_incoming(QIOChannel
*ioc
, Error
**errp
)
819 MigrationIncomingState
*mis
= migration_incoming_get_current();
820 Error
*local_err
= NULL
;
822 bool default_channel
= true;
823 uint32_t channel_magic
= 0;
826 if (migrate_multifd() && !migrate_postcopy_ram() &&
827 qio_channel_has_feature(ioc
, QIO_CHANNEL_FEATURE_READ_MSG_PEEK
)) {
829 * With multiple channels, it is possible that we receive channels
830 * out of order on destination side, causing incorrect mapping of
831 * source channels on destination side. Check channel MAGIC to
832 * decide type of channel. Please note this is best effort, postcopy
833 * preempt channel does not send any magic number so avoid it for
834 * postcopy live migration. Also tls live migration already does
835 * tls handshake while initializing main channel so with tls this
836 * issue is not possible.
838 ret
= migration_channel_read_peek(ioc
, (void *)&channel_magic
,
839 sizeof(channel_magic
), &local_err
);
842 error_propagate(errp
, local_err
);
846 default_channel
= (channel_magic
== cpu_to_be32(QEMU_VM_FILE_MAGIC
));
848 default_channel
= !mis
->from_src_file
;
851 if (multifd_load_setup(errp
) != 0) {
852 error_setg(errp
, "Failed to setup multifd channels");
856 if (default_channel
) {
857 f
= qemu_file_new_input(ioc
);
859 if (!migration_incoming_setup(f
, errp
)) {
863 /* Multiple connections */
864 assert(migration_needs_multiple_sockets());
865 if (migrate_multifd()) {
866 multifd_recv_new_channel(ioc
, &local_err
);
868 assert(migrate_postcopy_preempt());
869 f
= qemu_file_new_input(ioc
);
870 postcopy_preempt_new_channel(mis
, f
);
873 error_propagate(errp
, local_err
);
878 if (migration_should_start_incoming(default_channel
)) {
879 /* If it's a recovery, we're done */
880 if (postcopy_try_recover()) {
883 migration_incoming_process();
888 * @migration_has_all_channels: We have received all channels that we need
890 * Returns true when we have got connections to all the channels that
891 * we need for migration.
893 bool migration_has_all_channels(void)
895 MigrationIncomingState
*mis
= migration_incoming_get_current();
897 if (!mis
->from_src_file
) {
901 if (migrate_multifd()) {
902 return multifd_recv_all_channels_created();
905 if (migrate_postcopy_preempt()) {
906 return mis
->postcopy_qemufile_dst
!= NULL
;
912 int migrate_send_rp_switchover_ack(MigrationIncomingState
*mis
)
914 return migrate_send_rp_message(mis
, MIG_RP_MSG_SWITCHOVER_ACK
, 0, NULL
);
918 * Send a 'SHUT' message on the return channel with the given value
919 * to indicate that we've finished with the RP. Non-0 value indicates
922 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
927 buf
= cpu_to_be32(value
);
928 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
932 * Send a 'PONG' message on the return channel with the given value
933 * (normally in response to a 'PING')
935 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
940 buf
= cpu_to_be32(value
);
941 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
944 void migrate_send_rp_recv_bitmap(MigrationIncomingState
*mis
,
952 * First, we send the header part. It contains only the len of
953 * idstr, and the idstr itself.
955 len
= strlen(block_name
);
957 memcpy(buf
+ 1, block_name
, len
);
959 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
960 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
965 migrate_send_rp_message(mis
, MIG_RP_MSG_RECV_BITMAP
, len
+ 1, buf
);
968 * Next, we dump the received bitmap to the stream.
970 * TODO: currently we are safe since we are the only one that is
971 * using the to_src_file handle (fault thread is still paused),
972 * and it's ok even not taking the mutex. However the best way is
973 * to take the lock before sending the message header, and release
974 * the lock after sending the bitmap.
976 qemu_mutex_lock(&mis
->rp_mutex
);
977 res
= ramblock_recv_bitmap_send(mis
->to_src_file
, block_name
);
978 qemu_mutex_unlock(&mis
->rp_mutex
);
980 trace_migrate_send_rp_recv_bitmap(block_name
, res
);
983 void migrate_send_rp_resume_ack(MigrationIncomingState
*mis
, uint32_t value
)
987 buf
= cpu_to_be32(value
);
988 migrate_send_rp_message(mis
, MIG_RP_MSG_RESUME_ACK
, sizeof(buf
), &buf
);
992 * Return true if we're already in the middle of a migration
993 * (i.e. any of the active or setup states)
995 bool migration_is_setup_or_active(int state
)
998 case MIGRATION_STATUS_ACTIVE
:
999 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1000 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1001 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1002 case MIGRATION_STATUS_SETUP
:
1003 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1004 case MIGRATION_STATUS_DEVICE
:
1005 case MIGRATION_STATUS_WAIT_UNPLUG
:
1006 case MIGRATION_STATUS_COLO
:
1015 bool migration_is_running(int state
)
1018 case MIGRATION_STATUS_ACTIVE
:
1019 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1020 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1021 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1022 case MIGRATION_STATUS_SETUP
:
1023 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1024 case MIGRATION_STATUS_DEVICE
:
1025 case MIGRATION_STATUS_WAIT_UNPLUG
:
1026 case MIGRATION_STATUS_CANCELLING
:
1035 static bool migrate_show_downtime(MigrationState
*s
)
1037 return (s
->state
== MIGRATION_STATUS_COMPLETED
) || migration_in_postcopy();
1040 static void populate_time_info(MigrationInfo
*info
, MigrationState
*s
)
1042 info
->has_status
= true;
1043 info
->has_setup_time
= true;
1044 info
->setup_time
= s
->setup_time
;
1046 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1047 info
->has_total_time
= true;
1048 info
->total_time
= s
->total_time
;
1050 info
->has_total_time
= true;
1051 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) -
1055 if (migrate_show_downtime(s
)) {
1056 info
->has_downtime
= true;
1057 info
->downtime
= s
->downtime
;
1059 info
->has_expected_downtime
= true;
1060 info
->expected_downtime
= s
->expected_downtime
;
1064 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
1066 size_t page_size
= qemu_target_page_size();
1068 info
->ram
= g_malloc0(sizeof(*info
->ram
));
1069 info
->ram
->transferred
= migration_transferred_bytes();
1070 info
->ram
->total
= ram_bytes_total();
1071 info
->ram
->duplicate
= stat64_get(&mig_stats
.zero_pages
);
1072 /* legacy value. It is not used anymore */
1073 info
->ram
->skipped
= 0;
1074 info
->ram
->normal
= stat64_get(&mig_stats
.normal_pages
);
1075 info
->ram
->normal_bytes
= info
->ram
->normal
* page_size
;
1076 info
->ram
->mbps
= s
->mbps
;
1077 info
->ram
->dirty_sync_count
=
1078 stat64_get(&mig_stats
.dirty_sync_count
);
1079 info
->ram
->dirty_sync_missed_zero_copy
=
1080 stat64_get(&mig_stats
.dirty_sync_missed_zero_copy
);
1081 info
->ram
->postcopy_requests
=
1082 stat64_get(&mig_stats
.postcopy_requests
);
1083 info
->ram
->page_size
= page_size
;
1084 info
->ram
->multifd_bytes
= stat64_get(&mig_stats
.multifd_bytes
);
1085 info
->ram
->pages_per_second
= s
->pages_per_second
;
1086 info
->ram
->precopy_bytes
= stat64_get(&mig_stats
.precopy_bytes
);
1087 info
->ram
->downtime_bytes
= stat64_get(&mig_stats
.downtime_bytes
);
1088 info
->ram
->postcopy_bytes
= stat64_get(&mig_stats
.postcopy_bytes
);
1090 if (migrate_xbzrle()) {
1091 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
1092 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
1093 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
1094 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
1095 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
1096 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
1097 info
->xbzrle_cache
->encoding_rate
= xbzrle_counters
.encoding_rate
;
1098 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
1101 populate_compress(info
);
1103 if (cpu_throttle_active()) {
1104 info
->has_cpu_throttle_percentage
= true;
1105 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
1108 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
1109 info
->ram
->remaining
= ram_bytes_remaining();
1110 info
->ram
->dirty_pages_rate
=
1111 stat64_get(&mig_stats
.dirty_pages_rate
);
1114 if (migrate_dirty_limit() && dirtylimit_in_service()) {
1115 info
->has_dirty_limit_throttle_time_per_round
= true;
1116 info
->dirty_limit_throttle_time_per_round
=
1117 dirtylimit_throttle_time_per_round();
1119 info
->has_dirty_limit_ring_full_time
= true;
1120 info
->dirty_limit_ring_full_time
= dirtylimit_ring_full_time();
1124 static void populate_disk_info(MigrationInfo
*info
)
1126 if (blk_mig_active()) {
1127 info
->disk
= g_malloc0(sizeof(*info
->disk
));
1128 info
->disk
->transferred
= blk_mig_bytes_transferred();
1129 info
->disk
->remaining
= blk_mig_bytes_remaining();
1130 info
->disk
->total
= blk_mig_bytes_total();
1134 static void fill_source_migration_info(MigrationInfo
*info
)
1136 MigrationState
*s
= migrate_get_current();
1137 int state
= qatomic_read(&s
->state
);
1138 GSList
*cur_blocker
= migration_blockers
[migrate_mode()];
1140 info
->blocked_reasons
= NULL
;
1143 * There are two types of reasons a migration might be blocked;
1144 * a) devices marked in VMState as non-migratable, and
1145 * b) Explicit migration blockers
1146 * We need to add both of them here.
1148 qemu_savevm_non_migratable_list(&info
->blocked_reasons
);
1150 while (cur_blocker
) {
1151 QAPI_LIST_PREPEND(info
->blocked_reasons
,
1152 g_strdup(error_get_pretty(cur_blocker
->data
)));
1153 cur_blocker
= g_slist_next(cur_blocker
);
1155 info
->has_blocked_reasons
= info
->blocked_reasons
!= NULL
;
1158 case MIGRATION_STATUS_NONE
:
1159 /* no migration has happened ever */
1160 /* do not overwrite destination migration status */
1162 case MIGRATION_STATUS_SETUP
:
1163 info
->has_status
= true;
1164 info
->has_total_time
= false;
1166 case MIGRATION_STATUS_ACTIVE
:
1167 case MIGRATION_STATUS_CANCELLING
:
1168 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1169 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1170 case MIGRATION_STATUS_DEVICE
:
1171 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1172 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1173 /* TODO add some postcopy stats */
1174 populate_time_info(info
, s
);
1175 populate_ram_info(info
, s
);
1176 populate_disk_info(info
);
1177 migration_populate_vfio_info(info
);
1179 case MIGRATION_STATUS_COLO
:
1180 info
->has_status
= true;
1181 /* TODO: display COLO specific information (checkpoint info etc.) */
1183 case MIGRATION_STATUS_COMPLETED
:
1184 populate_time_info(info
, s
);
1185 populate_ram_info(info
, s
);
1186 migration_populate_vfio_info(info
);
1188 case MIGRATION_STATUS_FAILED
:
1189 info
->has_status
= true;
1191 case MIGRATION_STATUS_CANCELLED
:
1192 info
->has_status
= true;
1194 case MIGRATION_STATUS_WAIT_UNPLUG
:
1195 info
->has_status
= true;
1198 info
->status
= state
;
1200 QEMU_LOCK_GUARD(&s
->error_mutex
);
1202 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
1206 static void fill_destination_migration_info(MigrationInfo
*info
)
1208 MigrationIncomingState
*mis
= migration_incoming_get_current();
1210 if (mis
->socket_address_list
) {
1211 info
->has_socket_address
= true;
1212 info
->socket_address
=
1213 QAPI_CLONE(SocketAddressList
, mis
->socket_address_list
);
1216 switch (mis
->state
) {
1217 case MIGRATION_STATUS_NONE
:
1219 case MIGRATION_STATUS_SETUP
:
1220 case MIGRATION_STATUS_CANCELLING
:
1221 case MIGRATION_STATUS_CANCELLED
:
1222 case MIGRATION_STATUS_ACTIVE
:
1223 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1224 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1225 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1226 case MIGRATION_STATUS_FAILED
:
1227 case MIGRATION_STATUS_COLO
:
1228 info
->has_status
= true;
1230 case MIGRATION_STATUS_COMPLETED
:
1231 info
->has_status
= true;
1232 fill_destination_postcopy_migration_info(info
);
1235 info
->status
= mis
->state
;
1238 MigrationInfo
*qmp_query_migrate(Error
**errp
)
1240 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
1242 fill_destination_migration_info(info
);
1243 fill_source_migration_info(info
);
1248 void qmp_migrate_start_postcopy(Error
**errp
)
1250 MigrationState
*s
= migrate_get_current();
1252 if (!migrate_postcopy()) {
1253 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1254 " the start of migration");
1258 if (s
->state
== MIGRATION_STATUS_NONE
) {
1259 error_setg(errp
, "Postcopy must be started after migration has been"
1264 * we don't error if migration has finished since that would be racy
1265 * with issuing this command.
1267 qatomic_set(&s
->start_postcopy
, true);
1270 /* shared migration helpers */
1272 void migrate_set_state(int *state
, int old_state
, int new_state
)
1274 assert(new_state
< MIGRATION_STATUS__MAX
);
1275 if (qatomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1276 trace_migrate_set_state(MigrationStatus_str(new_state
));
1277 migrate_generate_event(new_state
);
1281 static void migrate_fd_cleanup(MigrationState
*s
)
1283 qemu_bh_delete(s
->cleanup_bh
);
1284 s
->cleanup_bh
= NULL
;
1286 g_free(s
->hostname
);
1288 json_writer_free(s
->vmdesc
);
1291 qemu_savevm_state_cleanup();
1293 if (s
->to_dst_file
) {
1296 trace_migrate_fd_cleanup();
1297 qemu_mutex_unlock_iothread();
1298 if (s
->migration_thread_running
) {
1299 qemu_thread_join(&s
->thread
);
1300 s
->migration_thread_running
= false;
1302 qemu_mutex_lock_iothread();
1304 multifd_save_cleanup();
1305 qemu_mutex_lock(&s
->qemu_file_lock
);
1306 tmp
= s
->to_dst_file
;
1307 s
->to_dst_file
= NULL
;
1308 qemu_mutex_unlock(&s
->qemu_file_lock
);
1310 * Close the file handle without the lock to make sure the
1311 * critical section won't block for long.
1313 migration_ioc_unregister_yank_from_file(tmp
);
1318 * We already cleaned up to_dst_file, so errors from the return
1319 * path might be due to that, ignore them.
1321 close_return_path_on_source(s
);
1323 assert(!migration_is_active(s
));
1325 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1326 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1327 MIGRATION_STATUS_CANCELLED
);
1331 /* It is used on info migrate. We can't free it */
1332 error_report_err(error_copy(s
->error
));
1334 migration_call_notifiers(s
);
1335 block_cleanup_parameters();
1336 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1339 static void migrate_fd_cleanup_schedule(MigrationState
*s
)
1342 * Ref the state for bh, because it may be called when
1343 * there're already no other refs
1345 object_ref(OBJECT(s
));
1346 qemu_bh_schedule(s
->cleanup_bh
);
1349 static void migrate_fd_cleanup_bh(void *opaque
)
1351 MigrationState
*s
= opaque
;
1352 migrate_fd_cleanup(s
);
1353 object_unref(OBJECT(s
));
1356 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1358 QEMU_LOCK_GUARD(&s
->error_mutex
);
1360 s
->error
= error_copy(error
);
1364 bool migrate_has_error(MigrationState
*s
)
1366 /* The lock is not helpful here, but still follow the rule */
1367 QEMU_LOCK_GUARD(&s
->error_mutex
);
1368 return qatomic_read(&s
->error
);
1371 static void migrate_error_free(MigrationState
*s
)
1373 QEMU_LOCK_GUARD(&s
->error_mutex
);
1375 error_free(s
->error
);
1380 static void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1382 trace_migrate_fd_error(error_get_pretty(error
));
1383 assert(s
->to_dst_file
== NULL
);
1384 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1385 MIGRATION_STATUS_FAILED
);
1386 migrate_set_error(s
, error
);
1389 static void migrate_fd_cancel(MigrationState
*s
)
1393 trace_migrate_fd_cancel();
1395 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1396 if (s
->rp_state
.from_dst_file
) {
1397 /* shutdown the rp socket, so causing the rp thread to shutdown */
1398 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1403 old_state
= s
->state
;
1404 if (!migration_is_running(old_state
)) {
1407 /* If the migration is paused, kick it out of the pause */
1408 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1409 qemu_sem_post(&s
->pause_sem
);
1411 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1412 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1415 * If we're unlucky the migration code might be stuck somewhere in a
1416 * send/write while the network has failed and is waiting to timeout;
1417 * if we've got shutdown(2) available then we can force it to quit.
1419 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1420 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1421 if (s
->to_dst_file
) {
1422 qemu_file_shutdown(s
->to_dst_file
);
1426 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1427 Error
*local_err
= NULL
;
1429 bdrv_activate_all(&local_err
);
1431 error_report_err(local_err
);
1433 s
->block_inactive
= false;
1438 void migration_add_notifier(Notifier
*notify
,
1439 void (*func
)(Notifier
*notifier
, void *data
))
1441 notify
->notify
= func
;
1442 notifier_list_add(&migration_state_notifiers
, notify
);
1445 void migration_remove_notifier(Notifier
*notify
)
1447 if (notify
->notify
) {
1448 notifier_remove(notify
);
1449 notify
->notify
= NULL
;
1453 void migration_call_notifiers(MigrationState
*s
)
1455 notifier_list_notify(&migration_state_notifiers
, s
);
1458 bool migration_in_setup(MigrationState
*s
)
1460 return s
->state
== MIGRATION_STATUS_SETUP
;
1463 bool migration_has_finished(MigrationState
*s
)
1465 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1468 bool migration_has_failed(MigrationState
*s
)
1470 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1471 s
->state
== MIGRATION_STATUS_FAILED
);
1474 bool migration_in_postcopy(void)
1476 MigrationState
*s
= migrate_get_current();
1479 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1480 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1481 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1488 bool migration_postcopy_is_alive(int state
)
1491 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1492 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1499 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1501 return migration_in_postcopy() && s
->postcopy_after_devices
;
1504 bool migration_in_incoming_postcopy(void)
1506 PostcopyState ps
= postcopy_state_get();
1508 return ps
>= POSTCOPY_INCOMING_DISCARD
&& ps
< POSTCOPY_INCOMING_END
;
1511 bool migration_incoming_postcopy_advised(void)
1513 PostcopyState ps
= postcopy_state_get();
1515 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
1518 bool migration_in_bg_snapshot(void)
1520 MigrationState
*s
= migrate_get_current();
1522 return migrate_background_snapshot() &&
1523 migration_is_setup_or_active(s
->state
);
1526 bool migration_is_idle(void)
1528 MigrationState
*s
= current_migration
;
1535 case MIGRATION_STATUS_NONE
:
1536 case MIGRATION_STATUS_CANCELLED
:
1537 case MIGRATION_STATUS_COMPLETED
:
1538 case MIGRATION_STATUS_FAILED
:
1540 case MIGRATION_STATUS_SETUP
:
1541 case MIGRATION_STATUS_CANCELLING
:
1542 case MIGRATION_STATUS_ACTIVE
:
1543 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1544 case MIGRATION_STATUS_COLO
:
1545 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1546 case MIGRATION_STATUS_DEVICE
:
1547 case MIGRATION_STATUS_WAIT_UNPLUG
:
1549 case MIGRATION_STATUS__MAX
:
1550 g_assert_not_reached();
1556 bool migration_is_active(MigrationState
*s
)
1558 return (s
->state
== MIGRATION_STATUS_ACTIVE
||
1559 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1562 int migrate_init(MigrationState
*s
, Error
**errp
)
1566 ret
= qemu_savevm_state_prepare(errp
);
1572 * Reinitialise all migration state, except
1573 * parameters/capabilities that the user set, and
1578 s
->to_dst_file
= NULL
;
1579 s
->state
= MIGRATION_STATUS_NONE
;
1580 s
->rp_state
.from_dst_file
= NULL
;
1582 s
->pages_per_second
= 0.0;
1584 s
->expected_downtime
= 0;
1586 s
->start_postcopy
= false;
1587 s
->postcopy_after_devices
= false;
1588 s
->migration_thread_running
= false;
1589 error_free(s
->error
);
1594 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1596 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1598 s
->vm_old_state
= -1;
1599 s
->iteration_initial_bytes
= 0;
1600 s
->threshold_size
= 0;
1601 s
->switchover_acked
= false;
1602 s
->rdma_migration
= false;
1604 * set mig_stats memory to zero for a new migration
1606 memset(&mig_stats
, 0, sizeof(mig_stats
));
1607 migration_reset_vfio_bytes_transferred();
1612 static bool is_busy(Error
**reasonp
, Error
**errp
)
1616 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1617 if (runstate_check(RUN_STATE_SAVE_VM
) || !migration_is_idle()) {
1618 error_propagate_prepend(errp
, *reasonp
,
1619 "disallowing migration blocker "
1620 "(migration/snapshot in progress) for: ");
1627 static bool is_only_migratable(Error
**reasonp
, Error
**errp
, int modes
)
1631 if (only_migratable
&& (modes
& BIT(MIG_MODE_NORMAL
))) {
1632 error_propagate_prepend(errp
, *reasonp
,
1633 "disallowing migration blocker "
1634 "(--only-migratable) for: ");
1641 static int get_modes(MigMode mode
, va_list ap
)
1645 while (mode
!= -1 && mode
!= MIG_MODE_ALL
) {
1646 assert(mode
>= MIG_MODE_NORMAL
&& mode
< MIG_MODE__MAX
);
1648 mode
= va_arg(ap
, MigMode
);
1650 if (mode
== MIG_MODE_ALL
) {
1651 modes
= BIT(MIG_MODE__MAX
) - 1;
1656 static int add_blockers(Error
**reasonp
, Error
**errp
, int modes
)
1658 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1659 if (modes
& BIT(mode
)) {
1660 migration_blockers
[mode
] = g_slist_prepend(migration_blockers
[mode
],
1667 int migrate_add_blocker(Error
**reasonp
, Error
**errp
)
1669 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_ALL
);
1672 int migrate_add_blocker_normal(Error
**reasonp
, Error
**errp
)
1674 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_NORMAL
, -1);
1677 int migrate_add_blocker_modes(Error
**reasonp
, Error
**errp
, MigMode mode
, ...)
1683 modes
= get_modes(mode
, ap
);
1686 if (is_only_migratable(reasonp
, errp
, modes
)) {
1688 } else if (is_busy(reasonp
, errp
)) {
1691 return add_blockers(reasonp
, errp
, modes
);
1694 int migrate_add_blocker_internal(Error
**reasonp
, Error
**errp
)
1696 int modes
= BIT(MIG_MODE__MAX
) - 1;
1698 if (is_busy(reasonp
, errp
)) {
1701 return add_blockers(reasonp
, errp
, modes
);
1704 void migrate_del_blocker(Error
**reasonp
)
1707 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1708 migration_blockers
[mode
] = g_slist_remove(migration_blockers
[mode
],
1711 error_free(*reasonp
);
1716 void qmp_migrate_incoming(const char *uri
, bool has_channels
,
1717 MigrationChannelList
*channels
, Error
**errp
)
1719 Error
*local_err
= NULL
;
1720 static bool once
= true;
1723 error_setg(errp
, "The incoming migration has already been started");
1726 if (!runstate_check(RUN_STATE_INMIGRATE
)) {
1727 error_setg(errp
, "'-incoming' was not specified on the command line");
1731 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1735 qemu_start_incoming_migration(uri
, has_channels
, channels
, &local_err
);
1738 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1739 error_propagate(errp
, local_err
);
1746 void qmp_migrate_recover(const char *uri
, Error
**errp
)
1748 MigrationIncomingState
*mis
= migration_incoming_get_current();
1751 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1752 * callers (no one should ignore a recover failure); if there is, it's a
1753 * programming error.
1757 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1758 error_setg(errp
, "Migrate recover can only be run "
1759 "when postcopy is paused.");
1763 /* If there's an existing transport, release it */
1764 migration_incoming_transport_cleanup(mis
);
1767 * Note that this call will never start a real migration; it will
1768 * only re-setup the migration stream and poke existing migration
1769 * to continue using that newly established channel.
1771 qemu_start_incoming_migration(uri
, false, NULL
, errp
);
1774 void qmp_migrate_pause(Error
**errp
)
1776 MigrationState
*ms
= migrate_get_current();
1777 MigrationIncomingState
*mis
= migration_incoming_get_current();
1780 if (migration_postcopy_is_alive(ms
->state
)) {
1781 /* Source side, during postcopy */
1782 Error
*error
= NULL
;
1784 /* Tell the core migration that we're pausing */
1785 error_setg(&error
, "Postcopy migration is paused by the user");
1786 migrate_set_error(ms
, error
);
1789 qemu_mutex_lock(&ms
->qemu_file_lock
);
1790 if (ms
->to_dst_file
) {
1791 ret
= qemu_file_shutdown(ms
->to_dst_file
);
1793 qemu_mutex_unlock(&ms
->qemu_file_lock
);
1795 error_setg(errp
, "Failed to pause source migration");
1799 * Kick the migration thread out of any waiting windows (on behalf
1800 * of the rp thread).
1802 migration_rp_kick(ms
);
1807 if (migration_postcopy_is_alive(mis
->state
)) {
1808 ret
= qemu_file_shutdown(mis
->from_src_file
);
1810 error_setg(errp
, "Failed to pause destination migration");
1815 error_setg(errp
, "migrate-pause is currently only supported "
1816 "during postcopy-active or postcopy-recover state");
1819 bool migration_is_blocked(Error
**errp
)
1821 GSList
*blockers
= migration_blockers
[migrate_mode()];
1823 if (qemu_savevm_state_blocked(errp
)) {
1828 error_propagate(errp
, error_copy(blockers
->data
));
1835 /* Returns true if continue to migrate, or false if error detected */
1836 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1837 bool resume
, Error
**errp
)
1839 Error
*local_err
= NULL
;
1842 warn_report("parameter 'inc' is deprecated;"
1843 " use blockdev-mirror with NBD instead");
1847 warn_report("parameter 'blk' is deprecated;"
1848 " use blockdev-mirror with NBD instead");
1852 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1853 error_setg(errp
, "Cannot resume if there is no "
1854 "paused migration");
1859 * Postcopy recovery won't work well with release-ram
1860 * capability since release-ram will drop the page buffer as
1861 * long as the page is put into the send buffer. So if there
1862 * is a network failure happened, any page buffers that have
1863 * not yet reached the destination VM but have already been
1864 * sent from the source VM will be lost forever. Let's refuse
1865 * the client from resuming such a postcopy migration.
1866 * Luckily release-ram was designed to only be used when src
1867 * and destination VMs are on the same host, so it should be
1870 if (migrate_release_ram()) {
1871 error_setg(errp
, "Postcopy recovery cannot work "
1872 "when release-ram capability is set");
1876 /* This is a resume, skip init status */
1880 if (migration_is_running(s
->state
)) {
1881 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1885 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1886 error_setg(errp
, "Guest is waiting for an incoming migration");
1890 if (runstate_check(RUN_STATE_POSTMIGRATE
)) {
1891 error_setg(errp
, "Can't migrate the vm that was paused due to "
1892 "previous migration");
1896 if (migration_is_blocked(errp
)) {
1900 if (blk
|| blk_inc
) {
1901 if (migrate_colo()) {
1902 error_setg(errp
, "No disk migration is required in COLO mode");
1905 if (migrate_block() || migrate_block_incremental()) {
1906 error_setg(errp
, "Command options are incompatible with "
1907 "current migration capabilities");
1910 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK
, true, &local_err
)) {
1911 error_propagate(errp
, local_err
);
1914 s
->must_remove_block_options
= true;
1918 migrate_set_block_incremental(true);
1921 if (migrate_init(s
, errp
)) {
1928 void qmp_migrate(const char *uri
, bool has_channels
,
1929 MigrationChannelList
*channels
, bool has_blk
, bool blk
,
1930 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1931 bool has_resume
, bool resume
, Error
**errp
)
1933 bool resume_requested
;
1934 Error
*local_err
= NULL
;
1935 MigrationState
*s
= migrate_get_current();
1936 g_autoptr(MigrationChannel
) channel
= NULL
;
1937 MigrationAddress
*addr
= NULL
;
1940 * Having preliminary checks for uri and channel
1942 if (uri
&& has_channels
) {
1943 error_setg(errp
, "'uri' and 'channels' arguments are mutually "
1944 "exclusive; exactly one of the two should be present in "
1945 "'migrate' qmp command ");
1947 } else if (channels
) {
1948 /* To verify that Migrate channel list has only item */
1949 if (channels
->next
) {
1950 error_setg(errp
, "Channel list has more than one entries");
1953 addr
= channels
->value
->addr
;
1955 /* caller uses the old URI syntax */
1956 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
1959 addr
= channel
->addr
;
1961 error_setg(errp
, "neither 'uri' or 'channels' argument are "
1962 "specified in 'migrate' qmp command ");
1966 /* transport mechanism not suitable for migration? */
1967 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
1971 resume_requested
= has_resume
&& resume
;
1972 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
1973 resume_requested
, errp
)) {
1974 /* Error detected, put into errp */
1978 if (!resume_requested
) {
1979 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1984 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
1985 SocketAddress
*saddr
= &addr
->u
.socket
;
1986 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
1987 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
1988 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
1989 socket_start_outgoing_migration(s
, saddr
, &local_err
);
1990 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
1991 fd_start_outgoing_migration(s
, saddr
->u
.fd
.str
, &local_err
);
1994 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
1995 rdma_start_outgoing_migration(s
, &addr
->u
.rdma
, &local_err
);
1997 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
1998 exec_start_outgoing_migration(s
, addr
->u
.exec
.args
, &local_err
);
1999 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
2000 file_start_outgoing_migration(s
, &addr
->u
.file
, &local_err
);
2002 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "uri",
2003 "a valid migration protocol");
2004 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2005 MIGRATION_STATUS_FAILED
);
2006 block_cleanup_parameters();
2010 if (!resume_requested
) {
2011 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
2013 migrate_fd_error(s
, local_err
);
2014 error_propagate(errp
, local_err
);
2019 void qmp_migrate_cancel(Error
**errp
)
2021 migration_cancel(NULL
);
2024 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
2026 MigrationState
*s
= migrate_get_current();
2027 if (s
->state
!= state
) {
2028 error_setg(errp
, "Migration not in expected state: %s",
2029 MigrationStatus_str(s
->state
));
2032 qemu_sem_post(&s
->pause_sem
);
2035 int migration_rp_wait(MigrationState
*s
)
2037 /* If migration has failure already, ignore the wait */
2038 if (migrate_has_error(s
)) {
2042 qemu_sem_wait(&s
->rp_state
.rp_sem
);
2044 /* After wait, double check that there's no failure */
2045 if (migrate_has_error(s
)) {
2052 void migration_rp_kick(MigrationState
*s
)
2054 qemu_sem_post(&s
->rp_state
.rp_sem
);
2057 static struct rp_cmd_args
{
2058 ssize_t len
; /* -1 = variable */
2061 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
2062 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
2063 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
2064 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
2065 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
2066 [MIG_RP_MSG_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
2067 [MIG_RP_MSG_RESUME_ACK
] = { .len
= 4, .name
= "RESUME_ACK" },
2068 [MIG_RP_MSG_SWITCHOVER_ACK
] = { .len
= 0, .name
= "SWITCHOVER_ACK" },
2069 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
2073 * Process a request for pages received on the return path,
2074 * We're allowed to send more than requested (e.g. to round to our page size)
2075 * and we don't need to send pages that have already been sent.
2078 migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
2079 ram_addr_t start
, size_t len
, Error
**errp
)
2081 long our_host_ps
= qemu_real_host_page_size();
2083 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
2086 * Since we currently insist on matching page sizes, just sanity check
2087 * we're being asked for whole host pages.
2089 if (!QEMU_IS_ALIGNED(start
, our_host_ps
) ||
2090 !QEMU_IS_ALIGNED(len
, our_host_ps
)) {
2091 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
2092 RAM_ADDR_FMT
" len: %zd", start
, len
);
2096 ram_save_queue_pages(rbname
, start
, len
, errp
);
2099 static bool migrate_handle_rp_recv_bitmap(MigrationState
*s
, char *block_name
,
2102 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
2105 error_setg(errp
, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
2110 /* Fetch the received bitmap and refresh the dirty bitmap */
2111 return ram_dirty_bitmap_reload(s
, block
, errp
);
2114 static bool migrate_handle_rp_resume_ack(MigrationState
*s
,
2115 uint32_t value
, Error
**errp
)
2117 trace_source_return_path_thread_resume_ack(value
);
2119 if (value
!= MIGRATION_RESUME_ACK_VALUE
) {
2120 error_setg(errp
, "illegal resume_ack value %"PRIu32
, value
);
2124 /* Now both sides are active. */
2125 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
2126 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2128 /* Notify send thread that time to continue send pages */
2129 migration_rp_kick(s
);
2135 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2136 * existed) in a safe way.
2138 static void migration_release_dst_files(MigrationState
*ms
)
2142 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2144 * Reset the from_dst_file pointer first before releasing it, as we
2145 * can't block within lock section
2147 file
= ms
->rp_state
.from_dst_file
;
2148 ms
->rp_state
.from_dst_file
= NULL
;
2152 * Do the same to postcopy fast path socket too if there is. No
2153 * locking needed because this qemufile should only be managed by
2154 * return path thread.
2156 if (ms
->postcopy_qemufile_src
) {
2157 migration_ioc_unregister_yank_from_file(ms
->postcopy_qemufile_src
);
2158 qemu_file_shutdown(ms
->postcopy_qemufile_src
);
2159 qemu_fclose(ms
->postcopy_qemufile_src
);
2160 ms
->postcopy_qemufile_src
= NULL
;
2167 * Handles messages sent on the return path towards the source VM
2170 static void *source_return_path_thread(void *opaque
)
2172 MigrationState
*ms
= opaque
;
2173 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
2174 uint16_t header_len
, header_type
;
2176 uint32_t tmp32
, sibling_error
;
2177 ram_addr_t start
= 0; /* =0 to silence warning */
2178 size_t len
= 0, expected_len
;
2182 trace_source_return_path_thread_entry();
2183 rcu_register_thread();
2185 while (migration_is_setup_or_active(ms
->state
)) {
2186 trace_source_return_path_thread_loop_top();
2188 header_type
= qemu_get_be16(rp
);
2189 header_len
= qemu_get_be16(rp
);
2191 if (qemu_file_get_error(rp
)) {
2192 qemu_file_get_error_obj(rp
, &err
);
2196 if (header_type
>= MIG_RP_MSG_MAX
||
2197 header_type
== MIG_RP_MSG_INVALID
) {
2198 error_setg(&err
, "Received invalid message 0x%04x length 0x%04x",
2199 header_type
, header_len
);
2203 if ((rp_cmd_args
[header_type
].len
!= -1 &&
2204 header_len
!= rp_cmd_args
[header_type
].len
) ||
2205 header_len
> sizeof(buf
)) {
2206 error_setg(&err
, "Received '%s' message (0x%04x) with"
2207 "incorrect length %d expecting %zu",
2208 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
2209 (size_t)rp_cmd_args
[header_type
].len
);
2213 /* We know we've got a valid header by this point */
2214 res
= qemu_get_buffer(rp
, buf
, header_len
);
2215 if (res
!= header_len
) {
2216 error_setg(&err
, "Failed reading data for message 0x%04x"
2217 " read %d expected %d",
2218 header_type
, res
, header_len
);
2222 /* OK, we have the message and the data */
2223 switch (header_type
) {
2224 case MIG_RP_MSG_SHUT
:
2225 sibling_error
= ldl_be_p(buf
);
2226 trace_source_return_path_thread_shut(sibling_error
);
2227 if (sibling_error
) {
2228 error_setg(&err
, "Sibling indicated error %d", sibling_error
);
2231 * We'll let the main thread deal with closing the RP
2232 * we could do a shutdown(2) on it, but we're the only user
2233 * anyway, so there's nothing gained.
2237 case MIG_RP_MSG_PONG
:
2238 tmp32
= ldl_be_p(buf
);
2239 trace_source_return_path_thread_pong(tmp32
);
2240 qemu_sem_post(&ms
->rp_state
.rp_pong_acks
);
2243 case MIG_RP_MSG_REQ_PAGES
:
2244 start
= ldq_be_p(buf
);
2245 len
= ldl_be_p(buf
+ 8);
2246 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
, &err
);
2252 case MIG_RP_MSG_REQ_PAGES_ID
:
2253 expected_len
= 12 + 1; /* header + termination */
2255 if (header_len
>= expected_len
) {
2256 start
= ldq_be_p(buf
);
2257 len
= ldl_be_p(buf
+ 8);
2258 /* Now we expect an idstr */
2259 tmp32
= buf
[12]; /* Length of the following idstr */
2260 buf
[13 + tmp32
] = '\0';
2261 expected_len
+= tmp32
;
2263 if (header_len
!= expected_len
) {
2264 error_setg(&err
, "Req_Page_id with length %d expecting %zd",
2265 header_len
, expected_len
);
2268 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
,
2275 case MIG_RP_MSG_RECV_BITMAP
:
2276 if (header_len
< 1) {
2277 error_setg(&err
, "MIG_RP_MSG_RECV_BITMAP missing block name");
2280 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2281 buf
[buf
[0] + 1] = '\0';
2282 if (!migrate_handle_rp_recv_bitmap(ms
, (char *)(buf
+ 1), &err
)) {
2287 case MIG_RP_MSG_RESUME_ACK
:
2288 tmp32
= ldl_be_p(buf
);
2289 if (!migrate_handle_rp_resume_ack(ms
, tmp32
, &err
)) {
2294 case MIG_RP_MSG_SWITCHOVER_ACK
:
2295 ms
->switchover_acked
= true;
2296 trace_source_return_path_thread_switchover_acked();
2306 migrate_set_error(ms
, err
);
2308 trace_source_return_path_thread_bad_end();
2311 if (ms
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2313 * this will be extremely unlikely: that we got yet another network
2314 * issue during recovering of the 1st network failure.. during this
2315 * period the main migration thread can be waiting on rp_sem for
2316 * this thread to sync with the other side.
2318 * When this happens, explicitly kick the migration thread out of
2319 * RECOVER stage and back to PAUSED, so the admin can try
2322 migration_rp_kick(ms
);
2325 trace_source_return_path_thread_end();
2326 rcu_unregister_thread();
2331 static int open_return_path_on_source(MigrationState
*ms
)
2333 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
2334 if (!ms
->rp_state
.from_dst_file
) {
2338 trace_open_return_path_on_source();
2340 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2341 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2342 ms
->rp_state
.rp_thread_created
= true;
2344 trace_open_return_path_on_source_continue();
2349 /* Return true if error detected, or false otherwise */
2350 static bool close_return_path_on_source(MigrationState
*ms
)
2352 if (!ms
->rp_state
.rp_thread_created
) {
2356 trace_migration_return_path_end_before();
2359 * If this is a normal exit then the destination will send a SHUT
2360 * and the rp_thread will exit, however if there's an error we
2361 * need to cause it to exit. shutdown(2), if we have it, will
2362 * cause it to unblock if it's stuck waiting for the destination.
2364 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2365 if (ms
->to_dst_file
&& ms
->rp_state
.from_dst_file
&&
2366 qemu_file_get_error(ms
->to_dst_file
)) {
2367 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2371 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2372 ms
->rp_state
.rp_thread_created
= false;
2373 migration_release_dst_files(ms
);
2374 trace_migration_return_path_end_after();
2376 /* Return path will persist the error in MigrationState when quit */
2377 return migrate_has_error(ms
);
2381 migration_wait_main_channel(MigrationState
*ms
)
2383 /* Wait until one PONG message received */
2384 qemu_sem_wait(&ms
->rp_state
.rp_pong_acks
);
2388 * Switch from normal iteration to postcopy
2389 * Returns non-0 on error
2391 static int postcopy_start(MigrationState
*ms
, Error
**errp
)
2394 QIOChannelBuffer
*bioc
;
2396 uint64_t bandwidth
= migrate_max_postcopy_bandwidth();
2397 bool restart_block
= false;
2398 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2400 if (migrate_postcopy_preempt()) {
2401 migration_wait_main_channel(ms
);
2402 if (postcopy_preempt_establish_channel(ms
)) {
2403 migrate_set_state(&ms
->state
, ms
->state
, MIGRATION_STATUS_FAILED
);
2408 if (!migrate_pause_before_switchover()) {
2409 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2410 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2413 trace_postcopy_start();
2414 qemu_mutex_lock_iothread();
2415 trace_postcopy_start_set_run();
2417 migration_downtime_start(ms
);
2419 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2420 global_state_store();
2421 ret
= migration_stop_vm(RUN_STATE_FINISH_MIGRATE
);
2426 ret
= migration_maybe_pause(ms
, &cur_state
,
2427 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2432 ret
= bdrv_inactivate_all();
2436 restart_block
= true;
2439 * Cause any non-postcopiable, but iterative devices to
2440 * send out their final data.
2442 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2445 * in Finish migrate and with the io-lock held everything should
2446 * be quiet, but we've potentially still got dirty pages and we
2447 * need to tell the destination to throw any pages it's already received
2450 if (migrate_postcopy_ram()) {
2451 ram_postcopy_send_discard_bitmap(ms
);
2455 * send rest of state - note things that are doing postcopy
2456 * will notice we're in POSTCOPY_ACTIVE and not actually
2457 * wrap their state up here
2459 migration_rate_set(bandwidth
);
2460 if (migrate_postcopy_ram()) {
2461 /* Ping just for debugging, helps line traces up */
2462 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2466 * While loading the device state we may trigger page transfer
2467 * requests and the fd must be free to process those, and thus
2468 * the destination must read the whole device state off the fd before
2469 * it starts processing it. Unfortunately the ad-hoc migration format
2470 * doesn't allow the destination to know the size to read without fully
2471 * parsing it through each devices load-state code (especially the open
2472 * coded devices that use get/put).
2473 * So we wrap the device state up in a package with a length at the start;
2474 * to do this we use a qemu_buf to hold the whole of the device state.
2476 bioc
= qio_channel_buffer_new(4096);
2477 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2478 fb
= qemu_file_new_output(QIO_CHANNEL(bioc
));
2479 object_unref(OBJECT(bioc
));
2482 * Make sure the receiver can get incoming pages before we send the rest
2485 qemu_savevm_send_postcopy_listen(fb
);
2487 qemu_savevm_state_complete_precopy(fb
, false, false);
2488 if (migrate_postcopy_ram()) {
2489 qemu_savevm_send_ping(fb
, 3);
2492 qemu_savevm_send_postcopy_run(fb
);
2494 /* <><> end of stuff going into the package */
2496 /* Last point of recovery; as soon as we send the package the destination
2497 * can open devices and potentially start running.
2498 * Lets just check again we've not got any errors.
2500 ret
= qemu_file_get_error(ms
->to_dst_file
);
2502 error_setg(errp
, "postcopy_start: Migration stream errored (pre package)");
2506 restart_block
= false;
2508 /* Now send that blob */
2509 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2514 /* Send a notify to give a chance for anything that needs to happen
2515 * at the transition to postcopy and after the device state; in particular
2516 * spice needs to trigger a transition now
2518 ms
->postcopy_after_devices
= true;
2519 migration_call_notifiers(ms
);
2521 migration_downtime_end(ms
);
2523 qemu_mutex_unlock_iothread();
2525 if (migrate_postcopy_ram()) {
2527 * Although this ping is just for debug, it could potentially be
2528 * used for getting a better measurement of downtime at the source.
2530 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2533 if (migrate_release_ram()) {
2534 ram_postcopy_migrated_memory_release(ms
);
2537 ret
= qemu_file_get_error(ms
->to_dst_file
);
2539 error_setg(errp
, "postcopy_start: Migration stream errored");
2540 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2541 MIGRATION_STATUS_FAILED
);
2544 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2551 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2552 MIGRATION_STATUS_FAILED
);
2553 if (restart_block
) {
2554 /* A failure happened early enough that we know the destination hasn't
2555 * accessed block devices, so we're safe to recover.
2557 Error
*local_err
= NULL
;
2559 bdrv_activate_all(&local_err
);
2561 error_report_err(local_err
);
2564 qemu_mutex_unlock_iothread();
2569 * migration_maybe_pause: Pause if required to by
2570 * migrate_pause_before_switchover called with the iothread locked
2571 * Returns: 0 on success
2573 static int migration_maybe_pause(MigrationState
*s
,
2574 int *current_active_state
,
2577 if (!migrate_pause_before_switchover()) {
2581 /* Since leaving this state is not atomic with posting the semaphore
2582 * it's possible that someone could have issued multiple migrate_continue
2583 * and the semaphore is incorrectly positive at this point;
2584 * the docs say it's undefined to reinit a semaphore that's already
2585 * init'd, so use timedwait to eat up any existing posts.
2587 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2588 /* This block intentionally left blank */
2592 * If the migration is cancelled when it is in the completion phase,
2593 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2594 * So we don't need to wait a semaphore, otherwise we would always
2595 * wait for the 'pause_sem' semaphore.
2597 if (s
->state
!= MIGRATION_STATUS_CANCELLING
) {
2598 qemu_mutex_unlock_iothread();
2599 migrate_set_state(&s
->state
, *current_active_state
,
2600 MIGRATION_STATUS_PRE_SWITCHOVER
);
2601 qemu_sem_wait(&s
->pause_sem
);
2602 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2604 *current_active_state
= new_state
;
2605 qemu_mutex_lock_iothread();
2608 return s
->state
== new_state
? 0 : -EINVAL
;
2611 static int migration_completion_precopy(MigrationState
*s
,
2612 int *current_active_state
)
2616 qemu_mutex_lock_iothread();
2617 migration_downtime_start(s
);
2618 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2620 s
->vm_old_state
= runstate_get();
2621 global_state_store();
2623 ret
= migration_stop_vm(RUN_STATE_FINISH_MIGRATE
);
2624 trace_migration_completion_vm_stop(ret
);
2629 ret
= migration_maybe_pause(s
, current_active_state
,
2630 MIGRATION_STATUS_DEVICE
);
2636 * Inactivate disks except in COLO, and track that we have done so in order
2637 * to remember to reactivate them if migration fails or is cancelled.
2639 s
->block_inactive
= !migrate_colo();
2640 migration_rate_set(RATE_LIMIT_DISABLED
);
2641 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2644 qemu_mutex_unlock_iothread();
2648 static void migration_completion_postcopy(MigrationState
*s
)
2650 trace_migration_completion_postcopy_end();
2652 qemu_mutex_lock_iothread();
2653 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2654 qemu_mutex_unlock_iothread();
2657 * Shutdown the postcopy fast path thread. This is only needed when dest
2658 * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
2660 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
2661 postcopy_preempt_shutdown_file(s
);
2664 trace_migration_completion_postcopy_end_after_complete();
2667 static void migration_completion_failed(MigrationState
*s
,
2668 int current_active_state
)
2670 if (s
->block_inactive
&& (s
->state
== MIGRATION_STATUS_ACTIVE
||
2671 s
->state
== MIGRATION_STATUS_DEVICE
)) {
2673 * If not doing postcopy, vm_start() will be called: let's
2674 * regain control on images.
2676 Error
*local_err
= NULL
;
2678 qemu_mutex_lock_iothread();
2679 bdrv_activate_all(&local_err
);
2681 error_report_err(local_err
);
2683 s
->block_inactive
= false;
2685 qemu_mutex_unlock_iothread();
2688 migrate_set_state(&s
->state
, current_active_state
,
2689 MIGRATION_STATUS_FAILED
);
2693 * migration_completion: Used by migration_thread when there's not much left.
2694 * The caller 'breaks' the loop when this returns.
2696 * @s: Current migration state
2698 static void migration_completion(MigrationState
*s
)
2701 int current_active_state
= s
->state
;
2703 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2704 ret
= migration_completion_precopy(s
, ¤t_active_state
);
2705 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2706 migration_completion_postcopy(s
);
2715 if (close_return_path_on_source(s
)) {
2719 if (qemu_file_get_error(s
->to_dst_file
)) {
2720 trace_migration_completion_file_err();
2724 if (migrate_colo() && s
->state
== MIGRATION_STATUS_ACTIVE
) {
2725 /* COLO does not support postcopy */
2726 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
2727 MIGRATION_STATUS_COLO
);
2729 migrate_set_state(&s
->state
, current_active_state
,
2730 MIGRATION_STATUS_COMPLETED
);
2736 migration_completion_failed(s
, current_active_state
);
2740 * bg_migration_completion: Used by bg_migration_thread when after all the
2741 * RAM has been saved. The caller 'breaks' the loop when this returns.
2743 * @s: Current migration state
2745 static void bg_migration_completion(MigrationState
*s
)
2747 int current_active_state
= s
->state
;
2749 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2751 * By this moment we have RAM content saved into the migration stream.
2752 * The next step is to flush the non-RAM content (device state)
2753 * right after the ram content. The device state has been stored into
2754 * the temporary buffer before RAM saving started.
2756 qemu_put_buffer(s
->to_dst_file
, s
->bioc
->data
, s
->bioc
->usage
);
2757 qemu_fflush(s
->to_dst_file
);
2758 } else if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
2762 if (qemu_file_get_error(s
->to_dst_file
)) {
2763 trace_migration_completion_file_err();
2767 migrate_set_state(&s
->state
, current_active_state
,
2768 MIGRATION_STATUS_COMPLETED
);
2772 migrate_set_state(&s
->state
, current_active_state
,
2773 MIGRATION_STATUS_FAILED
);
2776 typedef enum MigThrError
{
2777 /* No error detected */
2778 MIG_THR_ERR_NONE
= 0,
2779 /* Detected error, but resumed successfully */
2780 MIG_THR_ERR_RECOVERED
= 1,
2781 /* Detected fatal error, need to exit */
2782 MIG_THR_ERR_FATAL
= 2,
2785 static int postcopy_resume_handshake(MigrationState
*s
)
2787 qemu_savevm_send_postcopy_resume(s
->to_dst_file
);
2789 while (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2790 if (migration_rp_wait(s
)) {
2795 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2802 /* Return zero if success, or <0 for error */
2803 static int postcopy_do_resume(MigrationState
*s
)
2808 * Call all the resume_prepare() hooks, so that modules can be
2809 * ready for the migration resume.
2811 ret
= qemu_savevm_state_resume_prepare(s
);
2813 error_report("%s: resume_prepare() failure detected: %d",
2819 * If preempt is enabled, re-establish the preempt channel. Note that
2820 * we do it after resume prepare to make sure the main channel will be
2821 * created before the preempt channel. E.g. with weak network, the
2822 * dest QEMU may get messed up with the preempt and main channels on
2823 * the order of connection setup. This guarantees the correct order.
2825 ret
= postcopy_preempt_establish_channel(s
);
2827 error_report("%s: postcopy_preempt_establish_channel(): %d",
2833 * Last handshake with destination on the resume (destination will
2834 * switch to postcopy-active afterwards)
2836 ret
= postcopy_resume_handshake(s
);
2838 error_report("%s: handshake failed: %d", __func__
, ret
);
2846 * We don't return until we are in a safe state to continue current
2847 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2848 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2850 static MigThrError
postcopy_pause(MigrationState
*s
)
2852 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2858 * Current channel is possibly broken. Release it. Note that this is
2859 * guaranteed even without lock because to_dst_file should only be
2860 * modified by the migration thread. That also guarantees that the
2861 * unregister of yank is safe too without the lock. It should be safe
2862 * even to be within the qemu_file_lock, but we didn't do that to avoid
2863 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2864 * the qemu_file_lock critical section as small as possible.
2866 assert(s
->to_dst_file
);
2867 migration_ioc_unregister_yank_from_file(s
->to_dst_file
);
2868 qemu_mutex_lock(&s
->qemu_file_lock
);
2869 file
= s
->to_dst_file
;
2870 s
->to_dst_file
= NULL
;
2871 qemu_mutex_unlock(&s
->qemu_file_lock
);
2873 qemu_file_shutdown(file
);
2877 * We're already pausing, so ignore any errors on the return
2878 * path and just wait for the thread to finish. It will be
2879 * re-created when we resume.
2881 close_return_path_on_source(s
);
2883 migrate_set_state(&s
->state
, s
->state
,
2884 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2886 error_report("Detected IO failure for postcopy. "
2887 "Migration paused.");
2890 * We wait until things fixed up. Then someone will setup the
2891 * status back for us.
2893 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2894 qemu_sem_wait(&s
->postcopy_pause_sem
);
2897 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2898 /* Woken up by a recover procedure. Give it a shot */
2900 /* Do the resume logic */
2901 if (postcopy_do_resume(s
) == 0) {
2902 /* Let's continue! */
2903 trace_postcopy_pause_continued();
2904 return MIG_THR_ERR_RECOVERED
;
2907 * Something wrong happened during the recovery, let's
2908 * pause again. Pause is always better than throwing
2914 /* This is not right... Time to quit. */
2915 return MIG_THR_ERR_FATAL
;
2920 static MigThrError
migration_detect_error(MigrationState
*s
)
2923 int state
= s
->state
;
2924 Error
*local_error
= NULL
;
2926 if (state
== MIGRATION_STATUS_CANCELLING
||
2927 state
== MIGRATION_STATUS_CANCELLED
) {
2928 /* End the migration, but don't set the state to failed */
2929 return MIG_THR_ERR_FATAL
;
2933 * Try to detect any file errors. Note that postcopy_qemufile_src will
2934 * be NULL when postcopy preempt is not enabled.
2936 ret
= qemu_file_get_error_obj_any(s
->to_dst_file
,
2937 s
->postcopy_qemufile_src
,
2940 /* Everything is fine */
2941 assert(!local_error
);
2942 return MIG_THR_ERR_NONE
;
2946 migrate_set_error(s
, local_error
);
2947 error_free(local_error
);
2950 if (state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
) {
2952 * For postcopy, we allow the network to be down for a
2953 * while. After that, it can be continued by a
2956 return postcopy_pause(s
);
2959 * For precopy (or postcopy with error outside IO), we fail
2962 migrate_set_state(&s
->state
, state
, MIGRATION_STATUS_FAILED
);
2963 trace_migration_thread_file_err();
2965 /* Time to stop the migration, now. */
2966 return MIG_THR_ERR_FATAL
;
2970 static void migration_calculate_complete(MigrationState
*s
)
2972 uint64_t bytes
= migration_transferred_bytes();
2973 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2974 int64_t transfer_time
;
2976 migration_downtime_end(s
);
2977 s
->total_time
= end_time
- s
->start_time
;
2978 transfer_time
= s
->total_time
- s
->setup_time
;
2979 if (transfer_time
) {
2980 s
->mbps
= ((double) bytes
* 8.0) / transfer_time
/ 1000;
2984 static void update_iteration_initial_status(MigrationState
*s
)
2987 * Update these three fields at the same time to avoid mismatch info lead
2988 * wrong speed calculation.
2990 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2991 s
->iteration_initial_bytes
= migration_transferred_bytes();
2992 s
->iteration_initial_pages
= ram_get_total_transferred_pages();
2995 static void migration_update_counters(MigrationState
*s
,
2996 int64_t current_time
)
2998 uint64_t transferred
, transferred_pages
, time_spent
;
2999 uint64_t current_bytes
; /* bytes transferred since the beginning */
3000 uint64_t switchover_bw
;
3001 /* Expected bandwidth when switching over to destination QEMU */
3002 double expected_bw_per_ms
;
3005 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
3009 switchover_bw
= migrate_avail_switchover_bandwidth();
3010 current_bytes
= migration_transferred_bytes();
3011 transferred
= current_bytes
- s
->iteration_initial_bytes
;
3012 time_spent
= current_time
- s
->iteration_start_time
;
3013 bandwidth
= (double)transferred
/ time_spent
;
3015 if (switchover_bw
) {
3017 * If the user specified a switchover bandwidth, let's trust the
3018 * user so that can be more accurate than what we estimated.
3020 expected_bw_per_ms
= switchover_bw
/ 1000;
3022 /* If the user doesn't specify bandwidth, we use the estimated */
3023 expected_bw_per_ms
= bandwidth
;
3026 s
->threshold_size
= expected_bw_per_ms
* migrate_downtime_limit();
3028 s
->mbps
= (((double) transferred
* 8.0) /
3029 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
3031 transferred_pages
= ram_get_total_transferred_pages() -
3032 s
->iteration_initial_pages
;
3033 s
->pages_per_second
= (double) transferred_pages
/
3034 (((double) time_spent
/ 1000.0));
3037 * if we haven't sent anything, we don't want to
3038 * recalculate. 10000 is a small enough number for our purposes
3040 if (stat64_get(&mig_stats
.dirty_pages_rate
) &&
3041 transferred
> 10000) {
3042 s
->expected_downtime
=
3043 stat64_get(&mig_stats
.dirty_bytes_last_sync
) / expected_bw_per_ms
;
3046 migration_rate_reset();
3048 update_iteration_initial_status(s
);
3050 trace_migrate_transferred(transferred
, time_spent
,
3051 /* Both in unit bytes/ms */
3052 bandwidth
, switchover_bw
/ 1000,
3056 static bool migration_can_switchover(MigrationState
*s
)
3058 if (!migrate_switchover_ack()) {
3062 /* No reason to wait for switchover ACK if VM is stopped */
3063 if (!runstate_is_running()) {
3067 return s
->switchover_acked
;
3070 /* Migration thread iteration status */
3072 MIG_ITERATE_RESUME
, /* Resume current iteration */
3073 MIG_ITERATE_SKIP
, /* Skip current iteration */
3074 MIG_ITERATE_BREAK
, /* Break the loop */
3078 * Return true if continue to the next iteration directly, false
3081 static MigIterateState
migration_iteration_run(MigrationState
*s
)
3083 uint64_t must_precopy
, can_postcopy
;
3084 Error
*local_err
= NULL
;
3085 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
3086 bool can_switchover
= migration_can_switchover(s
);
3088 qemu_savevm_state_pending_estimate(&must_precopy
, &can_postcopy
);
3089 uint64_t pending_size
= must_precopy
+ can_postcopy
;
3091 trace_migrate_pending_estimate(pending_size
, must_precopy
, can_postcopy
);
3093 if (must_precopy
<= s
->threshold_size
) {
3094 qemu_savevm_state_pending_exact(&must_precopy
, &can_postcopy
);
3095 pending_size
= must_precopy
+ can_postcopy
;
3096 trace_migrate_pending_exact(pending_size
, must_precopy
, can_postcopy
);
3099 if ((!pending_size
|| pending_size
< s
->threshold_size
) && can_switchover
) {
3100 trace_migration_thread_low_pending(pending_size
);
3101 migration_completion(s
);
3102 return MIG_ITERATE_BREAK
;
3105 /* Still a significant amount to transfer */
3106 if (!in_postcopy
&& must_precopy
<= s
->threshold_size
&& can_switchover
&&
3107 qatomic_read(&s
->start_postcopy
)) {
3108 if (postcopy_start(s
, &local_err
)) {
3109 migrate_set_error(s
, local_err
);
3110 error_report_err(local_err
);
3112 return MIG_ITERATE_SKIP
;
3115 /* Just another iteration step */
3116 qemu_savevm_state_iterate(s
->to_dst_file
, in_postcopy
);
3117 return MIG_ITERATE_RESUME
;
3120 static void migration_iteration_finish(MigrationState
*s
)
3122 /* If we enabled cpu throttling for auto-converge, turn it off. */
3123 cpu_throttle_stop();
3125 qemu_mutex_lock_iothread();
3127 case MIGRATION_STATUS_COMPLETED
:
3128 migration_calculate_complete(s
);
3129 runstate_set(RUN_STATE_POSTMIGRATE
);
3131 case MIGRATION_STATUS_COLO
:
3132 assert(migrate_colo());
3133 migrate_start_colo_process(s
);
3134 s
->vm_old_state
= RUN_STATE_RUNNING
;
3136 case MIGRATION_STATUS_FAILED
:
3137 case MIGRATION_STATUS_CANCELLED
:
3138 case MIGRATION_STATUS_CANCELLING
:
3139 if (s
->vm_old_state
== RUN_STATE_RUNNING
) {
3140 if (!runstate_check(RUN_STATE_SHUTDOWN
)) {
3144 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
3145 runstate_set(s
->vm_old_state
);
3151 /* Should not reach here, but if so, forgive the VM. */
3152 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3155 migrate_fd_cleanup_schedule(s
);
3156 qemu_mutex_unlock_iothread();
3159 static void bg_migration_iteration_finish(MigrationState
*s
)
3162 * Stop tracking RAM writes - un-protect memory, un-register UFFD
3163 * memory ranges, flush kernel wait queues and wake up threads
3164 * waiting for write fault to be resolved.
3166 ram_write_tracking_stop();
3168 qemu_mutex_lock_iothread();
3170 case MIGRATION_STATUS_COMPLETED
:
3171 migration_calculate_complete(s
);
3174 case MIGRATION_STATUS_ACTIVE
:
3175 case MIGRATION_STATUS_FAILED
:
3176 case MIGRATION_STATUS_CANCELLED
:
3177 case MIGRATION_STATUS_CANCELLING
:
3181 /* Should not reach here, but if so, forgive the VM. */
3182 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3186 migrate_fd_cleanup_schedule(s
);
3187 qemu_mutex_unlock_iothread();
3191 * Return true if continue to the next iteration directly, false
3194 static MigIterateState
bg_migration_iteration_run(MigrationState
*s
)
3198 res
= qemu_savevm_state_iterate(s
->to_dst_file
, false);
3200 bg_migration_completion(s
);
3201 return MIG_ITERATE_BREAK
;
3204 return MIG_ITERATE_RESUME
;
3207 void migration_make_urgent_request(void)
3209 qemu_sem_post(&migrate_get_current()->rate_limit_sem
);
3212 void migration_consume_urgent_request(void)
3214 qemu_sem_wait(&migrate_get_current()->rate_limit_sem
);
3217 /* Returns true if the rate limiting was broken by an urgent request */
3218 bool migration_rate_limit(void)
3220 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3221 MigrationState
*s
= migrate_get_current();
3223 bool urgent
= false;
3224 migration_update_counters(s
, now
);
3225 if (migration_rate_exceeded(s
->to_dst_file
)) {
3227 if (qemu_file_get_error(s
->to_dst_file
)) {
3231 * Wait for a delay to do rate limiting OR
3232 * something urgent to post the semaphore.
3234 int ms
= s
->iteration_start_time
+ BUFFER_DELAY
- now
;
3235 trace_migration_rate_limit_pre(ms
);
3236 if (qemu_sem_timedwait(&s
->rate_limit_sem
, ms
) == 0) {
3238 * We were woken by one or more urgent things but
3239 * the timedwait will have consumed one of them.
3240 * The service routine for the urgent wake will dec
3241 * the semaphore itself for each item it consumes,
3242 * so add this one we just eat back.
3244 qemu_sem_post(&s
->rate_limit_sem
);
3247 trace_migration_rate_limit_post(urgent
);
3253 * if failover devices are present, wait they are completely
3257 static void qemu_savevm_wait_unplug(MigrationState
*s
, int old_state
,
3260 if (qemu_savevm_state_guest_unplug_pending()) {
3261 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_WAIT_UNPLUG
);
3263 while (s
->state
== MIGRATION_STATUS_WAIT_UNPLUG
&&
3264 qemu_savevm_state_guest_unplug_pending()) {
3265 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3267 if (s
->state
!= MIGRATION_STATUS_WAIT_UNPLUG
) {
3268 int timeout
= 120; /* 30 seconds */
3270 * migration has been canceled
3271 * but as we have started an unplug we must wait the end
3272 * to be able to plug back the card
3274 while (timeout
-- && qemu_savevm_state_guest_unplug_pending()) {
3275 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3277 if (qemu_savevm_state_guest_unplug_pending() &&
3279 warn_report("migration: partially unplugged device on "
3284 migrate_set_state(&s
->state
, MIGRATION_STATUS_WAIT_UNPLUG
, new_state
);
3286 migrate_set_state(&s
->state
, old_state
, new_state
);
3291 * Master migration thread on the source VM.
3292 * It drives the migration and pumps the data down the outgoing channel.
3294 static void *migration_thread(void *opaque
)
3296 MigrationState
*s
= opaque
;
3297 MigrationThread
*thread
= NULL
;
3298 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3299 MigThrError thr_error
;
3300 bool urgent
= false;
3302 thread
= migration_threads_add("live_migration", qemu_get_thread_id());
3304 rcu_register_thread();
3306 object_ref(OBJECT(s
));
3307 update_iteration_initial_status(s
);
3309 qemu_mutex_lock_iothread();
3310 qemu_savevm_state_header(s
->to_dst_file
);
3311 qemu_mutex_unlock_iothread();
3314 * If we opened the return path, we need to make sure dst has it
3317 if (s
->rp_state
.rp_thread_created
) {
3318 /* Now tell the dest that it should open its end so it can reply */
3319 qemu_savevm_send_open_return_path(s
->to_dst_file
);
3321 /* And do a ping that will make stuff easier to debug */
3322 qemu_savevm_send_ping(s
->to_dst_file
, 1);
3325 if (migrate_postcopy()) {
3327 * Tell the destination that we *might* want to do postcopy later;
3328 * if the other end can't do postcopy it should fail now, nice and
3331 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
3334 if (migrate_colo()) {
3335 /* Notify migration destination that we enable COLO */
3336 qemu_savevm_send_colo_enable(s
->to_dst_file
);
3339 qemu_mutex_lock_iothread();
3340 qemu_savevm_state_setup(s
->to_dst_file
);
3341 qemu_mutex_unlock_iothread();
3343 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3344 MIGRATION_STATUS_ACTIVE
);
3346 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3348 trace_migration_thread_setup_complete();
3350 while (migration_is_active(s
)) {
3351 if (urgent
|| !migration_rate_exceeded(s
->to_dst_file
)) {
3352 MigIterateState iter_state
= migration_iteration_run(s
);
3353 if (iter_state
== MIG_ITERATE_SKIP
) {
3355 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3361 * Try to detect any kind of failures, and see whether we
3362 * should stop the migration now.
3364 thr_error
= migration_detect_error(s
);
3365 if (thr_error
== MIG_THR_ERR_FATAL
) {
3366 /* Stop migration */
3368 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
3370 * Just recovered from a e.g. network failure, reset all
3371 * the local variables. This is important to avoid
3372 * breaking transferred_bytes and bandwidth calculation
3374 update_iteration_initial_status(s
);
3377 urgent
= migration_rate_limit();
3380 trace_migration_thread_after_loop();
3381 migration_iteration_finish(s
);
3382 object_unref(OBJECT(s
));
3383 rcu_unregister_thread();
3384 migration_threads_remove(thread
);
3388 static void bg_migration_vm_start_bh(void *opaque
)
3390 MigrationState
*s
= opaque
;
3392 qemu_bh_delete(s
->vm_start_bh
);
3393 s
->vm_start_bh
= NULL
;
3396 migration_downtime_end(s
);
3400 * Background snapshot thread, based on live migration code.
3401 * This is an alternative implementation of live migration mechanism
3402 * introduced specifically to support background snapshots.
3404 * It takes advantage of userfault_fd write protection mechanism introduced
3405 * in v5.7 kernel. Compared to existing dirty page logging migration much
3406 * lesser stream traffic is produced resulting in smaller snapshot images,
3407 * simply cause of no page duplicates can get into the stream.
3409 * Another key point is that generated vmstate stream reflects machine state
3410 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3411 * mechanism, which effectively results in that saved snapshot is the state of VM
3412 * at the end of the process.
3414 static void *bg_migration_thread(void *opaque
)
3416 MigrationState
*s
= opaque
;
3417 int64_t setup_start
;
3418 MigThrError thr_error
;
3420 bool early_fail
= true;
3422 rcu_register_thread();
3423 object_ref(OBJECT(s
));
3425 migration_rate_set(RATE_LIMIT_DISABLED
);
3427 setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3429 * We want to save vmstate for the moment when migration has been
3430 * initiated but also we want to save RAM content while VM is running.
3431 * The RAM content should appear first in the vmstate. So, we first
3432 * stash the non-RAM part of the vmstate to the temporary buffer,
3433 * then write RAM part of the vmstate to the migration stream
3434 * with vCPUs running and, finally, write stashed non-RAM part of
3435 * the vmstate from the buffer to the migration stream.
3437 s
->bioc
= qio_channel_buffer_new(512 * 1024);
3438 qio_channel_set_name(QIO_CHANNEL(s
->bioc
), "vmstate-buffer");
3439 fb
= qemu_file_new_output(QIO_CHANNEL(s
->bioc
));
3440 object_unref(OBJECT(s
->bioc
));
3442 update_iteration_initial_status(s
);
3445 * Prepare for tracking memory writes with UFFD-WP - populate
3446 * RAM pages before protecting.
3449 ram_write_tracking_prepare();
3452 qemu_mutex_lock_iothread();
3453 qemu_savevm_state_header(s
->to_dst_file
);
3454 qemu_savevm_state_setup(s
->to_dst_file
);
3455 qemu_mutex_unlock_iothread();
3457 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3458 MIGRATION_STATUS_ACTIVE
);
3460 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3462 trace_migration_thread_setup_complete();
3463 migration_downtime_start(s
);
3465 qemu_mutex_lock_iothread();
3468 * If VM is currently in suspended state, then, to make a valid runstate
3469 * transition in vm_stop_force_state() we need to wakeup it up.
3471 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
3472 s
->vm_old_state
= runstate_get();
3474 global_state_store();
3475 /* Forcibly stop VM before saving state of vCPUs and devices */
3476 if (migration_stop_vm(RUN_STATE_PAUSED
)) {
3480 * Put vCPUs in sync with shadow context structures, then
3481 * save their state to channel-buffer along with devices.
3483 cpu_synchronize_all_states();
3484 if (qemu_savevm_state_complete_precopy_non_iterable(fb
, false, false)) {
3488 * Since we are going to get non-iterable state data directly
3489 * from s->bioc->data, explicit flush is needed here.
3493 /* Now initialize UFFD context and start tracking RAM writes */
3494 if (ram_write_tracking_start()) {
3500 * Start VM from BH handler to avoid write-fault lock here.
3501 * UFFD-WP protection for the whole RAM is already enabled so
3502 * calling VM state change notifiers from vm_start() would initiate
3503 * writes to virtio VQs memory which is in write-protected region.
3505 s
->vm_start_bh
= qemu_bh_new(bg_migration_vm_start_bh
, s
);
3506 qemu_bh_schedule(s
->vm_start_bh
);
3508 qemu_mutex_unlock_iothread();
3510 while (migration_is_active(s
)) {
3511 MigIterateState iter_state
= bg_migration_iteration_run(s
);
3512 if (iter_state
== MIG_ITERATE_SKIP
) {
3514 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3519 * Try to detect any kind of failures, and see whether we
3520 * should stop the migration now.
3522 thr_error
= migration_detect_error(s
);
3523 if (thr_error
== MIG_THR_ERR_FATAL
) {
3524 /* Stop migration */
3528 migration_update_counters(s
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
));
3531 trace_migration_thread_after_loop();
3535 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
3536 MIGRATION_STATUS_FAILED
);
3537 qemu_mutex_unlock_iothread();
3540 bg_migration_iteration_finish(s
);
3543 object_unref(OBJECT(s
));
3544 rcu_unregister_thread();
3549 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
3551 Error
*local_err
= NULL
;
3552 uint64_t rate_limit
;
3553 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
3556 * If there's a previous error, free it and prepare for another one.
3557 * Meanwhile if migration completes successfully, there won't have an error
3558 * dumped when calling migrate_fd_cleanup().
3560 migrate_error_free(s
);
3562 s
->expected_downtime
= migrate_downtime_limit();
3564 assert(s
->cleanup_bh
);
3566 assert(!s
->cleanup_bh
);
3567 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup_bh
, s
);
3570 migrate_fd_error(s
, error_in
);
3573 * Don't do cleanup for resume if channel is invalid, but only dump
3574 * the error. We wait for another channel connect from the user.
3575 * The error_report still gives HMP user a hint on what failed.
3576 * It's normally done in migrate_fd_cleanup(), but call it here
3579 error_report_err(error_copy(s
->error
));
3581 migrate_fd_cleanup(s
);
3587 /* This is a resumed migration */
3588 rate_limit
= migrate_max_postcopy_bandwidth();
3590 /* This is a fresh new migration */
3591 rate_limit
= migrate_max_bandwidth();
3593 /* Notify before starting migration thread */
3594 migration_call_notifiers(s
);
3597 migration_rate_set(rate_limit
);
3598 qemu_file_set_blocking(s
->to_dst_file
, true);
3601 * Open the return path. For postcopy, it is used exclusively. For
3602 * precopy, only if user specified "return-path" capability would
3603 * QEMU uses the return path.
3605 if (migrate_postcopy_ram() || migrate_return_path()) {
3606 if (open_return_path_on_source(s
)) {
3607 error_setg(&local_err
, "Unable to open return-path for postcopy");
3608 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
3609 migrate_set_error(s
, local_err
);
3610 error_report_err(local_err
);
3611 migrate_fd_cleanup(s
);
3617 * This needs to be done before resuming a postcopy. Note: for newer
3618 * QEMUs we will delay the channel creation until postcopy_start(), to
3619 * avoid disorder of channel creations.
3621 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
3622 postcopy_preempt_setup(s
);
3626 /* Wakeup the main migration thread to do the recovery */
3627 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
3628 MIGRATION_STATUS_POSTCOPY_RECOVER
);
3629 qemu_sem_post(&s
->postcopy_pause_sem
);
3633 if (multifd_save_setup(&local_err
) != 0) {
3634 migrate_set_error(s
, local_err
);
3635 error_report_err(local_err
);
3636 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
3637 MIGRATION_STATUS_FAILED
);
3638 migrate_fd_cleanup(s
);
3642 if (migrate_background_snapshot()) {
3643 qemu_thread_create(&s
->thread
, "bg_snapshot",
3644 bg_migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3646 qemu_thread_create(&s
->thread
, "live_migration",
3647 migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3649 s
->migration_thread_running
= true;
3652 static void migration_class_init(ObjectClass
*klass
, void *data
)
3654 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3656 dc
->user_creatable
= false;
3657 device_class_set_props(dc
, migration_properties
);
3660 static void migration_instance_finalize(Object
*obj
)
3662 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3664 qemu_mutex_destroy(&ms
->error_mutex
);
3665 qemu_mutex_destroy(&ms
->qemu_file_lock
);
3666 qemu_sem_destroy(&ms
->wait_unplug_sem
);
3667 qemu_sem_destroy(&ms
->rate_limit_sem
);
3668 qemu_sem_destroy(&ms
->pause_sem
);
3669 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
3670 qemu_sem_destroy(&ms
->rp_state
.rp_sem
);
3671 qemu_sem_destroy(&ms
->rp_state
.rp_pong_acks
);
3672 qemu_sem_destroy(&ms
->postcopy_qemufile_src_sem
);
3673 error_free(ms
->error
);
3676 static void migration_instance_init(Object
*obj
)
3678 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3680 ms
->state
= MIGRATION_STATUS_NONE
;
3682 ms
->pages_per_second
= -1;
3683 qemu_sem_init(&ms
->pause_sem
, 0);
3684 qemu_mutex_init(&ms
->error_mutex
);
3686 migrate_params_init(&ms
->parameters
);
3688 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
3689 qemu_sem_init(&ms
->rp_state
.rp_sem
, 0);
3690 qemu_sem_init(&ms
->rp_state
.rp_pong_acks
, 0);
3691 qemu_sem_init(&ms
->rate_limit_sem
, 0);
3692 qemu_sem_init(&ms
->wait_unplug_sem
, 0);
3693 qemu_sem_init(&ms
->postcopy_qemufile_src_sem
, 0);
3694 qemu_mutex_init(&ms
->qemu_file_lock
);
3698 * Return true if check pass, false otherwise. Error will be put
3699 * inside errp if provided.
3701 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
3703 /* Assuming all off */
3704 bool old_caps
[MIGRATION_CAPABILITY__MAX
] = { 0 };
3706 if (!migrate_params_check(&ms
->parameters
, errp
)) {
3710 return migrate_caps_check(old_caps
, ms
->capabilities
, errp
);
3713 static const TypeInfo migration_type
= {
3714 .name
= TYPE_MIGRATION
,
3716 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3717 * not created using qdev_new(), it is not attached to the qdev
3718 * device tree, and it is never realized.
3720 * TODO: Make this TYPE_OBJECT once QOM provides something like
3721 * TYPE_DEVICE's "-global" properties.
3723 .parent
= TYPE_DEVICE
,
3724 .class_init
= migration_class_init
,
3725 .class_size
= sizeof(MigrationClass
),
3726 .instance_size
= sizeof(MigrationState
),
3727 .instance_init
= migration_instance_init
,
3728 .instance_finalize
= migration_instance_finalize
,
3731 static void register_migration_types(void)
3733 type_register_static(&migration_type
);
3736 type_init(register_migration_types
);