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"
24 #include "sysemu/runstate.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/cpu-throttle.h"
29 #include "ram-compress.h"
30 #include "migration/global_state.h"
31 #include "migration/misc.h"
32 #include "migration.h"
33 #include "migration-stats.h"
35 #include "qemu-file.h"
37 #include "migration/vmstate.h"
38 #include "block/block.h"
39 #include "qapi/error.h"
40 #include "qapi/clone-visitor.h"
41 #include "qapi/qapi-visit-migration.h"
42 #include "qapi/qapi-visit-sockets.h"
43 #include "qapi/qapi-commands-migration.h"
44 #include "qapi/qapi-events-migration.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qmp/qnull.h"
49 #include "postcopy-ram.h"
50 #include "qemu/thread.h"
52 #include "exec/target_page.h"
53 #include "io/channel-buffer.h"
54 #include "io/channel-tls.h"
55 #include "migration/colo.h"
56 #include "hw/boards.h"
57 #include "monitor/monitor.h"
58 #include "net/announce.h"
59 #include "qemu/queue.h"
61 #include "threadinfo.h"
62 #include "qemu/yank.h"
63 #include "sysemu/cpus.h"
64 #include "yank_functions.h"
65 #include "sysemu/qtest.h"
68 static NotifierList migration_state_notifiers
=
69 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
71 /* Messages sent on the return path from destination to source */
72 enum mig_rp_message_type
{
73 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
74 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
75 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
77 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
78 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
79 MIG_RP_MSG_RECV_BITMAP
, /* send recved_bitmap back to source */
80 MIG_RP_MSG_RESUME_ACK
, /* tell source that we are ready to resume */
81 MIG_RP_MSG_SWITCHOVER_ACK
, /* Tell source it's OK to do switchover */
86 /* When we add fault tolerance, we could have several
87 migrations at once. For now we don't need to add
88 dynamic creation of migration */
90 static MigrationState
*current_migration
;
91 static MigrationIncomingState
*current_incoming
;
93 static GSList
*migration_blockers
;
95 static bool migration_object_check(MigrationState
*ms
, Error
**errp
);
96 static int migration_maybe_pause(MigrationState
*s
,
97 int *current_active_state
,
99 static void migrate_fd_cancel(MigrationState
*s
);
101 static bool migration_needs_multiple_sockets(void)
103 return migrate_multifd() || migrate_postcopy_preempt();
106 static bool uri_supports_multi_channels(const char *uri
)
108 return strstart(uri
, "tcp:", NULL
) || strstart(uri
, "unix:", NULL
) ||
109 strstart(uri
, "vsock:", NULL
);
113 migration_channels_and_uri_compatible(const char *uri
, Error
**errp
)
115 if (migration_needs_multiple_sockets() &&
116 !uri_supports_multi_channels(uri
)) {
117 error_setg(errp
, "Migration requires multi-channel URIs (e.g. tcp)");
124 static gint
page_request_addr_cmp(gconstpointer ap
, gconstpointer bp
)
126 uintptr_t a
= (uintptr_t) ap
, b
= (uintptr_t) bp
;
128 return (a
> b
) - (a
< b
);
131 void migration_object_init(void)
133 /* This can only be called once. */
134 assert(!current_migration
);
135 current_migration
= MIGRATION_OBJ(object_new(TYPE_MIGRATION
));
138 * Init the migrate incoming object as well no matter whether
139 * we'll use it or not.
141 assert(!current_incoming
);
142 current_incoming
= g_new0(MigrationIncomingState
, 1);
143 current_incoming
->state
= MIGRATION_STATUS_NONE
;
144 current_incoming
->postcopy_remote_fds
=
145 g_array_new(FALSE
, TRUE
, sizeof(struct PostCopyFD
));
146 qemu_mutex_init(¤t_incoming
->rp_mutex
);
147 qemu_mutex_init(¤t_incoming
->postcopy_prio_thread_mutex
);
148 qemu_event_init(¤t_incoming
->main_thread_load_event
, false);
149 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_dst
, 0);
150 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fault
, 0);
151 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fast_load
, 0);
152 qemu_sem_init(¤t_incoming
->postcopy_qemufile_dst_done
, 0);
154 qemu_mutex_init(¤t_incoming
->page_request_mutex
);
155 current_incoming
->page_requested
= g_tree_new(page_request_addr_cmp
);
157 migration_object_check(current_migration
, &error_fatal
);
161 dirty_bitmap_mig_init();
164 void migration_cancel(const Error
*error
)
167 migrate_set_error(current_migration
, error
);
169 migrate_fd_cancel(current_migration
);
172 void migration_shutdown(void)
175 * When the QEMU main thread exit, the COLO thread
176 * may wait a semaphore. So, we should wakeup the
177 * COLO thread before migration shutdown.
181 * Cancel the current migration - that will (eventually)
182 * stop the migration using this structure
184 migration_cancel(NULL
);
185 object_unref(OBJECT(current_migration
));
188 * Cancel outgoing migration of dirty bitmaps. It should
189 * at least unref used block nodes.
191 dirty_bitmap_mig_cancel_outgoing();
194 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
195 * are non-critical data, and their loss never considered as
198 dirty_bitmap_mig_cancel_incoming();
202 MigrationState
*migrate_get_current(void)
204 /* This can only be called after the object created. */
205 assert(current_migration
);
206 return current_migration
;
209 MigrationIncomingState
*migration_incoming_get_current(void)
211 assert(current_incoming
);
212 return current_incoming
;
215 void migration_incoming_transport_cleanup(MigrationIncomingState
*mis
)
217 if (mis
->socket_address_list
) {
218 qapi_free_SocketAddressList(mis
->socket_address_list
);
219 mis
->socket_address_list
= NULL
;
222 if (mis
->transport_cleanup
) {
223 mis
->transport_cleanup(mis
->transport_data
);
224 mis
->transport_data
= mis
->transport_cleanup
= NULL
;
228 void migration_incoming_state_destroy(void)
230 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
232 multifd_load_cleanup();
233 compress_threads_load_cleanup();
235 if (mis
->to_src_file
) {
236 /* Tell source that we are done */
237 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
238 qemu_fclose(mis
->to_src_file
);
239 mis
->to_src_file
= NULL
;
242 if (mis
->from_src_file
) {
243 migration_ioc_unregister_yank_from_file(mis
->from_src_file
);
244 qemu_fclose(mis
->from_src_file
);
245 mis
->from_src_file
= NULL
;
247 if (mis
->postcopy_remote_fds
) {
248 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
249 mis
->postcopy_remote_fds
= NULL
;
252 migration_incoming_transport_cleanup(mis
);
253 qemu_event_reset(&mis
->main_thread_load_event
);
255 if (mis
->page_requested
) {
256 g_tree_destroy(mis
->page_requested
);
257 mis
->page_requested
= NULL
;
260 if (mis
->postcopy_qemufile_dst
) {
261 migration_ioc_unregister_yank_from_file(mis
->postcopy_qemufile_dst
);
262 qemu_fclose(mis
->postcopy_qemufile_dst
);
263 mis
->postcopy_qemufile_dst
= NULL
;
266 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
269 static void migrate_generate_event(int new_state
)
271 if (migrate_events()) {
272 qapi_event_send_migration(new_state
);
277 * Send a message on the return channel back to the source
280 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
281 enum mig_rp_message_type message_type
,
282 uint16_t len
, void *data
)
286 trace_migrate_send_rp_message((int)message_type
, len
);
287 QEMU_LOCK_GUARD(&mis
->rp_mutex
);
290 * It's possible that the file handle got lost due to network
293 if (!mis
->to_src_file
) {
298 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
299 qemu_put_be16(mis
->to_src_file
, len
);
300 qemu_put_buffer(mis
->to_src_file
, data
, len
);
301 qemu_fflush(mis
->to_src_file
);
303 /* It's possible that qemu file got error during sending */
304 ret
= qemu_file_get_error(mis
->to_src_file
);
309 /* Request one page from the source VM at the given start address.
310 * rb: the RAMBlock to request the page in
311 * Start: Address offset within the RB
312 * Len: Length in bytes required - must be a multiple of pagesize
314 int migrate_send_rp_message_req_pages(MigrationIncomingState
*mis
,
315 RAMBlock
*rb
, ram_addr_t start
)
317 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
318 size_t msglen
= 12; /* start + len */
319 size_t len
= qemu_ram_pagesize(rb
);
320 enum mig_rp_message_type msg_type
;
324 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
325 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
328 * We maintain the last ramblock that we requested for page. Note that we
329 * don't need locking because this function will only be called within the
330 * postcopy ram fault thread.
332 if (rb
!= mis
->last_rb
) {
335 rbname
= qemu_ram_get_idstr(rb
);
336 rbname_len
= strlen(rbname
);
338 assert(rbname_len
< 256);
340 bufc
[msglen
++] = rbname_len
;
341 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
342 msglen
+= rbname_len
;
343 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
345 msg_type
= MIG_RP_MSG_REQ_PAGES
;
348 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
351 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
,
352 RAMBlock
*rb
, ram_addr_t start
, uint64_t haddr
)
354 void *aligned
= (void *)(uintptr_t)ROUND_DOWN(haddr
, qemu_ram_pagesize(rb
));
355 bool received
= false;
357 WITH_QEMU_LOCK_GUARD(&mis
->page_request_mutex
) {
358 received
= ramblock_recv_bitmap_test_byte_offset(rb
, start
);
359 if (!received
&& !g_tree_lookup(mis
->page_requested
, aligned
)) {
361 * The page has not been received, and it's not yet in the page
362 * request list. Queue it. Set the value of element to 1, so that
363 * things like g_tree_lookup() will return TRUE (1) when found.
365 g_tree_insert(mis
->page_requested
, aligned
, (gpointer
)1);
366 mis
->page_requested_count
++;
367 trace_postcopy_page_req_add(aligned
, mis
->page_requested_count
);
372 * If the page is there, skip sending the message. We don't even need the
373 * lock because as long as the page arrived, it'll be there forever.
379 return migrate_send_rp_message_req_pages(mis
, rb
, start
);
382 static bool migration_colo_enabled
;
383 bool migration_incoming_colo_enabled(void)
385 return migration_colo_enabled
;
388 void migration_incoming_disable_colo(void)
390 ram_block_discard_disable(false);
391 migration_colo_enabled
= false;
394 int migration_incoming_enable_colo(void)
396 #ifndef CONFIG_REPLICATION
397 error_report("ENABLE_COLO command come in migration stream, but COLO "
398 "module is not built in");
402 if (!migrate_colo()) {
403 error_report("ENABLE_COLO command come in migration stream, but c-colo "
404 "capability is not set");
408 if (ram_block_discard_disable(true)) {
409 error_report("COLO: cannot disable RAM discard");
412 migration_colo_enabled
= true;
416 void migrate_add_address(SocketAddress
*address
)
418 MigrationIncomingState
*mis
= migration_incoming_get_current();
420 QAPI_LIST_PREPEND(mis
->socket_address_list
,
421 QAPI_CLONE(SocketAddress
, address
));
424 static void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
426 const char *p
= NULL
;
428 /* URI is not suitable for migration? */
429 if (!migration_channels_and_uri_compatible(uri
, errp
)) {
433 qapi_event_send_migration(MIGRATION_STATUS_SETUP
);
434 if (strstart(uri
, "tcp:", &p
) ||
435 strstart(uri
, "unix:", NULL
) ||
436 strstart(uri
, "vsock:", NULL
)) {
437 socket_start_incoming_migration(p
? p
: uri
, errp
);
439 } else if (strstart(uri
, "rdma:", &p
)) {
440 rdma_start_incoming_migration(p
, errp
);
442 } else if (strstart(uri
, "exec:", &p
)) {
443 exec_start_incoming_migration(p
, errp
);
444 } else if (strstart(uri
, "fd:", &p
)) {
445 fd_start_incoming_migration(p
, errp
);
447 error_setg(errp
, "unknown migration protocol: %s", uri
);
451 static void process_incoming_migration_bh(void *opaque
)
453 Error
*local_err
= NULL
;
454 MigrationIncomingState
*mis
= opaque
;
456 /* If capability late_block_activate is set:
457 * Only fire up the block code now if we're going to restart the
458 * VM, else 'cont' will do it.
459 * This causes file locking to happen; so we don't want it to happen
460 * unless we really are starting the VM.
462 if (!migrate_late_block_activate() ||
463 (autostart
&& (!global_state_received() ||
464 global_state_get_runstate() == RUN_STATE_RUNNING
))) {
465 /* Make sure all file formats throw away their mutable metadata.
466 * If we get an error here, just don't restart the VM yet. */
467 bdrv_activate_all(&local_err
);
469 error_report_err(local_err
);
476 * This must happen after all error conditions are dealt with and
477 * we're sure the VM is going to be running on this host.
479 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
481 multifd_load_shutdown();
483 dirty_bitmap_mig_before_vm_start();
485 if (!global_state_received() ||
486 global_state_get_runstate() == RUN_STATE_RUNNING
) {
490 runstate_set(RUN_STATE_PAUSED
);
492 } else if (migration_incoming_colo_enabled()) {
493 migration_incoming_disable_colo();
496 runstate_set(global_state_get_runstate());
499 * This must happen after any state changes since as soon as an external
500 * observer sees this event they might start to prod at the VM assuming
503 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
504 MIGRATION_STATUS_COMPLETED
);
505 qemu_bh_delete(mis
->bh
);
506 migration_incoming_state_destroy();
509 static void coroutine_fn
510 process_incoming_migration_co(void *opaque
)
512 MigrationIncomingState
*mis
= migration_incoming_get_current();
516 assert(mis
->from_src_file
);
518 if (compress_threads_load_setup(mis
->from_src_file
)) {
519 error_report("Failed to setup decompress threads");
523 mis
->largest_page_size
= qemu_ram_pagesize_largest();
524 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
525 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
526 MIGRATION_STATUS_ACTIVE
);
528 mis
->loadvm_co
= qemu_coroutine_self();
529 ret
= qemu_loadvm_state(mis
->from_src_file
);
530 mis
->loadvm_co
= NULL
;
532 ps
= postcopy_state_get();
533 trace_process_incoming_migration_co_end(ret
, ps
);
534 if (ps
!= POSTCOPY_INCOMING_NONE
) {
535 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
537 * Where a migration had postcopy enabled (and thus went to advise)
538 * but managed to complete within the precopy period, we can use
541 postcopy_ram_incoming_cleanup(mis
);
542 } else if (ret
>= 0) {
544 * Postcopy was started, cleanup should happen at the end of the
547 trace_process_incoming_migration_co_postcopy_end_main();
550 /* Else if something went wrong then just fall out of the normal exit */
554 error_report("load of migration failed: %s", strerror(-ret
));
558 if (colo_incoming_co() < 0) {
562 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
563 qemu_bh_schedule(mis
->bh
);
566 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
567 MIGRATION_STATUS_FAILED
);
568 qemu_fclose(mis
->from_src_file
);
570 multifd_load_cleanup();
571 compress_threads_load_cleanup();
577 * migration_incoming_setup: Setup incoming migration
578 * @f: file for main migration channel
579 * @errp: where to put errors
581 * Returns: %true on success, %false on error.
583 static bool migration_incoming_setup(QEMUFile
*f
, Error
**errp
)
585 MigrationIncomingState
*mis
= migration_incoming_get_current();
587 if (!mis
->from_src_file
) {
588 mis
->from_src_file
= f
;
590 qemu_file_set_blocking(f
, false);
594 void migration_incoming_process(void)
596 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
597 qemu_coroutine_enter(co
);
600 /* Returns true if recovered from a paused migration, otherwise false */
601 static bool postcopy_try_recover(void)
603 MigrationIncomingState
*mis
= migration_incoming_get_current();
605 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
606 /* Resumed from a paused postcopy migration */
608 /* This should be set already in migration_incoming_setup() */
609 assert(mis
->from_src_file
);
610 /* Postcopy has standalone thread to do vm load */
611 qemu_file_set_blocking(mis
->from_src_file
, true);
613 /* Re-configure the return path */
614 mis
->to_src_file
= qemu_file_get_return_path(mis
->from_src_file
);
616 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
617 MIGRATION_STATUS_POSTCOPY_RECOVER
);
620 * Here, we only wake up the main loading thread (while the
621 * rest threads will still be waiting), so that we can receive
622 * commands from source now, and answer it if needed. The
623 * rest threads will be woken up afterwards until we are sure
624 * that source is ready to reply to page requests.
626 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
633 void migration_fd_process_incoming(QEMUFile
*f
, Error
**errp
)
635 if (!migration_incoming_setup(f
, errp
)) {
638 if (postcopy_try_recover()) {
641 migration_incoming_process();
645 * Returns true when we want to start a new incoming migration process,
648 static bool migration_should_start_incoming(bool main_channel
)
650 /* Multifd doesn't start unless all channels are established */
651 if (migrate_multifd()) {
652 return migration_has_all_channels();
655 /* Preempt channel only starts when the main channel is created */
656 if (migrate_postcopy_preempt()) {
661 * For all the rest types of migration, we should only reach here when
662 * it's the main channel that's being created, and we should always
663 * proceed with this channel.
665 assert(main_channel
);
669 void migration_ioc_process_incoming(QIOChannel
*ioc
, Error
**errp
)
671 MigrationIncomingState
*mis
= migration_incoming_get_current();
672 Error
*local_err
= NULL
;
674 bool default_channel
= true;
675 uint32_t channel_magic
= 0;
678 if (migrate_multifd() && !migrate_postcopy_ram() &&
679 qio_channel_has_feature(ioc
, QIO_CHANNEL_FEATURE_READ_MSG_PEEK
)) {
681 * With multiple channels, it is possible that we receive channels
682 * out of order on destination side, causing incorrect mapping of
683 * source channels on destination side. Check channel MAGIC to
684 * decide type of channel. Please note this is best effort, postcopy
685 * preempt channel does not send any magic number so avoid it for
686 * postcopy live migration. Also tls live migration already does
687 * tls handshake while initializing main channel so with tls this
688 * issue is not possible.
690 ret
= migration_channel_read_peek(ioc
, (void *)&channel_magic
,
691 sizeof(channel_magic
), &local_err
);
694 error_propagate(errp
, local_err
);
698 default_channel
= (channel_magic
== cpu_to_be32(QEMU_VM_FILE_MAGIC
));
700 default_channel
= !mis
->from_src_file
;
703 if (multifd_load_setup(errp
) != 0) {
704 error_setg(errp
, "Failed to setup multifd channels");
708 if (default_channel
) {
709 f
= qemu_file_new_input(ioc
);
711 if (!migration_incoming_setup(f
, errp
)) {
715 /* Multiple connections */
716 assert(migration_needs_multiple_sockets());
717 if (migrate_multifd()) {
718 multifd_recv_new_channel(ioc
, &local_err
);
720 assert(migrate_postcopy_preempt());
721 f
= qemu_file_new_input(ioc
);
722 postcopy_preempt_new_channel(mis
, f
);
725 error_propagate(errp
, local_err
);
730 if (migration_should_start_incoming(default_channel
)) {
731 /* If it's a recovery, we're done */
732 if (postcopy_try_recover()) {
735 migration_incoming_process();
740 * @migration_has_all_channels: We have received all channels that we need
742 * Returns true when we have got connections to all the channels that
743 * we need for migration.
745 bool migration_has_all_channels(void)
747 MigrationIncomingState
*mis
= migration_incoming_get_current();
749 if (!mis
->from_src_file
) {
753 if (migrate_multifd()) {
754 return multifd_recv_all_channels_created();
757 if (migrate_postcopy_preempt()) {
758 return mis
->postcopy_qemufile_dst
!= NULL
;
764 int migrate_send_rp_switchover_ack(MigrationIncomingState
*mis
)
766 return migrate_send_rp_message(mis
, MIG_RP_MSG_SWITCHOVER_ACK
, 0, NULL
);
770 * Send a 'SHUT' message on the return channel with the given value
771 * to indicate that we've finished with the RP. Non-0 value indicates
774 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
779 buf
= cpu_to_be32(value
);
780 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
784 * Send a 'PONG' message on the return channel with the given value
785 * (normally in response to a 'PING')
787 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
792 buf
= cpu_to_be32(value
);
793 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
796 void migrate_send_rp_recv_bitmap(MigrationIncomingState
*mis
,
804 * First, we send the header part. It contains only the len of
805 * idstr, and the idstr itself.
807 len
= strlen(block_name
);
809 memcpy(buf
+ 1, block_name
, len
);
811 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
812 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
817 migrate_send_rp_message(mis
, MIG_RP_MSG_RECV_BITMAP
, len
+ 1, buf
);
820 * Next, we dump the received bitmap to the stream.
822 * TODO: currently we are safe since we are the only one that is
823 * using the to_src_file handle (fault thread is still paused),
824 * and it's ok even not taking the mutex. However the best way is
825 * to take the lock before sending the message header, and release
826 * the lock after sending the bitmap.
828 qemu_mutex_lock(&mis
->rp_mutex
);
829 res
= ramblock_recv_bitmap_send(mis
->to_src_file
, block_name
);
830 qemu_mutex_unlock(&mis
->rp_mutex
);
832 trace_migrate_send_rp_recv_bitmap(block_name
, res
);
835 void migrate_send_rp_resume_ack(MigrationIncomingState
*mis
, uint32_t value
)
839 buf
= cpu_to_be32(value
);
840 migrate_send_rp_message(mis
, MIG_RP_MSG_RESUME_ACK
, sizeof(buf
), &buf
);
844 * Return true if we're already in the middle of a migration
845 * (i.e. any of the active or setup states)
847 bool migration_is_setup_or_active(int state
)
850 case MIGRATION_STATUS_ACTIVE
:
851 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
852 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
853 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
854 case MIGRATION_STATUS_SETUP
:
855 case MIGRATION_STATUS_PRE_SWITCHOVER
:
856 case MIGRATION_STATUS_DEVICE
:
857 case MIGRATION_STATUS_WAIT_UNPLUG
:
858 case MIGRATION_STATUS_COLO
:
867 bool migration_is_running(int state
)
870 case MIGRATION_STATUS_ACTIVE
:
871 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
872 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
873 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
874 case MIGRATION_STATUS_SETUP
:
875 case MIGRATION_STATUS_PRE_SWITCHOVER
:
876 case MIGRATION_STATUS_DEVICE
:
877 case MIGRATION_STATUS_WAIT_UNPLUG
:
878 case MIGRATION_STATUS_CANCELLING
:
887 static bool migrate_show_downtime(MigrationState
*s
)
889 return (s
->state
== MIGRATION_STATUS_COMPLETED
) || migration_in_postcopy();
892 static void populate_time_info(MigrationInfo
*info
, MigrationState
*s
)
894 info
->has_status
= true;
895 info
->has_setup_time
= true;
896 info
->setup_time
= s
->setup_time
;
898 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
899 info
->has_total_time
= true;
900 info
->total_time
= s
->total_time
;
902 info
->has_total_time
= true;
903 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) -
907 if (migrate_show_downtime(s
)) {
908 info
->has_downtime
= true;
909 info
->downtime
= s
->downtime
;
911 info
->has_expected_downtime
= true;
912 info
->expected_downtime
= s
->expected_downtime
;
916 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
918 size_t page_size
= qemu_target_page_size();
920 info
->ram
= g_malloc0(sizeof(*info
->ram
));
921 info
->ram
->transferred
= stat64_get(&mig_stats
.transferred
);
922 info
->ram
->total
= ram_bytes_total();
923 info
->ram
->duplicate
= stat64_get(&mig_stats
.zero_pages
);
924 /* legacy value. It is not used anymore */
925 info
->ram
->skipped
= 0;
926 info
->ram
->normal
= stat64_get(&mig_stats
.normal_pages
);
927 info
->ram
->normal_bytes
= info
->ram
->normal
* page_size
;
928 info
->ram
->mbps
= s
->mbps
;
929 info
->ram
->dirty_sync_count
=
930 stat64_get(&mig_stats
.dirty_sync_count
);
931 info
->ram
->dirty_sync_missed_zero_copy
=
932 stat64_get(&mig_stats
.dirty_sync_missed_zero_copy
);
933 info
->ram
->postcopy_requests
=
934 stat64_get(&mig_stats
.postcopy_requests
);
935 info
->ram
->page_size
= page_size
;
936 info
->ram
->multifd_bytes
= stat64_get(&mig_stats
.multifd_bytes
);
937 info
->ram
->pages_per_second
= s
->pages_per_second
;
938 info
->ram
->precopy_bytes
= stat64_get(&mig_stats
.precopy_bytes
);
939 info
->ram
->downtime_bytes
= stat64_get(&mig_stats
.downtime_bytes
);
940 info
->ram
->postcopy_bytes
= stat64_get(&mig_stats
.postcopy_bytes
);
942 if (migrate_xbzrle()) {
943 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
944 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
945 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
946 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
947 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
948 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
949 info
->xbzrle_cache
->encoding_rate
= xbzrle_counters
.encoding_rate
;
950 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
953 if (migrate_compress()) {
954 info
->compression
= g_malloc0(sizeof(*info
->compression
));
955 info
->compression
->pages
= compression_counters
.pages
;
956 info
->compression
->busy
= compression_counters
.busy
;
957 info
->compression
->busy_rate
= compression_counters
.busy_rate
;
958 info
->compression
->compressed_size
=
959 compression_counters
.compressed_size
;
960 info
->compression
->compression_rate
=
961 compression_counters
.compression_rate
;
964 if (cpu_throttle_active()) {
965 info
->has_cpu_throttle_percentage
= true;
966 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
969 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
970 info
->ram
->remaining
= ram_bytes_remaining();
971 info
->ram
->dirty_pages_rate
=
972 stat64_get(&mig_stats
.dirty_pages_rate
);
976 static void populate_disk_info(MigrationInfo
*info
)
978 if (blk_mig_active()) {
979 info
->disk
= g_malloc0(sizeof(*info
->disk
));
980 info
->disk
->transferred
= blk_mig_bytes_transferred();
981 info
->disk
->remaining
= blk_mig_bytes_remaining();
982 info
->disk
->total
= blk_mig_bytes_total();
986 static void fill_source_migration_info(MigrationInfo
*info
)
988 MigrationState
*s
= migrate_get_current();
989 int state
= qatomic_read(&s
->state
);
990 GSList
*cur_blocker
= migration_blockers
;
992 info
->blocked_reasons
= NULL
;
995 * There are two types of reasons a migration might be blocked;
996 * a) devices marked in VMState as non-migratable, and
997 * b) Explicit migration blockers
998 * We need to add both of them here.
1000 qemu_savevm_non_migratable_list(&info
->blocked_reasons
);
1002 while (cur_blocker
) {
1003 QAPI_LIST_PREPEND(info
->blocked_reasons
,
1004 g_strdup(error_get_pretty(cur_blocker
->data
)));
1005 cur_blocker
= g_slist_next(cur_blocker
);
1007 info
->has_blocked_reasons
= info
->blocked_reasons
!= NULL
;
1010 case MIGRATION_STATUS_NONE
:
1011 /* no migration has happened ever */
1012 /* do not overwrite destination migration status */
1014 case MIGRATION_STATUS_SETUP
:
1015 info
->has_status
= true;
1016 info
->has_total_time
= false;
1018 case MIGRATION_STATUS_ACTIVE
:
1019 case MIGRATION_STATUS_CANCELLING
:
1020 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1021 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1022 case MIGRATION_STATUS_DEVICE
:
1023 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1024 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1025 /* TODO add some postcopy stats */
1026 populate_time_info(info
, s
);
1027 populate_ram_info(info
, s
);
1028 populate_disk_info(info
);
1029 populate_vfio_info(info
);
1031 case MIGRATION_STATUS_COLO
:
1032 info
->has_status
= true;
1033 /* TODO: display COLO specific information (checkpoint info etc.) */
1035 case MIGRATION_STATUS_COMPLETED
:
1036 populate_time_info(info
, s
);
1037 populate_ram_info(info
, s
);
1038 populate_vfio_info(info
);
1040 case MIGRATION_STATUS_FAILED
:
1041 info
->has_status
= true;
1043 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
1046 case MIGRATION_STATUS_CANCELLED
:
1047 info
->has_status
= true;
1049 case MIGRATION_STATUS_WAIT_UNPLUG
:
1050 info
->has_status
= true;
1053 info
->status
= state
;
1056 static void fill_destination_migration_info(MigrationInfo
*info
)
1058 MigrationIncomingState
*mis
= migration_incoming_get_current();
1060 if (mis
->socket_address_list
) {
1061 info
->has_socket_address
= true;
1062 info
->socket_address
=
1063 QAPI_CLONE(SocketAddressList
, mis
->socket_address_list
);
1066 switch (mis
->state
) {
1067 case MIGRATION_STATUS_NONE
:
1069 case MIGRATION_STATUS_SETUP
:
1070 case MIGRATION_STATUS_CANCELLING
:
1071 case MIGRATION_STATUS_CANCELLED
:
1072 case MIGRATION_STATUS_ACTIVE
:
1073 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1074 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1075 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1076 case MIGRATION_STATUS_FAILED
:
1077 case MIGRATION_STATUS_COLO
:
1078 info
->has_status
= true;
1080 case MIGRATION_STATUS_COMPLETED
:
1081 info
->has_status
= true;
1082 fill_destination_postcopy_migration_info(info
);
1085 info
->status
= mis
->state
;
1088 MigrationInfo
*qmp_query_migrate(Error
**errp
)
1090 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
1092 fill_destination_migration_info(info
);
1093 fill_source_migration_info(info
);
1098 void qmp_migrate_start_postcopy(Error
**errp
)
1100 MigrationState
*s
= migrate_get_current();
1102 if (!migrate_postcopy()) {
1103 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1104 " the start of migration");
1108 if (s
->state
== MIGRATION_STATUS_NONE
) {
1109 error_setg(errp
, "Postcopy must be started after migration has been"
1114 * we don't error if migration has finished since that would be racy
1115 * with issuing this command.
1117 qatomic_set(&s
->start_postcopy
, true);
1120 /* shared migration helpers */
1122 void migrate_set_state(int *state
, int old_state
, int new_state
)
1124 assert(new_state
< MIGRATION_STATUS__MAX
);
1125 if (qatomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1126 trace_migrate_set_state(MigrationStatus_str(new_state
));
1127 migrate_generate_event(new_state
);
1131 static void migrate_fd_cleanup(MigrationState
*s
)
1133 qemu_bh_delete(s
->cleanup_bh
);
1134 s
->cleanup_bh
= NULL
;
1136 g_free(s
->hostname
);
1138 json_writer_free(s
->vmdesc
);
1141 qemu_savevm_state_cleanup();
1143 if (s
->to_dst_file
) {
1146 trace_migrate_fd_cleanup();
1147 qemu_mutex_unlock_iothread();
1148 if (s
->migration_thread_running
) {
1149 qemu_thread_join(&s
->thread
);
1150 s
->migration_thread_running
= false;
1152 qemu_mutex_lock_iothread();
1154 multifd_save_cleanup();
1155 qemu_mutex_lock(&s
->qemu_file_lock
);
1156 tmp
= s
->to_dst_file
;
1157 s
->to_dst_file
= NULL
;
1158 qemu_mutex_unlock(&s
->qemu_file_lock
);
1160 * Close the file handle without the lock to make sure the
1161 * critical section won't block for long.
1163 migration_ioc_unregister_yank_from_file(tmp
);
1167 if (s
->postcopy_qemufile_src
) {
1168 migration_ioc_unregister_yank_from_file(s
->postcopy_qemufile_src
);
1169 qemu_fclose(s
->postcopy_qemufile_src
);
1170 s
->postcopy_qemufile_src
= NULL
;
1173 assert(!migration_is_active(s
));
1175 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1176 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1177 MIGRATION_STATUS_CANCELLED
);
1181 /* It is used on info migrate. We can't free it */
1182 error_report_err(error_copy(s
->error
));
1184 notifier_list_notify(&migration_state_notifiers
, s
);
1185 block_cleanup_parameters();
1186 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1189 static void migrate_fd_cleanup_schedule(MigrationState
*s
)
1192 * Ref the state for bh, because it may be called when
1193 * there're already no other refs
1195 object_ref(OBJECT(s
));
1196 qemu_bh_schedule(s
->cleanup_bh
);
1199 static void migrate_fd_cleanup_bh(void *opaque
)
1201 MigrationState
*s
= opaque
;
1202 migrate_fd_cleanup(s
);
1203 object_unref(OBJECT(s
));
1206 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1208 QEMU_LOCK_GUARD(&s
->error_mutex
);
1210 s
->error
= error_copy(error
);
1214 static void migrate_error_free(MigrationState
*s
)
1216 QEMU_LOCK_GUARD(&s
->error_mutex
);
1218 error_free(s
->error
);
1223 static void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1225 trace_migrate_fd_error(error_get_pretty(error
));
1226 assert(s
->to_dst_file
== NULL
);
1227 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1228 MIGRATION_STATUS_FAILED
);
1229 migrate_set_error(s
, error
);
1232 static void migrate_fd_cancel(MigrationState
*s
)
1235 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
1236 trace_migrate_fd_cancel();
1238 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1239 if (s
->rp_state
.from_dst_file
) {
1240 /* shutdown the rp socket, so causing the rp thread to shutdown */
1241 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1246 old_state
= s
->state
;
1247 if (!migration_is_running(old_state
)) {
1250 /* If the migration is paused, kick it out of the pause */
1251 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1252 qemu_sem_post(&s
->pause_sem
);
1254 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1255 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1258 * If we're unlucky the migration code might be stuck somewhere in a
1259 * send/write while the network has failed and is waiting to timeout;
1260 * if we've got shutdown(2) available then we can force it to quit.
1261 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1262 * called in a bh, so there is no race against this cancel.
1264 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
1265 qemu_file_shutdown(f
);
1267 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1268 Error
*local_err
= NULL
;
1270 bdrv_activate_all(&local_err
);
1272 error_report_err(local_err
);
1274 s
->block_inactive
= false;
1279 void add_migration_state_change_notifier(Notifier
*notify
)
1281 notifier_list_add(&migration_state_notifiers
, notify
);
1284 void remove_migration_state_change_notifier(Notifier
*notify
)
1286 notifier_remove(notify
);
1289 bool migration_in_setup(MigrationState
*s
)
1291 return s
->state
== MIGRATION_STATUS_SETUP
;
1294 bool migration_has_finished(MigrationState
*s
)
1296 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1299 bool migration_has_failed(MigrationState
*s
)
1301 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1302 s
->state
== MIGRATION_STATUS_FAILED
);
1305 bool migration_in_postcopy(void)
1307 MigrationState
*s
= migrate_get_current();
1310 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1311 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1312 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1319 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1321 return migration_in_postcopy() && s
->postcopy_after_devices
;
1324 bool migration_in_incoming_postcopy(void)
1326 PostcopyState ps
= postcopy_state_get();
1328 return ps
>= POSTCOPY_INCOMING_DISCARD
&& ps
< POSTCOPY_INCOMING_END
;
1331 bool migration_incoming_postcopy_advised(void)
1333 PostcopyState ps
= postcopy_state_get();
1335 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
1338 bool migration_in_bg_snapshot(void)
1340 MigrationState
*s
= migrate_get_current();
1342 return migrate_background_snapshot() &&
1343 migration_is_setup_or_active(s
->state
);
1346 bool migration_is_idle(void)
1348 MigrationState
*s
= current_migration
;
1355 case MIGRATION_STATUS_NONE
:
1356 case MIGRATION_STATUS_CANCELLED
:
1357 case MIGRATION_STATUS_COMPLETED
:
1358 case MIGRATION_STATUS_FAILED
:
1360 case MIGRATION_STATUS_SETUP
:
1361 case MIGRATION_STATUS_CANCELLING
:
1362 case MIGRATION_STATUS_ACTIVE
:
1363 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1364 case MIGRATION_STATUS_COLO
:
1365 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1366 case MIGRATION_STATUS_DEVICE
:
1367 case MIGRATION_STATUS_WAIT_UNPLUG
:
1369 case MIGRATION_STATUS__MAX
:
1370 g_assert_not_reached();
1376 bool migration_is_active(MigrationState
*s
)
1378 return (s
->state
== MIGRATION_STATUS_ACTIVE
||
1379 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1382 void migrate_init(MigrationState
*s
)
1385 * Reinitialise all migration state, except
1386 * parameters/capabilities that the user set, and
1391 s
->to_dst_file
= NULL
;
1392 s
->state
= MIGRATION_STATUS_NONE
;
1393 s
->rp_state
.from_dst_file
= NULL
;
1394 s
->rp_state
.error
= false;
1396 s
->pages_per_second
= 0.0;
1398 s
->expected_downtime
= 0;
1400 s
->start_postcopy
= false;
1401 s
->postcopy_after_devices
= false;
1402 s
->migration_thread_running
= false;
1403 error_free(s
->error
);
1407 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1409 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1411 s
->vm_old_state
= -1;
1412 s
->iteration_initial_bytes
= 0;
1413 s
->threshold_size
= 0;
1414 s
->switchover_acked
= false;
1417 int migrate_add_blocker_internal(Error
*reason
, Error
**errp
)
1419 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1420 if (runstate_check(RUN_STATE_SAVE_VM
) || !migration_is_idle()) {
1421 error_propagate_prepend(errp
, error_copy(reason
),
1422 "disallowing migration blocker "
1423 "(migration/snapshot in progress) for: ");
1427 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
1431 int migrate_add_blocker(Error
*reason
, Error
**errp
)
1433 if (only_migratable
) {
1434 error_propagate_prepend(errp
, error_copy(reason
),
1435 "disallowing migration blocker "
1436 "(--only-migratable) for: ");
1440 return migrate_add_blocker_internal(reason
, errp
);
1443 void migrate_del_blocker(Error
*reason
)
1445 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
1448 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
1450 Error
*local_err
= NULL
;
1451 static bool once
= true;
1454 error_setg(errp
, "The incoming migration has already been started");
1457 if (!runstate_check(RUN_STATE_INMIGRATE
)) {
1458 error_setg(errp
, "'-incoming' was not specified on the command line");
1462 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1466 qemu_start_incoming_migration(uri
, &local_err
);
1469 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1470 error_propagate(errp
, local_err
);
1477 void qmp_migrate_recover(const char *uri
, Error
**errp
)
1479 MigrationIncomingState
*mis
= migration_incoming_get_current();
1482 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1483 * callers (no one should ignore a recover failure); if there is, it's a
1484 * programming error.
1488 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1489 error_setg(errp
, "Migrate recover can only be run "
1490 "when postcopy is paused.");
1494 /* If there's an existing transport, release it */
1495 migration_incoming_transport_cleanup(mis
);
1498 * Note that this call will never start a real migration; it will
1499 * only re-setup the migration stream and poke existing migration
1500 * to continue using that newly established channel.
1502 qemu_start_incoming_migration(uri
, errp
);
1505 void qmp_migrate_pause(Error
**errp
)
1507 MigrationState
*ms
= migrate_get_current();
1508 MigrationIncomingState
*mis
= migration_incoming_get_current();
1511 if (ms
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1512 /* Source side, during postcopy */
1513 qemu_mutex_lock(&ms
->qemu_file_lock
);
1514 ret
= qemu_file_shutdown(ms
->to_dst_file
);
1515 qemu_mutex_unlock(&ms
->qemu_file_lock
);
1517 error_setg(errp
, "Failed to pause source migration");
1522 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1523 ret
= qemu_file_shutdown(mis
->from_src_file
);
1525 error_setg(errp
, "Failed to pause destination migration");
1530 error_setg(errp
, "migrate-pause is currently only supported "
1531 "during postcopy-active state");
1534 bool migration_is_blocked(Error
**errp
)
1536 if (qemu_savevm_state_blocked(errp
)) {
1540 if (migration_blockers
) {
1541 error_propagate(errp
, error_copy(migration_blockers
->data
));
1548 /* Returns true if continue to migrate, or false if error detected */
1549 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1550 bool resume
, Error
**errp
)
1552 Error
*local_err
= NULL
;
1555 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1556 error_setg(errp
, "Cannot resume if there is no "
1557 "paused migration");
1562 * Postcopy recovery won't work well with release-ram
1563 * capability since release-ram will drop the page buffer as
1564 * long as the page is put into the send buffer. So if there
1565 * is a network failure happened, any page buffers that have
1566 * not yet reached the destination VM but have already been
1567 * sent from the source VM will be lost forever. Let's refuse
1568 * the client from resuming such a postcopy migration.
1569 * Luckily release-ram was designed to only be used when src
1570 * and destination VMs are on the same host, so it should be
1573 if (migrate_release_ram()) {
1574 error_setg(errp
, "Postcopy recovery cannot work "
1575 "when release-ram capability is set");
1579 /* This is a resume, skip init status */
1583 if (migration_is_running(s
->state
)) {
1584 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1588 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1589 error_setg(errp
, "Guest is waiting for an incoming migration");
1593 if (runstate_check(RUN_STATE_POSTMIGRATE
)) {
1594 error_setg(errp
, "Can't migrate the vm that was paused due to "
1595 "previous migration");
1599 if (migration_is_blocked(errp
)) {
1603 if (blk
|| blk_inc
) {
1604 if (migrate_colo()) {
1605 error_setg(errp
, "No disk migration is required in COLO mode");
1608 if (migrate_block() || migrate_block_incremental()) {
1609 error_setg(errp
, "Command options are incompatible with "
1610 "current migration capabilities");
1613 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK
, true, &local_err
)) {
1614 error_propagate(errp
, local_err
);
1617 s
->must_remove_block_options
= true;
1621 migrate_set_block_incremental(true);
1626 * set mig_stats compression_counters memory to zero for a
1629 memset(&mig_stats
, 0, sizeof(mig_stats
));
1630 memset(&compression_counters
, 0, sizeof(compression_counters
));
1631 reset_vfio_bytes_transferred();
1636 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1637 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1638 bool has_resume
, bool resume
, Error
**errp
)
1640 bool resume_requested
;
1641 Error
*local_err
= NULL
;
1642 MigrationState
*s
= migrate_get_current();
1643 const char *p
= NULL
;
1645 /* URI is not suitable for migration? */
1646 if (!migration_channels_and_uri_compatible(uri
, errp
)) {
1650 resume_requested
= has_resume
&& resume
;
1651 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
1652 resume_requested
, errp
)) {
1653 /* Error detected, put into errp */
1657 if (!resume_requested
) {
1658 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1663 if (strstart(uri
, "tcp:", &p
) ||
1664 strstart(uri
, "unix:", NULL
) ||
1665 strstart(uri
, "vsock:", NULL
)) {
1666 socket_start_outgoing_migration(s
, p
? p
: uri
, &local_err
);
1668 } else if (strstart(uri
, "rdma:", &p
)) {
1669 rdma_start_outgoing_migration(s
, p
, &local_err
);
1671 } else if (strstart(uri
, "exec:", &p
)) {
1672 exec_start_outgoing_migration(s
, p
, &local_err
);
1673 } else if (strstart(uri
, "fd:", &p
)) {
1674 fd_start_outgoing_migration(s
, p
, &local_err
);
1676 if (!resume_requested
) {
1677 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1679 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1680 "a valid migration protocol");
1681 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1682 MIGRATION_STATUS_FAILED
);
1683 block_cleanup_parameters();
1688 if (!resume_requested
) {
1689 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1691 migrate_fd_error(s
, local_err
);
1692 error_propagate(errp
, local_err
);
1697 void qmp_migrate_cancel(Error
**errp
)
1699 migration_cancel(NULL
);
1702 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
1704 MigrationState
*s
= migrate_get_current();
1705 if (s
->state
!= state
) {
1706 error_setg(errp
, "Migration not in expected state: %s",
1707 MigrationStatus_str(s
->state
));
1710 qemu_sem_post(&s
->pause_sem
);
1713 /* migration thread support */
1715 * Something bad happened to the RP stream, mark an error
1716 * The caller shall print or trace something to indicate why
1718 static void mark_source_rp_bad(MigrationState
*s
)
1720 s
->rp_state
.error
= true;
1723 static struct rp_cmd_args
{
1724 ssize_t len
; /* -1 = variable */
1727 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1728 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1729 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1730 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1731 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1732 [MIG_RP_MSG_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
1733 [MIG_RP_MSG_RESUME_ACK
] = { .len
= 4, .name
= "RESUME_ACK" },
1734 [MIG_RP_MSG_SWITCHOVER_ACK
] = { .len
= 0, .name
= "SWITCHOVER_ACK" },
1735 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1739 * Process a request for pages received on the return path,
1740 * We're allowed to send more than requested (e.g. to round to our page size)
1741 * and we don't need to send pages that have already been sent.
1743 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1744 ram_addr_t start
, size_t len
)
1746 long our_host_ps
= qemu_real_host_page_size();
1748 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1751 * Since we currently insist on matching page sizes, just sanity check
1752 * we're being asked for whole host pages.
1754 if (!QEMU_IS_ALIGNED(start
, our_host_ps
) ||
1755 !QEMU_IS_ALIGNED(len
, our_host_ps
)) {
1756 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1757 " len: %zd", __func__
, start
, len
);
1758 mark_source_rp_bad(ms
);
1762 if (ram_save_queue_pages(rbname
, start
, len
)) {
1763 mark_source_rp_bad(ms
);
1767 /* Return true to retry, false to quit */
1768 static bool postcopy_pause_return_path_thread(MigrationState
*s
)
1770 trace_postcopy_pause_return_path();
1772 qemu_sem_wait(&s
->postcopy_pause_rp_sem
);
1774 trace_postcopy_pause_return_path_continued();
1779 static int migrate_handle_rp_recv_bitmap(MigrationState
*s
, char *block_name
)
1781 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
1784 error_report("%s: invalid block name '%s'", __func__
, block_name
);
1788 /* Fetch the received bitmap and refresh the dirty bitmap */
1789 return ram_dirty_bitmap_reload(s
, block
);
1792 static int migrate_handle_rp_resume_ack(MigrationState
*s
, uint32_t value
)
1794 trace_source_return_path_thread_resume_ack(value
);
1796 if (value
!= MIGRATION_RESUME_ACK_VALUE
) {
1797 error_report("%s: illegal resume_ack value %"PRIu32
,
1802 /* Now both sides are active. */
1803 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
1804 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1806 /* Notify send thread that time to continue send pages */
1807 qemu_sem_post(&s
->rp_state
.rp_sem
);
1813 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
1814 * existed) in a safe way.
1816 static void migration_release_dst_files(MigrationState
*ms
)
1820 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
1822 * Reset the from_dst_file pointer first before releasing it, as we
1823 * can't block within lock section
1825 file
= ms
->rp_state
.from_dst_file
;
1826 ms
->rp_state
.from_dst_file
= NULL
;
1830 * Do the same to postcopy fast path socket too if there is. No
1831 * locking needed because this qemufile should only be managed by
1832 * return path thread.
1834 if (ms
->postcopy_qemufile_src
) {
1835 migration_ioc_unregister_yank_from_file(ms
->postcopy_qemufile_src
);
1836 qemu_file_shutdown(ms
->postcopy_qemufile_src
);
1837 qemu_fclose(ms
->postcopy_qemufile_src
);
1838 ms
->postcopy_qemufile_src
= NULL
;
1845 * Handles messages sent on the return path towards the source VM
1848 static void *source_return_path_thread(void *opaque
)
1850 MigrationState
*ms
= opaque
;
1851 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1852 uint16_t header_len
, header_type
;
1854 uint32_t tmp32
, sibling_error
;
1855 ram_addr_t start
= 0; /* =0 to silence warning */
1856 size_t len
= 0, expected_len
;
1859 trace_source_return_path_thread_entry();
1860 rcu_register_thread();
1863 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1864 migration_is_setup_or_active(ms
->state
)) {
1865 trace_source_return_path_thread_loop_top();
1866 header_type
= qemu_get_be16(rp
);
1867 header_len
= qemu_get_be16(rp
);
1869 if (qemu_file_get_error(rp
)) {
1870 mark_source_rp_bad(ms
);
1874 if (header_type
>= MIG_RP_MSG_MAX
||
1875 header_type
== MIG_RP_MSG_INVALID
) {
1876 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1877 header_type
, header_len
);
1878 mark_source_rp_bad(ms
);
1882 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1883 header_len
!= rp_cmd_args
[header_type
].len
) ||
1884 header_len
> sizeof(buf
)) {
1885 error_report("RP: Received '%s' message (0x%04x) with"
1886 "incorrect length %d expecting %zu",
1887 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1888 (size_t)rp_cmd_args
[header_type
].len
);
1889 mark_source_rp_bad(ms
);
1893 /* We know we've got a valid header by this point */
1894 res
= qemu_get_buffer(rp
, buf
, header_len
);
1895 if (res
!= header_len
) {
1896 error_report("RP: Failed reading data for message 0x%04x"
1897 " read %d expected %d",
1898 header_type
, res
, header_len
);
1899 mark_source_rp_bad(ms
);
1903 /* OK, we have the message and the data */
1904 switch (header_type
) {
1905 case MIG_RP_MSG_SHUT
:
1906 sibling_error
= ldl_be_p(buf
);
1907 trace_source_return_path_thread_shut(sibling_error
);
1908 if (sibling_error
) {
1909 error_report("RP: Sibling indicated error %d", sibling_error
);
1910 mark_source_rp_bad(ms
);
1913 * We'll let the main thread deal with closing the RP
1914 * we could do a shutdown(2) on it, but we're the only user
1915 * anyway, so there's nothing gained.
1919 case MIG_RP_MSG_PONG
:
1920 tmp32
= ldl_be_p(buf
);
1921 trace_source_return_path_thread_pong(tmp32
);
1922 qemu_sem_post(&ms
->rp_state
.rp_pong_acks
);
1925 case MIG_RP_MSG_REQ_PAGES
:
1926 start
= ldq_be_p(buf
);
1927 len
= ldl_be_p(buf
+ 8);
1928 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1931 case MIG_RP_MSG_REQ_PAGES_ID
:
1932 expected_len
= 12 + 1; /* header + termination */
1934 if (header_len
>= expected_len
) {
1935 start
= ldq_be_p(buf
);
1936 len
= ldl_be_p(buf
+ 8);
1937 /* Now we expect an idstr */
1938 tmp32
= buf
[12]; /* Length of the following idstr */
1939 buf
[13 + tmp32
] = '\0';
1940 expected_len
+= tmp32
;
1942 if (header_len
!= expected_len
) {
1943 error_report("RP: Req_Page_id with length %d expecting %zd",
1944 header_len
, expected_len
);
1945 mark_source_rp_bad(ms
);
1948 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1951 case MIG_RP_MSG_RECV_BITMAP
:
1952 if (header_len
< 1) {
1953 error_report("%s: missing block name", __func__
);
1954 mark_source_rp_bad(ms
);
1957 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
1958 buf
[buf
[0] + 1] = '\0';
1959 if (migrate_handle_rp_recv_bitmap(ms
, (char *)(buf
+ 1))) {
1960 mark_source_rp_bad(ms
);
1965 case MIG_RP_MSG_RESUME_ACK
:
1966 tmp32
= ldl_be_p(buf
);
1967 if (migrate_handle_rp_resume_ack(ms
, tmp32
)) {
1968 mark_source_rp_bad(ms
);
1973 case MIG_RP_MSG_SWITCHOVER_ACK
:
1974 ms
->switchover_acked
= true;
1975 trace_source_return_path_thread_switchover_acked();
1984 res
= qemu_file_get_error(rp
);
1986 if (res
&& migration_in_postcopy()) {
1988 * Maybe there is something we can do: it looks like a
1989 * network down issue, and we pause for a recovery.
1991 migration_release_dst_files(ms
);
1993 if (postcopy_pause_return_path_thread(ms
)) {
1995 * Reload rp, reset the rest. Referencing it is safe since
1996 * it's reset only by us above, or when migration completes
1998 rp
= ms
->rp_state
.from_dst_file
;
1999 ms
->rp_state
.error
= false;
2004 trace_source_return_path_thread_bad_end();
2005 mark_source_rp_bad(ms
);
2008 trace_source_return_path_thread_end();
2009 migration_release_dst_files(ms
);
2010 rcu_unregister_thread();
2014 static int open_return_path_on_source(MigrationState
*ms
,
2017 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
2018 if (!ms
->rp_state
.from_dst_file
) {
2022 trace_open_return_path_on_source();
2024 if (!create_thread
) {
2029 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2030 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2031 ms
->rp_state
.rp_thread_created
= true;
2033 trace_open_return_path_on_source_continue();
2038 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2039 static int await_return_path_close_on_source(MigrationState
*ms
)
2042 * If this is a normal exit then the destination will send a SHUT and the
2043 * rp_thread will exit, however if there's an error we need to cause
2046 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
2048 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2049 * waiting for the destination.
2051 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2052 mark_source_rp_bad(ms
);
2054 trace_await_return_path_close_on_source_joining();
2055 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2056 ms
->rp_state
.rp_thread_created
= false;
2057 trace_await_return_path_close_on_source_close();
2058 return ms
->rp_state
.error
;
2062 migration_wait_main_channel(MigrationState
*ms
)
2064 /* Wait until one PONG message received */
2065 qemu_sem_wait(&ms
->rp_state
.rp_pong_acks
);
2069 * Switch from normal iteration to postcopy
2070 * Returns non-0 on error
2072 static int postcopy_start(MigrationState
*ms
)
2075 QIOChannelBuffer
*bioc
;
2077 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2078 uint64_t bandwidth
= migrate_max_postcopy_bandwidth();
2079 bool restart_block
= false;
2080 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2082 if (migrate_postcopy_preempt()) {
2083 migration_wait_main_channel(ms
);
2084 if (postcopy_preempt_establish_channel(ms
)) {
2085 migrate_set_state(&ms
->state
, ms
->state
, MIGRATION_STATUS_FAILED
);
2090 if (!migrate_pause_before_switchover()) {
2091 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2092 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2095 trace_postcopy_start();
2096 qemu_mutex_lock_iothread();
2097 trace_postcopy_start_set_run();
2099 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2100 global_state_store();
2101 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2106 ret
= migration_maybe_pause(ms
, &cur_state
,
2107 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2112 ret
= bdrv_inactivate_all();
2116 restart_block
= true;
2119 * Cause any non-postcopiable, but iterative devices to
2120 * send out their final data.
2122 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2125 * in Finish migrate and with the io-lock held everything should
2126 * be quiet, but we've potentially still got dirty pages and we
2127 * need to tell the destination to throw any pages it's already received
2130 if (migrate_postcopy_ram()) {
2131 ram_postcopy_send_discard_bitmap(ms
);
2135 * send rest of state - note things that are doing postcopy
2136 * will notice we're in POSTCOPY_ACTIVE and not actually
2137 * wrap their state up here
2139 migration_rate_set(bandwidth
);
2140 if (migrate_postcopy_ram()) {
2141 /* Ping just for debugging, helps line traces up */
2142 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2146 * While loading the device state we may trigger page transfer
2147 * requests and the fd must be free to process those, and thus
2148 * the destination must read the whole device state off the fd before
2149 * it starts processing it. Unfortunately the ad-hoc migration format
2150 * doesn't allow the destination to know the size to read without fully
2151 * parsing it through each devices load-state code (especially the open
2152 * coded devices that use get/put).
2153 * So we wrap the device state up in a package with a length at the start;
2154 * to do this we use a qemu_buf to hold the whole of the device state.
2156 bioc
= qio_channel_buffer_new(4096);
2157 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2158 fb
= qemu_file_new_output(QIO_CHANNEL(bioc
));
2159 object_unref(OBJECT(bioc
));
2162 * Make sure the receiver can get incoming pages before we send the rest
2165 qemu_savevm_send_postcopy_listen(fb
);
2167 qemu_savevm_state_complete_precopy(fb
, false, false);
2168 if (migrate_postcopy_ram()) {
2169 qemu_savevm_send_ping(fb
, 3);
2172 qemu_savevm_send_postcopy_run(fb
);
2174 /* <><> end of stuff going into the package */
2176 /* Last point of recovery; as soon as we send the package the destination
2177 * can open devices and potentially start running.
2178 * Lets just check again we've not got any errors.
2180 ret
= qemu_file_get_error(ms
->to_dst_file
);
2182 error_report("postcopy_start: Migration stream errored (pre package)");
2186 restart_block
= false;
2188 /* Now send that blob */
2189 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2194 /* Send a notify to give a chance for anything that needs to happen
2195 * at the transition to postcopy and after the device state; in particular
2196 * spice needs to trigger a transition now
2198 ms
->postcopy_after_devices
= true;
2199 notifier_list_notify(&migration_state_notifiers
, ms
);
2201 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
2203 qemu_mutex_unlock_iothread();
2205 if (migrate_postcopy_ram()) {
2207 * Although this ping is just for debug, it could potentially be
2208 * used for getting a better measurement of downtime at the source.
2210 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2213 if (migrate_release_ram()) {
2214 ram_postcopy_migrated_memory_release(ms
);
2217 ret
= qemu_file_get_error(ms
->to_dst_file
);
2219 error_report("postcopy_start: Migration stream errored");
2220 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2221 MIGRATION_STATUS_FAILED
);
2224 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2231 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2232 MIGRATION_STATUS_FAILED
);
2233 if (restart_block
) {
2234 /* A failure happened early enough that we know the destination hasn't
2235 * accessed block devices, so we're safe to recover.
2237 Error
*local_err
= NULL
;
2239 bdrv_activate_all(&local_err
);
2241 error_report_err(local_err
);
2244 qemu_mutex_unlock_iothread();
2249 * migration_maybe_pause: Pause if required to by
2250 * migrate_pause_before_switchover called with the iothread locked
2251 * Returns: 0 on success
2253 static int migration_maybe_pause(MigrationState
*s
,
2254 int *current_active_state
,
2257 if (!migrate_pause_before_switchover()) {
2261 /* Since leaving this state is not atomic with posting the semaphore
2262 * it's possible that someone could have issued multiple migrate_continue
2263 * and the semaphore is incorrectly positive at this point;
2264 * the docs say it's undefined to reinit a semaphore that's already
2265 * init'd, so use timedwait to eat up any existing posts.
2267 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2268 /* This block intentionally left blank */
2272 * If the migration is cancelled when it is in the completion phase,
2273 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2274 * So we don't need to wait a semaphore, otherwise we would always
2275 * wait for the 'pause_sem' semaphore.
2277 if (s
->state
!= MIGRATION_STATUS_CANCELLING
) {
2278 qemu_mutex_unlock_iothread();
2279 migrate_set_state(&s
->state
, *current_active_state
,
2280 MIGRATION_STATUS_PRE_SWITCHOVER
);
2281 qemu_sem_wait(&s
->pause_sem
);
2282 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2284 *current_active_state
= new_state
;
2285 qemu_mutex_lock_iothread();
2288 return s
->state
== new_state
? 0 : -EINVAL
;
2292 * migration_completion: Used by migration_thread when there's not much left.
2293 * The caller 'breaks' the loop when this returns.
2295 * @s: Current migration state
2297 static void migration_completion(MigrationState
*s
)
2300 int current_active_state
= s
->state
;
2302 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2303 qemu_mutex_lock_iothread();
2304 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2305 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2307 s
->vm_old_state
= runstate_get();
2308 global_state_store();
2310 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2311 trace_migration_completion_vm_stop(ret
);
2313 ret
= migration_maybe_pause(s
, ¤t_active_state
,
2314 MIGRATION_STATUS_DEVICE
);
2318 * Inactivate disks except in COLO, and track that we
2319 * have done so in order to remember to reactivate
2320 * them if migration fails or is cancelled.
2322 s
->block_inactive
= !migrate_colo();
2323 migration_rate_set(RATE_LIMIT_DISABLED
);
2324 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2328 qemu_mutex_unlock_iothread();
2333 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2334 trace_migration_completion_postcopy_end();
2336 qemu_mutex_lock_iothread();
2337 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2338 qemu_mutex_unlock_iothread();
2341 * Shutdown the postcopy fast path thread. This is only needed
2342 * when dest QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need
2345 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
2346 postcopy_preempt_shutdown_file(s
);
2349 trace_migration_completion_postcopy_end_after_complete();
2355 * If rp was opened we must clean up the thread before
2356 * cleaning everything else up (since if there are no failures
2357 * it will wait for the destination to send it's status in
2360 if (s
->rp_state
.rp_thread_created
) {
2362 trace_migration_return_path_end_before();
2363 rp_error
= await_return_path_close_on_source(s
);
2364 trace_migration_return_path_end_after(rp_error
);
2370 if (qemu_file_get_error(s
->to_dst_file
)) {
2371 trace_migration_completion_file_err();
2375 if (migrate_colo() && s
->state
== MIGRATION_STATUS_ACTIVE
) {
2376 /* COLO does not support postcopy */
2377 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
2378 MIGRATION_STATUS_COLO
);
2380 migrate_set_state(&s
->state
, current_active_state
,
2381 MIGRATION_STATUS_COMPLETED
);
2387 if (s
->block_inactive
&& (s
->state
== MIGRATION_STATUS_ACTIVE
||
2388 s
->state
== MIGRATION_STATUS_DEVICE
)) {
2390 * If not doing postcopy, vm_start() will be called: let's
2391 * regain control on images.
2393 Error
*local_err
= NULL
;
2395 qemu_mutex_lock_iothread();
2396 bdrv_activate_all(&local_err
);
2398 error_report_err(local_err
);
2400 s
->block_inactive
= false;
2402 qemu_mutex_unlock_iothread();
2405 migrate_set_state(&s
->state
, current_active_state
,
2406 MIGRATION_STATUS_FAILED
);
2410 * bg_migration_completion: Used by bg_migration_thread when after all the
2411 * RAM has been saved. The caller 'breaks' the loop when this returns.
2413 * @s: Current migration state
2415 static void bg_migration_completion(MigrationState
*s
)
2417 int current_active_state
= s
->state
;
2419 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2421 * By this moment we have RAM content saved into the migration stream.
2422 * The next step is to flush the non-RAM content (device state)
2423 * right after the ram content. The device state has been stored into
2424 * the temporary buffer before RAM saving started.
2426 qemu_put_buffer(s
->to_dst_file
, s
->bioc
->data
, s
->bioc
->usage
);
2427 qemu_fflush(s
->to_dst_file
);
2428 } else if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
2432 if (qemu_file_get_error(s
->to_dst_file
)) {
2433 trace_migration_completion_file_err();
2437 migrate_set_state(&s
->state
, current_active_state
,
2438 MIGRATION_STATUS_COMPLETED
);
2442 migrate_set_state(&s
->state
, current_active_state
,
2443 MIGRATION_STATUS_FAILED
);
2446 typedef enum MigThrError
{
2447 /* No error detected */
2448 MIG_THR_ERR_NONE
= 0,
2449 /* Detected error, but resumed successfully */
2450 MIG_THR_ERR_RECOVERED
= 1,
2451 /* Detected fatal error, need to exit */
2452 MIG_THR_ERR_FATAL
= 2,
2455 static int postcopy_resume_handshake(MigrationState
*s
)
2457 qemu_savevm_send_postcopy_resume(s
->to_dst_file
);
2459 while (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2460 qemu_sem_wait(&s
->rp_state
.rp_sem
);
2463 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2470 /* Return zero if success, or <0 for error */
2471 static int postcopy_do_resume(MigrationState
*s
)
2476 * Call all the resume_prepare() hooks, so that modules can be
2477 * ready for the migration resume.
2479 ret
= qemu_savevm_state_resume_prepare(s
);
2481 error_report("%s: resume_prepare() failure detected: %d",
2487 * If preempt is enabled, re-establish the preempt channel. Note that
2488 * we do it after resume prepare to make sure the main channel will be
2489 * created before the preempt channel. E.g. with weak network, the
2490 * dest QEMU may get messed up with the preempt and main channels on
2491 * the order of connection setup. This guarantees the correct order.
2493 ret
= postcopy_preempt_establish_channel(s
);
2495 error_report("%s: postcopy_preempt_establish_channel(): %d",
2501 * Last handshake with destination on the resume (destination will
2502 * switch to postcopy-active afterwards)
2504 ret
= postcopy_resume_handshake(s
);
2506 error_report("%s: handshake failed: %d", __func__
, ret
);
2514 * We don't return until we are in a safe state to continue current
2515 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2516 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2518 static MigThrError
postcopy_pause(MigrationState
*s
)
2520 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2526 * Current channel is possibly broken. Release it. Note that this is
2527 * guaranteed even without lock because to_dst_file should only be
2528 * modified by the migration thread. That also guarantees that the
2529 * unregister of yank is safe too without the lock. It should be safe
2530 * even to be within the qemu_file_lock, but we didn't do that to avoid
2531 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2532 * the qemu_file_lock critical section as small as possible.
2534 assert(s
->to_dst_file
);
2535 migration_ioc_unregister_yank_from_file(s
->to_dst_file
);
2536 qemu_mutex_lock(&s
->qemu_file_lock
);
2537 file
= s
->to_dst_file
;
2538 s
->to_dst_file
= NULL
;
2539 qemu_mutex_unlock(&s
->qemu_file_lock
);
2541 qemu_file_shutdown(file
);
2544 migrate_set_state(&s
->state
, s
->state
,
2545 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2547 error_report("Detected IO failure for postcopy. "
2548 "Migration paused.");
2551 * We wait until things fixed up. Then someone will setup the
2552 * status back for us.
2554 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2555 qemu_sem_wait(&s
->postcopy_pause_sem
);
2558 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2559 /* Woken up by a recover procedure. Give it a shot */
2562 * Firstly, let's wake up the return path now, with a new
2563 * return path channel.
2565 qemu_sem_post(&s
->postcopy_pause_rp_sem
);
2567 /* Do the resume logic */
2568 if (postcopy_do_resume(s
) == 0) {
2569 /* Let's continue! */
2570 trace_postcopy_pause_continued();
2571 return MIG_THR_ERR_RECOVERED
;
2574 * Something wrong happened during the recovery, let's
2575 * pause again. Pause is always better than throwing
2581 /* This is not right... Time to quit. */
2582 return MIG_THR_ERR_FATAL
;
2587 static MigThrError
migration_detect_error(MigrationState
*s
)
2590 int state
= s
->state
;
2591 Error
*local_error
= NULL
;
2593 if (state
== MIGRATION_STATUS_CANCELLING
||
2594 state
== MIGRATION_STATUS_CANCELLED
) {
2595 /* End the migration, but don't set the state to failed */
2596 return MIG_THR_ERR_FATAL
;
2600 * Try to detect any file errors. Note that postcopy_qemufile_src will
2601 * be NULL when postcopy preempt is not enabled.
2603 ret
= qemu_file_get_error_obj_any(s
->to_dst_file
,
2604 s
->postcopy_qemufile_src
,
2607 /* Everything is fine */
2608 assert(!local_error
);
2609 return MIG_THR_ERR_NONE
;
2613 migrate_set_error(s
, local_error
);
2614 error_free(local_error
);
2617 if (state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
) {
2619 * For postcopy, we allow the network to be down for a
2620 * while. After that, it can be continued by a
2623 return postcopy_pause(s
);
2626 * For precopy (or postcopy with error outside IO), we fail
2629 migrate_set_state(&s
->state
, state
, MIGRATION_STATUS_FAILED
);
2630 trace_migration_thread_file_err();
2632 /* Time to stop the migration, now. */
2633 return MIG_THR_ERR_FATAL
;
2637 static void migration_calculate_complete(MigrationState
*s
)
2639 uint64_t bytes
= migration_transferred_bytes(s
->to_dst_file
);
2640 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2641 int64_t transfer_time
;
2643 s
->total_time
= end_time
- s
->start_time
;
2646 * It's still not set, so we are precopy migration. For
2647 * postcopy, downtime is calculated during postcopy_start().
2649 s
->downtime
= end_time
- s
->downtime_start
;
2652 transfer_time
= s
->total_time
- s
->setup_time
;
2653 if (transfer_time
) {
2654 s
->mbps
= ((double) bytes
* 8.0) / transfer_time
/ 1000;
2658 static void update_iteration_initial_status(MigrationState
*s
)
2661 * Update these three fields at the same time to avoid mismatch info lead
2662 * wrong speed calculation.
2664 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2665 s
->iteration_initial_bytes
= migration_transferred_bytes(s
->to_dst_file
);
2666 s
->iteration_initial_pages
= ram_get_total_transferred_pages();
2669 static void migration_update_counters(MigrationState
*s
,
2670 int64_t current_time
)
2672 uint64_t transferred
, transferred_pages
, time_spent
;
2673 uint64_t current_bytes
; /* bytes transferred since the beginning */
2676 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
2680 current_bytes
= migration_transferred_bytes(s
->to_dst_file
);
2681 transferred
= current_bytes
- s
->iteration_initial_bytes
;
2682 time_spent
= current_time
- s
->iteration_start_time
;
2683 bandwidth
= (double)transferred
/ time_spent
;
2684 s
->threshold_size
= bandwidth
* migrate_downtime_limit();
2686 s
->mbps
= (((double) transferred
* 8.0) /
2687 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
2689 transferred_pages
= ram_get_total_transferred_pages() -
2690 s
->iteration_initial_pages
;
2691 s
->pages_per_second
= (double) transferred_pages
/
2692 (((double) time_spent
/ 1000.0));
2695 * if we haven't sent anything, we don't want to
2696 * recalculate. 10000 is a small enough number for our purposes
2698 if (stat64_get(&mig_stats
.dirty_pages_rate
) &&
2699 transferred
> 10000) {
2700 s
->expected_downtime
=
2701 stat64_get(&mig_stats
.dirty_bytes_last_sync
) / bandwidth
;
2704 migration_rate_reset(s
->to_dst_file
);
2706 update_iteration_initial_status(s
);
2708 trace_migrate_transferred(transferred
, time_spent
,
2709 bandwidth
, s
->threshold_size
);
2712 static bool migration_can_switchover(MigrationState
*s
)
2714 if (!migrate_switchover_ack()) {
2718 /* No reason to wait for switchover ACK if VM is stopped */
2719 if (!runstate_is_running()) {
2723 return s
->switchover_acked
;
2726 /* Migration thread iteration status */
2728 MIG_ITERATE_RESUME
, /* Resume current iteration */
2729 MIG_ITERATE_SKIP
, /* Skip current iteration */
2730 MIG_ITERATE_BREAK
, /* Break the loop */
2734 * Return true if continue to the next iteration directly, false
2737 static MigIterateState
migration_iteration_run(MigrationState
*s
)
2739 uint64_t must_precopy
, can_postcopy
;
2740 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
2741 bool can_switchover
= migration_can_switchover(s
);
2743 qemu_savevm_state_pending_estimate(&must_precopy
, &can_postcopy
);
2744 uint64_t pending_size
= must_precopy
+ can_postcopy
;
2746 trace_migrate_pending_estimate(pending_size
, must_precopy
, can_postcopy
);
2748 if (must_precopy
<= s
->threshold_size
) {
2749 qemu_savevm_state_pending_exact(&must_precopy
, &can_postcopy
);
2750 pending_size
= must_precopy
+ can_postcopy
;
2751 trace_migrate_pending_exact(pending_size
, must_precopy
, can_postcopy
);
2754 if ((!pending_size
|| pending_size
< s
->threshold_size
) && can_switchover
) {
2755 trace_migration_thread_low_pending(pending_size
);
2756 migration_completion(s
);
2757 return MIG_ITERATE_BREAK
;
2760 /* Still a significant amount to transfer */
2761 if (!in_postcopy
&& must_precopy
<= s
->threshold_size
&& can_switchover
&&
2762 qatomic_read(&s
->start_postcopy
)) {
2763 if (postcopy_start(s
)) {
2764 error_report("%s: postcopy failed to start", __func__
);
2766 return MIG_ITERATE_SKIP
;
2769 /* Just another iteration step */
2770 qemu_savevm_state_iterate(s
->to_dst_file
, in_postcopy
);
2771 return MIG_ITERATE_RESUME
;
2774 static void migration_iteration_finish(MigrationState
*s
)
2776 /* If we enabled cpu throttling for auto-converge, turn it off. */
2777 cpu_throttle_stop();
2779 qemu_mutex_lock_iothread();
2781 case MIGRATION_STATUS_COMPLETED
:
2782 migration_calculate_complete(s
);
2783 runstate_set(RUN_STATE_POSTMIGRATE
);
2785 case MIGRATION_STATUS_COLO
:
2786 assert(migrate_colo());
2787 migrate_start_colo_process(s
);
2788 s
->vm_old_state
= RUN_STATE_RUNNING
;
2790 case MIGRATION_STATUS_FAILED
:
2791 case MIGRATION_STATUS_CANCELLED
:
2792 case MIGRATION_STATUS_CANCELLING
:
2793 if (s
->vm_old_state
== RUN_STATE_RUNNING
) {
2794 if (!runstate_check(RUN_STATE_SHUTDOWN
)) {
2798 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
2799 runstate_set(s
->vm_old_state
);
2805 /* Should not reach here, but if so, forgive the VM. */
2806 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2809 migrate_fd_cleanup_schedule(s
);
2810 qemu_mutex_unlock_iothread();
2813 static void bg_migration_iteration_finish(MigrationState
*s
)
2816 * Stop tracking RAM writes - un-protect memory, un-register UFFD
2817 * memory ranges, flush kernel wait queues and wake up threads
2818 * waiting for write fault to be resolved.
2820 ram_write_tracking_stop();
2822 qemu_mutex_lock_iothread();
2824 case MIGRATION_STATUS_COMPLETED
:
2825 migration_calculate_complete(s
);
2828 case MIGRATION_STATUS_ACTIVE
:
2829 case MIGRATION_STATUS_FAILED
:
2830 case MIGRATION_STATUS_CANCELLED
:
2831 case MIGRATION_STATUS_CANCELLING
:
2835 /* Should not reach here, but if so, forgive the VM. */
2836 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2840 migrate_fd_cleanup_schedule(s
);
2841 qemu_mutex_unlock_iothread();
2845 * Return true if continue to the next iteration directly, false
2848 static MigIterateState
bg_migration_iteration_run(MigrationState
*s
)
2852 res
= qemu_savevm_state_iterate(s
->to_dst_file
, false);
2854 bg_migration_completion(s
);
2855 return MIG_ITERATE_BREAK
;
2858 return MIG_ITERATE_RESUME
;
2861 void migration_make_urgent_request(void)
2863 qemu_sem_post(&migrate_get_current()->rate_limit_sem
);
2866 void migration_consume_urgent_request(void)
2868 qemu_sem_wait(&migrate_get_current()->rate_limit_sem
);
2871 /* Returns true if the rate limiting was broken by an urgent request */
2872 bool migration_rate_limit(void)
2874 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2875 MigrationState
*s
= migrate_get_current();
2877 bool urgent
= false;
2878 migration_update_counters(s
, now
);
2879 if (migration_rate_exceeded(s
->to_dst_file
)) {
2881 if (qemu_file_get_error(s
->to_dst_file
)) {
2885 * Wait for a delay to do rate limiting OR
2886 * something urgent to post the semaphore.
2888 int ms
= s
->iteration_start_time
+ BUFFER_DELAY
- now
;
2889 trace_migration_rate_limit_pre(ms
);
2890 if (qemu_sem_timedwait(&s
->rate_limit_sem
, ms
) == 0) {
2892 * We were woken by one or more urgent things but
2893 * the timedwait will have consumed one of them.
2894 * The service routine for the urgent wake will dec
2895 * the semaphore itself for each item it consumes,
2896 * so add this one we just eat back.
2898 qemu_sem_post(&s
->rate_limit_sem
);
2901 trace_migration_rate_limit_post(urgent
);
2907 * if failover devices are present, wait they are completely
2911 static void qemu_savevm_wait_unplug(MigrationState
*s
, int old_state
,
2914 if (qemu_savevm_state_guest_unplug_pending()) {
2915 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_WAIT_UNPLUG
);
2917 while (s
->state
== MIGRATION_STATUS_WAIT_UNPLUG
&&
2918 qemu_savevm_state_guest_unplug_pending()) {
2919 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
2921 if (s
->state
!= MIGRATION_STATUS_WAIT_UNPLUG
) {
2922 int timeout
= 120; /* 30 seconds */
2924 * migration has been canceled
2925 * but as we have started an unplug we must wait the end
2926 * to be able to plug back the card
2928 while (timeout
-- && qemu_savevm_state_guest_unplug_pending()) {
2929 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
2931 if (qemu_savevm_state_guest_unplug_pending() &&
2933 warn_report("migration: partially unplugged device on "
2938 migrate_set_state(&s
->state
, MIGRATION_STATUS_WAIT_UNPLUG
, new_state
);
2940 migrate_set_state(&s
->state
, old_state
, new_state
);
2945 * Master migration thread on the source VM.
2946 * It drives the migration and pumps the data down the outgoing channel.
2948 static void *migration_thread(void *opaque
)
2950 MigrationState
*s
= opaque
;
2951 MigrationThread
*thread
= NULL
;
2952 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
2953 MigThrError thr_error
;
2954 bool urgent
= false;
2956 thread
= MigrationThreadAdd("live_migration", qemu_get_thread_id());
2958 rcu_register_thread();
2960 object_ref(OBJECT(s
));
2961 update_iteration_initial_status(s
);
2963 qemu_savevm_state_header(s
->to_dst_file
);
2966 * If we opened the return path, we need to make sure dst has it
2969 if (s
->rp_state
.rp_thread_created
) {
2970 /* Now tell the dest that it should open its end so it can reply */
2971 qemu_savevm_send_open_return_path(s
->to_dst_file
);
2973 /* And do a ping that will make stuff easier to debug */
2974 qemu_savevm_send_ping(s
->to_dst_file
, 1);
2977 if (migrate_postcopy()) {
2979 * Tell the destination that we *might* want to do postcopy later;
2980 * if the other end can't do postcopy it should fail now, nice and
2983 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
2986 if (migrate_colo()) {
2987 /* Notify migration destination that we enable COLO */
2988 qemu_savevm_send_colo_enable(s
->to_dst_file
);
2991 qemu_savevm_state_setup(s
->to_dst_file
);
2993 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
2994 MIGRATION_STATUS_ACTIVE
);
2996 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
2998 trace_migration_thread_setup_complete();
3000 while (migration_is_active(s
)) {
3001 if (urgent
|| !migration_rate_exceeded(s
->to_dst_file
)) {
3002 MigIterateState iter_state
= migration_iteration_run(s
);
3003 if (iter_state
== MIG_ITERATE_SKIP
) {
3005 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3011 * Try to detect any kind of failures, and see whether we
3012 * should stop the migration now.
3014 thr_error
= migration_detect_error(s
);
3015 if (thr_error
== MIG_THR_ERR_FATAL
) {
3016 /* Stop migration */
3018 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
3020 * Just recovered from a e.g. network failure, reset all
3021 * the local variables. This is important to avoid
3022 * breaking transferred_bytes and bandwidth calculation
3024 update_iteration_initial_status(s
);
3027 urgent
= migration_rate_limit();
3030 trace_migration_thread_after_loop();
3031 migration_iteration_finish(s
);
3032 object_unref(OBJECT(s
));
3033 rcu_unregister_thread();
3034 MigrationThreadDel(thread
);
3038 static void bg_migration_vm_start_bh(void *opaque
)
3040 MigrationState
*s
= opaque
;
3042 qemu_bh_delete(s
->vm_start_bh
);
3043 s
->vm_start_bh
= NULL
;
3046 s
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - s
->downtime_start
;
3050 * Background snapshot thread, based on live migration code.
3051 * This is an alternative implementation of live migration mechanism
3052 * introduced specifically to support background snapshots.
3054 * It takes advantage of userfault_fd write protection mechanism introduced
3055 * in v5.7 kernel. Compared to existing dirty page logging migration much
3056 * lesser stream traffic is produced resulting in smaller snapshot images,
3057 * simply cause of no page duplicates can get into the stream.
3059 * Another key point is that generated vmstate stream reflects machine state
3060 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3061 * mechanism, which effectively results in that saved snapshot is the state of VM
3062 * at the end of the process.
3064 static void *bg_migration_thread(void *opaque
)
3066 MigrationState
*s
= opaque
;
3067 int64_t setup_start
;
3068 MigThrError thr_error
;
3070 bool early_fail
= true;
3072 rcu_register_thread();
3073 object_ref(OBJECT(s
));
3075 migration_rate_set(RATE_LIMIT_DISABLED
);
3077 setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3079 * We want to save vmstate for the moment when migration has been
3080 * initiated but also we want to save RAM content while VM is running.
3081 * The RAM content should appear first in the vmstate. So, we first
3082 * stash the non-RAM part of the vmstate to the temporary buffer,
3083 * then write RAM part of the vmstate to the migration stream
3084 * with vCPUs running and, finally, write stashed non-RAM part of
3085 * the vmstate from the buffer to the migration stream.
3087 s
->bioc
= qio_channel_buffer_new(512 * 1024);
3088 qio_channel_set_name(QIO_CHANNEL(s
->bioc
), "vmstate-buffer");
3089 fb
= qemu_file_new_output(QIO_CHANNEL(s
->bioc
));
3090 object_unref(OBJECT(s
->bioc
));
3092 update_iteration_initial_status(s
);
3095 * Prepare for tracking memory writes with UFFD-WP - populate
3096 * RAM pages before protecting.
3099 ram_write_tracking_prepare();
3102 qemu_savevm_state_header(s
->to_dst_file
);
3103 qemu_savevm_state_setup(s
->to_dst_file
);
3105 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3106 MIGRATION_STATUS_ACTIVE
);
3108 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3110 trace_migration_thread_setup_complete();
3111 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3113 qemu_mutex_lock_iothread();
3116 * If VM is currently in suspended state, then, to make a valid runstate
3117 * transition in vm_stop_force_state() we need to wakeup it up.
3119 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
3120 s
->vm_old_state
= runstate_get();
3122 global_state_store();
3123 /* Forcibly stop VM before saving state of vCPUs and devices */
3124 if (vm_stop_force_state(RUN_STATE_PAUSED
)) {
3128 * Put vCPUs in sync with shadow context structures, then
3129 * save their state to channel-buffer along with devices.
3131 cpu_synchronize_all_states();
3132 if (qemu_savevm_state_complete_precopy_non_iterable(fb
, false, false)) {
3136 * Since we are going to get non-iterable state data directly
3137 * from s->bioc->data, explicit flush is needed here.
3141 /* Now initialize UFFD context and start tracking RAM writes */
3142 if (ram_write_tracking_start()) {
3148 * Start VM from BH handler to avoid write-fault lock here.
3149 * UFFD-WP protection for the whole RAM is already enabled so
3150 * calling VM state change notifiers from vm_start() would initiate
3151 * writes to virtio VQs memory which is in write-protected region.
3153 s
->vm_start_bh
= qemu_bh_new(bg_migration_vm_start_bh
, s
);
3154 qemu_bh_schedule(s
->vm_start_bh
);
3156 qemu_mutex_unlock_iothread();
3158 while (migration_is_active(s
)) {
3159 MigIterateState iter_state
= bg_migration_iteration_run(s
);
3160 if (iter_state
== MIG_ITERATE_SKIP
) {
3162 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3167 * Try to detect any kind of failures, and see whether we
3168 * should stop the migration now.
3170 thr_error
= migration_detect_error(s
);
3171 if (thr_error
== MIG_THR_ERR_FATAL
) {
3172 /* Stop migration */
3176 migration_update_counters(s
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
));
3179 trace_migration_thread_after_loop();
3183 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
3184 MIGRATION_STATUS_FAILED
);
3185 qemu_mutex_unlock_iothread();
3188 bg_migration_iteration_finish(s
);
3191 object_unref(OBJECT(s
));
3192 rcu_unregister_thread();
3197 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
3199 Error
*local_err
= NULL
;
3200 uint64_t rate_limit
;
3201 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
3204 * If there's a previous error, free it and prepare for another one.
3205 * Meanwhile if migration completes successfully, there won't have an error
3206 * dumped when calling migrate_fd_cleanup().
3208 migrate_error_free(s
);
3210 s
->expected_downtime
= migrate_downtime_limit();
3212 assert(s
->cleanup_bh
);
3214 assert(!s
->cleanup_bh
);
3215 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup_bh
, s
);
3218 migrate_fd_error(s
, error_in
);
3221 * Don't do cleanup for resume if channel is invalid, but only dump
3222 * the error. We wait for another channel connect from the user.
3223 * The error_report still gives HMP user a hint on what failed.
3224 * It's normally done in migrate_fd_cleanup(), but call it here
3227 error_report_err(error_copy(s
->error
));
3229 migrate_fd_cleanup(s
);
3235 /* This is a resumed migration */
3236 rate_limit
= migrate_max_postcopy_bandwidth();
3238 /* This is a fresh new migration */
3239 rate_limit
= migrate_max_bandwidth();
3241 /* Notify before starting migration thread */
3242 notifier_list_notify(&migration_state_notifiers
, s
);
3245 migration_rate_set(rate_limit
);
3246 qemu_file_set_blocking(s
->to_dst_file
, true);
3249 * Open the return path. For postcopy, it is used exclusively. For
3250 * precopy, only if user specified "return-path" capability would
3251 * QEMU uses the return path.
3253 if (migrate_postcopy_ram() || migrate_return_path()) {
3254 if (open_return_path_on_source(s
, !resume
)) {
3255 error_report("Unable to open return-path for postcopy");
3256 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
3257 migrate_fd_cleanup(s
);
3263 * This needs to be done before resuming a postcopy. Note: for newer
3264 * QEMUs we will delay the channel creation until postcopy_start(), to
3265 * avoid disorder of channel creations.
3267 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
3268 postcopy_preempt_setup(s
);
3272 /* Wakeup the main migration thread to do the recovery */
3273 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
3274 MIGRATION_STATUS_POSTCOPY_RECOVER
);
3275 qemu_sem_post(&s
->postcopy_pause_sem
);
3279 if (multifd_save_setup(&local_err
) != 0) {
3280 error_report_err(local_err
);
3281 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
3282 MIGRATION_STATUS_FAILED
);
3283 migrate_fd_cleanup(s
);
3287 if (migrate_background_snapshot()) {
3288 qemu_thread_create(&s
->thread
, "bg_snapshot",
3289 bg_migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3291 qemu_thread_create(&s
->thread
, "live_migration",
3292 migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3294 s
->migration_thread_running
= true;
3297 static void migration_class_init(ObjectClass
*klass
, void *data
)
3299 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3301 dc
->user_creatable
= false;
3302 device_class_set_props(dc
, migration_properties
);
3305 static void migration_instance_finalize(Object
*obj
)
3307 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3309 qemu_mutex_destroy(&ms
->error_mutex
);
3310 qemu_mutex_destroy(&ms
->qemu_file_lock
);
3311 qemu_sem_destroy(&ms
->wait_unplug_sem
);
3312 qemu_sem_destroy(&ms
->rate_limit_sem
);
3313 qemu_sem_destroy(&ms
->pause_sem
);
3314 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
3315 qemu_sem_destroy(&ms
->postcopy_pause_rp_sem
);
3316 qemu_sem_destroy(&ms
->rp_state
.rp_sem
);
3317 qemu_sem_destroy(&ms
->rp_state
.rp_pong_acks
);
3318 qemu_sem_destroy(&ms
->postcopy_qemufile_src_sem
);
3319 error_free(ms
->error
);
3322 static void migration_instance_init(Object
*obj
)
3324 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3326 ms
->state
= MIGRATION_STATUS_NONE
;
3328 ms
->pages_per_second
= -1;
3329 qemu_sem_init(&ms
->pause_sem
, 0);
3330 qemu_mutex_init(&ms
->error_mutex
);
3332 migrate_params_init(&ms
->parameters
);
3334 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
3335 qemu_sem_init(&ms
->postcopy_pause_rp_sem
, 0);
3336 qemu_sem_init(&ms
->rp_state
.rp_sem
, 0);
3337 qemu_sem_init(&ms
->rp_state
.rp_pong_acks
, 0);
3338 qemu_sem_init(&ms
->rate_limit_sem
, 0);
3339 qemu_sem_init(&ms
->wait_unplug_sem
, 0);
3340 qemu_sem_init(&ms
->postcopy_qemufile_src_sem
, 0);
3341 qemu_mutex_init(&ms
->qemu_file_lock
);
3345 * Return true if check pass, false otherwise. Error will be put
3346 * inside errp if provided.
3348 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
3350 /* Assuming all off */
3351 bool old_caps
[MIGRATION_CAPABILITY__MAX
] = { 0 };
3353 if (!migrate_params_check(&ms
->parameters
, errp
)) {
3357 return migrate_caps_check(old_caps
, ms
->capabilities
, errp
);
3360 static const TypeInfo migration_type
= {
3361 .name
= TYPE_MIGRATION
,
3363 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3364 * not created using qdev_new(), it is not attached to the qdev
3365 * device tree, and it is never realized.
3367 * TODO: Make this TYPE_OBJECT once QOM provides something like
3368 * TYPE_DEVICE's "-global" properties.
3370 .parent
= TYPE_DEVICE
,
3371 .class_init
= migration_class_init
,
3372 .class_size
= sizeof(MigrationClass
),
3373 .instance_size
= sizeof(MigrationState
),
3374 .instance_init
= migration_instance_init
,
3375 .instance_finalize
= migration_instance_finalize
,
3378 static void register_migration_types(void)
3380 type_register_static(&migration_type
);
3383 type_init(register_migration_types
);