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
== !channels
) {
527 error_setg(errp
, "need either 'uri' or 'channels' argument");
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
;
541 /* caller uses the old URI syntax */
542 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
545 addr
= channel
->addr
;
548 /* transport mechanism not suitable for migration? */
549 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
553 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
554 MIGRATION_STATUS_SETUP
);
556 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
557 SocketAddress
*saddr
= &addr
->u
.socket
;
558 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
559 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
560 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
561 socket_start_incoming_migration(saddr
, errp
);
562 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
563 fd_start_incoming_migration(saddr
->u
.fd
.str
, errp
);
566 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
567 if (migrate_compress()) {
568 error_setg(errp
, "RDMA and compression can't be used together");
571 if (migrate_xbzrle()) {
572 error_setg(errp
, "RDMA and XBZRLE can't be used together");
575 if (migrate_multifd()) {
576 error_setg(errp
, "RDMA and multifd can't be used together");
579 rdma_start_incoming_migration(&addr
->u
.rdma
, errp
);
581 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
582 exec_start_incoming_migration(addr
->u
.exec
.args
, errp
);
583 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
584 file_start_incoming_migration(&addr
->u
.file
, errp
);
586 error_setg(errp
, "unknown migration protocol: %s", uri
);
590 static void process_incoming_migration_bh(void *opaque
)
592 Error
*local_err
= NULL
;
593 MigrationIncomingState
*mis
= opaque
;
595 trace_vmstate_downtime_checkpoint("dst-precopy-bh-enter");
597 /* If capability late_block_activate is set:
598 * Only fire up the block code now if we're going to restart the
599 * VM, else 'cont' will do it.
600 * This causes file locking to happen; so we don't want it to happen
601 * unless we really are starting the VM.
603 if (!migrate_late_block_activate() ||
604 (autostart
&& (!global_state_received() ||
605 runstate_is_live(global_state_get_runstate())))) {
606 /* Make sure all file formats throw away their mutable metadata.
607 * If we get an error here, just don't restart the VM yet. */
608 bdrv_activate_all(&local_err
);
610 error_report_err(local_err
);
617 * This must happen after all error conditions are dealt with and
618 * we're sure the VM is going to be running on this host.
620 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
622 trace_vmstate_downtime_checkpoint("dst-precopy-bh-announced");
624 multifd_load_shutdown();
626 dirty_bitmap_mig_before_vm_start();
628 if (!global_state_received() ||
629 runstate_is_live(global_state_get_runstate())) {
633 runstate_set(RUN_STATE_PAUSED
);
635 } else if (migration_incoming_colo_enabled()) {
636 migration_incoming_disable_colo();
639 runstate_set(global_state_get_runstate());
641 trace_vmstate_downtime_checkpoint("dst-precopy-bh-vm-started");
643 * This must happen after any state changes since as soon as an external
644 * observer sees this event they might start to prod at the VM assuming
647 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
648 MIGRATION_STATUS_COMPLETED
);
649 qemu_bh_delete(mis
->bh
);
650 migration_incoming_state_destroy();
651 object_unref(OBJECT(migrate_get_current()));
654 static void coroutine_fn
655 process_incoming_migration_co(void *opaque
)
657 MigrationIncomingState
*mis
= migration_incoming_get_current();
661 assert(mis
->from_src_file
);
663 if (compress_threads_load_setup(mis
->from_src_file
)) {
664 error_report("Failed to setup decompress threads");
668 mis
->largest_page_size
= qemu_ram_pagesize_largest();
669 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
670 migrate_set_state(&mis
->state
, MIGRATION_STATUS_SETUP
,
671 MIGRATION_STATUS_ACTIVE
);
673 mis
->loadvm_co
= qemu_coroutine_self();
674 ret
= qemu_loadvm_state(mis
->from_src_file
);
675 mis
->loadvm_co
= NULL
;
677 trace_vmstate_downtime_checkpoint("dst-precopy-loadvm-completed");
679 ps
= postcopy_state_get();
680 trace_process_incoming_migration_co_end(ret
, ps
);
681 if (ps
!= POSTCOPY_INCOMING_NONE
) {
682 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
684 * Where a migration had postcopy enabled (and thus went to advise)
685 * but managed to complete within the precopy period, we can use
688 postcopy_ram_incoming_cleanup(mis
);
689 } else if (ret
>= 0) {
691 * Postcopy was started, cleanup should happen at the end of the
694 trace_process_incoming_migration_co_postcopy_end_main();
697 /* Else if something went wrong then just fall out of the normal exit */
701 MigrationState
*s
= migrate_get_current();
703 if (migrate_has_error(s
)) {
704 WITH_QEMU_LOCK_GUARD(&s
->error_mutex
) {
705 error_report_err(s
->error
);
708 error_report("load of migration failed: %s", strerror(-ret
));
712 if (colo_incoming_co() < 0) {
716 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
717 object_ref(OBJECT(migrate_get_current()));
718 qemu_bh_schedule(mis
->bh
);
721 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
722 MIGRATION_STATUS_FAILED
);
723 qemu_fclose(mis
->from_src_file
);
725 multifd_load_cleanup();
726 compress_threads_load_cleanup();
732 * migration_incoming_setup: Setup incoming migration
733 * @f: file for main migration channel
735 static void migration_incoming_setup(QEMUFile
*f
)
737 MigrationIncomingState
*mis
= migration_incoming_get_current();
739 if (!mis
->from_src_file
) {
740 mis
->from_src_file
= f
;
742 qemu_file_set_blocking(f
, false);
745 void migration_incoming_process(void)
747 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
748 qemu_coroutine_enter(co
);
751 /* Returns true if recovered from a paused migration, otherwise false */
752 static bool postcopy_try_recover(void)
754 MigrationIncomingState
*mis
= migration_incoming_get_current();
756 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
757 /* Resumed from a paused postcopy migration */
759 /* This should be set already in migration_incoming_setup() */
760 assert(mis
->from_src_file
);
761 /* Postcopy has standalone thread to do vm load */
762 qemu_file_set_blocking(mis
->from_src_file
, true);
764 /* Re-configure the return path */
765 mis
->to_src_file
= qemu_file_get_return_path(mis
->from_src_file
);
767 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
768 MIGRATION_STATUS_POSTCOPY_RECOVER
);
771 * Here, we only wake up the main loading thread (while the
772 * rest threads will still be waiting), so that we can receive
773 * commands from source now, and answer it if needed. The
774 * rest threads will be woken up afterwards until we are sure
775 * that source is ready to reply to page requests.
777 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
784 void migration_fd_process_incoming(QEMUFile
*f
)
786 migration_incoming_setup(f
);
787 if (postcopy_try_recover()) {
790 migration_incoming_process();
794 * Returns true when we want to start a new incoming migration process,
797 static bool migration_should_start_incoming(bool main_channel
)
799 /* Multifd doesn't start unless all channels are established */
800 if (migrate_multifd()) {
801 return migration_has_all_channels();
804 /* Preempt channel only starts when the main channel is created */
805 if (migrate_postcopy_preempt()) {
810 * For all the rest types of migration, we should only reach here when
811 * it's the main channel that's being created, and we should always
812 * proceed with this channel.
814 assert(main_channel
);
818 void migration_ioc_process_incoming(QIOChannel
*ioc
, Error
**errp
)
820 MigrationIncomingState
*mis
= migration_incoming_get_current();
821 Error
*local_err
= NULL
;
823 bool default_channel
= true;
824 uint32_t channel_magic
= 0;
827 if (migrate_multifd() && !migrate_postcopy_ram() &&
828 qio_channel_has_feature(ioc
, QIO_CHANNEL_FEATURE_READ_MSG_PEEK
)) {
830 * With multiple channels, it is possible that we receive channels
831 * out of order on destination side, causing incorrect mapping of
832 * source channels on destination side. Check channel MAGIC to
833 * decide type of channel. Please note this is best effort, postcopy
834 * preempt channel does not send any magic number so avoid it for
835 * postcopy live migration. Also tls live migration already does
836 * tls handshake while initializing main channel so with tls this
837 * issue is not possible.
839 ret
= migration_channel_read_peek(ioc
, (void *)&channel_magic
,
840 sizeof(channel_magic
), errp
);
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) {
855 if (default_channel
) {
856 f
= qemu_file_new_input(ioc
);
857 migration_incoming_setup(f
);
859 /* Multiple connections */
860 assert(migration_needs_multiple_sockets());
861 if (migrate_multifd()) {
862 multifd_recv_new_channel(ioc
, &local_err
);
864 assert(migrate_postcopy_preempt());
865 f
= qemu_file_new_input(ioc
);
866 postcopy_preempt_new_channel(mis
, f
);
869 error_propagate(errp
, local_err
);
874 if (migration_should_start_incoming(default_channel
)) {
875 /* If it's a recovery, we're done */
876 if (postcopy_try_recover()) {
879 migration_incoming_process();
884 * @migration_has_all_channels: We have received all channels that we need
886 * Returns true when we have got connections to all the channels that
887 * we need for migration.
889 bool migration_has_all_channels(void)
891 MigrationIncomingState
*mis
= migration_incoming_get_current();
893 if (!mis
->from_src_file
) {
897 if (migrate_multifd()) {
898 return multifd_recv_all_channels_created();
901 if (migrate_postcopy_preempt()) {
902 return mis
->postcopy_qemufile_dst
!= NULL
;
908 int migrate_send_rp_switchover_ack(MigrationIncomingState
*mis
)
910 return migrate_send_rp_message(mis
, MIG_RP_MSG_SWITCHOVER_ACK
, 0, NULL
);
914 * Send a 'SHUT' message on the return channel with the given value
915 * to indicate that we've finished with the RP. Non-0 value indicates
918 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
923 buf
= cpu_to_be32(value
);
924 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
928 * Send a 'PONG' message on the return channel with the given value
929 * (normally in response to a 'PING')
931 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
936 buf
= cpu_to_be32(value
);
937 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
940 void migrate_send_rp_recv_bitmap(MigrationIncomingState
*mis
,
948 * First, we send the header part. It contains only the len of
949 * idstr, and the idstr itself.
951 len
= strlen(block_name
);
953 memcpy(buf
+ 1, block_name
, len
);
955 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
956 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
961 migrate_send_rp_message(mis
, MIG_RP_MSG_RECV_BITMAP
, len
+ 1, buf
);
964 * Next, we dump the received bitmap to the stream.
966 * TODO: currently we are safe since we are the only one that is
967 * using the to_src_file handle (fault thread is still paused),
968 * and it's ok even not taking the mutex. However the best way is
969 * to take the lock before sending the message header, and release
970 * the lock after sending the bitmap.
972 qemu_mutex_lock(&mis
->rp_mutex
);
973 res
= ramblock_recv_bitmap_send(mis
->to_src_file
, block_name
);
974 qemu_mutex_unlock(&mis
->rp_mutex
);
976 trace_migrate_send_rp_recv_bitmap(block_name
, res
);
979 void migrate_send_rp_resume_ack(MigrationIncomingState
*mis
, uint32_t value
)
983 buf
= cpu_to_be32(value
);
984 migrate_send_rp_message(mis
, MIG_RP_MSG_RESUME_ACK
, sizeof(buf
), &buf
);
988 * Return true if we're already in the middle of a migration
989 * (i.e. any of the active or setup states)
991 bool migration_is_setup_or_active(int state
)
994 case MIGRATION_STATUS_ACTIVE
:
995 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
996 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
997 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
998 case MIGRATION_STATUS_SETUP
:
999 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1000 case MIGRATION_STATUS_DEVICE
:
1001 case MIGRATION_STATUS_WAIT_UNPLUG
:
1002 case MIGRATION_STATUS_COLO
:
1011 bool migration_is_running(int state
)
1014 case MIGRATION_STATUS_ACTIVE
:
1015 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1016 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1017 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1018 case MIGRATION_STATUS_SETUP
:
1019 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1020 case MIGRATION_STATUS_DEVICE
:
1021 case MIGRATION_STATUS_WAIT_UNPLUG
:
1022 case MIGRATION_STATUS_CANCELLING
:
1031 static bool migrate_show_downtime(MigrationState
*s
)
1033 return (s
->state
== MIGRATION_STATUS_COMPLETED
) || migration_in_postcopy();
1036 static void populate_time_info(MigrationInfo
*info
, MigrationState
*s
)
1038 info
->has_status
= true;
1039 info
->has_setup_time
= true;
1040 info
->setup_time
= s
->setup_time
;
1042 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1043 info
->has_total_time
= true;
1044 info
->total_time
= s
->total_time
;
1046 info
->has_total_time
= true;
1047 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) -
1051 if (migrate_show_downtime(s
)) {
1052 info
->has_downtime
= true;
1053 info
->downtime
= s
->downtime
;
1055 info
->has_expected_downtime
= true;
1056 info
->expected_downtime
= s
->expected_downtime
;
1060 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
1062 size_t page_size
= qemu_target_page_size();
1064 info
->ram
= g_malloc0(sizeof(*info
->ram
));
1065 info
->ram
->transferred
= migration_transferred_bytes();
1066 info
->ram
->total
= ram_bytes_total();
1067 info
->ram
->duplicate
= stat64_get(&mig_stats
.zero_pages
);
1068 /* legacy value. It is not used anymore */
1069 info
->ram
->skipped
= 0;
1070 info
->ram
->normal
= stat64_get(&mig_stats
.normal_pages
);
1071 info
->ram
->normal_bytes
= info
->ram
->normal
* page_size
;
1072 info
->ram
->mbps
= s
->mbps
;
1073 info
->ram
->dirty_sync_count
=
1074 stat64_get(&mig_stats
.dirty_sync_count
);
1075 info
->ram
->dirty_sync_missed_zero_copy
=
1076 stat64_get(&mig_stats
.dirty_sync_missed_zero_copy
);
1077 info
->ram
->postcopy_requests
=
1078 stat64_get(&mig_stats
.postcopy_requests
);
1079 info
->ram
->page_size
= page_size
;
1080 info
->ram
->multifd_bytes
= stat64_get(&mig_stats
.multifd_bytes
);
1081 info
->ram
->pages_per_second
= s
->pages_per_second
;
1082 info
->ram
->precopy_bytes
= stat64_get(&mig_stats
.precopy_bytes
);
1083 info
->ram
->downtime_bytes
= stat64_get(&mig_stats
.downtime_bytes
);
1084 info
->ram
->postcopy_bytes
= stat64_get(&mig_stats
.postcopy_bytes
);
1086 if (migrate_xbzrle()) {
1087 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
1088 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
1089 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
1090 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
1091 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
1092 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
1093 info
->xbzrle_cache
->encoding_rate
= xbzrle_counters
.encoding_rate
;
1094 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
1097 populate_compress(info
);
1099 if (cpu_throttle_active()) {
1100 info
->has_cpu_throttle_percentage
= true;
1101 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
1104 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
1105 info
->ram
->remaining
= ram_bytes_remaining();
1106 info
->ram
->dirty_pages_rate
=
1107 stat64_get(&mig_stats
.dirty_pages_rate
);
1110 if (migrate_dirty_limit() && dirtylimit_in_service()) {
1111 info
->has_dirty_limit_throttle_time_per_round
= true;
1112 info
->dirty_limit_throttle_time_per_round
=
1113 dirtylimit_throttle_time_per_round();
1115 info
->has_dirty_limit_ring_full_time
= true;
1116 info
->dirty_limit_ring_full_time
= dirtylimit_ring_full_time();
1120 static void populate_disk_info(MigrationInfo
*info
)
1122 if (blk_mig_active()) {
1123 info
->disk
= g_malloc0(sizeof(*info
->disk
));
1124 info
->disk
->transferred
= blk_mig_bytes_transferred();
1125 info
->disk
->remaining
= blk_mig_bytes_remaining();
1126 info
->disk
->total
= blk_mig_bytes_total();
1130 static void fill_source_migration_info(MigrationInfo
*info
)
1132 MigrationState
*s
= migrate_get_current();
1133 int state
= qatomic_read(&s
->state
);
1134 GSList
*cur_blocker
= migration_blockers
[migrate_mode()];
1136 info
->blocked_reasons
= NULL
;
1139 * There are two types of reasons a migration might be blocked;
1140 * a) devices marked in VMState as non-migratable, and
1141 * b) Explicit migration blockers
1142 * We need to add both of them here.
1144 qemu_savevm_non_migratable_list(&info
->blocked_reasons
);
1146 while (cur_blocker
) {
1147 QAPI_LIST_PREPEND(info
->blocked_reasons
,
1148 g_strdup(error_get_pretty(cur_blocker
->data
)));
1149 cur_blocker
= g_slist_next(cur_blocker
);
1151 info
->has_blocked_reasons
= info
->blocked_reasons
!= NULL
;
1154 case MIGRATION_STATUS_NONE
:
1155 /* no migration has happened ever */
1156 /* do not overwrite destination migration status */
1158 case MIGRATION_STATUS_SETUP
:
1159 info
->has_status
= true;
1160 info
->has_total_time
= false;
1162 case MIGRATION_STATUS_ACTIVE
:
1163 case MIGRATION_STATUS_CANCELLING
:
1164 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1165 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1166 case MIGRATION_STATUS_DEVICE
:
1167 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1168 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1169 /* TODO add some postcopy stats */
1170 populate_time_info(info
, s
);
1171 populate_ram_info(info
, s
);
1172 populate_disk_info(info
);
1173 migration_populate_vfio_info(info
);
1175 case MIGRATION_STATUS_COLO
:
1176 info
->has_status
= true;
1177 /* TODO: display COLO specific information (checkpoint info etc.) */
1179 case MIGRATION_STATUS_COMPLETED
:
1180 populate_time_info(info
, s
);
1181 populate_ram_info(info
, s
);
1182 migration_populate_vfio_info(info
);
1184 case MIGRATION_STATUS_FAILED
:
1185 info
->has_status
= true;
1187 case MIGRATION_STATUS_CANCELLED
:
1188 info
->has_status
= true;
1190 case MIGRATION_STATUS_WAIT_UNPLUG
:
1191 info
->has_status
= true;
1194 info
->status
= state
;
1196 QEMU_LOCK_GUARD(&s
->error_mutex
);
1198 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
1202 static void fill_destination_migration_info(MigrationInfo
*info
)
1204 MigrationIncomingState
*mis
= migration_incoming_get_current();
1206 if (mis
->socket_address_list
) {
1207 info
->has_socket_address
= true;
1208 info
->socket_address
=
1209 QAPI_CLONE(SocketAddressList
, mis
->socket_address_list
);
1212 switch (mis
->state
) {
1213 case MIGRATION_STATUS_NONE
:
1215 case MIGRATION_STATUS_SETUP
:
1216 case MIGRATION_STATUS_CANCELLING
:
1217 case MIGRATION_STATUS_CANCELLED
:
1218 case MIGRATION_STATUS_ACTIVE
:
1219 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1220 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1221 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1222 case MIGRATION_STATUS_FAILED
:
1223 case MIGRATION_STATUS_COLO
:
1224 info
->has_status
= true;
1226 case MIGRATION_STATUS_COMPLETED
:
1227 info
->has_status
= true;
1228 fill_destination_postcopy_migration_info(info
);
1231 info
->status
= mis
->state
;
1234 MigrationInfo
*qmp_query_migrate(Error
**errp
)
1236 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
1238 fill_destination_migration_info(info
);
1239 fill_source_migration_info(info
);
1244 void qmp_migrate_start_postcopy(Error
**errp
)
1246 MigrationState
*s
= migrate_get_current();
1248 if (!migrate_postcopy()) {
1249 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1250 " the start of migration");
1254 if (s
->state
== MIGRATION_STATUS_NONE
) {
1255 error_setg(errp
, "Postcopy must be started after migration has been"
1260 * we don't error if migration has finished since that would be racy
1261 * with issuing this command.
1263 qatomic_set(&s
->start_postcopy
, true);
1266 /* shared migration helpers */
1268 void migrate_set_state(int *state
, int old_state
, int new_state
)
1270 assert(new_state
< MIGRATION_STATUS__MAX
);
1271 if (qatomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1272 trace_migrate_set_state(MigrationStatus_str(new_state
));
1273 migrate_generate_event(new_state
);
1277 static void migrate_fd_cleanup(MigrationState
*s
)
1279 qemu_bh_delete(s
->cleanup_bh
);
1280 s
->cleanup_bh
= NULL
;
1282 g_free(s
->hostname
);
1284 json_writer_free(s
->vmdesc
);
1287 qemu_savevm_state_cleanup();
1289 if (s
->to_dst_file
) {
1292 trace_migrate_fd_cleanup();
1294 if (s
->migration_thread_running
) {
1295 qemu_thread_join(&s
->thread
);
1296 s
->migration_thread_running
= false;
1300 multifd_save_cleanup();
1301 qemu_mutex_lock(&s
->qemu_file_lock
);
1302 tmp
= s
->to_dst_file
;
1303 s
->to_dst_file
= NULL
;
1304 qemu_mutex_unlock(&s
->qemu_file_lock
);
1306 * Close the file handle without the lock to make sure the
1307 * critical section won't block for long.
1309 migration_ioc_unregister_yank_from_file(tmp
);
1314 * We already cleaned up to_dst_file, so errors from the return
1315 * path might be due to that, ignore them.
1317 close_return_path_on_source(s
);
1319 assert(!migration_is_active(s
));
1321 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1322 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1323 MIGRATION_STATUS_CANCELLED
);
1327 /* It is used on info migrate. We can't free it */
1328 error_report_err(error_copy(s
->error
));
1330 migration_call_notifiers(s
);
1331 block_cleanup_parameters();
1332 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1335 static void migrate_fd_cleanup_schedule(MigrationState
*s
)
1338 * Ref the state for bh, because it may be called when
1339 * there're already no other refs
1341 object_ref(OBJECT(s
));
1342 qemu_bh_schedule(s
->cleanup_bh
);
1345 static void migrate_fd_cleanup_bh(void *opaque
)
1347 MigrationState
*s
= opaque
;
1348 migrate_fd_cleanup(s
);
1349 object_unref(OBJECT(s
));
1352 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1354 QEMU_LOCK_GUARD(&s
->error_mutex
);
1356 s
->error
= error_copy(error
);
1360 bool migrate_has_error(MigrationState
*s
)
1362 /* The lock is not helpful here, but still follow the rule */
1363 QEMU_LOCK_GUARD(&s
->error_mutex
);
1364 return qatomic_read(&s
->error
);
1367 static void migrate_error_free(MigrationState
*s
)
1369 QEMU_LOCK_GUARD(&s
->error_mutex
);
1371 error_free(s
->error
);
1376 static void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1378 trace_migrate_fd_error(error_get_pretty(error
));
1379 assert(s
->to_dst_file
== NULL
);
1380 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1381 MIGRATION_STATUS_FAILED
);
1382 migrate_set_error(s
, error
);
1385 static void migrate_fd_cancel(MigrationState
*s
)
1389 trace_migrate_fd_cancel();
1391 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1392 if (s
->rp_state
.from_dst_file
) {
1393 /* shutdown the rp socket, so causing the rp thread to shutdown */
1394 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1399 old_state
= s
->state
;
1400 if (!migration_is_running(old_state
)) {
1403 /* If the migration is paused, kick it out of the pause */
1404 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1405 qemu_sem_post(&s
->pause_sem
);
1407 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1408 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1411 * If we're unlucky the migration code might be stuck somewhere in a
1412 * send/write while the network has failed and is waiting to timeout;
1413 * if we've got shutdown(2) available then we can force it to quit.
1415 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1416 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1417 if (s
->to_dst_file
) {
1418 qemu_file_shutdown(s
->to_dst_file
);
1422 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1423 Error
*local_err
= NULL
;
1425 bdrv_activate_all(&local_err
);
1427 error_report_err(local_err
);
1429 s
->block_inactive
= false;
1434 void migration_add_notifier(Notifier
*notify
,
1435 void (*func
)(Notifier
*notifier
, void *data
))
1437 notify
->notify
= func
;
1438 notifier_list_add(&migration_state_notifiers
, notify
);
1441 void migration_remove_notifier(Notifier
*notify
)
1443 if (notify
->notify
) {
1444 notifier_remove(notify
);
1445 notify
->notify
= NULL
;
1449 void migration_call_notifiers(MigrationState
*s
)
1451 notifier_list_notify(&migration_state_notifiers
, s
);
1454 bool migration_in_setup(MigrationState
*s
)
1456 return s
->state
== MIGRATION_STATUS_SETUP
;
1459 bool migration_has_finished(MigrationState
*s
)
1461 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1464 bool migration_has_failed(MigrationState
*s
)
1466 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1467 s
->state
== MIGRATION_STATUS_FAILED
);
1470 bool migration_in_postcopy(void)
1472 MigrationState
*s
= migrate_get_current();
1475 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1476 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1477 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1484 bool migration_postcopy_is_alive(int state
)
1487 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1488 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1495 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1497 return migration_in_postcopy() && s
->postcopy_after_devices
;
1500 bool migration_in_incoming_postcopy(void)
1502 PostcopyState ps
= postcopy_state_get();
1504 return ps
>= POSTCOPY_INCOMING_DISCARD
&& ps
< POSTCOPY_INCOMING_END
;
1507 bool migration_incoming_postcopy_advised(void)
1509 PostcopyState ps
= postcopy_state_get();
1511 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
1514 bool migration_in_bg_snapshot(void)
1516 MigrationState
*s
= migrate_get_current();
1518 return migrate_background_snapshot() &&
1519 migration_is_setup_or_active(s
->state
);
1522 bool migration_is_idle(void)
1524 MigrationState
*s
= current_migration
;
1531 case MIGRATION_STATUS_NONE
:
1532 case MIGRATION_STATUS_CANCELLED
:
1533 case MIGRATION_STATUS_COMPLETED
:
1534 case MIGRATION_STATUS_FAILED
:
1536 case MIGRATION_STATUS_SETUP
:
1537 case MIGRATION_STATUS_CANCELLING
:
1538 case MIGRATION_STATUS_ACTIVE
:
1539 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1540 case MIGRATION_STATUS_COLO
:
1541 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1542 case MIGRATION_STATUS_DEVICE
:
1543 case MIGRATION_STATUS_WAIT_UNPLUG
:
1545 case MIGRATION_STATUS__MAX
:
1546 g_assert_not_reached();
1552 bool migration_is_active(MigrationState
*s
)
1554 return (s
->state
== MIGRATION_STATUS_ACTIVE
||
1555 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1558 int migrate_init(MigrationState
*s
, Error
**errp
)
1562 ret
= qemu_savevm_state_prepare(errp
);
1568 * Reinitialise all migration state, except
1569 * parameters/capabilities that the user set, and
1574 s
->to_dst_file
= NULL
;
1575 s
->state
= MIGRATION_STATUS_NONE
;
1576 s
->rp_state
.from_dst_file
= NULL
;
1578 s
->pages_per_second
= 0.0;
1580 s
->expected_downtime
= 0;
1582 s
->start_postcopy
= false;
1583 s
->postcopy_after_devices
= false;
1584 s
->migration_thread_running
= false;
1585 error_free(s
->error
);
1589 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1591 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1593 s
->vm_old_state
= -1;
1594 s
->iteration_initial_bytes
= 0;
1595 s
->threshold_size
= 0;
1596 s
->switchover_acked
= false;
1597 s
->rdma_migration
= false;
1599 * set mig_stats memory to zero for a new migration
1601 memset(&mig_stats
, 0, sizeof(mig_stats
));
1602 migration_reset_vfio_bytes_transferred();
1607 static bool is_busy(Error
**reasonp
, Error
**errp
)
1611 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1612 if (runstate_check(RUN_STATE_SAVE_VM
) || !migration_is_idle()) {
1613 error_propagate_prepend(errp
, *reasonp
,
1614 "disallowing migration blocker "
1615 "(migration/snapshot in progress) for: ");
1622 static bool is_only_migratable(Error
**reasonp
, Error
**errp
, int modes
)
1626 if (only_migratable
&& (modes
& BIT(MIG_MODE_NORMAL
))) {
1627 error_propagate_prepend(errp
, *reasonp
,
1628 "disallowing migration blocker "
1629 "(--only-migratable) for: ");
1636 static int get_modes(MigMode mode
, va_list ap
)
1640 while (mode
!= -1 && mode
!= MIG_MODE_ALL
) {
1641 assert(mode
>= MIG_MODE_NORMAL
&& mode
< MIG_MODE__MAX
);
1643 mode
= va_arg(ap
, MigMode
);
1645 if (mode
== MIG_MODE_ALL
) {
1646 modes
= BIT(MIG_MODE__MAX
) - 1;
1651 static int add_blockers(Error
**reasonp
, Error
**errp
, int modes
)
1653 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1654 if (modes
& BIT(mode
)) {
1655 migration_blockers
[mode
] = g_slist_prepend(migration_blockers
[mode
],
1662 int migrate_add_blocker(Error
**reasonp
, Error
**errp
)
1664 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_ALL
);
1667 int migrate_add_blocker_normal(Error
**reasonp
, Error
**errp
)
1669 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_NORMAL
, -1);
1672 int migrate_add_blocker_modes(Error
**reasonp
, Error
**errp
, MigMode mode
, ...)
1678 modes
= get_modes(mode
, ap
);
1681 if (is_only_migratable(reasonp
, errp
, modes
)) {
1683 } else if (is_busy(reasonp
, errp
)) {
1686 return add_blockers(reasonp
, errp
, modes
);
1689 int migrate_add_blocker_internal(Error
**reasonp
, Error
**errp
)
1691 int modes
= BIT(MIG_MODE__MAX
) - 1;
1693 if (is_busy(reasonp
, errp
)) {
1696 return add_blockers(reasonp
, errp
, modes
);
1699 void migrate_del_blocker(Error
**reasonp
)
1702 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1703 migration_blockers
[mode
] = g_slist_remove(migration_blockers
[mode
],
1706 error_free(*reasonp
);
1711 void qmp_migrate_incoming(const char *uri
, bool has_channels
,
1712 MigrationChannelList
*channels
, Error
**errp
)
1714 Error
*local_err
= NULL
;
1715 static bool once
= true;
1718 error_setg(errp
, "The incoming migration has already been started");
1721 if (!runstate_check(RUN_STATE_INMIGRATE
)) {
1722 error_setg(errp
, "'-incoming' was not specified on the command line");
1726 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1730 qemu_start_incoming_migration(uri
, has_channels
, channels
, &local_err
);
1733 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1734 error_propagate(errp
, local_err
);
1741 void qmp_migrate_recover(const char *uri
, Error
**errp
)
1743 MigrationIncomingState
*mis
= migration_incoming_get_current();
1746 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1747 * callers (no one should ignore a recover failure); if there is, it's a
1748 * programming error.
1752 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1753 error_setg(errp
, "Migrate recover can only be run "
1754 "when postcopy is paused.");
1758 /* If there's an existing transport, release it */
1759 migration_incoming_transport_cleanup(mis
);
1762 * Note that this call will never start a real migration; it will
1763 * only re-setup the migration stream and poke existing migration
1764 * to continue using that newly established channel.
1766 qemu_start_incoming_migration(uri
, false, NULL
, errp
);
1769 void qmp_migrate_pause(Error
**errp
)
1771 MigrationState
*ms
= migrate_get_current();
1772 MigrationIncomingState
*mis
= migration_incoming_get_current();
1775 if (migration_postcopy_is_alive(ms
->state
)) {
1776 /* Source side, during postcopy */
1777 Error
*error
= NULL
;
1779 /* Tell the core migration that we're pausing */
1780 error_setg(&error
, "Postcopy migration is paused by the user");
1781 migrate_set_error(ms
, error
);
1784 qemu_mutex_lock(&ms
->qemu_file_lock
);
1785 if (ms
->to_dst_file
) {
1786 ret
= qemu_file_shutdown(ms
->to_dst_file
);
1788 qemu_mutex_unlock(&ms
->qemu_file_lock
);
1790 error_setg(errp
, "Failed to pause source migration");
1794 * Kick the migration thread out of any waiting windows (on behalf
1795 * of the rp thread).
1797 migration_rp_kick(ms
);
1802 if (migration_postcopy_is_alive(mis
->state
)) {
1803 ret
= qemu_file_shutdown(mis
->from_src_file
);
1805 error_setg(errp
, "Failed to pause destination migration");
1810 error_setg(errp
, "migrate-pause is currently only supported "
1811 "during postcopy-active or postcopy-recover state");
1814 bool migration_is_blocked(Error
**errp
)
1816 GSList
*blockers
= migration_blockers
[migrate_mode()];
1818 if (qemu_savevm_state_blocked(errp
)) {
1823 error_propagate(errp
, error_copy(blockers
->data
));
1830 /* Returns true if continue to migrate, or false if error detected */
1831 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1832 bool resume
, Error
**errp
)
1835 warn_report("parameter 'inc' is deprecated;"
1836 " use blockdev-mirror with NBD instead");
1840 warn_report("parameter 'blk' is deprecated;"
1841 " use blockdev-mirror with NBD instead");
1845 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1846 error_setg(errp
, "Cannot resume if there is no "
1847 "paused migration");
1852 * Postcopy recovery won't work well with release-ram
1853 * capability since release-ram will drop the page buffer as
1854 * long as the page is put into the send buffer. So if there
1855 * is a network failure happened, any page buffers that have
1856 * not yet reached the destination VM but have already been
1857 * sent from the source VM will be lost forever. Let's refuse
1858 * the client from resuming such a postcopy migration.
1859 * Luckily release-ram was designed to only be used when src
1860 * and destination VMs are on the same host, so it should be
1863 if (migrate_release_ram()) {
1864 error_setg(errp
, "Postcopy recovery cannot work "
1865 "when release-ram capability is set");
1869 /* This is a resume, skip init status */
1873 if (migration_is_running(s
->state
)) {
1874 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1878 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1879 error_setg(errp
, "Guest is waiting for an incoming migration");
1883 if (runstate_check(RUN_STATE_POSTMIGRATE
)) {
1884 error_setg(errp
, "Can't migrate the vm that was paused due to "
1885 "previous migration");
1889 if (migration_is_blocked(errp
)) {
1893 if (blk
|| blk_inc
) {
1894 if (migrate_colo()) {
1895 error_setg(errp
, "No disk migration is required in COLO mode");
1898 if (migrate_block() || migrate_block_incremental()) {
1899 error_setg(errp
, "Command options are incompatible with "
1900 "current migration capabilities");
1903 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK
, true, errp
)) {
1906 s
->must_remove_block_options
= true;
1910 migrate_set_block_incremental(true);
1913 if (migrate_init(s
, errp
)) {
1920 void qmp_migrate(const char *uri
, bool has_channels
,
1921 MigrationChannelList
*channels
, bool has_blk
, bool blk
,
1922 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1923 bool has_resume
, bool resume
, Error
**errp
)
1925 bool resume_requested
;
1926 Error
*local_err
= NULL
;
1927 MigrationState
*s
= migrate_get_current();
1928 g_autoptr(MigrationChannel
) channel
= NULL
;
1929 MigrationAddress
*addr
= NULL
;
1932 * Having preliminary checks for uri and channel
1934 if (!uri
== !channels
) {
1935 error_setg(errp
, "need either 'uri' or 'channels' argument");
1940 /* To verify that Migrate channel list has only item */
1941 if (channels
->next
) {
1942 error_setg(errp
, "Channel list has more than one entries");
1945 addr
= channels
->value
->addr
;
1949 /* caller uses the old URI syntax */
1950 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
1953 addr
= channel
->addr
;
1956 /* transport mechanism not suitable for migration? */
1957 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
1961 resume_requested
= has_resume
&& resume
;
1962 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
1963 resume_requested
, errp
)) {
1964 /* Error detected, put into errp */
1968 if (!resume_requested
) {
1969 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1974 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
1975 SocketAddress
*saddr
= &addr
->u
.socket
;
1976 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
1977 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
1978 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
1979 socket_start_outgoing_migration(s
, saddr
, &local_err
);
1980 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
1981 fd_start_outgoing_migration(s
, saddr
->u
.fd
.str
, &local_err
);
1984 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
1985 rdma_start_outgoing_migration(s
, &addr
->u
.rdma
, &local_err
);
1987 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
1988 exec_start_outgoing_migration(s
, addr
->u
.exec
.args
, &local_err
);
1989 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
1990 file_start_outgoing_migration(s
, &addr
->u
.file
, &local_err
);
1992 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1993 "a valid migration protocol");
1994 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1995 MIGRATION_STATUS_FAILED
);
1996 block_cleanup_parameters();
2000 if (!resume_requested
) {
2001 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
2003 migrate_fd_error(s
, local_err
);
2004 error_propagate(errp
, local_err
);
2009 void qmp_migrate_cancel(Error
**errp
)
2011 migration_cancel(NULL
);
2014 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
2016 MigrationState
*s
= migrate_get_current();
2017 if (s
->state
!= state
) {
2018 error_setg(errp
, "Migration not in expected state: %s",
2019 MigrationStatus_str(s
->state
));
2022 qemu_sem_post(&s
->pause_sem
);
2025 int migration_rp_wait(MigrationState
*s
)
2027 /* If migration has failure already, ignore the wait */
2028 if (migrate_has_error(s
)) {
2032 qemu_sem_wait(&s
->rp_state
.rp_sem
);
2034 /* After wait, double check that there's no failure */
2035 if (migrate_has_error(s
)) {
2042 void migration_rp_kick(MigrationState
*s
)
2044 qemu_sem_post(&s
->rp_state
.rp_sem
);
2047 static struct rp_cmd_args
{
2048 ssize_t len
; /* -1 = variable */
2051 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
2052 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
2053 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
2054 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
2055 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
2056 [MIG_RP_MSG_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
2057 [MIG_RP_MSG_RESUME_ACK
] = { .len
= 4, .name
= "RESUME_ACK" },
2058 [MIG_RP_MSG_SWITCHOVER_ACK
] = { .len
= 0, .name
= "SWITCHOVER_ACK" },
2059 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
2063 * Process a request for pages received on the return path,
2064 * We're allowed to send more than requested (e.g. to round to our page size)
2065 * and we don't need to send pages that have already been sent.
2068 migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
2069 ram_addr_t start
, size_t len
, Error
**errp
)
2071 long our_host_ps
= qemu_real_host_page_size();
2073 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
2076 * Since we currently insist on matching page sizes, just sanity check
2077 * we're being asked for whole host pages.
2079 if (!QEMU_IS_ALIGNED(start
, our_host_ps
) ||
2080 !QEMU_IS_ALIGNED(len
, our_host_ps
)) {
2081 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
2082 RAM_ADDR_FMT
" len: %zd", start
, len
);
2086 ram_save_queue_pages(rbname
, start
, len
, errp
);
2089 static bool migrate_handle_rp_recv_bitmap(MigrationState
*s
, char *block_name
,
2092 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
2095 error_setg(errp
, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
2100 /* Fetch the received bitmap and refresh the dirty bitmap */
2101 return ram_dirty_bitmap_reload(s
, block
, errp
);
2104 static bool migrate_handle_rp_resume_ack(MigrationState
*s
,
2105 uint32_t value
, Error
**errp
)
2107 trace_source_return_path_thread_resume_ack(value
);
2109 if (value
!= MIGRATION_RESUME_ACK_VALUE
) {
2110 error_setg(errp
, "illegal resume_ack value %"PRIu32
, value
);
2114 /* Now both sides are active. */
2115 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
2116 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2118 /* Notify send thread that time to continue send pages */
2119 migration_rp_kick(s
);
2125 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2126 * existed) in a safe way.
2128 static void migration_release_dst_files(MigrationState
*ms
)
2132 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2134 * Reset the from_dst_file pointer first before releasing it, as we
2135 * can't block within lock section
2137 file
= ms
->rp_state
.from_dst_file
;
2138 ms
->rp_state
.from_dst_file
= NULL
;
2142 * Do the same to postcopy fast path socket too if there is. No
2143 * locking needed because this qemufile should only be managed by
2144 * return path thread.
2146 if (ms
->postcopy_qemufile_src
) {
2147 migration_ioc_unregister_yank_from_file(ms
->postcopy_qemufile_src
);
2148 qemu_file_shutdown(ms
->postcopy_qemufile_src
);
2149 qemu_fclose(ms
->postcopy_qemufile_src
);
2150 ms
->postcopy_qemufile_src
= NULL
;
2157 * Handles messages sent on the return path towards the source VM
2160 static void *source_return_path_thread(void *opaque
)
2162 MigrationState
*ms
= opaque
;
2163 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
2164 uint16_t header_len
, header_type
;
2166 uint32_t tmp32
, sibling_error
;
2167 ram_addr_t start
= 0; /* =0 to silence warning */
2168 size_t len
= 0, expected_len
;
2172 trace_source_return_path_thread_entry();
2173 rcu_register_thread();
2175 while (migration_is_setup_or_active(ms
->state
)) {
2176 trace_source_return_path_thread_loop_top();
2178 header_type
= qemu_get_be16(rp
);
2179 header_len
= qemu_get_be16(rp
);
2181 if (qemu_file_get_error(rp
)) {
2182 qemu_file_get_error_obj(rp
, &err
);
2186 if (header_type
>= MIG_RP_MSG_MAX
||
2187 header_type
== MIG_RP_MSG_INVALID
) {
2188 error_setg(&err
, "Received invalid message 0x%04x length 0x%04x",
2189 header_type
, header_len
);
2193 if ((rp_cmd_args
[header_type
].len
!= -1 &&
2194 header_len
!= rp_cmd_args
[header_type
].len
) ||
2195 header_len
> sizeof(buf
)) {
2196 error_setg(&err
, "Received '%s' message (0x%04x) with"
2197 "incorrect length %d expecting %zu",
2198 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
2199 (size_t)rp_cmd_args
[header_type
].len
);
2203 /* We know we've got a valid header by this point */
2204 res
= qemu_get_buffer(rp
, buf
, header_len
);
2205 if (res
!= header_len
) {
2206 error_setg(&err
, "Failed reading data for message 0x%04x"
2207 " read %d expected %d",
2208 header_type
, res
, header_len
);
2212 /* OK, we have the message and the data */
2213 switch (header_type
) {
2214 case MIG_RP_MSG_SHUT
:
2215 sibling_error
= ldl_be_p(buf
);
2216 trace_source_return_path_thread_shut(sibling_error
);
2217 if (sibling_error
) {
2218 error_setg(&err
, "Sibling indicated error %d", sibling_error
);
2221 * We'll let the main thread deal with closing the RP
2222 * we could do a shutdown(2) on it, but we're the only user
2223 * anyway, so there's nothing gained.
2227 case MIG_RP_MSG_PONG
:
2228 tmp32
= ldl_be_p(buf
);
2229 trace_source_return_path_thread_pong(tmp32
);
2230 qemu_sem_post(&ms
->rp_state
.rp_pong_acks
);
2233 case MIG_RP_MSG_REQ_PAGES
:
2234 start
= ldq_be_p(buf
);
2235 len
= ldl_be_p(buf
+ 8);
2236 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
, &err
);
2242 case MIG_RP_MSG_REQ_PAGES_ID
:
2243 expected_len
= 12 + 1; /* header + termination */
2245 if (header_len
>= expected_len
) {
2246 start
= ldq_be_p(buf
);
2247 len
= ldl_be_p(buf
+ 8);
2248 /* Now we expect an idstr */
2249 tmp32
= buf
[12]; /* Length of the following idstr */
2250 buf
[13 + tmp32
] = '\0';
2251 expected_len
+= tmp32
;
2253 if (header_len
!= expected_len
) {
2254 error_setg(&err
, "Req_Page_id with length %d expecting %zd",
2255 header_len
, expected_len
);
2258 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
,
2265 case MIG_RP_MSG_RECV_BITMAP
:
2266 if (header_len
< 1) {
2267 error_setg(&err
, "MIG_RP_MSG_RECV_BITMAP missing block name");
2270 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2271 buf
[buf
[0] + 1] = '\0';
2272 if (!migrate_handle_rp_recv_bitmap(ms
, (char *)(buf
+ 1), &err
)) {
2277 case MIG_RP_MSG_RESUME_ACK
:
2278 tmp32
= ldl_be_p(buf
);
2279 if (!migrate_handle_rp_resume_ack(ms
, tmp32
, &err
)) {
2284 case MIG_RP_MSG_SWITCHOVER_ACK
:
2285 ms
->switchover_acked
= true;
2286 trace_source_return_path_thread_switchover_acked();
2296 migrate_set_error(ms
, err
);
2298 trace_source_return_path_thread_bad_end();
2301 if (ms
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2303 * this will be extremely unlikely: that we got yet another network
2304 * issue during recovering of the 1st network failure.. during this
2305 * period the main migration thread can be waiting on rp_sem for
2306 * this thread to sync with the other side.
2308 * When this happens, explicitly kick the migration thread out of
2309 * RECOVER stage and back to PAUSED, so the admin can try
2312 migration_rp_kick(ms
);
2315 trace_source_return_path_thread_end();
2316 rcu_unregister_thread();
2321 static int open_return_path_on_source(MigrationState
*ms
)
2323 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
2324 if (!ms
->rp_state
.from_dst_file
) {
2328 trace_open_return_path_on_source();
2330 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2331 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2332 ms
->rp_state
.rp_thread_created
= true;
2334 trace_open_return_path_on_source_continue();
2339 /* Return true if error detected, or false otherwise */
2340 static bool close_return_path_on_source(MigrationState
*ms
)
2342 if (!ms
->rp_state
.rp_thread_created
) {
2346 trace_migration_return_path_end_before();
2349 * If this is a normal exit then the destination will send a SHUT
2350 * and the rp_thread will exit, however if there's an error we
2351 * need to cause it to exit. shutdown(2), if we have it, will
2352 * cause it to unblock if it's stuck waiting for the destination.
2354 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2355 if (ms
->to_dst_file
&& ms
->rp_state
.from_dst_file
&&
2356 qemu_file_get_error(ms
->to_dst_file
)) {
2357 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2361 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2362 ms
->rp_state
.rp_thread_created
= false;
2363 migration_release_dst_files(ms
);
2364 trace_migration_return_path_end_after();
2366 /* Return path will persist the error in MigrationState when quit */
2367 return migrate_has_error(ms
);
2371 migration_wait_main_channel(MigrationState
*ms
)
2373 /* Wait until one PONG message received */
2374 qemu_sem_wait(&ms
->rp_state
.rp_pong_acks
);
2378 * Switch from normal iteration to postcopy
2379 * Returns non-0 on error
2381 static int postcopy_start(MigrationState
*ms
, Error
**errp
)
2384 QIOChannelBuffer
*bioc
;
2386 uint64_t bandwidth
= migrate_max_postcopy_bandwidth();
2387 bool restart_block
= false;
2388 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2390 if (migrate_postcopy_preempt()) {
2391 migration_wait_main_channel(ms
);
2392 if (postcopy_preempt_establish_channel(ms
)) {
2393 migrate_set_state(&ms
->state
, ms
->state
, MIGRATION_STATUS_FAILED
);
2398 if (!migrate_pause_before_switchover()) {
2399 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2400 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2403 trace_postcopy_start();
2405 trace_postcopy_start_set_run();
2407 migration_downtime_start(ms
);
2409 global_state_store();
2410 ret
= migration_stop_vm(RUN_STATE_FINISH_MIGRATE
);
2415 ret
= migration_maybe_pause(ms
, &cur_state
,
2416 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2421 ret
= bdrv_inactivate_all();
2425 restart_block
= true;
2428 * Cause any non-postcopiable, but iterative devices to
2429 * send out their final data.
2431 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2434 * in Finish migrate and with the io-lock held everything should
2435 * be quiet, but we've potentially still got dirty pages and we
2436 * need to tell the destination to throw any pages it's already received
2439 if (migrate_postcopy_ram()) {
2440 ram_postcopy_send_discard_bitmap(ms
);
2444 * send rest of state - note things that are doing postcopy
2445 * will notice we're in POSTCOPY_ACTIVE and not actually
2446 * wrap their state up here
2448 migration_rate_set(bandwidth
);
2449 if (migrate_postcopy_ram()) {
2450 /* Ping just for debugging, helps line traces up */
2451 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2455 * While loading the device state we may trigger page transfer
2456 * requests and the fd must be free to process those, and thus
2457 * the destination must read the whole device state off the fd before
2458 * it starts processing it. Unfortunately the ad-hoc migration format
2459 * doesn't allow the destination to know the size to read without fully
2460 * parsing it through each devices load-state code (especially the open
2461 * coded devices that use get/put).
2462 * So we wrap the device state up in a package with a length at the start;
2463 * to do this we use a qemu_buf to hold the whole of the device state.
2465 bioc
= qio_channel_buffer_new(4096);
2466 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2467 fb
= qemu_file_new_output(QIO_CHANNEL(bioc
));
2468 object_unref(OBJECT(bioc
));
2471 * Make sure the receiver can get incoming pages before we send the rest
2474 qemu_savevm_send_postcopy_listen(fb
);
2476 qemu_savevm_state_complete_precopy(fb
, false, false);
2477 if (migrate_postcopy_ram()) {
2478 qemu_savevm_send_ping(fb
, 3);
2481 qemu_savevm_send_postcopy_run(fb
);
2483 /* <><> end of stuff going into the package */
2485 /* Last point of recovery; as soon as we send the package the destination
2486 * can open devices and potentially start running.
2487 * Lets just check again we've not got any errors.
2489 ret
= qemu_file_get_error(ms
->to_dst_file
);
2491 error_setg(errp
, "postcopy_start: Migration stream errored (pre package)");
2495 restart_block
= false;
2497 /* Now send that blob */
2498 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2503 /* Send a notify to give a chance for anything that needs to happen
2504 * at the transition to postcopy and after the device state; in particular
2505 * spice needs to trigger a transition now
2507 ms
->postcopy_after_devices
= true;
2508 migration_call_notifiers(ms
);
2510 migration_downtime_end(ms
);
2514 if (migrate_postcopy_ram()) {
2516 * Although this ping is just for debug, it could potentially be
2517 * used for getting a better measurement of downtime at the source.
2519 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2522 if (migrate_release_ram()) {
2523 ram_postcopy_migrated_memory_release(ms
);
2526 ret
= qemu_file_get_error(ms
->to_dst_file
);
2528 error_setg(errp
, "postcopy_start: Migration stream errored");
2529 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2530 MIGRATION_STATUS_FAILED
);
2533 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2540 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2541 MIGRATION_STATUS_FAILED
);
2542 if (restart_block
) {
2543 /* A failure happened early enough that we know the destination hasn't
2544 * accessed block devices, so we're safe to recover.
2546 Error
*local_err
= NULL
;
2548 bdrv_activate_all(&local_err
);
2550 error_report_err(local_err
);
2558 * migration_maybe_pause: Pause if required to by
2559 * migrate_pause_before_switchover called with the BQL locked
2560 * Returns: 0 on success
2562 static int migration_maybe_pause(MigrationState
*s
,
2563 int *current_active_state
,
2566 if (!migrate_pause_before_switchover()) {
2570 /* Since leaving this state is not atomic with posting the semaphore
2571 * it's possible that someone could have issued multiple migrate_continue
2572 * and the semaphore is incorrectly positive at this point;
2573 * the docs say it's undefined to reinit a semaphore that's already
2574 * init'd, so use timedwait to eat up any existing posts.
2576 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2577 /* This block intentionally left blank */
2581 * If the migration is cancelled when it is in the completion phase,
2582 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2583 * So we don't need to wait a semaphore, otherwise we would always
2584 * wait for the 'pause_sem' semaphore.
2586 if (s
->state
!= MIGRATION_STATUS_CANCELLING
) {
2588 migrate_set_state(&s
->state
, *current_active_state
,
2589 MIGRATION_STATUS_PRE_SWITCHOVER
);
2590 qemu_sem_wait(&s
->pause_sem
);
2591 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2593 *current_active_state
= new_state
;
2597 return s
->state
== new_state
? 0 : -EINVAL
;
2600 static int migration_completion_precopy(MigrationState
*s
,
2601 int *current_active_state
)
2606 migration_downtime_start(s
);
2608 s
->vm_old_state
= runstate_get();
2609 global_state_store();
2611 ret
= migration_stop_vm(RUN_STATE_FINISH_MIGRATE
);
2612 trace_migration_completion_vm_stop(ret
);
2617 ret
= migration_maybe_pause(s
, current_active_state
,
2618 MIGRATION_STATUS_DEVICE
);
2624 * Inactivate disks except in COLO, and track that we have done so in order
2625 * to remember to reactivate them if migration fails or is cancelled.
2627 s
->block_inactive
= !migrate_colo();
2628 migration_rate_set(RATE_LIMIT_DISABLED
);
2629 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2636 static void migration_completion_postcopy(MigrationState
*s
)
2638 trace_migration_completion_postcopy_end();
2641 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2645 * Shutdown the postcopy fast path thread. This is only needed when dest
2646 * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
2648 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
2649 postcopy_preempt_shutdown_file(s
);
2652 trace_migration_completion_postcopy_end_after_complete();
2655 static void migration_completion_failed(MigrationState
*s
,
2656 int current_active_state
)
2658 if (s
->block_inactive
&& (s
->state
== MIGRATION_STATUS_ACTIVE
||
2659 s
->state
== MIGRATION_STATUS_DEVICE
)) {
2661 * If not doing postcopy, vm_start() will be called: let's
2662 * regain control on images.
2664 Error
*local_err
= NULL
;
2667 bdrv_activate_all(&local_err
);
2669 error_report_err(local_err
);
2671 s
->block_inactive
= false;
2676 migrate_set_state(&s
->state
, current_active_state
,
2677 MIGRATION_STATUS_FAILED
);
2681 * migration_completion: Used by migration_thread when there's not much left.
2682 * The caller 'breaks' the loop when this returns.
2684 * @s: Current migration state
2686 static void migration_completion(MigrationState
*s
)
2689 int current_active_state
= s
->state
;
2691 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2692 ret
= migration_completion_precopy(s
, ¤t_active_state
);
2693 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2694 migration_completion_postcopy(s
);
2703 if (close_return_path_on_source(s
)) {
2707 if (qemu_file_get_error(s
->to_dst_file
)) {
2708 trace_migration_completion_file_err();
2712 if (migrate_colo() && s
->state
== MIGRATION_STATUS_ACTIVE
) {
2713 /* COLO does not support postcopy */
2714 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
2715 MIGRATION_STATUS_COLO
);
2717 migrate_set_state(&s
->state
, current_active_state
,
2718 MIGRATION_STATUS_COMPLETED
);
2724 migration_completion_failed(s
, current_active_state
);
2728 * bg_migration_completion: Used by bg_migration_thread when after all the
2729 * RAM has been saved. The caller 'breaks' the loop when this returns.
2731 * @s: Current migration state
2733 static void bg_migration_completion(MigrationState
*s
)
2735 int current_active_state
= s
->state
;
2737 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2739 * By this moment we have RAM content saved into the migration stream.
2740 * The next step is to flush the non-RAM content (device state)
2741 * right after the ram content. The device state has been stored into
2742 * the temporary buffer before RAM saving started.
2744 qemu_put_buffer(s
->to_dst_file
, s
->bioc
->data
, s
->bioc
->usage
);
2745 qemu_fflush(s
->to_dst_file
);
2746 } else if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
2750 if (qemu_file_get_error(s
->to_dst_file
)) {
2751 trace_migration_completion_file_err();
2755 migrate_set_state(&s
->state
, current_active_state
,
2756 MIGRATION_STATUS_COMPLETED
);
2760 migrate_set_state(&s
->state
, current_active_state
,
2761 MIGRATION_STATUS_FAILED
);
2764 typedef enum MigThrError
{
2765 /* No error detected */
2766 MIG_THR_ERR_NONE
= 0,
2767 /* Detected error, but resumed successfully */
2768 MIG_THR_ERR_RECOVERED
= 1,
2769 /* Detected fatal error, need to exit */
2770 MIG_THR_ERR_FATAL
= 2,
2773 static int postcopy_resume_handshake(MigrationState
*s
)
2775 qemu_savevm_send_postcopy_resume(s
->to_dst_file
);
2777 while (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2778 if (migration_rp_wait(s
)) {
2783 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2790 /* Return zero if success, or <0 for error */
2791 static int postcopy_do_resume(MigrationState
*s
)
2796 * Call all the resume_prepare() hooks, so that modules can be
2797 * ready for the migration resume.
2799 ret
= qemu_savevm_state_resume_prepare(s
);
2801 error_report("%s: resume_prepare() failure detected: %d",
2807 * If preempt is enabled, re-establish the preempt channel. Note that
2808 * we do it after resume prepare to make sure the main channel will be
2809 * created before the preempt channel. E.g. with weak network, the
2810 * dest QEMU may get messed up with the preempt and main channels on
2811 * the order of connection setup. This guarantees the correct order.
2813 ret
= postcopy_preempt_establish_channel(s
);
2815 error_report("%s: postcopy_preempt_establish_channel(): %d",
2821 * Last handshake with destination on the resume (destination will
2822 * switch to postcopy-active afterwards)
2824 ret
= postcopy_resume_handshake(s
);
2826 error_report("%s: handshake failed: %d", __func__
, ret
);
2834 * We don't return until we are in a safe state to continue current
2835 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2836 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2838 static MigThrError
postcopy_pause(MigrationState
*s
)
2840 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2846 * Current channel is possibly broken. Release it. Note that this is
2847 * guaranteed even without lock because to_dst_file should only be
2848 * modified by the migration thread. That also guarantees that the
2849 * unregister of yank is safe too without the lock. It should be safe
2850 * even to be within the qemu_file_lock, but we didn't do that to avoid
2851 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2852 * the qemu_file_lock critical section as small as possible.
2854 assert(s
->to_dst_file
);
2855 migration_ioc_unregister_yank_from_file(s
->to_dst_file
);
2856 qemu_mutex_lock(&s
->qemu_file_lock
);
2857 file
= s
->to_dst_file
;
2858 s
->to_dst_file
= NULL
;
2859 qemu_mutex_unlock(&s
->qemu_file_lock
);
2861 qemu_file_shutdown(file
);
2865 * We're already pausing, so ignore any errors on the return
2866 * path and just wait for the thread to finish. It will be
2867 * re-created when we resume.
2869 close_return_path_on_source(s
);
2871 migrate_set_state(&s
->state
, s
->state
,
2872 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2874 error_report("Detected IO failure for postcopy. "
2875 "Migration paused.");
2878 * We wait until things fixed up. Then someone will setup the
2879 * status back for us.
2881 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2882 qemu_sem_wait(&s
->postcopy_pause_sem
);
2885 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2886 /* Woken up by a recover procedure. Give it a shot */
2888 /* Do the resume logic */
2889 if (postcopy_do_resume(s
) == 0) {
2890 /* Let's continue! */
2891 trace_postcopy_pause_continued();
2892 return MIG_THR_ERR_RECOVERED
;
2895 * Something wrong happened during the recovery, let's
2896 * pause again. Pause is always better than throwing
2902 /* This is not right... Time to quit. */
2903 return MIG_THR_ERR_FATAL
;
2908 static MigThrError
migration_detect_error(MigrationState
*s
)
2911 int state
= s
->state
;
2912 Error
*local_error
= NULL
;
2914 if (state
== MIGRATION_STATUS_CANCELLING
||
2915 state
== MIGRATION_STATUS_CANCELLED
) {
2916 /* End the migration, but don't set the state to failed */
2917 return MIG_THR_ERR_FATAL
;
2921 * Try to detect any file errors. Note that postcopy_qemufile_src will
2922 * be NULL when postcopy preempt is not enabled.
2924 ret
= qemu_file_get_error_obj_any(s
->to_dst_file
,
2925 s
->postcopy_qemufile_src
,
2928 /* Everything is fine */
2929 assert(!local_error
);
2930 return MIG_THR_ERR_NONE
;
2934 migrate_set_error(s
, local_error
);
2935 error_free(local_error
);
2938 if (state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
) {
2940 * For postcopy, we allow the network to be down for a
2941 * while. After that, it can be continued by a
2944 return postcopy_pause(s
);
2947 * For precopy (or postcopy with error outside IO), we fail
2950 migrate_set_state(&s
->state
, state
, MIGRATION_STATUS_FAILED
);
2951 trace_migration_thread_file_err();
2953 /* Time to stop the migration, now. */
2954 return MIG_THR_ERR_FATAL
;
2958 static void migration_calculate_complete(MigrationState
*s
)
2960 uint64_t bytes
= migration_transferred_bytes();
2961 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2962 int64_t transfer_time
;
2964 migration_downtime_end(s
);
2965 s
->total_time
= end_time
- s
->start_time
;
2966 transfer_time
= s
->total_time
- s
->setup_time
;
2967 if (transfer_time
) {
2968 s
->mbps
= ((double) bytes
* 8.0) / transfer_time
/ 1000;
2972 static void update_iteration_initial_status(MigrationState
*s
)
2975 * Update these three fields at the same time to avoid mismatch info lead
2976 * wrong speed calculation.
2978 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2979 s
->iteration_initial_bytes
= migration_transferred_bytes();
2980 s
->iteration_initial_pages
= ram_get_total_transferred_pages();
2983 static void migration_update_counters(MigrationState
*s
,
2984 int64_t current_time
)
2986 uint64_t transferred
, transferred_pages
, time_spent
;
2987 uint64_t current_bytes
; /* bytes transferred since the beginning */
2988 uint64_t switchover_bw
;
2989 /* Expected bandwidth when switching over to destination QEMU */
2990 double expected_bw_per_ms
;
2993 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
2997 switchover_bw
= migrate_avail_switchover_bandwidth();
2998 current_bytes
= migration_transferred_bytes();
2999 transferred
= current_bytes
- s
->iteration_initial_bytes
;
3000 time_spent
= current_time
- s
->iteration_start_time
;
3001 bandwidth
= (double)transferred
/ time_spent
;
3003 if (switchover_bw
) {
3005 * If the user specified a switchover bandwidth, let's trust the
3006 * user so that can be more accurate than what we estimated.
3008 expected_bw_per_ms
= switchover_bw
/ 1000;
3010 /* If the user doesn't specify bandwidth, we use the estimated */
3011 expected_bw_per_ms
= bandwidth
;
3014 s
->threshold_size
= expected_bw_per_ms
* migrate_downtime_limit();
3016 s
->mbps
= (((double) transferred
* 8.0) /
3017 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
3019 transferred_pages
= ram_get_total_transferred_pages() -
3020 s
->iteration_initial_pages
;
3021 s
->pages_per_second
= (double) transferred_pages
/
3022 (((double) time_spent
/ 1000.0));
3025 * if we haven't sent anything, we don't want to
3026 * recalculate. 10000 is a small enough number for our purposes
3028 if (stat64_get(&mig_stats
.dirty_pages_rate
) &&
3029 transferred
> 10000) {
3030 s
->expected_downtime
=
3031 stat64_get(&mig_stats
.dirty_bytes_last_sync
) / expected_bw_per_ms
;
3034 migration_rate_reset();
3036 update_iteration_initial_status(s
);
3038 trace_migrate_transferred(transferred
, time_spent
,
3039 /* Both in unit bytes/ms */
3040 bandwidth
, switchover_bw
/ 1000,
3044 static bool migration_can_switchover(MigrationState
*s
)
3046 if (!migrate_switchover_ack()) {
3050 /* No reason to wait for switchover ACK if VM is stopped */
3051 if (!runstate_is_running()) {
3055 return s
->switchover_acked
;
3058 /* Migration thread iteration status */
3060 MIG_ITERATE_RESUME
, /* Resume current iteration */
3061 MIG_ITERATE_SKIP
, /* Skip current iteration */
3062 MIG_ITERATE_BREAK
, /* Break the loop */
3066 * Return true if continue to the next iteration directly, false
3069 static MigIterateState
migration_iteration_run(MigrationState
*s
)
3071 uint64_t must_precopy
, can_postcopy
;
3072 Error
*local_err
= NULL
;
3073 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
3074 bool can_switchover
= migration_can_switchover(s
);
3076 qemu_savevm_state_pending_estimate(&must_precopy
, &can_postcopy
);
3077 uint64_t pending_size
= must_precopy
+ can_postcopy
;
3079 trace_migrate_pending_estimate(pending_size
, must_precopy
, can_postcopy
);
3081 if (must_precopy
<= s
->threshold_size
) {
3082 qemu_savevm_state_pending_exact(&must_precopy
, &can_postcopy
);
3083 pending_size
= must_precopy
+ can_postcopy
;
3084 trace_migrate_pending_exact(pending_size
, must_precopy
, can_postcopy
);
3087 if ((!pending_size
|| pending_size
< s
->threshold_size
) && can_switchover
) {
3088 trace_migration_thread_low_pending(pending_size
);
3089 migration_completion(s
);
3090 return MIG_ITERATE_BREAK
;
3093 /* Still a significant amount to transfer */
3094 if (!in_postcopy
&& must_precopy
<= s
->threshold_size
&& can_switchover
&&
3095 qatomic_read(&s
->start_postcopy
)) {
3096 if (postcopy_start(s
, &local_err
)) {
3097 migrate_set_error(s
, local_err
);
3098 error_report_err(local_err
);
3100 return MIG_ITERATE_SKIP
;
3103 /* Just another iteration step */
3104 qemu_savevm_state_iterate(s
->to_dst_file
, in_postcopy
);
3105 return MIG_ITERATE_RESUME
;
3108 static void migration_iteration_finish(MigrationState
*s
)
3110 /* If we enabled cpu throttling for auto-converge, turn it off. */
3111 cpu_throttle_stop();
3115 case MIGRATION_STATUS_COMPLETED
:
3116 migration_calculate_complete(s
);
3117 runstate_set(RUN_STATE_POSTMIGRATE
);
3119 case MIGRATION_STATUS_COLO
:
3120 assert(migrate_colo());
3121 migrate_start_colo_process(s
);
3122 s
->vm_old_state
= RUN_STATE_RUNNING
;
3124 case MIGRATION_STATUS_FAILED
:
3125 case MIGRATION_STATUS_CANCELLED
:
3126 case MIGRATION_STATUS_CANCELLING
:
3127 if (runstate_is_live(s
->vm_old_state
)) {
3128 if (!runstate_check(RUN_STATE_SHUTDOWN
)) {
3132 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
3133 runstate_set(s
->vm_old_state
);
3139 /* Should not reach here, but if so, forgive the VM. */
3140 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3143 migrate_fd_cleanup_schedule(s
);
3147 static void bg_migration_iteration_finish(MigrationState
*s
)
3150 * Stop tracking RAM writes - un-protect memory, un-register UFFD
3151 * memory ranges, flush kernel wait queues and wake up threads
3152 * waiting for write fault to be resolved.
3154 ram_write_tracking_stop();
3158 case MIGRATION_STATUS_COMPLETED
:
3159 migration_calculate_complete(s
);
3162 case MIGRATION_STATUS_ACTIVE
:
3163 case MIGRATION_STATUS_FAILED
:
3164 case MIGRATION_STATUS_CANCELLED
:
3165 case MIGRATION_STATUS_CANCELLING
:
3169 /* Should not reach here, but if so, forgive the VM. */
3170 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3174 migrate_fd_cleanup_schedule(s
);
3179 * Return true if continue to the next iteration directly, false
3182 static MigIterateState
bg_migration_iteration_run(MigrationState
*s
)
3186 res
= qemu_savevm_state_iterate(s
->to_dst_file
, false);
3188 bg_migration_completion(s
);
3189 return MIG_ITERATE_BREAK
;
3192 return MIG_ITERATE_RESUME
;
3195 void migration_make_urgent_request(void)
3197 qemu_sem_post(&migrate_get_current()->rate_limit_sem
);
3200 void migration_consume_urgent_request(void)
3202 qemu_sem_wait(&migrate_get_current()->rate_limit_sem
);
3205 /* Returns true if the rate limiting was broken by an urgent request */
3206 bool migration_rate_limit(void)
3208 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3209 MigrationState
*s
= migrate_get_current();
3211 bool urgent
= false;
3212 migration_update_counters(s
, now
);
3213 if (migration_rate_exceeded(s
->to_dst_file
)) {
3215 if (qemu_file_get_error(s
->to_dst_file
)) {
3219 * Wait for a delay to do rate limiting OR
3220 * something urgent to post the semaphore.
3222 int ms
= s
->iteration_start_time
+ BUFFER_DELAY
- now
;
3223 trace_migration_rate_limit_pre(ms
);
3224 if (qemu_sem_timedwait(&s
->rate_limit_sem
, ms
) == 0) {
3226 * We were woken by one or more urgent things but
3227 * the timedwait will have consumed one of them.
3228 * The service routine for the urgent wake will dec
3229 * the semaphore itself for each item it consumes,
3230 * so add this one we just eat back.
3232 qemu_sem_post(&s
->rate_limit_sem
);
3235 trace_migration_rate_limit_post(urgent
);
3241 * if failover devices are present, wait they are completely
3245 static void qemu_savevm_wait_unplug(MigrationState
*s
, int old_state
,
3248 if (qemu_savevm_state_guest_unplug_pending()) {
3249 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_WAIT_UNPLUG
);
3251 while (s
->state
== MIGRATION_STATUS_WAIT_UNPLUG
&&
3252 qemu_savevm_state_guest_unplug_pending()) {
3253 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3255 if (s
->state
!= MIGRATION_STATUS_WAIT_UNPLUG
) {
3256 int timeout
= 120; /* 30 seconds */
3258 * migration has been canceled
3259 * but as we have started an unplug we must wait the end
3260 * to be able to plug back the card
3262 while (timeout
-- && qemu_savevm_state_guest_unplug_pending()) {
3263 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3265 if (qemu_savevm_state_guest_unplug_pending() &&
3267 warn_report("migration: partially unplugged device on "
3272 migrate_set_state(&s
->state
, MIGRATION_STATUS_WAIT_UNPLUG
, new_state
);
3274 migrate_set_state(&s
->state
, old_state
, new_state
);
3279 * Master migration thread on the source VM.
3280 * It drives the migration and pumps the data down the outgoing channel.
3282 static void *migration_thread(void *opaque
)
3284 MigrationState
*s
= opaque
;
3285 MigrationThread
*thread
= NULL
;
3286 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3287 MigThrError thr_error
;
3288 bool urgent
= false;
3290 thread
= migration_threads_add("live_migration", qemu_get_thread_id());
3292 rcu_register_thread();
3294 object_ref(OBJECT(s
));
3295 update_iteration_initial_status(s
);
3298 qemu_savevm_state_header(s
->to_dst_file
);
3302 * If we opened the return path, we need to make sure dst has it
3305 if (s
->rp_state
.rp_thread_created
) {
3306 /* Now tell the dest that it should open its end so it can reply */
3307 qemu_savevm_send_open_return_path(s
->to_dst_file
);
3309 /* And do a ping that will make stuff easier to debug */
3310 qemu_savevm_send_ping(s
->to_dst_file
, 1);
3313 if (migrate_postcopy()) {
3315 * Tell the destination that we *might* want to do postcopy later;
3316 * if the other end can't do postcopy it should fail now, nice and
3319 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
3322 if (migrate_colo()) {
3323 /* Notify migration destination that we enable COLO */
3324 qemu_savevm_send_colo_enable(s
->to_dst_file
);
3328 qemu_savevm_state_setup(s
->to_dst_file
);
3331 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3332 MIGRATION_STATUS_ACTIVE
);
3334 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3336 trace_migration_thread_setup_complete();
3338 while (migration_is_active(s
)) {
3339 if (urgent
|| !migration_rate_exceeded(s
->to_dst_file
)) {
3340 MigIterateState iter_state
= migration_iteration_run(s
);
3341 if (iter_state
== MIG_ITERATE_SKIP
) {
3343 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3349 * Try to detect any kind of failures, and see whether we
3350 * should stop the migration now.
3352 thr_error
= migration_detect_error(s
);
3353 if (thr_error
== MIG_THR_ERR_FATAL
) {
3354 /* Stop migration */
3356 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
3358 * Just recovered from a e.g. network failure, reset all
3359 * the local variables. This is important to avoid
3360 * breaking transferred_bytes and bandwidth calculation
3362 update_iteration_initial_status(s
);
3365 urgent
= migration_rate_limit();
3368 trace_migration_thread_after_loop();
3369 migration_iteration_finish(s
);
3370 object_unref(OBJECT(s
));
3371 rcu_unregister_thread();
3372 migration_threads_remove(thread
);
3376 static void bg_migration_vm_start_bh(void *opaque
)
3378 MigrationState
*s
= opaque
;
3380 qemu_bh_delete(s
->vm_start_bh
);
3381 s
->vm_start_bh
= NULL
;
3383 vm_resume(s
->vm_old_state
);
3384 migration_downtime_end(s
);
3388 * Background snapshot thread, based on live migration code.
3389 * This is an alternative implementation of live migration mechanism
3390 * introduced specifically to support background snapshots.
3392 * It takes advantage of userfault_fd write protection mechanism introduced
3393 * in v5.7 kernel. Compared to existing dirty page logging migration much
3394 * lesser stream traffic is produced resulting in smaller snapshot images,
3395 * simply cause of no page duplicates can get into the stream.
3397 * Another key point is that generated vmstate stream reflects machine state
3398 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3399 * mechanism, which effectively results in that saved snapshot is the state of VM
3400 * at the end of the process.
3402 static void *bg_migration_thread(void *opaque
)
3404 MigrationState
*s
= opaque
;
3405 int64_t setup_start
;
3406 MigThrError thr_error
;
3408 bool early_fail
= true;
3410 rcu_register_thread();
3411 object_ref(OBJECT(s
));
3413 migration_rate_set(RATE_LIMIT_DISABLED
);
3415 setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3417 * We want to save vmstate for the moment when migration has been
3418 * initiated but also we want to save RAM content while VM is running.
3419 * The RAM content should appear first in the vmstate. So, we first
3420 * stash the non-RAM part of the vmstate to the temporary buffer,
3421 * then write RAM part of the vmstate to the migration stream
3422 * with vCPUs running and, finally, write stashed non-RAM part of
3423 * the vmstate from the buffer to the migration stream.
3425 s
->bioc
= qio_channel_buffer_new(512 * 1024);
3426 qio_channel_set_name(QIO_CHANNEL(s
->bioc
), "vmstate-buffer");
3427 fb
= qemu_file_new_output(QIO_CHANNEL(s
->bioc
));
3428 object_unref(OBJECT(s
->bioc
));
3430 update_iteration_initial_status(s
);
3433 * Prepare for tracking memory writes with UFFD-WP - populate
3434 * RAM pages before protecting.
3437 ram_write_tracking_prepare();
3441 qemu_savevm_state_header(s
->to_dst_file
);
3442 qemu_savevm_state_setup(s
->to_dst_file
);
3445 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3446 MIGRATION_STATUS_ACTIVE
);
3448 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3450 trace_migration_thread_setup_complete();
3451 migration_downtime_start(s
);
3455 s
->vm_old_state
= runstate_get();
3457 global_state_store();
3458 /* Forcibly stop VM before saving state of vCPUs and devices */
3459 if (migration_stop_vm(RUN_STATE_PAUSED
)) {
3463 * Put vCPUs in sync with shadow context structures, then
3464 * save their state to channel-buffer along with devices.
3466 cpu_synchronize_all_states();
3467 if (qemu_savevm_state_complete_precopy_non_iterable(fb
, false, false)) {
3471 * Since we are going to get non-iterable state data directly
3472 * from s->bioc->data, explicit flush is needed here.
3476 /* Now initialize UFFD context and start tracking RAM writes */
3477 if (ram_write_tracking_start()) {
3483 * Start VM from BH handler to avoid write-fault lock here.
3484 * UFFD-WP protection for the whole RAM is already enabled so
3485 * calling VM state change notifiers from vm_start() would initiate
3486 * writes to virtio VQs memory which is in write-protected region.
3488 s
->vm_start_bh
= qemu_bh_new(bg_migration_vm_start_bh
, s
);
3489 qemu_bh_schedule(s
->vm_start_bh
);
3493 while (migration_is_active(s
)) {
3494 MigIterateState iter_state
= bg_migration_iteration_run(s
);
3495 if (iter_state
== MIG_ITERATE_SKIP
) {
3497 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3502 * Try to detect any kind of failures, and see whether we
3503 * should stop the migration now.
3505 thr_error
= migration_detect_error(s
);
3506 if (thr_error
== MIG_THR_ERR_FATAL
) {
3507 /* Stop migration */
3511 migration_update_counters(s
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
));
3514 trace_migration_thread_after_loop();
3518 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
3519 MIGRATION_STATUS_FAILED
);
3523 bg_migration_iteration_finish(s
);
3526 object_unref(OBJECT(s
));
3527 rcu_unregister_thread();
3532 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
3534 Error
*local_err
= NULL
;
3535 uint64_t rate_limit
;
3536 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
3539 * If there's a previous error, free it and prepare for another one.
3540 * Meanwhile if migration completes successfully, there won't have an error
3541 * dumped when calling migrate_fd_cleanup().
3543 migrate_error_free(s
);
3545 s
->expected_downtime
= migrate_downtime_limit();
3547 assert(s
->cleanup_bh
);
3549 assert(!s
->cleanup_bh
);
3550 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup_bh
, s
);
3553 migrate_fd_error(s
, error_in
);
3556 * Don't do cleanup for resume if channel is invalid, but only dump
3557 * the error. We wait for another channel connect from the user.
3558 * The error_report still gives HMP user a hint on what failed.
3559 * It's normally done in migrate_fd_cleanup(), but call it here
3562 error_report_err(error_copy(s
->error
));
3564 migrate_fd_cleanup(s
);
3570 /* This is a resumed migration */
3571 rate_limit
= migrate_max_postcopy_bandwidth();
3573 /* This is a fresh new migration */
3574 rate_limit
= migrate_max_bandwidth();
3576 /* Notify before starting migration thread */
3577 migration_call_notifiers(s
);
3580 migration_rate_set(rate_limit
);
3581 qemu_file_set_blocking(s
->to_dst_file
, true);
3584 * Open the return path. For postcopy, it is used exclusively. For
3585 * precopy, only if user specified "return-path" capability would
3586 * QEMU uses the return path.
3588 if (migrate_postcopy_ram() || migrate_return_path()) {
3589 if (open_return_path_on_source(s
)) {
3590 error_setg(&local_err
, "Unable to open return-path for postcopy");
3591 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
3592 migrate_set_error(s
, local_err
);
3593 error_report_err(local_err
);
3594 migrate_fd_cleanup(s
);
3600 * This needs to be done before resuming a postcopy. Note: for newer
3601 * QEMUs we will delay the channel creation until postcopy_start(), to
3602 * avoid disorder of channel creations.
3604 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
3605 postcopy_preempt_setup(s
);
3609 /* Wakeup the main migration thread to do the recovery */
3610 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
3611 MIGRATION_STATUS_POSTCOPY_RECOVER
);
3612 qemu_sem_post(&s
->postcopy_pause_sem
);
3616 if (multifd_save_setup(&local_err
) != 0) {
3617 migrate_set_error(s
, local_err
);
3618 error_report_err(local_err
);
3619 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
3620 MIGRATION_STATUS_FAILED
);
3621 migrate_fd_cleanup(s
);
3625 if (migrate_background_snapshot()) {
3626 qemu_thread_create(&s
->thread
, "bg_snapshot",
3627 bg_migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3629 qemu_thread_create(&s
->thread
, "live_migration",
3630 migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3632 s
->migration_thread_running
= true;
3635 static void migration_class_init(ObjectClass
*klass
, void *data
)
3637 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3639 dc
->user_creatable
= false;
3640 device_class_set_props(dc
, migration_properties
);
3643 static void migration_instance_finalize(Object
*obj
)
3645 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3647 qemu_mutex_destroy(&ms
->error_mutex
);
3648 qemu_mutex_destroy(&ms
->qemu_file_lock
);
3649 qemu_sem_destroy(&ms
->wait_unplug_sem
);
3650 qemu_sem_destroy(&ms
->rate_limit_sem
);
3651 qemu_sem_destroy(&ms
->pause_sem
);
3652 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
3653 qemu_sem_destroy(&ms
->rp_state
.rp_sem
);
3654 qemu_sem_destroy(&ms
->rp_state
.rp_pong_acks
);
3655 qemu_sem_destroy(&ms
->postcopy_qemufile_src_sem
);
3656 error_free(ms
->error
);
3659 static void migration_instance_init(Object
*obj
)
3661 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3663 ms
->state
= MIGRATION_STATUS_NONE
;
3665 ms
->pages_per_second
= -1;
3666 qemu_sem_init(&ms
->pause_sem
, 0);
3667 qemu_mutex_init(&ms
->error_mutex
);
3669 migrate_params_init(&ms
->parameters
);
3671 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
3672 qemu_sem_init(&ms
->rp_state
.rp_sem
, 0);
3673 qemu_sem_init(&ms
->rp_state
.rp_pong_acks
, 0);
3674 qemu_sem_init(&ms
->rate_limit_sem
, 0);
3675 qemu_sem_init(&ms
->wait_unplug_sem
, 0);
3676 qemu_sem_init(&ms
->postcopy_qemufile_src_sem
, 0);
3677 qemu_mutex_init(&ms
->qemu_file_lock
);
3681 * Return true if check pass, false otherwise. Error will be put
3682 * inside errp if provided.
3684 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
3686 /* Assuming all off */
3687 bool old_caps
[MIGRATION_CAPABILITY__MAX
] = { 0 };
3689 if (!migrate_params_check(&ms
->parameters
, errp
)) {
3693 return migrate_caps_check(old_caps
, ms
->capabilities
, errp
);
3696 static const TypeInfo migration_type
= {
3697 .name
= TYPE_MIGRATION
,
3699 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3700 * not created using qdev_new(), it is not attached to the qdev
3701 * device tree, and it is never realized.
3703 * TODO: Make this TYPE_OBJECT once QOM provides something like
3704 * TYPE_DEVICE's "-global" properties.
3706 .parent
= TYPE_DEVICE
,
3707 .class_init
= migration_class_init
,
3708 .class_size
= sizeof(MigrationClass
),
3709 .instance_size
= sizeof(MigrationState
),
3710 .instance_init
= migration_instance_init
,
3711 .instance_finalize
= migration_instance_finalize
,
3714 static void register_migration_types(void)
3716 type_register_static(&migration_type
);
3719 type_init(register_migration_types
);