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();
208 static void migration_bh_dispatch_bh(void *opaque
)
210 MigrationState
*s
= migrate_get_current();
211 MigrationBH
*migbh
= opaque
;
213 /* cleanup this BH */
214 qemu_bh_delete(migbh
->bh
);
217 /* dispatch the other one */
218 migbh
->cb(migbh
->opaque
);
219 object_unref(OBJECT(s
));
224 void migration_bh_schedule(QEMUBHFunc
*cb
, void *opaque
)
226 MigrationState
*s
= migrate_get_current();
227 MigrationBH
*migbh
= g_new0(MigrationBH
, 1);
228 QEMUBH
*bh
= qemu_bh_new(migration_bh_dispatch_bh
, migbh
);
230 /* Store these to dispatch when the BH runs */
233 migbh
->opaque
= opaque
;
236 * Ref the state for bh, because it may be called when
237 * there're already no other refs
239 object_ref(OBJECT(s
));
240 qemu_bh_schedule(bh
);
243 void migration_cancel(const Error
*error
)
246 migrate_set_error(current_migration
, error
);
248 if (migrate_dirty_limit()) {
249 qmp_cancel_vcpu_dirty_limit(false, -1, NULL
);
251 migrate_fd_cancel(current_migration
);
254 void migration_shutdown(void)
257 * When the QEMU main thread exit, the COLO thread
258 * may wait a semaphore. So, we should wakeup the
259 * COLO thread before migration shutdown.
263 * Cancel the current migration - that will (eventually)
264 * stop the migration using this structure
266 migration_cancel(NULL
);
267 object_unref(OBJECT(current_migration
));
270 * Cancel outgoing migration of dirty bitmaps. It should
271 * at least unref used block nodes.
273 dirty_bitmap_mig_cancel_outgoing();
276 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
277 * are non-critical data, and their loss never considered as
280 dirty_bitmap_mig_cancel_incoming();
284 MigrationState
*migrate_get_current(void)
286 /* This can only be called after the object created. */
287 assert(current_migration
);
288 return current_migration
;
291 MigrationIncomingState
*migration_incoming_get_current(void)
293 assert(current_incoming
);
294 return current_incoming
;
297 void migration_incoming_transport_cleanup(MigrationIncomingState
*mis
)
299 if (mis
->socket_address_list
) {
300 qapi_free_SocketAddressList(mis
->socket_address_list
);
301 mis
->socket_address_list
= NULL
;
304 if (mis
->transport_cleanup
) {
305 mis
->transport_cleanup(mis
->transport_data
);
306 mis
->transport_data
= mis
->transport_cleanup
= NULL
;
310 void migration_incoming_state_destroy(void)
312 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
314 multifd_load_cleanup();
315 compress_threads_load_cleanup();
317 if (mis
->to_src_file
) {
318 /* Tell source that we are done */
319 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
320 qemu_fclose(mis
->to_src_file
);
321 mis
->to_src_file
= NULL
;
324 if (mis
->from_src_file
) {
325 migration_ioc_unregister_yank_from_file(mis
->from_src_file
);
326 qemu_fclose(mis
->from_src_file
);
327 mis
->from_src_file
= NULL
;
329 if (mis
->postcopy_remote_fds
) {
330 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
331 mis
->postcopy_remote_fds
= NULL
;
334 migration_incoming_transport_cleanup(mis
);
335 qemu_event_reset(&mis
->main_thread_load_event
);
337 if (mis
->page_requested
) {
338 g_tree_destroy(mis
->page_requested
);
339 mis
->page_requested
= NULL
;
342 if (mis
->postcopy_qemufile_dst
) {
343 migration_ioc_unregister_yank_from_file(mis
->postcopy_qemufile_dst
);
344 qemu_fclose(mis
->postcopy_qemufile_dst
);
345 mis
->postcopy_qemufile_dst
= NULL
;
348 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
351 static void migrate_generate_event(int new_state
)
353 if (migrate_events()) {
354 qapi_event_send_migration(new_state
);
359 * Send a message on the return channel back to the source
362 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
363 enum mig_rp_message_type message_type
,
364 uint16_t len
, void *data
)
368 trace_migrate_send_rp_message((int)message_type
, len
);
369 QEMU_LOCK_GUARD(&mis
->rp_mutex
);
372 * It's possible that the file handle got lost due to network
375 if (!mis
->to_src_file
) {
380 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
381 qemu_put_be16(mis
->to_src_file
, len
);
382 qemu_put_buffer(mis
->to_src_file
, data
, len
);
383 return qemu_fflush(mis
->to_src_file
);
386 /* Request one page from the source VM at the given start address.
387 * rb: the RAMBlock to request the page in
388 * Start: Address offset within the RB
389 * Len: Length in bytes required - must be a multiple of pagesize
391 int migrate_send_rp_message_req_pages(MigrationIncomingState
*mis
,
392 RAMBlock
*rb
, ram_addr_t start
)
394 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
395 size_t msglen
= 12; /* start + len */
396 size_t len
= qemu_ram_pagesize(rb
);
397 enum mig_rp_message_type msg_type
;
401 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
402 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
405 * We maintain the last ramblock that we requested for page. Note that we
406 * don't need locking because this function will only be called within the
407 * postcopy ram fault thread.
409 if (rb
!= mis
->last_rb
) {
412 rbname
= qemu_ram_get_idstr(rb
);
413 rbname_len
= strlen(rbname
);
415 assert(rbname_len
< 256);
417 bufc
[msglen
++] = rbname_len
;
418 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
419 msglen
+= rbname_len
;
420 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
422 msg_type
= MIG_RP_MSG_REQ_PAGES
;
425 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
428 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
,
429 RAMBlock
*rb
, ram_addr_t start
, uint64_t haddr
)
431 void *aligned
= (void *)(uintptr_t)ROUND_DOWN(haddr
, qemu_ram_pagesize(rb
));
432 bool received
= false;
434 WITH_QEMU_LOCK_GUARD(&mis
->page_request_mutex
) {
435 received
= ramblock_recv_bitmap_test_byte_offset(rb
, start
);
436 if (!received
&& !g_tree_lookup(mis
->page_requested
, aligned
)) {
438 * The page has not been received, and it's not yet in the page
439 * request list. Queue it. Set the value of element to 1, so that
440 * things like g_tree_lookup() will return TRUE (1) when found.
442 g_tree_insert(mis
->page_requested
, aligned
, (gpointer
)1);
443 qatomic_inc(&mis
->page_requested_count
);
444 trace_postcopy_page_req_add(aligned
, mis
->page_requested_count
);
449 * If the page is there, skip sending the message. We don't even need the
450 * lock because as long as the page arrived, it'll be there forever.
456 return migrate_send_rp_message_req_pages(mis
, rb
, start
);
459 static bool migration_colo_enabled
;
460 bool migration_incoming_colo_enabled(void)
462 return migration_colo_enabled
;
465 void migration_incoming_disable_colo(void)
467 ram_block_discard_disable(false);
468 migration_colo_enabled
= false;
471 int migration_incoming_enable_colo(void)
473 #ifndef CONFIG_REPLICATION
474 error_report("ENABLE_COLO command come in migration stream, but COLO "
475 "module is not built in");
479 if (!migrate_colo()) {
480 error_report("ENABLE_COLO command come in migration stream, but c-colo "
481 "capability is not set");
485 if (ram_block_discard_disable(true)) {
486 error_report("COLO: cannot disable RAM discard");
489 migration_colo_enabled
= true;
493 void migrate_add_address(SocketAddress
*address
)
495 MigrationIncomingState
*mis
= migration_incoming_get_current();
497 QAPI_LIST_PREPEND(mis
->socket_address_list
,
498 QAPI_CLONE(SocketAddress
, address
));
501 bool migrate_uri_parse(const char *uri
, MigrationChannel
**channel
,
504 g_autoptr(MigrationChannel
) val
= g_new0(MigrationChannel
, 1);
505 g_autoptr(MigrationAddress
) addr
= g_new0(MigrationAddress
, 1);
506 InetSocketAddress
*isock
= &addr
->u
.rdma
;
507 strList
**tail
= &addr
->u
.exec
.args
;
509 if (strstart(uri
, "exec:", NULL
)) {
510 addr
->transport
= MIGRATION_ADDRESS_TYPE_EXEC
;
512 QAPI_LIST_APPEND(tail
, g_strdup(exec_get_cmd_path()));
513 QAPI_LIST_APPEND(tail
, g_strdup("/c"));
515 QAPI_LIST_APPEND(tail
, g_strdup("/bin/sh"));
516 QAPI_LIST_APPEND(tail
, g_strdup("-c"));
518 QAPI_LIST_APPEND(tail
, g_strdup(uri
+ strlen("exec:")));
519 } else if (strstart(uri
, "rdma:", NULL
)) {
520 if (inet_parse(isock
, uri
+ strlen("rdma:"), errp
)) {
521 qapi_free_InetSocketAddress(isock
);
524 addr
->transport
= MIGRATION_ADDRESS_TYPE_RDMA
;
525 } else if (strstart(uri
, "tcp:", NULL
) ||
526 strstart(uri
, "unix:", NULL
) ||
527 strstart(uri
, "vsock:", NULL
) ||
528 strstart(uri
, "fd:", NULL
)) {
529 addr
->transport
= MIGRATION_ADDRESS_TYPE_SOCKET
;
530 SocketAddress
*saddr
= socket_parse(uri
, errp
);
534 addr
->u
.socket
.type
= saddr
->type
;
535 addr
->u
.socket
.u
= saddr
->u
;
536 /* Don't free the objects inside; their ownership moved to "addr" */
538 } else if (strstart(uri
, "file:", NULL
)) {
539 addr
->transport
= MIGRATION_ADDRESS_TYPE_FILE
;
540 addr
->u
.file
.filename
= g_strdup(uri
+ strlen("file:"));
541 if (file_parse_offset(addr
->u
.file
.filename
, &addr
->u
.file
.offset
,
546 error_setg(errp
, "unknown migration protocol: %s", uri
);
550 val
->channel_type
= MIGRATION_CHANNEL_TYPE_MAIN
;
551 val
->addr
= g_steal_pointer(&addr
);
552 *channel
= g_steal_pointer(&val
);
556 static void qemu_start_incoming_migration(const char *uri
, bool has_channels
,
557 MigrationChannelList
*channels
,
560 g_autoptr(MigrationChannel
) channel
= NULL
;
561 MigrationAddress
*addr
= NULL
;
562 MigrationIncomingState
*mis
= migration_incoming_get_current();
565 * Having preliminary checks for uri and channel
567 if (!uri
== !channels
) {
568 error_setg(errp
, "need either 'uri' or 'channels' argument");
573 /* To verify that Migrate channel list has only item */
574 if (channels
->next
) {
575 error_setg(errp
, "Channel list has more than one entries");
578 addr
= channels
->value
->addr
;
582 /* caller uses the old URI syntax */
583 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
586 addr
= channel
->addr
;
589 /* transport mechanism not suitable for migration? */
590 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
594 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
595 MIGRATION_STATUS_SETUP
);
597 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
598 SocketAddress
*saddr
= &addr
->u
.socket
;
599 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
600 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
601 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
602 socket_start_incoming_migration(saddr
, errp
);
603 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
604 fd_start_incoming_migration(saddr
->u
.fd
.str
, errp
);
607 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
608 if (migrate_compress()) {
609 error_setg(errp
, "RDMA and compression can't be used together");
612 if (migrate_xbzrle()) {
613 error_setg(errp
, "RDMA and XBZRLE can't be used together");
616 if (migrate_multifd()) {
617 error_setg(errp
, "RDMA and multifd can't be used together");
620 rdma_start_incoming_migration(&addr
->u
.rdma
, errp
);
622 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
623 exec_start_incoming_migration(addr
->u
.exec
.args
, errp
);
624 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
625 file_start_incoming_migration(&addr
->u
.file
, errp
);
627 error_setg(errp
, "unknown migration protocol: %s", uri
);
631 static void process_incoming_migration_bh(void *opaque
)
633 Error
*local_err
= NULL
;
634 MigrationIncomingState
*mis
= opaque
;
636 trace_vmstate_downtime_checkpoint("dst-precopy-bh-enter");
638 /* If capability late_block_activate is set:
639 * Only fire up the block code now if we're going to restart the
640 * VM, else 'cont' will do it.
641 * This causes file locking to happen; so we don't want it to happen
642 * unless we really are starting the VM.
644 if (!migrate_late_block_activate() ||
645 (autostart
&& (!global_state_received() ||
646 runstate_is_live(global_state_get_runstate())))) {
647 /* Make sure all file formats throw away their mutable metadata.
648 * If we get an error here, just don't restart the VM yet. */
649 bdrv_activate_all(&local_err
);
651 error_report_err(local_err
);
658 * This must happen after all error conditions are dealt with and
659 * we're sure the VM is going to be running on this host.
661 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
663 trace_vmstate_downtime_checkpoint("dst-precopy-bh-announced");
665 multifd_load_shutdown();
667 dirty_bitmap_mig_before_vm_start();
669 if (!global_state_received() ||
670 runstate_is_live(global_state_get_runstate())) {
674 runstate_set(RUN_STATE_PAUSED
);
676 } else if (migration_incoming_colo_enabled()) {
677 migration_incoming_disable_colo();
680 runstate_set(global_state_get_runstate());
682 trace_vmstate_downtime_checkpoint("dst-precopy-bh-vm-started");
684 * This must happen after any state changes since as soon as an external
685 * observer sees this event they might start to prod at the VM assuming
688 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
689 MIGRATION_STATUS_COMPLETED
);
690 migration_incoming_state_destroy();
693 static void coroutine_fn
694 process_incoming_migration_co(void *opaque
)
696 MigrationIncomingState
*mis
= migration_incoming_get_current();
700 assert(mis
->from_src_file
);
702 if (compress_threads_load_setup(mis
->from_src_file
)) {
703 error_report("Failed to setup decompress threads");
707 mis
->largest_page_size
= qemu_ram_pagesize_largest();
708 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
709 migrate_set_state(&mis
->state
, MIGRATION_STATUS_SETUP
,
710 MIGRATION_STATUS_ACTIVE
);
712 mis
->loadvm_co
= qemu_coroutine_self();
713 ret
= qemu_loadvm_state(mis
->from_src_file
);
714 mis
->loadvm_co
= NULL
;
716 trace_vmstate_downtime_checkpoint("dst-precopy-loadvm-completed");
718 ps
= postcopy_state_get();
719 trace_process_incoming_migration_co_end(ret
, ps
);
720 if (ps
!= POSTCOPY_INCOMING_NONE
) {
721 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
723 * Where a migration had postcopy enabled (and thus went to advise)
724 * but managed to complete within the precopy period, we can use
727 postcopy_ram_incoming_cleanup(mis
);
728 } else if (ret
>= 0) {
730 * Postcopy was started, cleanup should happen at the end of the
733 trace_process_incoming_migration_co_postcopy_end_main();
736 /* Else if something went wrong then just fall out of the normal exit */
740 MigrationState
*s
= migrate_get_current();
742 if (migrate_has_error(s
)) {
743 WITH_QEMU_LOCK_GUARD(&s
->error_mutex
) {
744 error_report_err(s
->error
);
747 error_report("load of migration failed: %s", strerror(-ret
));
751 if (colo_incoming_co() < 0) {
755 migration_bh_schedule(process_incoming_migration_bh
, mis
);
758 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
759 MIGRATION_STATUS_FAILED
);
760 qemu_fclose(mis
->from_src_file
);
762 multifd_load_cleanup();
763 compress_threads_load_cleanup();
769 * migration_incoming_setup: Setup incoming migration
770 * @f: file for main migration channel
772 static void migration_incoming_setup(QEMUFile
*f
)
774 MigrationIncomingState
*mis
= migration_incoming_get_current();
776 if (!mis
->from_src_file
) {
777 mis
->from_src_file
= f
;
779 qemu_file_set_blocking(f
, false);
782 void migration_incoming_process(void)
784 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
785 qemu_coroutine_enter(co
);
788 /* Returns true if recovered from a paused migration, otherwise false */
789 static bool postcopy_try_recover(void)
791 MigrationIncomingState
*mis
= migration_incoming_get_current();
793 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
794 /* Resumed from a paused postcopy migration */
796 /* This should be set already in migration_incoming_setup() */
797 assert(mis
->from_src_file
);
798 /* Postcopy has standalone thread to do vm load */
799 qemu_file_set_blocking(mis
->from_src_file
, true);
801 /* Re-configure the return path */
802 mis
->to_src_file
= qemu_file_get_return_path(mis
->from_src_file
);
804 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
805 MIGRATION_STATUS_POSTCOPY_RECOVER
);
808 * Here, we only wake up the main loading thread (while the
809 * rest threads will still be waiting), so that we can receive
810 * commands from source now, and answer it if needed. The
811 * rest threads will be woken up afterwards until we are sure
812 * that source is ready to reply to page requests.
814 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
821 void migration_fd_process_incoming(QEMUFile
*f
)
823 migration_incoming_setup(f
);
824 if (postcopy_try_recover()) {
827 migration_incoming_process();
831 * Returns true when we want to start a new incoming migration process,
834 static bool migration_should_start_incoming(bool main_channel
)
836 /* Multifd doesn't start unless all channels are established */
837 if (migrate_multifd()) {
838 return migration_has_all_channels();
841 /* Preempt channel only starts when the main channel is created */
842 if (migrate_postcopy_preempt()) {
847 * For all the rest types of migration, we should only reach here when
848 * it's the main channel that's being created, and we should always
849 * proceed with this channel.
851 assert(main_channel
);
855 void migration_ioc_process_incoming(QIOChannel
*ioc
, Error
**errp
)
857 MigrationIncomingState
*mis
= migration_incoming_get_current();
858 Error
*local_err
= NULL
;
860 bool default_channel
= true;
861 uint32_t channel_magic
= 0;
864 if (migrate_multifd() && !migrate_postcopy_ram() &&
865 qio_channel_has_feature(ioc
, QIO_CHANNEL_FEATURE_READ_MSG_PEEK
)) {
867 * With multiple channels, it is possible that we receive channels
868 * out of order on destination side, causing incorrect mapping of
869 * source channels on destination side. Check channel MAGIC to
870 * decide type of channel. Please note this is best effort, postcopy
871 * preempt channel does not send any magic number so avoid it for
872 * postcopy live migration. Also tls live migration already does
873 * tls handshake while initializing main channel so with tls this
874 * issue is not possible.
876 ret
= migration_channel_read_peek(ioc
, (void *)&channel_magic
,
877 sizeof(channel_magic
), errp
);
883 default_channel
= (channel_magic
== cpu_to_be32(QEMU_VM_FILE_MAGIC
));
885 default_channel
= !mis
->from_src_file
;
888 if (multifd_load_setup(errp
) != 0) {
892 if (default_channel
) {
893 f
= qemu_file_new_input(ioc
);
894 migration_incoming_setup(f
);
896 /* Multiple connections */
897 assert(migration_needs_multiple_sockets());
898 if (migrate_multifd()) {
899 multifd_recv_new_channel(ioc
, &local_err
);
901 assert(migrate_postcopy_preempt());
902 f
= qemu_file_new_input(ioc
);
903 postcopy_preempt_new_channel(mis
, f
);
906 error_propagate(errp
, local_err
);
911 if (migration_should_start_incoming(default_channel
)) {
912 /* If it's a recovery, we're done */
913 if (postcopy_try_recover()) {
916 migration_incoming_process();
921 * @migration_has_all_channels: We have received all channels that we need
923 * Returns true when we have got connections to all the channels that
924 * we need for migration.
926 bool migration_has_all_channels(void)
928 MigrationIncomingState
*mis
= migration_incoming_get_current();
930 if (!mis
->from_src_file
) {
934 if (migrate_multifd()) {
935 return multifd_recv_all_channels_created();
938 if (migrate_postcopy_preempt()) {
939 return mis
->postcopy_qemufile_dst
!= NULL
;
945 int migrate_send_rp_switchover_ack(MigrationIncomingState
*mis
)
947 return migrate_send_rp_message(mis
, MIG_RP_MSG_SWITCHOVER_ACK
, 0, NULL
);
951 * Send a 'SHUT' message on the return channel with the given value
952 * to indicate that we've finished with the RP. Non-0 value indicates
955 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
960 buf
= cpu_to_be32(value
);
961 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
965 * Send a 'PONG' message on the return channel with the given value
966 * (normally in response to a 'PING')
968 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
973 buf
= cpu_to_be32(value
);
974 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
977 void migrate_send_rp_recv_bitmap(MigrationIncomingState
*mis
,
985 * First, we send the header part. It contains only the len of
986 * idstr, and the idstr itself.
988 len
= strlen(block_name
);
990 memcpy(buf
+ 1, block_name
, len
);
992 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
993 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
998 migrate_send_rp_message(mis
, MIG_RP_MSG_RECV_BITMAP
, len
+ 1, buf
);
1001 * Next, we dump the received bitmap to the stream.
1003 * TODO: currently we are safe since we are the only one that is
1004 * using the to_src_file handle (fault thread is still paused),
1005 * and it's ok even not taking the mutex. However the best way is
1006 * to take the lock before sending the message header, and release
1007 * the lock after sending the bitmap.
1009 qemu_mutex_lock(&mis
->rp_mutex
);
1010 res
= ramblock_recv_bitmap_send(mis
->to_src_file
, block_name
);
1011 qemu_mutex_unlock(&mis
->rp_mutex
);
1013 trace_migrate_send_rp_recv_bitmap(block_name
, res
);
1016 void migrate_send_rp_resume_ack(MigrationIncomingState
*mis
, uint32_t value
)
1020 buf
= cpu_to_be32(value
);
1021 migrate_send_rp_message(mis
, MIG_RP_MSG_RESUME_ACK
, sizeof(buf
), &buf
);
1025 * Return true if we're already in the middle of a migration
1026 * (i.e. any of the active or setup states)
1028 bool migration_is_setup_or_active(int state
)
1031 case MIGRATION_STATUS_ACTIVE
:
1032 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1033 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1034 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1035 case MIGRATION_STATUS_SETUP
:
1036 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1037 case MIGRATION_STATUS_DEVICE
:
1038 case MIGRATION_STATUS_WAIT_UNPLUG
:
1039 case MIGRATION_STATUS_COLO
:
1048 bool migration_is_running(int state
)
1051 case MIGRATION_STATUS_ACTIVE
:
1052 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1053 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1054 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1055 case MIGRATION_STATUS_SETUP
:
1056 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1057 case MIGRATION_STATUS_DEVICE
:
1058 case MIGRATION_STATUS_WAIT_UNPLUG
:
1059 case MIGRATION_STATUS_CANCELLING
:
1068 static bool migrate_show_downtime(MigrationState
*s
)
1070 return (s
->state
== MIGRATION_STATUS_COMPLETED
) || migration_in_postcopy();
1073 static void populate_time_info(MigrationInfo
*info
, MigrationState
*s
)
1075 info
->has_status
= true;
1076 info
->has_setup_time
= true;
1077 info
->setup_time
= s
->setup_time
;
1079 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1080 info
->has_total_time
= true;
1081 info
->total_time
= s
->total_time
;
1083 info
->has_total_time
= true;
1084 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) -
1088 if (migrate_show_downtime(s
)) {
1089 info
->has_downtime
= true;
1090 info
->downtime
= s
->downtime
;
1092 info
->has_expected_downtime
= true;
1093 info
->expected_downtime
= s
->expected_downtime
;
1097 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
1099 size_t page_size
= qemu_target_page_size();
1101 info
->ram
= g_malloc0(sizeof(*info
->ram
));
1102 info
->ram
->transferred
= migration_transferred_bytes();
1103 info
->ram
->total
= ram_bytes_total();
1104 info
->ram
->duplicate
= stat64_get(&mig_stats
.zero_pages
);
1105 /* legacy value. It is not used anymore */
1106 info
->ram
->skipped
= 0;
1107 info
->ram
->normal
= stat64_get(&mig_stats
.normal_pages
);
1108 info
->ram
->normal_bytes
= info
->ram
->normal
* page_size
;
1109 info
->ram
->mbps
= s
->mbps
;
1110 info
->ram
->dirty_sync_count
=
1111 stat64_get(&mig_stats
.dirty_sync_count
);
1112 info
->ram
->dirty_sync_missed_zero_copy
=
1113 stat64_get(&mig_stats
.dirty_sync_missed_zero_copy
);
1114 info
->ram
->postcopy_requests
=
1115 stat64_get(&mig_stats
.postcopy_requests
);
1116 info
->ram
->page_size
= page_size
;
1117 info
->ram
->multifd_bytes
= stat64_get(&mig_stats
.multifd_bytes
);
1118 info
->ram
->pages_per_second
= s
->pages_per_second
;
1119 info
->ram
->precopy_bytes
= stat64_get(&mig_stats
.precopy_bytes
);
1120 info
->ram
->downtime_bytes
= stat64_get(&mig_stats
.downtime_bytes
);
1121 info
->ram
->postcopy_bytes
= stat64_get(&mig_stats
.postcopy_bytes
);
1123 if (migrate_xbzrle()) {
1124 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
1125 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
1126 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
1127 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
1128 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
1129 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
1130 info
->xbzrle_cache
->encoding_rate
= xbzrle_counters
.encoding_rate
;
1131 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
1134 populate_compress(info
);
1136 if (cpu_throttle_active()) {
1137 info
->has_cpu_throttle_percentage
= true;
1138 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
1141 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
1142 info
->ram
->remaining
= ram_bytes_remaining();
1143 info
->ram
->dirty_pages_rate
=
1144 stat64_get(&mig_stats
.dirty_pages_rate
);
1147 if (migrate_dirty_limit() && dirtylimit_in_service()) {
1148 info
->has_dirty_limit_throttle_time_per_round
= true;
1149 info
->dirty_limit_throttle_time_per_round
=
1150 dirtylimit_throttle_time_per_round();
1152 info
->has_dirty_limit_ring_full_time
= true;
1153 info
->dirty_limit_ring_full_time
= dirtylimit_ring_full_time();
1157 static void populate_disk_info(MigrationInfo
*info
)
1159 if (blk_mig_active()) {
1160 info
->disk
= g_malloc0(sizeof(*info
->disk
));
1161 info
->disk
->transferred
= blk_mig_bytes_transferred();
1162 info
->disk
->remaining
= blk_mig_bytes_remaining();
1163 info
->disk
->total
= blk_mig_bytes_total();
1167 static void fill_source_migration_info(MigrationInfo
*info
)
1169 MigrationState
*s
= migrate_get_current();
1170 int state
= qatomic_read(&s
->state
);
1171 GSList
*cur_blocker
= migration_blockers
[migrate_mode()];
1173 info
->blocked_reasons
= NULL
;
1176 * There are two types of reasons a migration might be blocked;
1177 * a) devices marked in VMState as non-migratable, and
1178 * b) Explicit migration blockers
1179 * We need to add both of them here.
1181 qemu_savevm_non_migratable_list(&info
->blocked_reasons
);
1183 while (cur_blocker
) {
1184 QAPI_LIST_PREPEND(info
->blocked_reasons
,
1185 g_strdup(error_get_pretty(cur_blocker
->data
)));
1186 cur_blocker
= g_slist_next(cur_blocker
);
1188 info
->has_blocked_reasons
= info
->blocked_reasons
!= NULL
;
1191 case MIGRATION_STATUS_NONE
:
1192 /* no migration has happened ever */
1193 /* do not overwrite destination migration status */
1195 case MIGRATION_STATUS_SETUP
:
1196 info
->has_status
= true;
1197 info
->has_total_time
= false;
1199 case MIGRATION_STATUS_ACTIVE
:
1200 case MIGRATION_STATUS_CANCELLING
:
1201 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1202 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1203 case MIGRATION_STATUS_DEVICE
:
1204 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1205 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1206 /* TODO add some postcopy stats */
1207 populate_time_info(info
, s
);
1208 populate_ram_info(info
, s
);
1209 populate_disk_info(info
);
1210 migration_populate_vfio_info(info
);
1212 case MIGRATION_STATUS_COLO
:
1213 info
->has_status
= true;
1214 /* TODO: display COLO specific information (checkpoint info etc.) */
1216 case MIGRATION_STATUS_COMPLETED
:
1217 populate_time_info(info
, s
);
1218 populate_ram_info(info
, s
);
1219 migration_populate_vfio_info(info
);
1221 case MIGRATION_STATUS_FAILED
:
1222 info
->has_status
= true;
1224 case MIGRATION_STATUS_CANCELLED
:
1225 info
->has_status
= true;
1227 case MIGRATION_STATUS_WAIT_UNPLUG
:
1228 info
->has_status
= true;
1231 info
->status
= state
;
1233 QEMU_LOCK_GUARD(&s
->error_mutex
);
1235 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
1239 static void fill_destination_migration_info(MigrationInfo
*info
)
1241 MigrationIncomingState
*mis
= migration_incoming_get_current();
1243 if (mis
->socket_address_list
) {
1244 info
->has_socket_address
= true;
1245 info
->socket_address
=
1246 QAPI_CLONE(SocketAddressList
, mis
->socket_address_list
);
1249 switch (mis
->state
) {
1250 case MIGRATION_STATUS_NONE
:
1252 case MIGRATION_STATUS_SETUP
:
1253 case MIGRATION_STATUS_CANCELLING
:
1254 case MIGRATION_STATUS_CANCELLED
:
1255 case MIGRATION_STATUS_ACTIVE
:
1256 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1257 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1258 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1259 case MIGRATION_STATUS_FAILED
:
1260 case MIGRATION_STATUS_COLO
:
1261 info
->has_status
= true;
1263 case MIGRATION_STATUS_COMPLETED
:
1264 info
->has_status
= true;
1265 fill_destination_postcopy_migration_info(info
);
1268 info
->status
= mis
->state
;
1271 MigrationInfo
*qmp_query_migrate(Error
**errp
)
1273 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
1275 fill_destination_migration_info(info
);
1276 fill_source_migration_info(info
);
1281 void qmp_migrate_start_postcopy(Error
**errp
)
1283 MigrationState
*s
= migrate_get_current();
1285 if (!migrate_postcopy()) {
1286 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1287 " the start of migration");
1291 if (s
->state
== MIGRATION_STATUS_NONE
) {
1292 error_setg(errp
, "Postcopy must be started after migration has been"
1297 * we don't error if migration has finished since that would be racy
1298 * with issuing this command.
1300 qatomic_set(&s
->start_postcopy
, true);
1303 /* shared migration helpers */
1305 void migrate_set_state(int *state
, int old_state
, int new_state
)
1307 assert(new_state
< MIGRATION_STATUS__MAX
);
1308 if (qatomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1309 trace_migrate_set_state(MigrationStatus_str(new_state
));
1310 migrate_generate_event(new_state
);
1314 static void migrate_fd_cleanup(MigrationState
*s
)
1316 g_free(s
->hostname
);
1318 json_writer_free(s
->vmdesc
);
1321 qemu_savevm_state_cleanup();
1323 if (s
->to_dst_file
) {
1326 trace_migrate_fd_cleanup();
1328 if (s
->migration_thread_running
) {
1329 qemu_thread_join(&s
->thread
);
1330 s
->migration_thread_running
= false;
1334 multifd_save_cleanup();
1335 qemu_mutex_lock(&s
->qemu_file_lock
);
1336 tmp
= s
->to_dst_file
;
1337 s
->to_dst_file
= NULL
;
1338 qemu_mutex_unlock(&s
->qemu_file_lock
);
1340 * Close the file handle without the lock to make sure the
1341 * critical section won't block for long.
1343 migration_ioc_unregister_yank_from_file(tmp
);
1348 * We already cleaned up to_dst_file, so errors from the return
1349 * path might be due to that, ignore them.
1351 close_return_path_on_source(s
);
1353 assert(!migration_is_active(s
));
1355 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1356 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1357 MIGRATION_STATUS_CANCELLED
);
1361 /* It is used on info migrate. We can't free it */
1362 error_report_err(error_copy(s
->error
));
1364 migration_call_notifiers(s
);
1365 block_cleanup_parameters();
1366 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1369 static void migrate_fd_cleanup_bh(void *opaque
)
1371 migrate_fd_cleanup(opaque
);
1374 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1376 QEMU_LOCK_GUARD(&s
->error_mutex
);
1378 s
->error
= error_copy(error
);
1382 bool migrate_has_error(MigrationState
*s
)
1384 /* The lock is not helpful here, but still follow the rule */
1385 QEMU_LOCK_GUARD(&s
->error_mutex
);
1386 return qatomic_read(&s
->error
);
1389 static void migrate_error_free(MigrationState
*s
)
1391 QEMU_LOCK_GUARD(&s
->error_mutex
);
1393 error_free(s
->error
);
1398 static void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1400 trace_migrate_fd_error(error_get_pretty(error
));
1401 assert(s
->to_dst_file
== NULL
);
1402 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1403 MIGRATION_STATUS_FAILED
);
1404 migrate_set_error(s
, error
);
1407 static void migrate_fd_cancel(MigrationState
*s
)
1411 trace_migrate_fd_cancel();
1413 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1414 if (s
->rp_state
.from_dst_file
) {
1415 /* shutdown the rp socket, so causing the rp thread to shutdown */
1416 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1421 old_state
= s
->state
;
1422 if (!migration_is_running(old_state
)) {
1425 /* If the migration is paused, kick it out of the pause */
1426 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1427 qemu_sem_post(&s
->pause_sem
);
1429 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1430 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1433 * If we're unlucky the migration code might be stuck somewhere in a
1434 * send/write while the network has failed and is waiting to timeout;
1435 * if we've got shutdown(2) available then we can force it to quit.
1437 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1438 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1439 if (s
->to_dst_file
) {
1440 qemu_file_shutdown(s
->to_dst_file
);
1444 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1445 Error
*local_err
= NULL
;
1447 bdrv_activate_all(&local_err
);
1449 error_report_err(local_err
);
1451 s
->block_inactive
= false;
1456 void migration_add_notifier(Notifier
*notify
,
1457 void (*func
)(Notifier
*notifier
, void *data
))
1459 notify
->notify
= func
;
1460 notifier_list_add(&migration_state_notifiers
, notify
);
1463 void migration_remove_notifier(Notifier
*notify
)
1465 if (notify
->notify
) {
1466 notifier_remove(notify
);
1467 notify
->notify
= NULL
;
1471 void migration_call_notifiers(MigrationState
*s
)
1473 notifier_list_notify(&migration_state_notifiers
, s
);
1476 bool migration_in_setup(MigrationState
*s
)
1478 return s
->state
== MIGRATION_STATUS_SETUP
;
1481 bool migration_has_finished(MigrationState
*s
)
1483 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1486 bool migration_has_failed(MigrationState
*s
)
1488 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1489 s
->state
== MIGRATION_STATUS_FAILED
);
1492 bool migration_in_postcopy(void)
1494 MigrationState
*s
= migrate_get_current();
1497 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1498 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1499 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1506 bool migration_postcopy_is_alive(int state
)
1509 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1510 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1517 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1519 return migration_in_postcopy() && s
->postcopy_after_devices
;
1522 bool migration_in_incoming_postcopy(void)
1524 PostcopyState ps
= postcopy_state_get();
1526 return ps
>= POSTCOPY_INCOMING_DISCARD
&& ps
< POSTCOPY_INCOMING_END
;
1529 bool migration_incoming_postcopy_advised(void)
1531 PostcopyState ps
= postcopy_state_get();
1533 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
1536 bool migration_in_bg_snapshot(void)
1538 MigrationState
*s
= migrate_get_current();
1540 return migrate_background_snapshot() &&
1541 migration_is_setup_or_active(s
->state
);
1544 bool migration_is_idle(void)
1546 MigrationState
*s
= current_migration
;
1553 case MIGRATION_STATUS_NONE
:
1554 case MIGRATION_STATUS_CANCELLED
:
1555 case MIGRATION_STATUS_COMPLETED
:
1556 case MIGRATION_STATUS_FAILED
:
1558 case MIGRATION_STATUS_SETUP
:
1559 case MIGRATION_STATUS_CANCELLING
:
1560 case MIGRATION_STATUS_ACTIVE
:
1561 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1562 case MIGRATION_STATUS_COLO
:
1563 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1564 case MIGRATION_STATUS_DEVICE
:
1565 case MIGRATION_STATUS_WAIT_UNPLUG
:
1567 case MIGRATION_STATUS__MAX
:
1568 g_assert_not_reached();
1574 bool migration_is_active(MigrationState
*s
)
1576 return (s
->state
== MIGRATION_STATUS_ACTIVE
||
1577 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1580 int migrate_init(MigrationState
*s
, Error
**errp
)
1584 ret
= qemu_savevm_state_prepare(errp
);
1590 * Reinitialise all migration state, except
1591 * parameters/capabilities that the user set, and
1594 s
->to_dst_file
= NULL
;
1595 s
->state
= MIGRATION_STATUS_NONE
;
1596 s
->rp_state
.from_dst_file
= NULL
;
1598 s
->pages_per_second
= 0.0;
1600 s
->expected_downtime
= 0;
1602 s
->start_postcopy
= false;
1603 s
->postcopy_after_devices
= false;
1604 s
->migration_thread_running
= false;
1605 error_free(s
->error
);
1609 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1611 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1613 s
->vm_old_state
= -1;
1614 s
->iteration_initial_bytes
= 0;
1615 s
->threshold_size
= 0;
1616 s
->switchover_acked
= false;
1617 s
->rdma_migration
= false;
1619 * set mig_stats memory to zero for a new migration
1621 memset(&mig_stats
, 0, sizeof(mig_stats
));
1622 migration_reset_vfio_bytes_transferred();
1627 static bool is_busy(Error
**reasonp
, Error
**errp
)
1631 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1632 if (runstate_check(RUN_STATE_SAVE_VM
) || !migration_is_idle()) {
1633 error_propagate_prepend(errp
, *reasonp
,
1634 "disallowing migration blocker "
1635 "(migration/snapshot in progress) for: ");
1642 static bool is_only_migratable(Error
**reasonp
, Error
**errp
, int modes
)
1646 if (only_migratable
&& (modes
& BIT(MIG_MODE_NORMAL
))) {
1647 error_propagate_prepend(errp
, *reasonp
,
1648 "disallowing migration blocker "
1649 "(--only-migratable) for: ");
1656 static int get_modes(MigMode mode
, va_list ap
)
1660 while (mode
!= -1 && mode
!= MIG_MODE_ALL
) {
1661 assert(mode
>= MIG_MODE_NORMAL
&& mode
< MIG_MODE__MAX
);
1663 mode
= va_arg(ap
, MigMode
);
1665 if (mode
== MIG_MODE_ALL
) {
1666 modes
= BIT(MIG_MODE__MAX
) - 1;
1671 static int add_blockers(Error
**reasonp
, Error
**errp
, int modes
)
1673 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1674 if (modes
& BIT(mode
)) {
1675 migration_blockers
[mode
] = g_slist_prepend(migration_blockers
[mode
],
1682 int migrate_add_blocker(Error
**reasonp
, Error
**errp
)
1684 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_ALL
);
1687 int migrate_add_blocker_normal(Error
**reasonp
, Error
**errp
)
1689 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_NORMAL
, -1);
1692 int migrate_add_blocker_modes(Error
**reasonp
, Error
**errp
, MigMode mode
, ...)
1698 modes
= get_modes(mode
, ap
);
1701 if (is_only_migratable(reasonp
, errp
, modes
)) {
1703 } else if (is_busy(reasonp
, errp
)) {
1706 return add_blockers(reasonp
, errp
, modes
);
1709 int migrate_add_blocker_internal(Error
**reasonp
, Error
**errp
)
1711 int modes
= BIT(MIG_MODE__MAX
) - 1;
1713 if (is_busy(reasonp
, errp
)) {
1716 return add_blockers(reasonp
, errp
, modes
);
1719 void migrate_del_blocker(Error
**reasonp
)
1722 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1723 migration_blockers
[mode
] = g_slist_remove(migration_blockers
[mode
],
1726 error_free(*reasonp
);
1731 void qmp_migrate_incoming(const char *uri
, bool has_channels
,
1732 MigrationChannelList
*channels
, Error
**errp
)
1734 Error
*local_err
= NULL
;
1735 static bool once
= true;
1738 error_setg(errp
, "The incoming migration has already been started");
1741 if (!runstate_check(RUN_STATE_INMIGRATE
)) {
1742 error_setg(errp
, "'-incoming' was not specified on the command line");
1746 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1750 qemu_start_incoming_migration(uri
, has_channels
, channels
, &local_err
);
1753 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1754 error_propagate(errp
, local_err
);
1761 void qmp_migrate_recover(const char *uri
, Error
**errp
)
1763 MigrationIncomingState
*mis
= migration_incoming_get_current();
1766 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1767 * callers (no one should ignore a recover failure); if there is, it's a
1768 * programming error.
1772 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1773 error_setg(errp
, "Migrate recover can only be run "
1774 "when postcopy is paused.");
1778 /* If there's an existing transport, release it */
1779 migration_incoming_transport_cleanup(mis
);
1782 * Note that this call will never start a real migration; it will
1783 * only re-setup the migration stream and poke existing migration
1784 * to continue using that newly established channel.
1786 qemu_start_incoming_migration(uri
, false, NULL
, errp
);
1789 void qmp_migrate_pause(Error
**errp
)
1791 MigrationState
*ms
= migrate_get_current();
1792 MigrationIncomingState
*mis
= migration_incoming_get_current();
1795 if (migration_postcopy_is_alive(ms
->state
)) {
1796 /* Source side, during postcopy */
1797 Error
*error
= NULL
;
1799 /* Tell the core migration that we're pausing */
1800 error_setg(&error
, "Postcopy migration is paused by the user");
1801 migrate_set_error(ms
, error
);
1804 qemu_mutex_lock(&ms
->qemu_file_lock
);
1805 if (ms
->to_dst_file
) {
1806 ret
= qemu_file_shutdown(ms
->to_dst_file
);
1808 qemu_mutex_unlock(&ms
->qemu_file_lock
);
1810 error_setg(errp
, "Failed to pause source migration");
1814 * Kick the migration thread out of any waiting windows (on behalf
1815 * of the rp thread).
1817 migration_rp_kick(ms
);
1822 if (migration_postcopy_is_alive(mis
->state
)) {
1823 ret
= qemu_file_shutdown(mis
->from_src_file
);
1825 error_setg(errp
, "Failed to pause destination migration");
1830 error_setg(errp
, "migrate-pause is currently only supported "
1831 "during postcopy-active or postcopy-recover state");
1834 bool migration_is_blocked(Error
**errp
)
1836 GSList
*blockers
= migration_blockers
[migrate_mode()];
1838 if (qemu_savevm_state_blocked(errp
)) {
1843 error_propagate(errp
, error_copy(blockers
->data
));
1850 /* Returns true if continue to migrate, or false if error detected */
1851 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1852 bool resume
, Error
**errp
)
1855 warn_report("parameter 'inc' is deprecated;"
1856 " use blockdev-mirror with NBD instead");
1860 warn_report("parameter 'blk' is deprecated;"
1861 " use blockdev-mirror with NBD instead");
1865 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1866 error_setg(errp
, "Cannot resume if there is no "
1867 "paused migration");
1872 * Postcopy recovery won't work well with release-ram
1873 * capability since release-ram will drop the page buffer as
1874 * long as the page is put into the send buffer. So if there
1875 * is a network failure happened, any page buffers that have
1876 * not yet reached the destination VM but have already been
1877 * sent from the source VM will be lost forever. Let's refuse
1878 * the client from resuming such a postcopy migration.
1879 * Luckily release-ram was designed to only be used when src
1880 * and destination VMs are on the same host, so it should be
1883 if (migrate_release_ram()) {
1884 error_setg(errp
, "Postcopy recovery cannot work "
1885 "when release-ram capability is set");
1889 /* This is a resume, skip init status */
1893 if (migration_is_running(s
->state
)) {
1894 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1898 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1899 error_setg(errp
, "Guest is waiting for an incoming migration");
1903 if (runstate_check(RUN_STATE_POSTMIGRATE
)) {
1904 error_setg(errp
, "Can't migrate the vm that was paused due to "
1905 "previous migration");
1909 if (migration_is_blocked(errp
)) {
1913 if (blk
|| blk_inc
) {
1914 if (migrate_colo()) {
1915 error_setg(errp
, "No disk migration is required in COLO mode");
1918 if (migrate_block() || migrate_block_incremental()) {
1919 error_setg(errp
, "Command options are incompatible with "
1920 "current migration capabilities");
1923 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK
, true, errp
)) {
1926 s
->must_remove_block_options
= true;
1930 migrate_set_block_incremental(true);
1933 if (migrate_init(s
, errp
)) {
1940 void qmp_migrate(const char *uri
, bool has_channels
,
1941 MigrationChannelList
*channels
, bool has_blk
, bool blk
,
1942 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1943 bool has_resume
, bool resume
, Error
**errp
)
1945 bool resume_requested
;
1946 Error
*local_err
= NULL
;
1947 MigrationState
*s
= migrate_get_current();
1948 g_autoptr(MigrationChannel
) channel
= NULL
;
1949 MigrationAddress
*addr
= NULL
;
1952 * Having preliminary checks for uri and channel
1954 if (!uri
== !channels
) {
1955 error_setg(errp
, "need either 'uri' or 'channels' argument");
1960 /* To verify that Migrate channel list has only item */
1961 if (channels
->next
) {
1962 error_setg(errp
, "Channel list has more than one entries");
1965 addr
= channels
->value
->addr
;
1969 /* caller uses the old URI syntax */
1970 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
1973 addr
= channel
->addr
;
1976 /* transport mechanism not suitable for migration? */
1977 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
1981 resume_requested
= has_resume
&& resume
;
1982 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
1983 resume_requested
, errp
)) {
1984 /* Error detected, put into errp */
1988 if (!resume_requested
) {
1989 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1994 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
1995 SocketAddress
*saddr
= &addr
->u
.socket
;
1996 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
1997 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
1998 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
1999 socket_start_outgoing_migration(s
, saddr
, &local_err
);
2000 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
2001 fd_start_outgoing_migration(s
, saddr
->u
.fd
.str
, &local_err
);
2004 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
2005 rdma_start_outgoing_migration(s
, &addr
->u
.rdma
, &local_err
);
2007 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
2008 exec_start_outgoing_migration(s
, addr
->u
.exec
.args
, &local_err
);
2009 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
2010 file_start_outgoing_migration(s
, &addr
->u
.file
, &local_err
);
2012 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "uri",
2013 "a valid migration protocol");
2014 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2015 MIGRATION_STATUS_FAILED
);
2016 block_cleanup_parameters();
2020 if (!resume_requested
) {
2021 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
2023 migrate_fd_error(s
, local_err
);
2024 error_propagate(errp
, local_err
);
2029 void qmp_migrate_cancel(Error
**errp
)
2031 migration_cancel(NULL
);
2034 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
2036 MigrationState
*s
= migrate_get_current();
2037 if (s
->state
!= state
) {
2038 error_setg(errp
, "Migration not in expected state: %s",
2039 MigrationStatus_str(s
->state
));
2042 qemu_sem_post(&s
->pause_sem
);
2045 int migration_rp_wait(MigrationState
*s
)
2047 /* If migration has failure already, ignore the wait */
2048 if (migrate_has_error(s
)) {
2052 qemu_sem_wait(&s
->rp_state
.rp_sem
);
2054 /* After wait, double check that there's no failure */
2055 if (migrate_has_error(s
)) {
2062 void migration_rp_kick(MigrationState
*s
)
2064 qemu_sem_post(&s
->rp_state
.rp_sem
);
2067 static struct rp_cmd_args
{
2068 ssize_t len
; /* -1 = variable */
2071 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
2072 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
2073 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
2074 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
2075 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
2076 [MIG_RP_MSG_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
2077 [MIG_RP_MSG_RESUME_ACK
] = { .len
= 4, .name
= "RESUME_ACK" },
2078 [MIG_RP_MSG_SWITCHOVER_ACK
] = { .len
= 0, .name
= "SWITCHOVER_ACK" },
2079 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
2083 * Process a request for pages received on the return path,
2084 * We're allowed to send more than requested (e.g. to round to our page size)
2085 * and we don't need to send pages that have already been sent.
2088 migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
2089 ram_addr_t start
, size_t len
, Error
**errp
)
2091 long our_host_ps
= qemu_real_host_page_size();
2093 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
2096 * Since we currently insist on matching page sizes, just sanity check
2097 * we're being asked for whole host pages.
2099 if (!QEMU_IS_ALIGNED(start
, our_host_ps
) ||
2100 !QEMU_IS_ALIGNED(len
, our_host_ps
)) {
2101 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
2102 RAM_ADDR_FMT
" len: %zd", start
, len
);
2106 ram_save_queue_pages(rbname
, start
, len
, errp
);
2109 static bool migrate_handle_rp_recv_bitmap(MigrationState
*s
, char *block_name
,
2112 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
2115 error_setg(errp
, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
2120 /* Fetch the received bitmap and refresh the dirty bitmap */
2121 return ram_dirty_bitmap_reload(s
, block
, errp
);
2124 static bool migrate_handle_rp_resume_ack(MigrationState
*s
,
2125 uint32_t value
, Error
**errp
)
2127 trace_source_return_path_thread_resume_ack(value
);
2129 if (value
!= MIGRATION_RESUME_ACK_VALUE
) {
2130 error_setg(errp
, "illegal resume_ack value %"PRIu32
, value
);
2134 /* Now both sides are active. */
2135 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
2136 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2138 /* Notify send thread that time to continue send pages */
2139 migration_rp_kick(s
);
2145 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2146 * existed) in a safe way.
2148 static void migration_release_dst_files(MigrationState
*ms
)
2152 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2154 * Reset the from_dst_file pointer first before releasing it, as we
2155 * can't block within lock section
2157 file
= ms
->rp_state
.from_dst_file
;
2158 ms
->rp_state
.from_dst_file
= NULL
;
2162 * Do the same to postcopy fast path socket too if there is. No
2163 * locking needed because this qemufile should only be managed by
2164 * return path thread.
2166 if (ms
->postcopy_qemufile_src
) {
2167 migration_ioc_unregister_yank_from_file(ms
->postcopy_qemufile_src
);
2168 qemu_file_shutdown(ms
->postcopy_qemufile_src
);
2169 qemu_fclose(ms
->postcopy_qemufile_src
);
2170 ms
->postcopy_qemufile_src
= NULL
;
2177 * Handles messages sent on the return path towards the source VM
2180 static void *source_return_path_thread(void *opaque
)
2182 MigrationState
*ms
= opaque
;
2183 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
2184 uint16_t header_len
, header_type
;
2186 uint32_t tmp32
, sibling_error
;
2187 ram_addr_t start
= 0; /* =0 to silence warning */
2188 size_t len
= 0, expected_len
;
2192 trace_source_return_path_thread_entry();
2193 rcu_register_thread();
2195 while (migration_is_setup_or_active(ms
->state
)) {
2196 trace_source_return_path_thread_loop_top();
2198 header_type
= qemu_get_be16(rp
);
2199 header_len
= qemu_get_be16(rp
);
2201 if (qemu_file_get_error(rp
)) {
2202 qemu_file_get_error_obj(rp
, &err
);
2206 if (header_type
>= MIG_RP_MSG_MAX
||
2207 header_type
== MIG_RP_MSG_INVALID
) {
2208 error_setg(&err
, "Received invalid message 0x%04x length 0x%04x",
2209 header_type
, header_len
);
2213 if ((rp_cmd_args
[header_type
].len
!= -1 &&
2214 header_len
!= rp_cmd_args
[header_type
].len
) ||
2215 header_len
> sizeof(buf
)) {
2216 error_setg(&err
, "Received '%s' message (0x%04x) with"
2217 "incorrect length %d expecting %zu",
2218 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
2219 (size_t)rp_cmd_args
[header_type
].len
);
2223 /* We know we've got a valid header by this point */
2224 res
= qemu_get_buffer(rp
, buf
, header_len
);
2225 if (res
!= header_len
) {
2226 error_setg(&err
, "Failed reading data for message 0x%04x"
2227 " read %d expected %d",
2228 header_type
, res
, header_len
);
2232 /* OK, we have the message and the data */
2233 switch (header_type
) {
2234 case MIG_RP_MSG_SHUT
:
2235 sibling_error
= ldl_be_p(buf
);
2236 trace_source_return_path_thread_shut(sibling_error
);
2237 if (sibling_error
) {
2238 error_setg(&err
, "Sibling indicated error %d", sibling_error
);
2241 * We'll let the main thread deal with closing the RP
2242 * we could do a shutdown(2) on it, but we're the only user
2243 * anyway, so there's nothing gained.
2247 case MIG_RP_MSG_PONG
:
2248 tmp32
= ldl_be_p(buf
);
2249 trace_source_return_path_thread_pong(tmp32
);
2250 qemu_sem_post(&ms
->rp_state
.rp_pong_acks
);
2253 case MIG_RP_MSG_REQ_PAGES
:
2254 start
= ldq_be_p(buf
);
2255 len
= ldl_be_p(buf
+ 8);
2256 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
, &err
);
2262 case MIG_RP_MSG_REQ_PAGES_ID
:
2263 expected_len
= 12 + 1; /* header + termination */
2265 if (header_len
>= expected_len
) {
2266 start
= ldq_be_p(buf
);
2267 len
= ldl_be_p(buf
+ 8);
2268 /* Now we expect an idstr */
2269 tmp32
= buf
[12]; /* Length of the following idstr */
2270 buf
[13 + tmp32
] = '\0';
2271 expected_len
+= tmp32
;
2273 if (header_len
!= expected_len
) {
2274 error_setg(&err
, "Req_Page_id with length %d expecting %zd",
2275 header_len
, expected_len
);
2278 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
,
2285 case MIG_RP_MSG_RECV_BITMAP
:
2286 if (header_len
< 1) {
2287 error_setg(&err
, "MIG_RP_MSG_RECV_BITMAP missing block name");
2290 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2291 buf
[buf
[0] + 1] = '\0';
2292 if (!migrate_handle_rp_recv_bitmap(ms
, (char *)(buf
+ 1), &err
)) {
2297 case MIG_RP_MSG_RESUME_ACK
:
2298 tmp32
= ldl_be_p(buf
);
2299 if (!migrate_handle_rp_resume_ack(ms
, tmp32
, &err
)) {
2304 case MIG_RP_MSG_SWITCHOVER_ACK
:
2305 ms
->switchover_acked
= true;
2306 trace_source_return_path_thread_switchover_acked();
2316 migrate_set_error(ms
, err
);
2318 trace_source_return_path_thread_bad_end();
2321 if (ms
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2323 * this will be extremely unlikely: that we got yet another network
2324 * issue during recovering of the 1st network failure.. during this
2325 * period the main migration thread can be waiting on rp_sem for
2326 * this thread to sync with the other side.
2328 * When this happens, explicitly kick the migration thread out of
2329 * RECOVER stage and back to PAUSED, so the admin can try
2332 migration_rp_kick(ms
);
2335 trace_source_return_path_thread_end();
2336 rcu_unregister_thread();
2341 static int open_return_path_on_source(MigrationState
*ms
)
2343 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
2344 if (!ms
->rp_state
.from_dst_file
) {
2348 trace_open_return_path_on_source();
2350 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2351 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2352 ms
->rp_state
.rp_thread_created
= true;
2354 trace_open_return_path_on_source_continue();
2359 /* Return true if error detected, or false otherwise */
2360 static bool close_return_path_on_source(MigrationState
*ms
)
2362 if (!ms
->rp_state
.rp_thread_created
) {
2366 trace_migration_return_path_end_before();
2369 * If this is a normal exit then the destination will send a SHUT
2370 * and the rp_thread will exit, however if there's an error we
2371 * need to cause it to exit. shutdown(2), if we have it, will
2372 * cause it to unblock if it's stuck waiting for the destination.
2374 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2375 if (ms
->to_dst_file
&& ms
->rp_state
.from_dst_file
&&
2376 qemu_file_get_error(ms
->to_dst_file
)) {
2377 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2381 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2382 ms
->rp_state
.rp_thread_created
= false;
2383 migration_release_dst_files(ms
);
2384 trace_migration_return_path_end_after();
2386 /* Return path will persist the error in MigrationState when quit */
2387 return migrate_has_error(ms
);
2391 migration_wait_main_channel(MigrationState
*ms
)
2393 /* Wait until one PONG message received */
2394 qemu_sem_wait(&ms
->rp_state
.rp_pong_acks
);
2398 * Switch from normal iteration to postcopy
2399 * Returns non-0 on error
2401 static int postcopy_start(MigrationState
*ms
, Error
**errp
)
2404 QIOChannelBuffer
*bioc
;
2406 uint64_t bandwidth
= migrate_max_postcopy_bandwidth();
2407 bool restart_block
= false;
2408 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2410 if (migrate_postcopy_preempt()) {
2411 migration_wait_main_channel(ms
);
2412 if (postcopy_preempt_establish_channel(ms
)) {
2413 migrate_set_state(&ms
->state
, ms
->state
, MIGRATION_STATUS_FAILED
);
2418 if (!migrate_pause_before_switchover()) {
2419 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2420 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2423 trace_postcopy_start();
2425 trace_postcopy_start_set_run();
2427 migration_downtime_start(ms
);
2429 global_state_store();
2430 ret
= migration_stop_vm(RUN_STATE_FINISH_MIGRATE
);
2435 ret
= migration_maybe_pause(ms
, &cur_state
,
2436 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2441 ret
= bdrv_inactivate_all();
2445 restart_block
= true;
2448 * Cause any non-postcopiable, but iterative devices to
2449 * send out their final data.
2451 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2454 * in Finish migrate and with the io-lock held everything should
2455 * be quiet, but we've potentially still got dirty pages and we
2456 * need to tell the destination to throw any pages it's already received
2459 if (migrate_postcopy_ram()) {
2460 ram_postcopy_send_discard_bitmap(ms
);
2464 * send rest of state - note things that are doing postcopy
2465 * will notice we're in POSTCOPY_ACTIVE and not actually
2466 * wrap their state up here
2468 migration_rate_set(bandwidth
);
2469 if (migrate_postcopy_ram()) {
2470 /* Ping just for debugging, helps line traces up */
2471 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2475 * While loading the device state we may trigger page transfer
2476 * requests and the fd must be free to process those, and thus
2477 * the destination must read the whole device state off the fd before
2478 * it starts processing it. Unfortunately the ad-hoc migration format
2479 * doesn't allow the destination to know the size to read without fully
2480 * parsing it through each devices load-state code (especially the open
2481 * coded devices that use get/put).
2482 * So we wrap the device state up in a package with a length at the start;
2483 * to do this we use a qemu_buf to hold the whole of the device state.
2485 bioc
= qio_channel_buffer_new(4096);
2486 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2487 fb
= qemu_file_new_output(QIO_CHANNEL(bioc
));
2488 object_unref(OBJECT(bioc
));
2491 * Make sure the receiver can get incoming pages before we send the rest
2494 qemu_savevm_send_postcopy_listen(fb
);
2496 qemu_savevm_state_complete_precopy(fb
, false, false);
2497 if (migrate_postcopy_ram()) {
2498 qemu_savevm_send_ping(fb
, 3);
2501 qemu_savevm_send_postcopy_run(fb
);
2503 /* <><> end of stuff going into the package */
2505 /* Last point of recovery; as soon as we send the package the destination
2506 * can open devices and potentially start running.
2507 * Lets just check again we've not got any errors.
2509 ret
= qemu_file_get_error(ms
->to_dst_file
);
2511 error_setg(errp
, "postcopy_start: Migration stream errored (pre package)");
2515 restart_block
= false;
2517 /* Now send that blob */
2518 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2523 /* Send a notify to give a chance for anything that needs to happen
2524 * at the transition to postcopy and after the device state; in particular
2525 * spice needs to trigger a transition now
2527 ms
->postcopy_after_devices
= true;
2528 migration_call_notifiers(ms
);
2530 migration_downtime_end(ms
);
2534 if (migrate_postcopy_ram()) {
2536 * Although this ping is just for debug, it could potentially be
2537 * used for getting a better measurement of downtime at the source.
2539 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2542 if (migrate_release_ram()) {
2543 ram_postcopy_migrated_memory_release(ms
);
2546 ret
= qemu_file_get_error(ms
->to_dst_file
);
2548 error_setg(errp
, "postcopy_start: Migration stream errored");
2549 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2550 MIGRATION_STATUS_FAILED
);
2553 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2560 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2561 MIGRATION_STATUS_FAILED
);
2562 if (restart_block
) {
2563 /* A failure happened early enough that we know the destination hasn't
2564 * accessed block devices, so we're safe to recover.
2566 Error
*local_err
= NULL
;
2568 bdrv_activate_all(&local_err
);
2570 error_report_err(local_err
);
2578 * migration_maybe_pause: Pause if required to by
2579 * migrate_pause_before_switchover called with the BQL locked
2580 * Returns: 0 on success
2582 static int migration_maybe_pause(MigrationState
*s
,
2583 int *current_active_state
,
2586 if (!migrate_pause_before_switchover()) {
2590 /* Since leaving this state is not atomic with posting the semaphore
2591 * it's possible that someone could have issued multiple migrate_continue
2592 * and the semaphore is incorrectly positive at this point;
2593 * the docs say it's undefined to reinit a semaphore that's already
2594 * init'd, so use timedwait to eat up any existing posts.
2596 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2597 /* This block intentionally left blank */
2601 * If the migration is cancelled when it is in the completion phase,
2602 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2603 * So we don't need to wait a semaphore, otherwise we would always
2604 * wait for the 'pause_sem' semaphore.
2606 if (s
->state
!= MIGRATION_STATUS_CANCELLING
) {
2608 migrate_set_state(&s
->state
, *current_active_state
,
2609 MIGRATION_STATUS_PRE_SWITCHOVER
);
2610 qemu_sem_wait(&s
->pause_sem
);
2611 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2613 *current_active_state
= new_state
;
2617 return s
->state
== new_state
? 0 : -EINVAL
;
2620 static int migration_completion_precopy(MigrationState
*s
,
2621 int *current_active_state
)
2626 migration_downtime_start(s
);
2628 s
->vm_old_state
= runstate_get();
2629 global_state_store();
2631 ret
= migration_stop_vm(RUN_STATE_FINISH_MIGRATE
);
2632 trace_migration_completion_vm_stop(ret
);
2637 ret
= migration_maybe_pause(s
, current_active_state
,
2638 MIGRATION_STATUS_DEVICE
);
2644 * Inactivate disks except in COLO, and track that we have done so in order
2645 * to remember to reactivate them if migration fails or is cancelled.
2647 s
->block_inactive
= !migrate_colo();
2648 migration_rate_set(RATE_LIMIT_DISABLED
);
2649 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2656 static void migration_completion_postcopy(MigrationState
*s
)
2658 trace_migration_completion_postcopy_end();
2661 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2665 * Shutdown the postcopy fast path thread. This is only needed when dest
2666 * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
2668 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
2669 postcopy_preempt_shutdown_file(s
);
2672 trace_migration_completion_postcopy_end_after_complete();
2675 static void migration_completion_failed(MigrationState
*s
,
2676 int current_active_state
)
2678 if (s
->block_inactive
&& (s
->state
== MIGRATION_STATUS_ACTIVE
||
2679 s
->state
== MIGRATION_STATUS_DEVICE
)) {
2681 * If not doing postcopy, vm_start() will be called: let's
2682 * regain control on images.
2684 Error
*local_err
= NULL
;
2687 bdrv_activate_all(&local_err
);
2689 error_report_err(local_err
);
2691 s
->block_inactive
= false;
2696 migrate_set_state(&s
->state
, current_active_state
,
2697 MIGRATION_STATUS_FAILED
);
2701 * migration_completion: Used by migration_thread when there's not much left.
2702 * The caller 'breaks' the loop when this returns.
2704 * @s: Current migration state
2706 static void migration_completion(MigrationState
*s
)
2709 int current_active_state
= s
->state
;
2711 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2712 ret
= migration_completion_precopy(s
, ¤t_active_state
);
2713 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2714 migration_completion_postcopy(s
);
2723 if (close_return_path_on_source(s
)) {
2727 if (qemu_file_get_error(s
->to_dst_file
)) {
2728 trace_migration_completion_file_err();
2732 if (migrate_colo() && s
->state
== MIGRATION_STATUS_ACTIVE
) {
2733 /* COLO does not support postcopy */
2734 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
2735 MIGRATION_STATUS_COLO
);
2737 migrate_set_state(&s
->state
, current_active_state
,
2738 MIGRATION_STATUS_COMPLETED
);
2744 migration_completion_failed(s
, current_active_state
);
2748 * bg_migration_completion: Used by bg_migration_thread when after all the
2749 * RAM has been saved. The caller 'breaks' the loop when this returns.
2751 * @s: Current migration state
2753 static void bg_migration_completion(MigrationState
*s
)
2755 int current_active_state
= s
->state
;
2757 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2759 * By this moment we have RAM content saved into the migration stream.
2760 * The next step is to flush the non-RAM content (device state)
2761 * right after the ram content. The device state has been stored into
2762 * the temporary buffer before RAM saving started.
2764 qemu_put_buffer(s
->to_dst_file
, s
->bioc
->data
, s
->bioc
->usage
);
2765 qemu_fflush(s
->to_dst_file
);
2766 } else if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
2770 if (qemu_file_get_error(s
->to_dst_file
)) {
2771 trace_migration_completion_file_err();
2775 migrate_set_state(&s
->state
, current_active_state
,
2776 MIGRATION_STATUS_COMPLETED
);
2780 migrate_set_state(&s
->state
, current_active_state
,
2781 MIGRATION_STATUS_FAILED
);
2784 typedef enum MigThrError
{
2785 /* No error detected */
2786 MIG_THR_ERR_NONE
= 0,
2787 /* Detected error, but resumed successfully */
2788 MIG_THR_ERR_RECOVERED
= 1,
2789 /* Detected fatal error, need to exit */
2790 MIG_THR_ERR_FATAL
= 2,
2793 static int postcopy_resume_handshake(MigrationState
*s
)
2795 qemu_savevm_send_postcopy_resume(s
->to_dst_file
);
2797 while (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2798 if (migration_rp_wait(s
)) {
2803 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2810 /* Return zero if success, or <0 for error */
2811 static int postcopy_do_resume(MigrationState
*s
)
2816 * Call all the resume_prepare() hooks, so that modules can be
2817 * ready for the migration resume.
2819 ret
= qemu_savevm_state_resume_prepare(s
);
2821 error_report("%s: resume_prepare() failure detected: %d",
2827 * If preempt is enabled, re-establish the preempt channel. Note that
2828 * we do it after resume prepare to make sure the main channel will be
2829 * created before the preempt channel. E.g. with weak network, the
2830 * dest QEMU may get messed up with the preempt and main channels on
2831 * the order of connection setup. This guarantees the correct order.
2833 ret
= postcopy_preempt_establish_channel(s
);
2835 error_report("%s: postcopy_preempt_establish_channel(): %d",
2841 * Last handshake with destination on the resume (destination will
2842 * switch to postcopy-active afterwards)
2844 ret
= postcopy_resume_handshake(s
);
2846 error_report("%s: handshake failed: %d", __func__
, ret
);
2854 * We don't return until we are in a safe state to continue current
2855 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2856 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2858 static MigThrError
postcopy_pause(MigrationState
*s
)
2860 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2866 * Current channel is possibly broken. Release it. Note that this is
2867 * guaranteed even without lock because to_dst_file should only be
2868 * modified by the migration thread. That also guarantees that the
2869 * unregister of yank is safe too without the lock. It should be safe
2870 * even to be within the qemu_file_lock, but we didn't do that to avoid
2871 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2872 * the qemu_file_lock critical section as small as possible.
2874 assert(s
->to_dst_file
);
2875 migration_ioc_unregister_yank_from_file(s
->to_dst_file
);
2876 qemu_mutex_lock(&s
->qemu_file_lock
);
2877 file
= s
->to_dst_file
;
2878 s
->to_dst_file
= NULL
;
2879 qemu_mutex_unlock(&s
->qemu_file_lock
);
2881 qemu_file_shutdown(file
);
2885 * We're already pausing, so ignore any errors on the return
2886 * path and just wait for the thread to finish. It will be
2887 * re-created when we resume.
2889 close_return_path_on_source(s
);
2891 migrate_set_state(&s
->state
, s
->state
,
2892 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2894 error_report("Detected IO failure for postcopy. "
2895 "Migration paused.");
2898 * We wait until things fixed up. Then someone will setup the
2899 * status back for us.
2901 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2902 qemu_sem_wait(&s
->postcopy_pause_sem
);
2905 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2906 /* Woken up by a recover procedure. Give it a shot */
2908 /* Do the resume logic */
2909 if (postcopy_do_resume(s
) == 0) {
2910 /* Let's continue! */
2911 trace_postcopy_pause_continued();
2912 return MIG_THR_ERR_RECOVERED
;
2915 * Something wrong happened during the recovery, let's
2916 * pause again. Pause is always better than throwing
2922 /* This is not right... Time to quit. */
2923 return MIG_THR_ERR_FATAL
;
2928 static MigThrError
migration_detect_error(MigrationState
*s
)
2931 int state
= s
->state
;
2932 Error
*local_error
= NULL
;
2934 if (state
== MIGRATION_STATUS_CANCELLING
||
2935 state
== MIGRATION_STATUS_CANCELLED
) {
2936 /* End the migration, but don't set the state to failed */
2937 return MIG_THR_ERR_FATAL
;
2941 * Try to detect any file errors. Note that postcopy_qemufile_src will
2942 * be NULL when postcopy preempt is not enabled.
2944 ret
= qemu_file_get_error_obj_any(s
->to_dst_file
,
2945 s
->postcopy_qemufile_src
,
2948 /* Everything is fine */
2949 assert(!local_error
);
2950 return MIG_THR_ERR_NONE
;
2954 migrate_set_error(s
, local_error
);
2955 error_free(local_error
);
2958 if (state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
) {
2960 * For postcopy, we allow the network to be down for a
2961 * while. After that, it can be continued by a
2964 return postcopy_pause(s
);
2967 * For precopy (or postcopy with error outside IO), we fail
2970 migrate_set_state(&s
->state
, state
, MIGRATION_STATUS_FAILED
);
2971 trace_migration_thread_file_err();
2973 /* Time to stop the migration, now. */
2974 return MIG_THR_ERR_FATAL
;
2978 static void migration_calculate_complete(MigrationState
*s
)
2980 uint64_t bytes
= migration_transferred_bytes();
2981 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2982 int64_t transfer_time
;
2984 migration_downtime_end(s
);
2985 s
->total_time
= end_time
- s
->start_time
;
2986 transfer_time
= s
->total_time
- s
->setup_time
;
2987 if (transfer_time
) {
2988 s
->mbps
= ((double) bytes
* 8.0) / transfer_time
/ 1000;
2992 static void update_iteration_initial_status(MigrationState
*s
)
2995 * Update these three fields at the same time to avoid mismatch info lead
2996 * wrong speed calculation.
2998 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2999 s
->iteration_initial_bytes
= migration_transferred_bytes();
3000 s
->iteration_initial_pages
= ram_get_total_transferred_pages();
3003 static void migration_update_counters(MigrationState
*s
,
3004 int64_t current_time
)
3006 uint64_t transferred
, transferred_pages
, time_spent
;
3007 uint64_t current_bytes
; /* bytes transferred since the beginning */
3008 uint64_t switchover_bw
;
3009 /* Expected bandwidth when switching over to destination QEMU */
3010 double expected_bw_per_ms
;
3013 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
3017 switchover_bw
= migrate_avail_switchover_bandwidth();
3018 current_bytes
= migration_transferred_bytes();
3019 transferred
= current_bytes
- s
->iteration_initial_bytes
;
3020 time_spent
= current_time
- s
->iteration_start_time
;
3021 bandwidth
= (double)transferred
/ time_spent
;
3023 if (switchover_bw
) {
3025 * If the user specified a switchover bandwidth, let's trust the
3026 * user so that can be more accurate than what we estimated.
3028 expected_bw_per_ms
= switchover_bw
/ 1000;
3030 /* If the user doesn't specify bandwidth, we use the estimated */
3031 expected_bw_per_ms
= bandwidth
;
3034 s
->threshold_size
= expected_bw_per_ms
* migrate_downtime_limit();
3036 s
->mbps
= (((double) transferred
* 8.0) /
3037 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
3039 transferred_pages
= ram_get_total_transferred_pages() -
3040 s
->iteration_initial_pages
;
3041 s
->pages_per_second
= (double) transferred_pages
/
3042 (((double) time_spent
/ 1000.0));
3045 * if we haven't sent anything, we don't want to
3046 * recalculate. 10000 is a small enough number for our purposes
3048 if (stat64_get(&mig_stats
.dirty_pages_rate
) &&
3049 transferred
> 10000) {
3050 s
->expected_downtime
=
3051 stat64_get(&mig_stats
.dirty_bytes_last_sync
) / expected_bw_per_ms
;
3054 migration_rate_reset();
3056 update_iteration_initial_status(s
);
3058 trace_migrate_transferred(transferred
, time_spent
,
3059 /* Both in unit bytes/ms */
3060 bandwidth
, switchover_bw
/ 1000,
3064 static bool migration_can_switchover(MigrationState
*s
)
3066 if (!migrate_switchover_ack()) {
3070 /* No reason to wait for switchover ACK if VM is stopped */
3071 if (!runstate_is_running()) {
3075 return s
->switchover_acked
;
3078 /* Migration thread iteration status */
3080 MIG_ITERATE_RESUME
, /* Resume current iteration */
3081 MIG_ITERATE_SKIP
, /* Skip current iteration */
3082 MIG_ITERATE_BREAK
, /* Break the loop */
3086 * Return true if continue to the next iteration directly, false
3089 static MigIterateState
migration_iteration_run(MigrationState
*s
)
3091 uint64_t must_precopy
, can_postcopy
;
3092 Error
*local_err
= NULL
;
3093 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
3094 bool can_switchover
= migration_can_switchover(s
);
3096 qemu_savevm_state_pending_estimate(&must_precopy
, &can_postcopy
);
3097 uint64_t pending_size
= must_precopy
+ can_postcopy
;
3099 trace_migrate_pending_estimate(pending_size
, must_precopy
, can_postcopy
);
3101 if (must_precopy
<= s
->threshold_size
) {
3102 qemu_savevm_state_pending_exact(&must_precopy
, &can_postcopy
);
3103 pending_size
= must_precopy
+ can_postcopy
;
3104 trace_migrate_pending_exact(pending_size
, must_precopy
, can_postcopy
);
3107 if ((!pending_size
|| pending_size
< s
->threshold_size
) && can_switchover
) {
3108 trace_migration_thread_low_pending(pending_size
);
3109 migration_completion(s
);
3110 return MIG_ITERATE_BREAK
;
3113 /* Still a significant amount to transfer */
3114 if (!in_postcopy
&& must_precopy
<= s
->threshold_size
&& can_switchover
&&
3115 qatomic_read(&s
->start_postcopy
)) {
3116 if (postcopy_start(s
, &local_err
)) {
3117 migrate_set_error(s
, local_err
);
3118 error_report_err(local_err
);
3120 return MIG_ITERATE_SKIP
;
3123 /* Just another iteration step */
3124 qemu_savevm_state_iterate(s
->to_dst_file
, in_postcopy
);
3125 return MIG_ITERATE_RESUME
;
3128 static void migration_iteration_finish(MigrationState
*s
)
3130 /* If we enabled cpu throttling for auto-converge, turn it off. */
3131 cpu_throttle_stop();
3135 case MIGRATION_STATUS_COMPLETED
:
3136 migration_calculate_complete(s
);
3137 runstate_set(RUN_STATE_POSTMIGRATE
);
3139 case MIGRATION_STATUS_COLO
:
3140 assert(migrate_colo());
3141 migrate_start_colo_process(s
);
3142 s
->vm_old_state
= RUN_STATE_RUNNING
;
3144 case MIGRATION_STATUS_FAILED
:
3145 case MIGRATION_STATUS_CANCELLED
:
3146 case MIGRATION_STATUS_CANCELLING
:
3147 if (runstate_is_live(s
->vm_old_state
)) {
3148 if (!runstate_check(RUN_STATE_SHUTDOWN
)) {
3152 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
3153 runstate_set(s
->vm_old_state
);
3159 /* Should not reach here, but if so, forgive the VM. */
3160 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3164 migration_bh_schedule(migrate_fd_cleanup_bh
, s
);
3168 static void bg_migration_iteration_finish(MigrationState
*s
)
3171 * Stop tracking RAM writes - un-protect memory, un-register UFFD
3172 * memory ranges, flush kernel wait queues and wake up threads
3173 * waiting for write fault to be resolved.
3175 ram_write_tracking_stop();
3179 case MIGRATION_STATUS_COMPLETED
:
3180 migration_calculate_complete(s
);
3183 case MIGRATION_STATUS_ACTIVE
:
3184 case MIGRATION_STATUS_FAILED
:
3185 case MIGRATION_STATUS_CANCELLED
:
3186 case MIGRATION_STATUS_CANCELLING
:
3190 /* Should not reach here, but if so, forgive the VM. */
3191 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3195 migration_bh_schedule(migrate_fd_cleanup_bh
, s
);
3200 * Return true if continue to the next iteration directly, false
3203 static MigIterateState
bg_migration_iteration_run(MigrationState
*s
)
3207 res
= qemu_savevm_state_iterate(s
->to_dst_file
, false);
3209 bg_migration_completion(s
);
3210 return MIG_ITERATE_BREAK
;
3213 return MIG_ITERATE_RESUME
;
3216 void migration_make_urgent_request(void)
3218 qemu_sem_post(&migrate_get_current()->rate_limit_sem
);
3221 void migration_consume_urgent_request(void)
3223 qemu_sem_wait(&migrate_get_current()->rate_limit_sem
);
3226 /* Returns true if the rate limiting was broken by an urgent request */
3227 bool migration_rate_limit(void)
3229 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3230 MigrationState
*s
= migrate_get_current();
3232 bool urgent
= false;
3233 migration_update_counters(s
, now
);
3234 if (migration_rate_exceeded(s
->to_dst_file
)) {
3236 if (qemu_file_get_error(s
->to_dst_file
)) {
3240 * Wait for a delay to do rate limiting OR
3241 * something urgent to post the semaphore.
3243 int ms
= s
->iteration_start_time
+ BUFFER_DELAY
- now
;
3244 trace_migration_rate_limit_pre(ms
);
3245 if (qemu_sem_timedwait(&s
->rate_limit_sem
, ms
) == 0) {
3247 * We were woken by one or more urgent things but
3248 * the timedwait will have consumed one of them.
3249 * The service routine for the urgent wake will dec
3250 * the semaphore itself for each item it consumes,
3251 * so add this one we just eat back.
3253 qemu_sem_post(&s
->rate_limit_sem
);
3256 trace_migration_rate_limit_post(urgent
);
3262 * if failover devices are present, wait they are completely
3266 static void qemu_savevm_wait_unplug(MigrationState
*s
, int old_state
,
3269 if (qemu_savevm_state_guest_unplug_pending()) {
3270 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_WAIT_UNPLUG
);
3272 while (s
->state
== MIGRATION_STATUS_WAIT_UNPLUG
&&
3273 qemu_savevm_state_guest_unplug_pending()) {
3274 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3276 if (s
->state
!= MIGRATION_STATUS_WAIT_UNPLUG
) {
3277 int timeout
= 120; /* 30 seconds */
3279 * migration has been canceled
3280 * but as we have started an unplug we must wait the end
3281 * to be able to plug back the card
3283 while (timeout
-- && qemu_savevm_state_guest_unplug_pending()) {
3284 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3286 if (qemu_savevm_state_guest_unplug_pending() &&
3288 warn_report("migration: partially unplugged device on "
3293 migrate_set_state(&s
->state
, MIGRATION_STATUS_WAIT_UNPLUG
, new_state
);
3295 migrate_set_state(&s
->state
, old_state
, new_state
);
3300 * Master migration thread on the source VM.
3301 * It drives the migration and pumps the data down the outgoing channel.
3303 static void *migration_thread(void *opaque
)
3305 MigrationState
*s
= opaque
;
3306 MigrationThread
*thread
= NULL
;
3307 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3308 MigThrError thr_error
;
3309 bool urgent
= false;
3311 thread
= migration_threads_add("live_migration", qemu_get_thread_id());
3313 rcu_register_thread();
3315 object_ref(OBJECT(s
));
3316 update_iteration_initial_status(s
);
3319 qemu_savevm_state_header(s
->to_dst_file
);
3323 * If we opened the return path, we need to make sure dst has it
3326 if (s
->rp_state
.rp_thread_created
) {
3327 /* Now tell the dest that it should open its end so it can reply */
3328 qemu_savevm_send_open_return_path(s
->to_dst_file
);
3330 /* And do a ping that will make stuff easier to debug */
3331 qemu_savevm_send_ping(s
->to_dst_file
, 1);
3334 if (migrate_postcopy()) {
3336 * Tell the destination that we *might* want to do postcopy later;
3337 * if the other end can't do postcopy it should fail now, nice and
3340 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
3343 if (migrate_colo()) {
3344 /* Notify migration destination that we enable COLO */
3345 qemu_savevm_send_colo_enable(s
->to_dst_file
);
3349 qemu_savevm_state_setup(s
->to_dst_file
);
3352 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3353 MIGRATION_STATUS_ACTIVE
);
3355 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3357 trace_migration_thread_setup_complete();
3359 while (migration_is_active(s
)) {
3360 if (urgent
|| !migration_rate_exceeded(s
->to_dst_file
)) {
3361 MigIterateState iter_state
= migration_iteration_run(s
);
3362 if (iter_state
== MIG_ITERATE_SKIP
) {
3364 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3370 * Try to detect any kind of failures, and see whether we
3371 * should stop the migration now.
3373 thr_error
= migration_detect_error(s
);
3374 if (thr_error
== MIG_THR_ERR_FATAL
) {
3375 /* Stop migration */
3377 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
3379 * Just recovered from a e.g. network failure, reset all
3380 * the local variables. This is important to avoid
3381 * breaking transferred_bytes and bandwidth calculation
3383 update_iteration_initial_status(s
);
3386 urgent
= migration_rate_limit();
3389 trace_migration_thread_after_loop();
3390 migration_iteration_finish(s
);
3391 object_unref(OBJECT(s
));
3392 rcu_unregister_thread();
3393 migration_threads_remove(thread
);
3397 static void bg_migration_vm_start_bh(void *opaque
)
3399 MigrationState
*s
= opaque
;
3401 vm_resume(s
->vm_old_state
);
3402 migration_downtime_end(s
);
3406 * Background snapshot thread, based on live migration code.
3407 * This is an alternative implementation of live migration mechanism
3408 * introduced specifically to support background snapshots.
3410 * It takes advantage of userfault_fd write protection mechanism introduced
3411 * in v5.7 kernel. Compared to existing dirty page logging migration much
3412 * lesser stream traffic is produced resulting in smaller snapshot images,
3413 * simply cause of no page duplicates can get into the stream.
3415 * Another key point is that generated vmstate stream reflects machine state
3416 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3417 * mechanism, which effectively results in that saved snapshot is the state of VM
3418 * at the end of the process.
3420 static void *bg_migration_thread(void *opaque
)
3422 MigrationState
*s
= opaque
;
3423 int64_t setup_start
;
3424 MigThrError thr_error
;
3426 bool early_fail
= true;
3428 rcu_register_thread();
3429 object_ref(OBJECT(s
));
3431 migration_rate_set(RATE_LIMIT_DISABLED
);
3433 setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3435 * We want to save vmstate for the moment when migration has been
3436 * initiated but also we want to save RAM content while VM is running.
3437 * The RAM content should appear first in the vmstate. So, we first
3438 * stash the non-RAM part of the vmstate to the temporary buffer,
3439 * then write RAM part of the vmstate to the migration stream
3440 * with vCPUs running and, finally, write stashed non-RAM part of
3441 * the vmstate from the buffer to the migration stream.
3443 s
->bioc
= qio_channel_buffer_new(512 * 1024);
3444 qio_channel_set_name(QIO_CHANNEL(s
->bioc
), "vmstate-buffer");
3445 fb
= qemu_file_new_output(QIO_CHANNEL(s
->bioc
));
3446 object_unref(OBJECT(s
->bioc
));
3448 update_iteration_initial_status(s
);
3451 * Prepare for tracking memory writes with UFFD-WP - populate
3452 * RAM pages before protecting.
3455 ram_write_tracking_prepare();
3459 qemu_savevm_state_header(s
->to_dst_file
);
3460 qemu_savevm_state_setup(s
->to_dst_file
);
3463 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3464 MIGRATION_STATUS_ACTIVE
);
3466 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3468 trace_migration_thread_setup_complete();
3469 migration_downtime_start(s
);
3473 s
->vm_old_state
= runstate_get();
3475 global_state_store();
3476 /* Forcibly stop VM before saving state of vCPUs and devices */
3477 if (migration_stop_vm(RUN_STATE_PAUSED
)) {
3481 * Put vCPUs in sync with shadow context structures, then
3482 * save their state to channel-buffer along with devices.
3484 cpu_synchronize_all_states();
3485 if (qemu_savevm_state_complete_precopy_non_iterable(fb
, false, false)) {
3489 * Since we are going to get non-iterable state data directly
3490 * from s->bioc->data, explicit flush is needed here.
3494 /* Now initialize UFFD context and start tracking RAM writes */
3495 if (ram_write_tracking_start()) {
3501 * Start VM from BH handler to avoid write-fault lock here.
3502 * UFFD-WP protection for the whole RAM is already enabled so
3503 * calling VM state change notifiers from vm_start() would initiate
3504 * writes to virtio VQs memory which is in write-protected region.
3506 migration_bh_schedule(bg_migration_vm_start_bh
, s
);
3509 while (migration_is_active(s
)) {
3510 MigIterateState iter_state
= bg_migration_iteration_run(s
);
3511 if (iter_state
== MIG_ITERATE_SKIP
) {
3513 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3518 * Try to detect any kind of failures, and see whether we
3519 * should stop the migration now.
3521 thr_error
= migration_detect_error(s
);
3522 if (thr_error
== MIG_THR_ERR_FATAL
) {
3523 /* Stop migration */
3527 migration_update_counters(s
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
));
3530 trace_migration_thread_after_loop();
3534 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
3535 MIGRATION_STATUS_FAILED
);
3539 bg_migration_iteration_finish(s
);
3542 object_unref(OBJECT(s
));
3543 rcu_unregister_thread();
3548 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
3550 Error
*local_err
= NULL
;
3551 uint64_t rate_limit
;
3552 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
3555 * If there's a previous error, free it and prepare for another one.
3556 * Meanwhile if migration completes successfully, there won't have an error
3557 * dumped when calling migrate_fd_cleanup().
3559 migrate_error_free(s
);
3561 s
->expected_downtime
= migrate_downtime_limit();
3563 migrate_fd_error(s
, error_in
);
3566 * Don't do cleanup for resume if channel is invalid, but only dump
3567 * the error. We wait for another channel connect from the user.
3568 * The error_report still gives HMP user a hint on what failed.
3569 * It's normally done in migrate_fd_cleanup(), but call it here
3572 error_report_err(error_copy(s
->error
));
3574 migrate_fd_cleanup(s
);
3580 /* This is a resumed migration */
3581 rate_limit
= migrate_max_postcopy_bandwidth();
3583 /* This is a fresh new migration */
3584 rate_limit
= migrate_max_bandwidth();
3586 /* Notify before starting migration thread */
3587 migration_call_notifiers(s
);
3590 migration_rate_set(rate_limit
);
3591 qemu_file_set_blocking(s
->to_dst_file
, true);
3594 * Open the return path. For postcopy, it is used exclusively. For
3595 * precopy, only if user specified "return-path" capability would
3596 * QEMU uses the return path.
3598 if (migrate_postcopy_ram() || migrate_return_path()) {
3599 if (open_return_path_on_source(s
)) {
3600 error_setg(&local_err
, "Unable to open return-path for postcopy");
3601 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
3602 migrate_set_error(s
, local_err
);
3603 error_report_err(local_err
);
3604 migrate_fd_cleanup(s
);
3610 * This needs to be done before resuming a postcopy. Note: for newer
3611 * QEMUs we will delay the channel creation until postcopy_start(), to
3612 * avoid disorder of channel creations.
3614 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
3615 postcopy_preempt_setup(s
);
3619 /* Wakeup the main migration thread to do the recovery */
3620 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
3621 MIGRATION_STATUS_POSTCOPY_RECOVER
);
3622 qemu_sem_post(&s
->postcopy_pause_sem
);
3626 if (multifd_save_setup(&local_err
) != 0) {
3627 migrate_set_error(s
, local_err
);
3628 error_report_err(local_err
);
3629 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
3630 MIGRATION_STATUS_FAILED
);
3631 migrate_fd_cleanup(s
);
3635 if (migrate_background_snapshot()) {
3636 qemu_thread_create(&s
->thread
, "bg_snapshot",
3637 bg_migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3639 qemu_thread_create(&s
->thread
, "live_migration",
3640 migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3642 s
->migration_thread_running
= true;
3645 static void migration_class_init(ObjectClass
*klass
, void *data
)
3647 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3649 dc
->user_creatable
= false;
3650 device_class_set_props(dc
, migration_properties
);
3653 static void migration_instance_finalize(Object
*obj
)
3655 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3657 qemu_mutex_destroy(&ms
->error_mutex
);
3658 qemu_mutex_destroy(&ms
->qemu_file_lock
);
3659 qemu_sem_destroy(&ms
->wait_unplug_sem
);
3660 qemu_sem_destroy(&ms
->rate_limit_sem
);
3661 qemu_sem_destroy(&ms
->pause_sem
);
3662 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
3663 qemu_sem_destroy(&ms
->rp_state
.rp_sem
);
3664 qemu_sem_destroy(&ms
->rp_state
.rp_pong_acks
);
3665 qemu_sem_destroy(&ms
->postcopy_qemufile_src_sem
);
3666 error_free(ms
->error
);
3669 static void migration_instance_init(Object
*obj
)
3671 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3673 ms
->state
= MIGRATION_STATUS_NONE
;
3675 ms
->pages_per_second
= -1;
3676 qemu_sem_init(&ms
->pause_sem
, 0);
3677 qemu_mutex_init(&ms
->error_mutex
);
3679 migrate_params_init(&ms
->parameters
);
3681 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
3682 qemu_sem_init(&ms
->rp_state
.rp_sem
, 0);
3683 qemu_sem_init(&ms
->rp_state
.rp_pong_acks
, 0);
3684 qemu_sem_init(&ms
->rate_limit_sem
, 0);
3685 qemu_sem_init(&ms
->wait_unplug_sem
, 0);
3686 qemu_sem_init(&ms
->postcopy_qemufile_src_sem
, 0);
3687 qemu_mutex_init(&ms
->qemu_file_lock
);
3691 * Return true if check pass, false otherwise. Error will be put
3692 * inside errp if provided.
3694 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
3696 /* Assuming all off */
3697 bool old_caps
[MIGRATION_CAPABILITY__MAX
] = { 0 };
3699 if (!migrate_params_check(&ms
->parameters
, errp
)) {
3703 return migrate_caps_check(old_caps
, ms
->capabilities
, errp
);
3706 static const TypeInfo migration_type
= {
3707 .name
= TYPE_MIGRATION
,
3709 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3710 * not created using qdev_new(), it is not attached to the qdev
3711 * device tree, and it is never realized.
3713 * TODO: Make this TYPE_OBJECT once QOM provides something like
3714 * TYPE_DEVICE's "-global" properties.
3716 .parent
= TYPE_DEVICE
,
3717 .class_init
= migration_class_init
,
3718 .class_size
= sizeof(MigrationClass
),
3719 .instance_size
= sizeof(MigrationState
),
3720 .instance_init
= migration_instance_init
,
3721 .instance_finalize
= migration_instance_finalize
,
3724 static void register_migration_types(void)
3726 type_register_static(&migration_type
);
3729 type_init(register_migration_types
);