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"
70 static NotifierList migration_state_notifiers
=
71 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
73 /* Messages sent on the return path from destination to source */
74 enum mig_rp_message_type
{
75 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
76 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
77 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
79 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
80 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
81 MIG_RP_MSG_RECV_BITMAP
, /* send recved_bitmap back to source */
82 MIG_RP_MSG_RESUME_ACK
, /* tell source that we are ready to resume */
83 MIG_RP_MSG_SWITCHOVER_ACK
, /* Tell source it's OK to do switchover */
88 /* When we add fault tolerance, we could have several
89 migrations at once. For now we don't need to add
90 dynamic creation of migration */
92 static MigrationState
*current_migration
;
93 static MigrationIncomingState
*current_incoming
;
95 static GSList
*migration_blockers
;
97 static bool migration_object_check(MigrationState
*ms
, Error
**errp
);
98 static int migration_maybe_pause(MigrationState
*s
,
99 int *current_active_state
,
101 static void migrate_fd_cancel(MigrationState
*s
);
102 static int close_return_path_on_source(MigrationState
*s
);
104 static bool migration_needs_multiple_sockets(void)
106 return migrate_multifd() || migrate_postcopy_preempt();
109 static bool uri_supports_multi_channels(const char *uri
)
111 return strstart(uri
, "tcp:", NULL
) || strstart(uri
, "unix:", NULL
) ||
112 strstart(uri
, "vsock:", NULL
);
116 migration_channels_and_uri_compatible(const char *uri
, Error
**errp
)
118 if (migration_needs_multiple_sockets() &&
119 !uri_supports_multi_channels(uri
)) {
120 error_setg(errp
, "Migration requires multi-channel URIs (e.g. tcp)");
127 static gint
page_request_addr_cmp(gconstpointer ap
, gconstpointer bp
)
129 uintptr_t a
= (uintptr_t) ap
, b
= (uintptr_t) bp
;
131 return (a
> b
) - (a
< b
);
134 void migration_object_init(void)
136 /* This can only be called once. */
137 assert(!current_migration
);
138 current_migration
= MIGRATION_OBJ(object_new(TYPE_MIGRATION
));
141 * Init the migrate incoming object as well no matter whether
142 * we'll use it or not.
144 assert(!current_incoming
);
145 current_incoming
= g_new0(MigrationIncomingState
, 1);
146 current_incoming
->state
= MIGRATION_STATUS_NONE
;
147 current_incoming
->postcopy_remote_fds
=
148 g_array_new(FALSE
, TRUE
, sizeof(struct PostCopyFD
));
149 qemu_mutex_init(¤t_incoming
->rp_mutex
);
150 qemu_mutex_init(¤t_incoming
->postcopy_prio_thread_mutex
);
151 qemu_event_init(¤t_incoming
->main_thread_load_event
, false);
152 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_dst
, 0);
153 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fault
, 0);
154 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fast_load
, 0);
155 qemu_sem_init(¤t_incoming
->postcopy_qemufile_dst_done
, 0);
157 qemu_mutex_init(¤t_incoming
->page_request_mutex
);
158 qemu_cond_init(¤t_incoming
->page_request_cond
);
159 current_incoming
->page_requested
= g_tree_new(page_request_addr_cmp
);
161 migration_object_check(current_migration
, &error_fatal
);
165 dirty_bitmap_mig_init();
168 void migration_cancel(const Error
*error
)
171 migrate_set_error(current_migration
, error
);
173 if (migrate_dirty_limit()) {
174 qmp_cancel_vcpu_dirty_limit(false, -1, NULL
);
176 migrate_fd_cancel(current_migration
);
179 void migration_shutdown(void)
182 * When the QEMU main thread exit, the COLO thread
183 * may wait a semaphore. So, we should wakeup the
184 * COLO thread before migration shutdown.
188 * Cancel the current migration - that will (eventually)
189 * stop the migration using this structure
191 migration_cancel(NULL
);
192 object_unref(OBJECT(current_migration
));
195 * Cancel outgoing migration of dirty bitmaps. It should
196 * at least unref used block nodes.
198 dirty_bitmap_mig_cancel_outgoing();
201 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
202 * are non-critical data, and their loss never considered as
205 dirty_bitmap_mig_cancel_incoming();
209 MigrationState
*migrate_get_current(void)
211 /* This can only be called after the object created. */
212 assert(current_migration
);
213 return current_migration
;
216 MigrationIncomingState
*migration_incoming_get_current(void)
218 assert(current_incoming
);
219 return current_incoming
;
222 void migration_incoming_transport_cleanup(MigrationIncomingState
*mis
)
224 if (mis
->socket_address_list
) {
225 qapi_free_SocketAddressList(mis
->socket_address_list
);
226 mis
->socket_address_list
= NULL
;
229 if (mis
->transport_cleanup
) {
230 mis
->transport_cleanup(mis
->transport_data
);
231 mis
->transport_data
= mis
->transport_cleanup
= NULL
;
235 void migration_incoming_state_destroy(void)
237 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
239 multifd_load_cleanup();
240 compress_threads_load_cleanup();
242 if (mis
->to_src_file
) {
243 /* Tell source that we are done */
244 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
245 qemu_fclose(mis
->to_src_file
);
246 mis
->to_src_file
= NULL
;
249 if (mis
->from_src_file
) {
250 migration_ioc_unregister_yank_from_file(mis
->from_src_file
);
251 qemu_fclose(mis
->from_src_file
);
252 mis
->from_src_file
= NULL
;
254 if (mis
->postcopy_remote_fds
) {
255 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
256 mis
->postcopy_remote_fds
= NULL
;
259 migration_incoming_transport_cleanup(mis
);
260 qemu_event_reset(&mis
->main_thread_load_event
);
262 if (mis
->page_requested
) {
263 g_tree_destroy(mis
->page_requested
);
264 mis
->page_requested
= NULL
;
267 if (mis
->postcopy_qemufile_dst
) {
268 migration_ioc_unregister_yank_from_file(mis
->postcopy_qemufile_dst
);
269 qemu_fclose(mis
->postcopy_qemufile_dst
);
270 mis
->postcopy_qemufile_dst
= NULL
;
273 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
276 static void migrate_generate_event(int new_state
)
278 if (migrate_events()) {
279 qapi_event_send_migration(new_state
);
284 * Send a message on the return channel back to the source
287 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
288 enum mig_rp_message_type message_type
,
289 uint16_t len
, void *data
)
293 trace_migrate_send_rp_message((int)message_type
, len
);
294 QEMU_LOCK_GUARD(&mis
->rp_mutex
);
297 * It's possible that the file handle got lost due to network
300 if (!mis
->to_src_file
) {
305 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
306 qemu_put_be16(mis
->to_src_file
, len
);
307 qemu_put_buffer(mis
->to_src_file
, data
, len
);
308 qemu_fflush(mis
->to_src_file
);
310 /* It's possible that qemu file got error during sending */
311 ret
= qemu_file_get_error(mis
->to_src_file
);
316 /* Request one page from the source VM at the given start address.
317 * rb: the RAMBlock to request the page in
318 * Start: Address offset within the RB
319 * Len: Length in bytes required - must be a multiple of pagesize
321 int migrate_send_rp_message_req_pages(MigrationIncomingState
*mis
,
322 RAMBlock
*rb
, ram_addr_t start
)
324 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
325 size_t msglen
= 12; /* start + len */
326 size_t len
= qemu_ram_pagesize(rb
);
327 enum mig_rp_message_type msg_type
;
331 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
332 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
335 * We maintain the last ramblock that we requested for page. Note that we
336 * don't need locking because this function will only be called within the
337 * postcopy ram fault thread.
339 if (rb
!= mis
->last_rb
) {
342 rbname
= qemu_ram_get_idstr(rb
);
343 rbname_len
= strlen(rbname
);
345 assert(rbname_len
< 256);
347 bufc
[msglen
++] = rbname_len
;
348 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
349 msglen
+= rbname_len
;
350 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
352 msg_type
= MIG_RP_MSG_REQ_PAGES
;
355 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
358 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
,
359 RAMBlock
*rb
, ram_addr_t start
, uint64_t haddr
)
361 void *aligned
= (void *)(uintptr_t)ROUND_DOWN(haddr
, qemu_ram_pagesize(rb
));
362 bool received
= false;
364 WITH_QEMU_LOCK_GUARD(&mis
->page_request_mutex
) {
365 received
= ramblock_recv_bitmap_test_byte_offset(rb
, start
);
366 if (!received
&& !g_tree_lookup(mis
->page_requested
, aligned
)) {
368 * The page has not been received, and it's not yet in the page
369 * request list. Queue it. Set the value of element to 1, so that
370 * things like g_tree_lookup() will return TRUE (1) when found.
372 g_tree_insert(mis
->page_requested
, aligned
, (gpointer
)1);
373 qatomic_inc(&mis
->page_requested_count
);
374 trace_postcopy_page_req_add(aligned
, mis
->page_requested_count
);
379 * If the page is there, skip sending the message. We don't even need the
380 * lock because as long as the page arrived, it'll be there forever.
386 return migrate_send_rp_message_req_pages(mis
, rb
, start
);
389 static bool migration_colo_enabled
;
390 bool migration_incoming_colo_enabled(void)
392 return migration_colo_enabled
;
395 void migration_incoming_disable_colo(void)
397 ram_block_discard_disable(false);
398 migration_colo_enabled
= false;
401 int migration_incoming_enable_colo(void)
403 #ifndef CONFIG_REPLICATION
404 error_report("ENABLE_COLO command come in migration stream, but COLO "
405 "module is not built in");
409 if (!migrate_colo()) {
410 error_report("ENABLE_COLO command come in migration stream, but c-colo "
411 "capability is not set");
415 if (ram_block_discard_disable(true)) {
416 error_report("COLO: cannot disable RAM discard");
419 migration_colo_enabled
= true;
423 void migrate_add_address(SocketAddress
*address
)
425 MigrationIncomingState
*mis
= migration_incoming_get_current();
427 QAPI_LIST_PREPEND(mis
->socket_address_list
,
428 QAPI_CLONE(SocketAddress
, address
));
431 static void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
433 const char *p
= NULL
;
434 MigrationIncomingState
*mis
= migration_incoming_get_current();
436 /* URI is not suitable for migration? */
437 if (!migration_channels_and_uri_compatible(uri
, errp
)) {
441 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
442 MIGRATION_STATUS_SETUP
);
444 if (strstart(uri
, "tcp:", &p
) ||
445 strstart(uri
, "unix:", NULL
) ||
446 strstart(uri
, "vsock:", NULL
)) {
447 socket_start_incoming_migration(p
? p
: uri
, errp
);
449 } else if (strstart(uri
, "rdma:", &p
)) {
450 if (migrate_compress()) {
451 error_setg(errp
, "RDMA and compression can't be used together");
454 if (migrate_xbzrle()) {
455 error_setg(errp
, "RDMA and XBZRLE can't be used together");
458 if (migrate_multifd()) {
459 error_setg(errp
, "RDMA and multifd can't be used together");
462 rdma_start_incoming_migration(p
, errp
);
464 } else if (strstart(uri
, "exec:", &p
)) {
465 exec_start_incoming_migration(p
, errp
);
466 } else if (strstart(uri
, "fd:", &p
)) {
467 fd_start_incoming_migration(p
, errp
);
468 } else if (strstart(uri
, "file:", &p
)) {
469 file_start_incoming_migration(p
, errp
);
471 error_setg(errp
, "unknown migration protocol: %s", uri
);
475 static void process_incoming_migration_bh(void *opaque
)
477 Error
*local_err
= NULL
;
478 MigrationIncomingState
*mis
= opaque
;
480 /* If capability late_block_activate is set:
481 * Only fire up the block code now if we're going to restart the
482 * VM, else 'cont' will do it.
483 * This causes file locking to happen; so we don't want it to happen
484 * unless we really are starting the VM.
486 if (!migrate_late_block_activate() ||
487 (autostart
&& (!global_state_received() ||
488 global_state_get_runstate() == RUN_STATE_RUNNING
))) {
489 /* Make sure all file formats throw away their mutable metadata.
490 * If we get an error here, just don't restart the VM yet. */
491 bdrv_activate_all(&local_err
);
493 error_report_err(local_err
);
500 * This must happen after all error conditions are dealt with and
501 * we're sure the VM is going to be running on this host.
503 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
505 multifd_load_shutdown();
507 dirty_bitmap_mig_before_vm_start();
509 if (!global_state_received() ||
510 global_state_get_runstate() == RUN_STATE_RUNNING
) {
514 runstate_set(RUN_STATE_PAUSED
);
516 } else if (migration_incoming_colo_enabled()) {
517 migration_incoming_disable_colo();
520 runstate_set(global_state_get_runstate());
523 * This must happen after any state changes since as soon as an external
524 * observer sees this event they might start to prod at the VM assuming
527 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
528 MIGRATION_STATUS_COMPLETED
);
529 qemu_bh_delete(mis
->bh
);
530 migration_incoming_state_destroy();
533 static void coroutine_fn
534 process_incoming_migration_co(void *opaque
)
536 MigrationIncomingState
*mis
= migration_incoming_get_current();
540 assert(mis
->from_src_file
);
542 if (compress_threads_load_setup(mis
->from_src_file
)) {
543 error_report("Failed to setup decompress threads");
547 mis
->largest_page_size
= qemu_ram_pagesize_largest();
548 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
549 migrate_set_state(&mis
->state
, MIGRATION_STATUS_SETUP
,
550 MIGRATION_STATUS_ACTIVE
);
552 mis
->loadvm_co
= qemu_coroutine_self();
553 ret
= qemu_loadvm_state(mis
->from_src_file
);
554 mis
->loadvm_co
= NULL
;
556 ps
= postcopy_state_get();
557 trace_process_incoming_migration_co_end(ret
, ps
);
558 if (ps
!= POSTCOPY_INCOMING_NONE
) {
559 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
561 * Where a migration had postcopy enabled (and thus went to advise)
562 * but managed to complete within the precopy period, we can use
565 postcopy_ram_incoming_cleanup(mis
);
566 } else if (ret
>= 0) {
568 * Postcopy was started, cleanup should happen at the end of the
571 trace_process_incoming_migration_co_postcopy_end_main();
574 /* Else if something went wrong then just fall out of the normal exit */
578 error_report("load of migration failed: %s", strerror(-ret
));
582 if (colo_incoming_co() < 0) {
586 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
587 qemu_bh_schedule(mis
->bh
);
590 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
591 MIGRATION_STATUS_FAILED
);
592 qemu_fclose(mis
->from_src_file
);
594 multifd_load_cleanup();
595 compress_threads_load_cleanup();
601 * migration_incoming_setup: Setup incoming migration
602 * @f: file for main migration channel
603 * @errp: where to put errors
605 * Returns: %true on success, %false on error.
607 static bool migration_incoming_setup(QEMUFile
*f
, Error
**errp
)
609 MigrationIncomingState
*mis
= migration_incoming_get_current();
611 if (!mis
->from_src_file
) {
612 mis
->from_src_file
= f
;
614 qemu_file_set_blocking(f
, false);
618 void migration_incoming_process(void)
620 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
621 qemu_coroutine_enter(co
);
624 /* Returns true if recovered from a paused migration, otherwise false */
625 static bool postcopy_try_recover(void)
627 MigrationIncomingState
*mis
= migration_incoming_get_current();
629 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
630 /* Resumed from a paused postcopy migration */
632 /* This should be set already in migration_incoming_setup() */
633 assert(mis
->from_src_file
);
634 /* Postcopy has standalone thread to do vm load */
635 qemu_file_set_blocking(mis
->from_src_file
, true);
637 /* Re-configure the return path */
638 mis
->to_src_file
= qemu_file_get_return_path(mis
->from_src_file
);
640 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
641 MIGRATION_STATUS_POSTCOPY_RECOVER
);
644 * Here, we only wake up the main loading thread (while the
645 * rest threads will still be waiting), so that we can receive
646 * commands from source now, and answer it if needed. The
647 * rest threads will be woken up afterwards until we are sure
648 * that source is ready to reply to page requests.
650 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
657 void migration_fd_process_incoming(QEMUFile
*f
, Error
**errp
)
659 if (!migration_incoming_setup(f
, errp
)) {
662 if (postcopy_try_recover()) {
665 migration_incoming_process();
669 * Returns true when we want to start a new incoming migration process,
672 static bool migration_should_start_incoming(bool main_channel
)
674 /* Multifd doesn't start unless all channels are established */
675 if (migrate_multifd()) {
676 return migration_has_all_channels();
679 /* Preempt channel only starts when the main channel is created */
680 if (migrate_postcopy_preempt()) {
685 * For all the rest types of migration, we should only reach here when
686 * it's the main channel that's being created, and we should always
687 * proceed with this channel.
689 assert(main_channel
);
693 void migration_ioc_process_incoming(QIOChannel
*ioc
, Error
**errp
)
695 MigrationIncomingState
*mis
= migration_incoming_get_current();
696 Error
*local_err
= NULL
;
698 bool default_channel
= true;
699 uint32_t channel_magic
= 0;
702 if (migrate_multifd() && !migrate_postcopy_ram() &&
703 qio_channel_has_feature(ioc
, QIO_CHANNEL_FEATURE_READ_MSG_PEEK
)) {
705 * With multiple channels, it is possible that we receive channels
706 * out of order on destination side, causing incorrect mapping of
707 * source channels on destination side. Check channel MAGIC to
708 * decide type of channel. Please note this is best effort, postcopy
709 * preempt channel does not send any magic number so avoid it for
710 * postcopy live migration. Also tls live migration already does
711 * tls handshake while initializing main channel so with tls this
712 * issue is not possible.
714 ret
= migration_channel_read_peek(ioc
, (void *)&channel_magic
,
715 sizeof(channel_magic
), &local_err
);
718 error_propagate(errp
, local_err
);
722 default_channel
= (channel_magic
== cpu_to_be32(QEMU_VM_FILE_MAGIC
));
724 default_channel
= !mis
->from_src_file
;
727 if (multifd_load_setup(errp
) != 0) {
728 error_setg(errp
, "Failed to setup multifd channels");
732 if (default_channel
) {
733 f
= qemu_file_new_input(ioc
);
735 if (!migration_incoming_setup(f
, errp
)) {
739 /* Multiple connections */
740 assert(migration_needs_multiple_sockets());
741 if (migrate_multifd()) {
742 multifd_recv_new_channel(ioc
, &local_err
);
744 assert(migrate_postcopy_preempt());
745 f
= qemu_file_new_input(ioc
);
746 postcopy_preempt_new_channel(mis
, f
);
749 error_propagate(errp
, local_err
);
754 if (migration_should_start_incoming(default_channel
)) {
755 /* If it's a recovery, we're done */
756 if (postcopy_try_recover()) {
759 migration_incoming_process();
764 * @migration_has_all_channels: We have received all channels that we need
766 * Returns true when we have got connections to all the channels that
767 * we need for migration.
769 bool migration_has_all_channels(void)
771 MigrationIncomingState
*mis
= migration_incoming_get_current();
773 if (!mis
->from_src_file
) {
777 if (migrate_multifd()) {
778 return multifd_recv_all_channels_created();
781 if (migrate_postcopy_preempt()) {
782 return mis
->postcopy_qemufile_dst
!= NULL
;
788 int migrate_send_rp_switchover_ack(MigrationIncomingState
*mis
)
790 return migrate_send_rp_message(mis
, MIG_RP_MSG_SWITCHOVER_ACK
, 0, NULL
);
794 * Send a 'SHUT' message on the return channel with the given value
795 * to indicate that we've finished with the RP. Non-0 value indicates
798 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
803 buf
= cpu_to_be32(value
);
804 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
808 * Send a 'PONG' message on the return channel with the given value
809 * (normally in response to a 'PING')
811 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
816 buf
= cpu_to_be32(value
);
817 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
820 void migrate_send_rp_recv_bitmap(MigrationIncomingState
*mis
,
828 * First, we send the header part. It contains only the len of
829 * idstr, and the idstr itself.
831 len
= strlen(block_name
);
833 memcpy(buf
+ 1, block_name
, len
);
835 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
836 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
841 migrate_send_rp_message(mis
, MIG_RP_MSG_RECV_BITMAP
, len
+ 1, buf
);
844 * Next, we dump the received bitmap to the stream.
846 * TODO: currently we are safe since we are the only one that is
847 * using the to_src_file handle (fault thread is still paused),
848 * and it's ok even not taking the mutex. However the best way is
849 * to take the lock before sending the message header, and release
850 * the lock after sending the bitmap.
852 qemu_mutex_lock(&mis
->rp_mutex
);
853 res
= ramblock_recv_bitmap_send(mis
->to_src_file
, block_name
);
854 qemu_mutex_unlock(&mis
->rp_mutex
);
856 trace_migrate_send_rp_recv_bitmap(block_name
, res
);
859 void migrate_send_rp_resume_ack(MigrationIncomingState
*mis
, uint32_t value
)
863 buf
= cpu_to_be32(value
);
864 migrate_send_rp_message(mis
, MIG_RP_MSG_RESUME_ACK
, sizeof(buf
), &buf
);
868 * Return true if we're already in the middle of a migration
869 * (i.e. any of the active or setup states)
871 bool migration_is_setup_or_active(int state
)
874 case MIGRATION_STATUS_ACTIVE
:
875 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
876 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
877 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
878 case MIGRATION_STATUS_SETUP
:
879 case MIGRATION_STATUS_PRE_SWITCHOVER
:
880 case MIGRATION_STATUS_DEVICE
:
881 case MIGRATION_STATUS_WAIT_UNPLUG
:
882 case MIGRATION_STATUS_COLO
:
891 bool migration_is_running(int state
)
894 case MIGRATION_STATUS_ACTIVE
:
895 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
896 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
897 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
898 case MIGRATION_STATUS_SETUP
:
899 case MIGRATION_STATUS_PRE_SWITCHOVER
:
900 case MIGRATION_STATUS_DEVICE
:
901 case MIGRATION_STATUS_WAIT_UNPLUG
:
902 case MIGRATION_STATUS_CANCELLING
:
911 static bool migrate_show_downtime(MigrationState
*s
)
913 return (s
->state
== MIGRATION_STATUS_COMPLETED
) || migration_in_postcopy();
916 static void populate_time_info(MigrationInfo
*info
, MigrationState
*s
)
918 info
->has_status
= true;
919 info
->has_setup_time
= true;
920 info
->setup_time
= s
->setup_time
;
922 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
923 info
->has_total_time
= true;
924 info
->total_time
= s
->total_time
;
926 info
->has_total_time
= true;
927 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) -
931 if (migrate_show_downtime(s
)) {
932 info
->has_downtime
= true;
933 info
->downtime
= s
->downtime
;
935 info
->has_expected_downtime
= true;
936 info
->expected_downtime
= s
->expected_downtime
;
940 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
942 size_t page_size
= qemu_target_page_size();
944 info
->ram
= g_malloc0(sizeof(*info
->ram
));
945 info
->ram
->transferred
= stat64_get(&mig_stats
.transferred
);
946 info
->ram
->total
= ram_bytes_total();
947 info
->ram
->duplicate
= stat64_get(&mig_stats
.zero_pages
);
948 /* legacy value. It is not used anymore */
949 info
->ram
->skipped
= 0;
950 info
->ram
->normal
= stat64_get(&mig_stats
.normal_pages
);
951 info
->ram
->normal_bytes
= info
->ram
->normal
* page_size
;
952 info
->ram
->mbps
= s
->mbps
;
953 info
->ram
->dirty_sync_count
=
954 stat64_get(&mig_stats
.dirty_sync_count
);
955 info
->ram
->dirty_sync_missed_zero_copy
=
956 stat64_get(&mig_stats
.dirty_sync_missed_zero_copy
);
957 info
->ram
->postcopy_requests
=
958 stat64_get(&mig_stats
.postcopy_requests
);
959 info
->ram
->page_size
= page_size
;
960 info
->ram
->multifd_bytes
= stat64_get(&mig_stats
.multifd_bytes
);
961 info
->ram
->pages_per_second
= s
->pages_per_second
;
962 info
->ram
->precopy_bytes
= stat64_get(&mig_stats
.precopy_bytes
);
963 info
->ram
->downtime_bytes
= stat64_get(&mig_stats
.downtime_bytes
);
964 info
->ram
->postcopy_bytes
= stat64_get(&mig_stats
.postcopy_bytes
);
966 if (migrate_xbzrle()) {
967 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
968 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
969 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
970 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
971 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
972 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
973 info
->xbzrle_cache
->encoding_rate
= xbzrle_counters
.encoding_rate
;
974 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
977 populate_compress(info
);
979 if (cpu_throttle_active()) {
980 info
->has_cpu_throttle_percentage
= true;
981 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
984 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
985 info
->ram
->remaining
= ram_bytes_remaining();
986 info
->ram
->dirty_pages_rate
=
987 stat64_get(&mig_stats
.dirty_pages_rate
);
990 if (migrate_dirty_limit() && dirtylimit_in_service()) {
991 info
->has_dirty_limit_throttle_time_per_round
= true;
992 info
->dirty_limit_throttle_time_per_round
=
993 dirtylimit_throttle_time_per_round();
995 info
->has_dirty_limit_ring_full_time
= true;
996 info
->dirty_limit_ring_full_time
= dirtylimit_ring_full_time();
1000 static void populate_disk_info(MigrationInfo
*info
)
1002 if (blk_mig_active()) {
1003 info
->disk
= g_malloc0(sizeof(*info
->disk
));
1004 info
->disk
->transferred
= blk_mig_bytes_transferred();
1005 info
->disk
->remaining
= blk_mig_bytes_remaining();
1006 info
->disk
->total
= blk_mig_bytes_total();
1010 static void fill_source_migration_info(MigrationInfo
*info
)
1012 MigrationState
*s
= migrate_get_current();
1013 int state
= qatomic_read(&s
->state
);
1014 GSList
*cur_blocker
= migration_blockers
;
1016 info
->blocked_reasons
= NULL
;
1019 * There are two types of reasons a migration might be blocked;
1020 * a) devices marked in VMState as non-migratable, and
1021 * b) Explicit migration blockers
1022 * We need to add both of them here.
1024 qemu_savevm_non_migratable_list(&info
->blocked_reasons
);
1026 while (cur_blocker
) {
1027 QAPI_LIST_PREPEND(info
->blocked_reasons
,
1028 g_strdup(error_get_pretty(cur_blocker
->data
)));
1029 cur_blocker
= g_slist_next(cur_blocker
);
1031 info
->has_blocked_reasons
= info
->blocked_reasons
!= NULL
;
1034 case MIGRATION_STATUS_NONE
:
1035 /* no migration has happened ever */
1036 /* do not overwrite destination migration status */
1038 case MIGRATION_STATUS_SETUP
:
1039 info
->has_status
= true;
1040 info
->has_total_time
= false;
1042 case MIGRATION_STATUS_ACTIVE
:
1043 case MIGRATION_STATUS_CANCELLING
:
1044 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1045 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1046 case MIGRATION_STATUS_DEVICE
:
1047 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1048 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1049 /* TODO add some postcopy stats */
1050 populate_time_info(info
, s
);
1051 populate_ram_info(info
, s
);
1052 populate_disk_info(info
);
1053 migration_populate_vfio_info(info
);
1055 case MIGRATION_STATUS_COLO
:
1056 info
->has_status
= true;
1057 /* TODO: display COLO specific information (checkpoint info etc.) */
1059 case MIGRATION_STATUS_COMPLETED
:
1060 populate_time_info(info
, s
);
1061 populate_ram_info(info
, s
);
1062 migration_populate_vfio_info(info
);
1064 case MIGRATION_STATUS_FAILED
:
1065 info
->has_status
= true;
1067 case MIGRATION_STATUS_CANCELLED
:
1068 info
->has_status
= true;
1070 case MIGRATION_STATUS_WAIT_UNPLUG
:
1071 info
->has_status
= true;
1074 info
->status
= state
;
1076 QEMU_LOCK_GUARD(&s
->error_mutex
);
1078 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
1082 static void fill_destination_migration_info(MigrationInfo
*info
)
1084 MigrationIncomingState
*mis
= migration_incoming_get_current();
1086 if (mis
->socket_address_list
) {
1087 info
->has_socket_address
= true;
1088 info
->socket_address
=
1089 QAPI_CLONE(SocketAddressList
, mis
->socket_address_list
);
1092 switch (mis
->state
) {
1093 case MIGRATION_STATUS_NONE
:
1095 case MIGRATION_STATUS_SETUP
:
1096 case MIGRATION_STATUS_CANCELLING
:
1097 case MIGRATION_STATUS_CANCELLED
:
1098 case MIGRATION_STATUS_ACTIVE
:
1099 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1100 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1101 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1102 case MIGRATION_STATUS_FAILED
:
1103 case MIGRATION_STATUS_COLO
:
1104 info
->has_status
= true;
1106 case MIGRATION_STATUS_COMPLETED
:
1107 info
->has_status
= true;
1108 fill_destination_postcopy_migration_info(info
);
1111 info
->status
= mis
->state
;
1114 MigrationInfo
*qmp_query_migrate(Error
**errp
)
1116 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
1118 fill_destination_migration_info(info
);
1119 fill_source_migration_info(info
);
1124 void qmp_migrate_start_postcopy(Error
**errp
)
1126 MigrationState
*s
= migrate_get_current();
1128 if (!migrate_postcopy()) {
1129 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1130 " the start of migration");
1134 if (s
->state
== MIGRATION_STATUS_NONE
) {
1135 error_setg(errp
, "Postcopy must be started after migration has been"
1140 * we don't error if migration has finished since that would be racy
1141 * with issuing this command.
1143 qatomic_set(&s
->start_postcopy
, true);
1146 /* shared migration helpers */
1148 void migrate_set_state(int *state
, int old_state
, int new_state
)
1150 assert(new_state
< MIGRATION_STATUS__MAX
);
1151 if (qatomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1152 trace_migrate_set_state(MigrationStatus_str(new_state
));
1153 migrate_generate_event(new_state
);
1157 static void migrate_fd_cleanup(MigrationState
*s
)
1159 qemu_bh_delete(s
->cleanup_bh
);
1160 s
->cleanup_bh
= NULL
;
1162 g_free(s
->hostname
);
1164 json_writer_free(s
->vmdesc
);
1167 qemu_savevm_state_cleanup();
1169 if (s
->to_dst_file
) {
1172 trace_migrate_fd_cleanup();
1173 qemu_mutex_unlock_iothread();
1174 if (s
->migration_thread_running
) {
1175 qemu_thread_join(&s
->thread
);
1176 s
->migration_thread_running
= false;
1178 qemu_mutex_lock_iothread();
1180 multifd_save_cleanup();
1181 qemu_mutex_lock(&s
->qemu_file_lock
);
1182 tmp
= s
->to_dst_file
;
1183 s
->to_dst_file
= NULL
;
1184 qemu_mutex_unlock(&s
->qemu_file_lock
);
1186 * Close the file handle without the lock to make sure the
1187 * critical section won't block for long.
1189 migration_ioc_unregister_yank_from_file(tmp
);
1194 * We already cleaned up to_dst_file, so errors from the return
1195 * path might be due to that, ignore them.
1197 close_return_path_on_source(s
);
1199 assert(!migration_is_active(s
));
1201 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1202 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1203 MIGRATION_STATUS_CANCELLED
);
1207 /* It is used on info migrate. We can't free it */
1208 error_report_err(error_copy(s
->error
));
1210 migration_call_notifiers(s
);
1211 block_cleanup_parameters();
1212 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1215 static void migrate_fd_cleanup_schedule(MigrationState
*s
)
1218 * Ref the state for bh, because it may be called when
1219 * there're already no other refs
1221 object_ref(OBJECT(s
));
1222 qemu_bh_schedule(s
->cleanup_bh
);
1225 static void migrate_fd_cleanup_bh(void *opaque
)
1227 MigrationState
*s
= opaque
;
1228 migrate_fd_cleanup(s
);
1229 object_unref(OBJECT(s
));
1232 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1234 QEMU_LOCK_GUARD(&s
->error_mutex
);
1236 s
->error
= error_copy(error
);
1240 bool migrate_has_error(MigrationState
*s
)
1242 /* The lock is not helpful here, but still follow the rule */
1243 QEMU_LOCK_GUARD(&s
->error_mutex
);
1244 return qatomic_read(&s
->error
);
1247 static void migrate_error_free(MigrationState
*s
)
1249 QEMU_LOCK_GUARD(&s
->error_mutex
);
1251 error_free(s
->error
);
1256 static void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1258 trace_migrate_fd_error(error_get_pretty(error
));
1259 assert(s
->to_dst_file
== NULL
);
1260 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1261 MIGRATION_STATUS_FAILED
);
1262 migrate_set_error(s
, error
);
1265 static void migrate_fd_cancel(MigrationState
*s
)
1269 trace_migrate_fd_cancel();
1271 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1272 if (s
->rp_state
.from_dst_file
) {
1273 /* shutdown the rp socket, so causing the rp thread to shutdown */
1274 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1279 old_state
= s
->state
;
1280 if (!migration_is_running(old_state
)) {
1283 /* If the migration is paused, kick it out of the pause */
1284 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1285 qemu_sem_post(&s
->pause_sem
);
1287 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1288 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1291 * If we're unlucky the migration code might be stuck somewhere in a
1292 * send/write while the network has failed and is waiting to timeout;
1293 * if we've got shutdown(2) available then we can force it to quit.
1295 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1296 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1297 if (s
->to_dst_file
) {
1298 qemu_file_shutdown(s
->to_dst_file
);
1302 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1303 Error
*local_err
= NULL
;
1305 bdrv_activate_all(&local_err
);
1307 error_report_err(local_err
);
1309 s
->block_inactive
= false;
1314 void migration_add_notifier(Notifier
*notify
,
1315 void (*func
)(Notifier
*notifier
, void *data
))
1317 notify
->notify
= func
;
1318 notifier_list_add(&migration_state_notifiers
, notify
);
1321 void migration_remove_notifier(Notifier
*notify
)
1323 if (notify
->notify
) {
1324 notifier_remove(notify
);
1325 notify
->notify
= NULL
;
1329 void migration_call_notifiers(MigrationState
*s
)
1331 notifier_list_notify(&migration_state_notifiers
, s
);
1334 bool migration_in_setup(MigrationState
*s
)
1336 return s
->state
== MIGRATION_STATUS_SETUP
;
1339 bool migration_has_finished(MigrationState
*s
)
1341 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1344 bool migration_has_failed(MigrationState
*s
)
1346 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1347 s
->state
== MIGRATION_STATUS_FAILED
);
1350 bool migration_in_postcopy(void)
1352 MigrationState
*s
= migrate_get_current();
1355 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1356 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1357 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1364 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1366 return migration_in_postcopy() && s
->postcopy_after_devices
;
1369 bool migration_in_incoming_postcopy(void)
1371 PostcopyState ps
= postcopy_state_get();
1373 return ps
>= POSTCOPY_INCOMING_DISCARD
&& ps
< POSTCOPY_INCOMING_END
;
1376 bool migration_incoming_postcopy_advised(void)
1378 PostcopyState ps
= postcopy_state_get();
1380 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
1383 bool migration_in_bg_snapshot(void)
1385 MigrationState
*s
= migrate_get_current();
1387 return migrate_background_snapshot() &&
1388 migration_is_setup_or_active(s
->state
);
1391 bool migration_is_idle(void)
1393 MigrationState
*s
= current_migration
;
1400 case MIGRATION_STATUS_NONE
:
1401 case MIGRATION_STATUS_CANCELLED
:
1402 case MIGRATION_STATUS_COMPLETED
:
1403 case MIGRATION_STATUS_FAILED
:
1405 case MIGRATION_STATUS_SETUP
:
1406 case MIGRATION_STATUS_CANCELLING
:
1407 case MIGRATION_STATUS_ACTIVE
:
1408 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1409 case MIGRATION_STATUS_COLO
:
1410 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1411 case MIGRATION_STATUS_DEVICE
:
1412 case MIGRATION_STATUS_WAIT_UNPLUG
:
1414 case MIGRATION_STATUS__MAX
:
1415 g_assert_not_reached();
1421 bool migration_is_active(MigrationState
*s
)
1423 return (s
->state
== MIGRATION_STATUS_ACTIVE
||
1424 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1427 int migrate_init(MigrationState
*s
, Error
**errp
)
1431 ret
= qemu_savevm_state_prepare(errp
);
1437 * Reinitialise all migration state, except
1438 * parameters/capabilities that the user set, and
1443 s
->to_dst_file
= NULL
;
1444 s
->state
= MIGRATION_STATUS_NONE
;
1445 s
->rp_state
.from_dst_file
= NULL
;
1446 s
->rp_state
.error
= false;
1448 s
->pages_per_second
= 0.0;
1450 s
->expected_downtime
= 0;
1452 s
->start_postcopy
= false;
1453 s
->postcopy_after_devices
= false;
1454 s
->migration_thread_running
= false;
1455 error_free(s
->error
);
1460 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1462 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1464 s
->vm_old_state
= -1;
1465 s
->iteration_initial_bytes
= 0;
1466 s
->threshold_size
= 0;
1467 s
->switchover_acked
= false;
1468 s
->rdma_migration
= false;
1470 * set mig_stats memory to zero for a new migration
1472 memset(&mig_stats
, 0, sizeof(mig_stats
));
1473 migration_reset_vfio_bytes_transferred();
1478 int migrate_add_blocker_internal(Error
**reasonp
, Error
**errp
)
1480 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1481 if (runstate_check(RUN_STATE_SAVE_VM
) || !migration_is_idle()) {
1482 error_propagate_prepend(errp
, *reasonp
,
1483 "disallowing migration blocker "
1484 "(migration/snapshot in progress) for: ");
1489 migration_blockers
= g_slist_prepend(migration_blockers
, *reasonp
);
1493 int migrate_add_blocker(Error
**reasonp
, Error
**errp
)
1495 if (only_migratable
) {
1496 error_propagate_prepend(errp
, *reasonp
,
1497 "disallowing migration blocker "
1498 "(--only-migratable) for: ");
1503 return migrate_add_blocker_internal(reasonp
, errp
);
1506 void migrate_del_blocker(Error
**reasonp
)
1509 migration_blockers
= g_slist_remove(migration_blockers
, *reasonp
);
1510 error_free(*reasonp
);
1515 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
1517 Error
*local_err
= NULL
;
1518 static bool once
= true;
1521 error_setg(errp
, "The incoming migration has already been started");
1524 if (!runstate_check(RUN_STATE_INMIGRATE
)) {
1525 error_setg(errp
, "'-incoming' was not specified on the command line");
1529 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1533 qemu_start_incoming_migration(uri
, &local_err
);
1536 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1537 error_propagate(errp
, local_err
);
1544 void qmp_migrate_recover(const char *uri
, Error
**errp
)
1546 MigrationIncomingState
*mis
= migration_incoming_get_current();
1549 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1550 * callers (no one should ignore a recover failure); if there is, it's a
1551 * programming error.
1555 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1556 error_setg(errp
, "Migrate recover can only be run "
1557 "when postcopy is paused.");
1561 /* If there's an existing transport, release it */
1562 migration_incoming_transport_cleanup(mis
);
1565 * Note that this call will never start a real migration; it will
1566 * only re-setup the migration stream and poke existing migration
1567 * to continue using that newly established channel.
1569 qemu_start_incoming_migration(uri
, errp
);
1572 void qmp_migrate_pause(Error
**errp
)
1574 MigrationState
*ms
= migrate_get_current();
1575 MigrationIncomingState
*mis
= migration_incoming_get_current();
1578 if (ms
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1579 /* Source side, during postcopy */
1580 qemu_mutex_lock(&ms
->qemu_file_lock
);
1581 if (ms
->to_dst_file
) {
1582 ret
= qemu_file_shutdown(ms
->to_dst_file
);
1584 qemu_mutex_unlock(&ms
->qemu_file_lock
);
1586 error_setg(errp
, "Failed to pause source migration");
1591 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1592 ret
= qemu_file_shutdown(mis
->from_src_file
);
1594 error_setg(errp
, "Failed to pause destination migration");
1599 error_setg(errp
, "migrate-pause is currently only supported "
1600 "during postcopy-active state");
1603 bool migration_is_blocked(Error
**errp
)
1605 if (qemu_savevm_state_blocked(errp
)) {
1609 if (migration_blockers
) {
1610 error_propagate(errp
, error_copy(migration_blockers
->data
));
1617 /* Returns true if continue to migrate, or false if error detected */
1618 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1619 bool resume
, Error
**errp
)
1621 Error
*local_err
= NULL
;
1624 warn_report("parameter 'inc' is deprecated;"
1625 " use blockdev-mirror with NBD instead");
1629 warn_report("parameter 'blk' is deprecated;"
1630 " use blockdev-mirror with NBD instead");
1634 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1635 error_setg(errp
, "Cannot resume if there is no "
1636 "paused migration");
1641 * Postcopy recovery won't work well with release-ram
1642 * capability since release-ram will drop the page buffer as
1643 * long as the page is put into the send buffer. So if there
1644 * is a network failure happened, any page buffers that have
1645 * not yet reached the destination VM but have already been
1646 * sent from the source VM will be lost forever. Let's refuse
1647 * the client from resuming such a postcopy migration.
1648 * Luckily release-ram was designed to only be used when src
1649 * and destination VMs are on the same host, so it should be
1652 if (migrate_release_ram()) {
1653 error_setg(errp
, "Postcopy recovery cannot work "
1654 "when release-ram capability is set");
1658 /* This is a resume, skip init status */
1662 if (migration_is_running(s
->state
)) {
1663 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1667 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1668 error_setg(errp
, "Guest is waiting for an incoming migration");
1672 if (runstate_check(RUN_STATE_POSTMIGRATE
)) {
1673 error_setg(errp
, "Can't migrate the vm that was paused due to "
1674 "previous migration");
1678 if (migration_is_blocked(errp
)) {
1682 if (blk
|| blk_inc
) {
1683 if (migrate_colo()) {
1684 error_setg(errp
, "No disk migration is required in COLO mode");
1687 if (migrate_block() || migrate_block_incremental()) {
1688 error_setg(errp
, "Command options are incompatible with "
1689 "current migration capabilities");
1692 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK
, true, &local_err
)) {
1693 error_propagate(errp
, local_err
);
1696 s
->must_remove_block_options
= true;
1700 migrate_set_block_incremental(true);
1703 if (migrate_init(s
, errp
)) {
1710 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1711 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1712 bool has_resume
, bool resume
, Error
**errp
)
1714 bool resume_requested
;
1715 Error
*local_err
= NULL
;
1716 MigrationState
*s
= migrate_get_current();
1717 const char *p
= NULL
;
1719 /* URI is not suitable for migration? */
1720 if (!migration_channels_and_uri_compatible(uri
, errp
)) {
1724 resume_requested
= has_resume
&& resume
;
1725 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
1726 resume_requested
, errp
)) {
1727 /* Error detected, put into errp */
1731 if (!resume_requested
) {
1732 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1737 if (strstart(uri
, "tcp:", &p
) ||
1738 strstart(uri
, "unix:", NULL
) ||
1739 strstart(uri
, "vsock:", NULL
)) {
1740 socket_start_outgoing_migration(s
, p
? p
: uri
, &local_err
);
1742 } else if (strstart(uri
, "rdma:", &p
)) {
1743 rdma_start_outgoing_migration(s
, p
, &local_err
);
1745 } else if (strstart(uri
, "exec:", &p
)) {
1746 exec_start_outgoing_migration(s
, p
, &local_err
);
1747 } else if (strstart(uri
, "fd:", &p
)) {
1748 fd_start_outgoing_migration(s
, p
, &local_err
);
1749 } else if (strstart(uri
, "file:", &p
)) {
1750 file_start_outgoing_migration(s
, p
, &local_err
);
1752 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1753 "a valid migration protocol");
1754 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1755 MIGRATION_STATUS_FAILED
);
1756 block_cleanup_parameters();
1760 if (!resume_requested
) {
1761 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1763 migrate_fd_error(s
, local_err
);
1764 error_propagate(errp
, local_err
);
1769 void qmp_migrate_cancel(Error
**errp
)
1771 migration_cancel(NULL
);
1774 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
1776 MigrationState
*s
= migrate_get_current();
1777 if (s
->state
!= state
) {
1778 error_setg(errp
, "Migration not in expected state: %s",
1779 MigrationStatus_str(s
->state
));
1782 qemu_sem_post(&s
->pause_sem
);
1785 /* migration thread support */
1787 * Something bad happened to the RP stream, mark an error
1788 * The caller shall print or trace something to indicate why
1790 static void mark_source_rp_bad(MigrationState
*s
)
1792 s
->rp_state
.error
= true;
1795 void migration_rp_wait(MigrationState
*s
)
1797 qemu_sem_wait(&s
->rp_state
.rp_sem
);
1800 void migration_rp_kick(MigrationState
*s
)
1802 qemu_sem_post(&s
->rp_state
.rp_sem
);
1805 static struct rp_cmd_args
{
1806 ssize_t len
; /* -1 = variable */
1809 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1810 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1811 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1812 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1813 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1814 [MIG_RP_MSG_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
1815 [MIG_RP_MSG_RESUME_ACK
] = { .len
= 4, .name
= "RESUME_ACK" },
1816 [MIG_RP_MSG_SWITCHOVER_ACK
] = { .len
= 0, .name
= "SWITCHOVER_ACK" },
1817 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1821 * Process a request for pages received on the return path,
1822 * We're allowed to send more than requested (e.g. to round to our page size)
1823 * and we don't need to send pages that have already been sent.
1825 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1826 ram_addr_t start
, size_t len
)
1828 long our_host_ps
= qemu_real_host_page_size();
1830 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1833 * Since we currently insist on matching page sizes, just sanity check
1834 * we're being asked for whole host pages.
1836 if (!QEMU_IS_ALIGNED(start
, our_host_ps
) ||
1837 !QEMU_IS_ALIGNED(len
, our_host_ps
)) {
1838 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1839 " len: %zd", __func__
, start
, len
);
1840 mark_source_rp_bad(ms
);
1844 if (ram_save_queue_pages(rbname
, start
, len
)) {
1845 mark_source_rp_bad(ms
);
1849 static int migrate_handle_rp_recv_bitmap(MigrationState
*s
, char *block_name
)
1851 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
1854 error_report("%s: invalid block name '%s'", __func__
, block_name
);
1858 /* Fetch the received bitmap and refresh the dirty bitmap */
1859 return ram_dirty_bitmap_reload(s
, block
);
1862 static int migrate_handle_rp_resume_ack(MigrationState
*s
, uint32_t value
)
1864 trace_source_return_path_thread_resume_ack(value
);
1866 if (value
!= MIGRATION_RESUME_ACK_VALUE
) {
1867 error_report("%s: illegal resume_ack value %"PRIu32
,
1872 /* Now both sides are active. */
1873 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
1874 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1876 /* Notify send thread that time to continue send pages */
1877 migration_rp_kick(s
);
1883 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
1884 * existed) in a safe way.
1886 static void migration_release_dst_files(MigrationState
*ms
)
1890 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
1892 * Reset the from_dst_file pointer first before releasing it, as we
1893 * can't block within lock section
1895 file
= ms
->rp_state
.from_dst_file
;
1896 ms
->rp_state
.from_dst_file
= NULL
;
1900 * Do the same to postcopy fast path socket too if there is. No
1901 * locking needed because this qemufile should only be managed by
1902 * return path thread.
1904 if (ms
->postcopy_qemufile_src
) {
1905 migration_ioc_unregister_yank_from_file(ms
->postcopy_qemufile_src
);
1906 qemu_file_shutdown(ms
->postcopy_qemufile_src
);
1907 qemu_fclose(ms
->postcopy_qemufile_src
);
1908 ms
->postcopy_qemufile_src
= NULL
;
1915 * Handles messages sent on the return path towards the source VM
1918 static void *source_return_path_thread(void *opaque
)
1920 MigrationState
*ms
= opaque
;
1921 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1922 uint16_t header_len
, header_type
;
1924 uint32_t tmp32
, sibling_error
;
1925 ram_addr_t start
= 0; /* =0 to silence warning */
1926 size_t len
= 0, expected_len
;
1929 trace_source_return_path_thread_entry();
1930 rcu_register_thread();
1932 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1933 migration_is_setup_or_active(ms
->state
)) {
1934 trace_source_return_path_thread_loop_top();
1935 header_type
= qemu_get_be16(rp
);
1936 header_len
= qemu_get_be16(rp
);
1938 if (qemu_file_get_error(rp
)) {
1939 mark_source_rp_bad(ms
);
1943 if (header_type
>= MIG_RP_MSG_MAX
||
1944 header_type
== MIG_RP_MSG_INVALID
) {
1945 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1946 header_type
, header_len
);
1947 mark_source_rp_bad(ms
);
1951 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1952 header_len
!= rp_cmd_args
[header_type
].len
) ||
1953 header_len
> sizeof(buf
)) {
1954 error_report("RP: Received '%s' message (0x%04x) with"
1955 "incorrect length %d expecting %zu",
1956 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1957 (size_t)rp_cmd_args
[header_type
].len
);
1958 mark_source_rp_bad(ms
);
1962 /* We know we've got a valid header by this point */
1963 res
= qemu_get_buffer(rp
, buf
, header_len
);
1964 if (res
!= header_len
) {
1965 error_report("RP: Failed reading data for message 0x%04x"
1966 " read %d expected %d",
1967 header_type
, res
, header_len
);
1968 mark_source_rp_bad(ms
);
1972 /* OK, we have the message and the data */
1973 switch (header_type
) {
1974 case MIG_RP_MSG_SHUT
:
1975 sibling_error
= ldl_be_p(buf
);
1976 trace_source_return_path_thread_shut(sibling_error
);
1977 if (sibling_error
) {
1978 error_report("RP: Sibling indicated error %d", sibling_error
);
1979 mark_source_rp_bad(ms
);
1982 * We'll let the main thread deal with closing the RP
1983 * we could do a shutdown(2) on it, but we're the only user
1984 * anyway, so there's nothing gained.
1988 case MIG_RP_MSG_PONG
:
1989 tmp32
= ldl_be_p(buf
);
1990 trace_source_return_path_thread_pong(tmp32
);
1991 qemu_sem_post(&ms
->rp_state
.rp_pong_acks
);
1994 case MIG_RP_MSG_REQ_PAGES
:
1995 start
= ldq_be_p(buf
);
1996 len
= ldl_be_p(buf
+ 8);
1997 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
2000 case MIG_RP_MSG_REQ_PAGES_ID
:
2001 expected_len
= 12 + 1; /* header + termination */
2003 if (header_len
>= expected_len
) {
2004 start
= ldq_be_p(buf
);
2005 len
= ldl_be_p(buf
+ 8);
2006 /* Now we expect an idstr */
2007 tmp32
= buf
[12]; /* Length of the following idstr */
2008 buf
[13 + tmp32
] = '\0';
2009 expected_len
+= tmp32
;
2011 if (header_len
!= expected_len
) {
2012 error_report("RP: Req_Page_id with length %d expecting %zd",
2013 header_len
, expected_len
);
2014 mark_source_rp_bad(ms
);
2017 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
2020 case MIG_RP_MSG_RECV_BITMAP
:
2021 if (header_len
< 1) {
2022 error_report("%s: missing block name", __func__
);
2023 mark_source_rp_bad(ms
);
2026 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2027 buf
[buf
[0] + 1] = '\0';
2028 if (migrate_handle_rp_recv_bitmap(ms
, (char *)(buf
+ 1))) {
2029 mark_source_rp_bad(ms
);
2034 case MIG_RP_MSG_RESUME_ACK
:
2035 tmp32
= ldl_be_p(buf
);
2036 if (migrate_handle_rp_resume_ack(ms
, tmp32
)) {
2037 mark_source_rp_bad(ms
);
2042 case MIG_RP_MSG_SWITCHOVER_ACK
:
2043 ms
->switchover_acked
= true;
2044 trace_source_return_path_thread_switchover_acked();
2053 if (qemu_file_get_error(rp
)) {
2054 trace_source_return_path_thread_bad_end();
2055 mark_source_rp_bad(ms
);
2058 trace_source_return_path_thread_end();
2059 rcu_unregister_thread();
2063 static int open_return_path_on_source(MigrationState
*ms
)
2065 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
2066 if (!ms
->rp_state
.from_dst_file
) {
2070 trace_open_return_path_on_source();
2072 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2073 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2074 ms
->rp_state
.rp_thread_created
= true;
2076 trace_open_return_path_on_source_continue();
2081 static int close_return_path_on_source(MigrationState
*ms
)
2085 if (!ms
->rp_state
.rp_thread_created
) {
2089 trace_migration_return_path_end_before();
2092 * If this is a normal exit then the destination will send a SHUT
2093 * and the rp_thread will exit, however if there's an error we
2094 * need to cause it to exit. shutdown(2), if we have it, will
2095 * cause it to unblock if it's stuck waiting for the destination.
2097 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2098 if (ms
->to_dst_file
&& ms
->rp_state
.from_dst_file
&&
2099 qemu_file_get_error(ms
->to_dst_file
)) {
2100 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2104 trace_await_return_path_close_on_source_joining();
2105 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2106 ms
->rp_state
.rp_thread_created
= false;
2107 trace_await_return_path_close_on_source_close();
2109 ret
= ms
->rp_state
.error
;
2110 ms
->rp_state
.error
= false;
2112 migration_release_dst_files(ms
);
2114 trace_migration_return_path_end_after(ret
);
2119 migration_wait_main_channel(MigrationState
*ms
)
2121 /* Wait until one PONG message received */
2122 qemu_sem_wait(&ms
->rp_state
.rp_pong_acks
);
2126 * Switch from normal iteration to postcopy
2127 * Returns non-0 on error
2129 static int postcopy_start(MigrationState
*ms
, Error
**errp
)
2132 QIOChannelBuffer
*bioc
;
2134 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2135 uint64_t bandwidth
= migrate_max_postcopy_bandwidth();
2136 bool restart_block
= false;
2137 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2139 if (migrate_postcopy_preempt()) {
2140 migration_wait_main_channel(ms
);
2141 if (postcopy_preempt_establish_channel(ms
)) {
2142 migrate_set_state(&ms
->state
, ms
->state
, MIGRATION_STATUS_FAILED
);
2147 if (!migrate_pause_before_switchover()) {
2148 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2149 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2152 trace_postcopy_start();
2153 qemu_mutex_lock_iothread();
2154 trace_postcopy_start_set_run();
2156 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2157 global_state_store();
2158 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2163 ret
= migration_maybe_pause(ms
, &cur_state
,
2164 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2169 ret
= bdrv_inactivate_all();
2173 restart_block
= true;
2176 * Cause any non-postcopiable, but iterative devices to
2177 * send out their final data.
2179 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2182 * in Finish migrate and with the io-lock held everything should
2183 * be quiet, but we've potentially still got dirty pages and we
2184 * need to tell the destination to throw any pages it's already received
2187 if (migrate_postcopy_ram()) {
2188 ram_postcopy_send_discard_bitmap(ms
);
2192 * send rest of state - note things that are doing postcopy
2193 * will notice we're in POSTCOPY_ACTIVE and not actually
2194 * wrap their state up here
2196 migration_rate_set(bandwidth
);
2197 if (migrate_postcopy_ram()) {
2198 /* Ping just for debugging, helps line traces up */
2199 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2203 * While loading the device state we may trigger page transfer
2204 * requests and the fd must be free to process those, and thus
2205 * the destination must read the whole device state off the fd before
2206 * it starts processing it. Unfortunately the ad-hoc migration format
2207 * doesn't allow the destination to know the size to read without fully
2208 * parsing it through each devices load-state code (especially the open
2209 * coded devices that use get/put).
2210 * So we wrap the device state up in a package with a length at the start;
2211 * to do this we use a qemu_buf to hold the whole of the device state.
2213 bioc
= qio_channel_buffer_new(4096);
2214 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2215 fb
= qemu_file_new_output(QIO_CHANNEL(bioc
));
2216 object_unref(OBJECT(bioc
));
2219 * Make sure the receiver can get incoming pages before we send the rest
2222 qemu_savevm_send_postcopy_listen(fb
);
2224 qemu_savevm_state_complete_precopy(fb
, false, false);
2225 if (migrate_postcopy_ram()) {
2226 qemu_savevm_send_ping(fb
, 3);
2229 qemu_savevm_send_postcopy_run(fb
);
2231 /* <><> end of stuff going into the package */
2233 /* Last point of recovery; as soon as we send the package the destination
2234 * can open devices and potentially start running.
2235 * Lets just check again we've not got any errors.
2237 ret
= qemu_file_get_error(ms
->to_dst_file
);
2239 error_setg(errp
, "postcopy_start: Migration stream errored (pre package)");
2243 restart_block
= false;
2245 /* Now send that blob */
2246 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2251 /* Send a notify to give a chance for anything that needs to happen
2252 * at the transition to postcopy and after the device state; in particular
2253 * spice needs to trigger a transition now
2255 ms
->postcopy_after_devices
= true;
2256 migration_call_notifiers(ms
);
2258 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
2260 qemu_mutex_unlock_iothread();
2262 if (migrate_postcopy_ram()) {
2264 * Although this ping is just for debug, it could potentially be
2265 * used for getting a better measurement of downtime at the source.
2267 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2270 if (migrate_release_ram()) {
2271 ram_postcopy_migrated_memory_release(ms
);
2274 ret
= qemu_file_get_error(ms
->to_dst_file
);
2276 error_setg(errp
, "postcopy_start: Migration stream errored");
2277 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2278 MIGRATION_STATUS_FAILED
);
2281 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2288 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2289 MIGRATION_STATUS_FAILED
);
2290 if (restart_block
) {
2291 /* A failure happened early enough that we know the destination hasn't
2292 * accessed block devices, so we're safe to recover.
2294 Error
*local_err
= NULL
;
2296 bdrv_activate_all(&local_err
);
2298 error_report_err(local_err
);
2301 qemu_mutex_unlock_iothread();
2306 * migration_maybe_pause: Pause if required to by
2307 * migrate_pause_before_switchover called with the iothread locked
2308 * Returns: 0 on success
2310 static int migration_maybe_pause(MigrationState
*s
,
2311 int *current_active_state
,
2314 if (!migrate_pause_before_switchover()) {
2318 /* Since leaving this state is not atomic with posting the semaphore
2319 * it's possible that someone could have issued multiple migrate_continue
2320 * and the semaphore is incorrectly positive at this point;
2321 * the docs say it's undefined to reinit a semaphore that's already
2322 * init'd, so use timedwait to eat up any existing posts.
2324 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2325 /* This block intentionally left blank */
2329 * If the migration is cancelled when it is in the completion phase,
2330 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2331 * So we don't need to wait a semaphore, otherwise we would always
2332 * wait for the 'pause_sem' semaphore.
2334 if (s
->state
!= MIGRATION_STATUS_CANCELLING
) {
2335 qemu_mutex_unlock_iothread();
2336 migrate_set_state(&s
->state
, *current_active_state
,
2337 MIGRATION_STATUS_PRE_SWITCHOVER
);
2338 qemu_sem_wait(&s
->pause_sem
);
2339 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2341 *current_active_state
= new_state
;
2342 qemu_mutex_lock_iothread();
2345 return s
->state
== new_state
? 0 : -EINVAL
;
2348 static int migration_completion_precopy(MigrationState
*s
,
2349 int *current_active_state
)
2353 qemu_mutex_lock_iothread();
2354 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2355 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2357 s
->vm_old_state
= runstate_get();
2358 global_state_store();
2360 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2361 trace_migration_completion_vm_stop(ret
);
2366 ret
= migration_maybe_pause(s
, current_active_state
,
2367 MIGRATION_STATUS_DEVICE
);
2373 * Inactivate disks except in COLO, and track that we have done so in order
2374 * to remember to reactivate them if migration fails or is cancelled.
2376 s
->block_inactive
= !migrate_colo();
2377 migration_rate_set(RATE_LIMIT_DISABLED
);
2378 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2381 qemu_mutex_unlock_iothread();
2385 static void migration_completion_postcopy(MigrationState
*s
)
2387 trace_migration_completion_postcopy_end();
2389 qemu_mutex_lock_iothread();
2390 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2391 qemu_mutex_unlock_iothread();
2394 * Shutdown the postcopy fast path thread. This is only needed when dest
2395 * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
2397 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
2398 postcopy_preempt_shutdown_file(s
);
2401 trace_migration_completion_postcopy_end_after_complete();
2404 static void migration_completion_failed(MigrationState
*s
,
2405 int current_active_state
)
2407 if (s
->block_inactive
&& (s
->state
== MIGRATION_STATUS_ACTIVE
||
2408 s
->state
== MIGRATION_STATUS_DEVICE
)) {
2410 * If not doing postcopy, vm_start() will be called: let's
2411 * regain control on images.
2413 Error
*local_err
= NULL
;
2415 qemu_mutex_lock_iothread();
2416 bdrv_activate_all(&local_err
);
2418 error_report_err(local_err
);
2420 s
->block_inactive
= false;
2422 qemu_mutex_unlock_iothread();
2425 migrate_set_state(&s
->state
, current_active_state
,
2426 MIGRATION_STATUS_FAILED
);
2430 * migration_completion: Used by migration_thread when there's not much left.
2431 * The caller 'breaks' the loop when this returns.
2433 * @s: Current migration state
2435 static void migration_completion(MigrationState
*s
)
2438 int current_active_state
= s
->state
;
2440 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2441 ret
= migration_completion_precopy(s
, ¤t_active_state
);
2442 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2443 migration_completion_postcopy(s
);
2452 if (close_return_path_on_source(s
)) {
2456 if (qemu_file_get_error(s
->to_dst_file
)) {
2457 trace_migration_completion_file_err();
2461 if (migrate_colo() && s
->state
== MIGRATION_STATUS_ACTIVE
) {
2462 /* COLO does not support postcopy */
2463 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
2464 MIGRATION_STATUS_COLO
);
2466 migrate_set_state(&s
->state
, current_active_state
,
2467 MIGRATION_STATUS_COMPLETED
);
2473 migration_completion_failed(s
, current_active_state
);
2477 * bg_migration_completion: Used by bg_migration_thread when after all the
2478 * RAM has been saved. The caller 'breaks' the loop when this returns.
2480 * @s: Current migration state
2482 static void bg_migration_completion(MigrationState
*s
)
2484 int current_active_state
= s
->state
;
2486 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2488 * By this moment we have RAM content saved into the migration stream.
2489 * The next step is to flush the non-RAM content (device state)
2490 * right after the ram content. The device state has been stored into
2491 * the temporary buffer before RAM saving started.
2493 qemu_put_buffer(s
->to_dst_file
, s
->bioc
->data
, s
->bioc
->usage
);
2494 qemu_fflush(s
->to_dst_file
);
2495 } else if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
2499 if (qemu_file_get_error(s
->to_dst_file
)) {
2500 trace_migration_completion_file_err();
2504 migrate_set_state(&s
->state
, current_active_state
,
2505 MIGRATION_STATUS_COMPLETED
);
2509 migrate_set_state(&s
->state
, current_active_state
,
2510 MIGRATION_STATUS_FAILED
);
2513 typedef enum MigThrError
{
2514 /* No error detected */
2515 MIG_THR_ERR_NONE
= 0,
2516 /* Detected error, but resumed successfully */
2517 MIG_THR_ERR_RECOVERED
= 1,
2518 /* Detected fatal error, need to exit */
2519 MIG_THR_ERR_FATAL
= 2,
2522 static int postcopy_resume_handshake(MigrationState
*s
)
2524 qemu_savevm_send_postcopy_resume(s
->to_dst_file
);
2526 while (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2527 migration_rp_wait(s
);
2530 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2537 /* Return zero if success, or <0 for error */
2538 static int postcopy_do_resume(MigrationState
*s
)
2543 * Call all the resume_prepare() hooks, so that modules can be
2544 * ready for the migration resume.
2546 ret
= qemu_savevm_state_resume_prepare(s
);
2548 error_report("%s: resume_prepare() failure detected: %d",
2554 * If preempt is enabled, re-establish the preempt channel. Note that
2555 * we do it after resume prepare to make sure the main channel will be
2556 * created before the preempt channel. E.g. with weak network, the
2557 * dest QEMU may get messed up with the preempt and main channels on
2558 * the order of connection setup. This guarantees the correct order.
2560 ret
= postcopy_preempt_establish_channel(s
);
2562 error_report("%s: postcopy_preempt_establish_channel(): %d",
2568 * Last handshake with destination on the resume (destination will
2569 * switch to postcopy-active afterwards)
2571 ret
= postcopy_resume_handshake(s
);
2573 error_report("%s: handshake failed: %d", __func__
, ret
);
2581 * We don't return until we are in a safe state to continue current
2582 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2583 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2585 static MigThrError
postcopy_pause(MigrationState
*s
)
2587 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2593 * Current channel is possibly broken. Release it. Note that this is
2594 * guaranteed even without lock because to_dst_file should only be
2595 * modified by the migration thread. That also guarantees that the
2596 * unregister of yank is safe too without the lock. It should be safe
2597 * even to be within the qemu_file_lock, but we didn't do that to avoid
2598 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2599 * the qemu_file_lock critical section as small as possible.
2601 assert(s
->to_dst_file
);
2602 migration_ioc_unregister_yank_from_file(s
->to_dst_file
);
2603 qemu_mutex_lock(&s
->qemu_file_lock
);
2604 file
= s
->to_dst_file
;
2605 s
->to_dst_file
= NULL
;
2606 qemu_mutex_unlock(&s
->qemu_file_lock
);
2608 qemu_file_shutdown(file
);
2612 * We're already pausing, so ignore any errors on the return
2613 * path and just wait for the thread to finish. It will be
2614 * re-created when we resume.
2616 close_return_path_on_source(s
);
2618 migrate_set_state(&s
->state
, s
->state
,
2619 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2621 error_report("Detected IO failure for postcopy. "
2622 "Migration paused.");
2625 * We wait until things fixed up. Then someone will setup the
2626 * status back for us.
2628 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2629 qemu_sem_wait(&s
->postcopy_pause_sem
);
2632 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2633 /* Woken up by a recover procedure. Give it a shot */
2635 /* Do the resume logic */
2636 if (postcopy_do_resume(s
) == 0) {
2637 /* Let's continue! */
2638 trace_postcopy_pause_continued();
2639 return MIG_THR_ERR_RECOVERED
;
2642 * Something wrong happened during the recovery, let's
2643 * pause again. Pause is always better than throwing
2649 /* This is not right... Time to quit. */
2650 return MIG_THR_ERR_FATAL
;
2655 static MigThrError
migration_detect_error(MigrationState
*s
)
2658 int state
= s
->state
;
2659 Error
*local_error
= NULL
;
2661 if (state
== MIGRATION_STATUS_CANCELLING
||
2662 state
== MIGRATION_STATUS_CANCELLED
) {
2663 /* End the migration, but don't set the state to failed */
2664 return MIG_THR_ERR_FATAL
;
2668 * Try to detect any file errors. Note that postcopy_qemufile_src will
2669 * be NULL when postcopy preempt is not enabled.
2671 ret
= qemu_file_get_error_obj_any(s
->to_dst_file
,
2672 s
->postcopy_qemufile_src
,
2675 /* Everything is fine */
2676 assert(!local_error
);
2677 return MIG_THR_ERR_NONE
;
2681 migrate_set_error(s
, local_error
);
2682 error_free(local_error
);
2685 if (state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
) {
2687 * For postcopy, we allow the network to be down for a
2688 * while. After that, it can be continued by a
2691 return postcopy_pause(s
);
2694 * For precopy (or postcopy with error outside IO), we fail
2697 migrate_set_state(&s
->state
, state
, MIGRATION_STATUS_FAILED
);
2698 trace_migration_thread_file_err();
2700 /* Time to stop the migration, now. */
2701 return MIG_THR_ERR_FATAL
;
2705 static void migration_calculate_complete(MigrationState
*s
)
2707 uint64_t bytes
= migration_transferred_bytes();
2708 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2709 int64_t transfer_time
;
2711 s
->total_time
= end_time
- s
->start_time
;
2714 * It's still not set, so we are precopy migration. For
2715 * postcopy, downtime is calculated during postcopy_start().
2717 s
->downtime
= end_time
- s
->downtime_start
;
2720 transfer_time
= s
->total_time
- s
->setup_time
;
2721 if (transfer_time
) {
2722 s
->mbps
= ((double) bytes
* 8.0) / transfer_time
/ 1000;
2726 static void update_iteration_initial_status(MigrationState
*s
)
2729 * Update these three fields at the same time to avoid mismatch info lead
2730 * wrong speed calculation.
2732 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2733 s
->iteration_initial_bytes
= migration_transferred_bytes();
2734 s
->iteration_initial_pages
= ram_get_total_transferred_pages();
2737 static void migration_update_counters(MigrationState
*s
,
2738 int64_t current_time
)
2740 uint64_t transferred
, transferred_pages
, time_spent
;
2741 uint64_t current_bytes
; /* bytes transferred since the beginning */
2742 uint64_t switchover_bw
;
2743 /* Expected bandwidth when switching over to destination QEMU */
2744 double expected_bw_per_ms
;
2747 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
2751 switchover_bw
= migrate_avail_switchover_bandwidth();
2752 current_bytes
= migration_transferred_bytes();
2753 transferred
= current_bytes
- s
->iteration_initial_bytes
;
2754 time_spent
= current_time
- s
->iteration_start_time
;
2755 bandwidth
= (double)transferred
/ time_spent
;
2757 if (switchover_bw
) {
2759 * If the user specified a switchover bandwidth, let's trust the
2760 * user so that can be more accurate than what we estimated.
2762 expected_bw_per_ms
= switchover_bw
/ 1000;
2764 /* If the user doesn't specify bandwidth, we use the estimated */
2765 expected_bw_per_ms
= bandwidth
;
2768 s
->threshold_size
= expected_bw_per_ms
* migrate_downtime_limit();
2770 s
->mbps
= (((double) transferred
* 8.0) /
2771 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
2773 transferred_pages
= ram_get_total_transferred_pages() -
2774 s
->iteration_initial_pages
;
2775 s
->pages_per_second
= (double) transferred_pages
/
2776 (((double) time_spent
/ 1000.0));
2779 * if we haven't sent anything, we don't want to
2780 * recalculate. 10000 is a small enough number for our purposes
2782 if (stat64_get(&mig_stats
.dirty_pages_rate
) &&
2783 transferred
> 10000) {
2784 s
->expected_downtime
=
2785 stat64_get(&mig_stats
.dirty_bytes_last_sync
) / expected_bw_per_ms
;
2788 migration_rate_reset();
2790 update_iteration_initial_status(s
);
2792 trace_migrate_transferred(transferred
, time_spent
,
2793 /* Both in unit bytes/ms */
2794 bandwidth
, switchover_bw
/ 1000,
2798 static bool migration_can_switchover(MigrationState
*s
)
2800 if (!migrate_switchover_ack()) {
2804 /* No reason to wait for switchover ACK if VM is stopped */
2805 if (!runstate_is_running()) {
2809 return s
->switchover_acked
;
2812 /* Migration thread iteration status */
2814 MIG_ITERATE_RESUME
, /* Resume current iteration */
2815 MIG_ITERATE_SKIP
, /* Skip current iteration */
2816 MIG_ITERATE_BREAK
, /* Break the loop */
2820 * Return true if continue to the next iteration directly, false
2823 static MigIterateState
migration_iteration_run(MigrationState
*s
)
2825 uint64_t must_precopy
, can_postcopy
;
2826 Error
*local_err
= NULL
;
2827 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
2828 bool can_switchover
= migration_can_switchover(s
);
2830 qemu_savevm_state_pending_estimate(&must_precopy
, &can_postcopy
);
2831 uint64_t pending_size
= must_precopy
+ can_postcopy
;
2833 trace_migrate_pending_estimate(pending_size
, must_precopy
, can_postcopy
);
2835 if (must_precopy
<= s
->threshold_size
) {
2836 qemu_savevm_state_pending_exact(&must_precopy
, &can_postcopy
);
2837 pending_size
= must_precopy
+ can_postcopy
;
2838 trace_migrate_pending_exact(pending_size
, must_precopy
, can_postcopy
);
2841 if ((!pending_size
|| pending_size
< s
->threshold_size
) && can_switchover
) {
2842 trace_migration_thread_low_pending(pending_size
);
2843 migration_completion(s
);
2844 return MIG_ITERATE_BREAK
;
2847 /* Still a significant amount to transfer */
2848 if (!in_postcopy
&& must_precopy
<= s
->threshold_size
&& can_switchover
&&
2849 qatomic_read(&s
->start_postcopy
)) {
2850 if (postcopy_start(s
, &local_err
)) {
2851 migrate_set_error(s
, local_err
);
2852 error_report_err(local_err
);
2854 return MIG_ITERATE_SKIP
;
2857 /* Just another iteration step */
2858 qemu_savevm_state_iterate(s
->to_dst_file
, in_postcopy
);
2859 return MIG_ITERATE_RESUME
;
2862 static void migration_iteration_finish(MigrationState
*s
)
2864 /* If we enabled cpu throttling for auto-converge, turn it off. */
2865 cpu_throttle_stop();
2867 qemu_mutex_lock_iothread();
2869 case MIGRATION_STATUS_COMPLETED
:
2870 migration_calculate_complete(s
);
2871 runstate_set(RUN_STATE_POSTMIGRATE
);
2873 case MIGRATION_STATUS_COLO
:
2874 assert(migrate_colo());
2875 migrate_start_colo_process(s
);
2876 s
->vm_old_state
= RUN_STATE_RUNNING
;
2878 case MIGRATION_STATUS_FAILED
:
2879 case MIGRATION_STATUS_CANCELLED
:
2880 case MIGRATION_STATUS_CANCELLING
:
2881 if (s
->vm_old_state
== RUN_STATE_RUNNING
) {
2882 if (!runstate_check(RUN_STATE_SHUTDOWN
)) {
2886 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
2887 runstate_set(s
->vm_old_state
);
2893 /* Should not reach here, but if so, forgive the VM. */
2894 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2897 migrate_fd_cleanup_schedule(s
);
2898 qemu_mutex_unlock_iothread();
2901 static void bg_migration_iteration_finish(MigrationState
*s
)
2904 * Stop tracking RAM writes - un-protect memory, un-register UFFD
2905 * memory ranges, flush kernel wait queues and wake up threads
2906 * waiting for write fault to be resolved.
2908 ram_write_tracking_stop();
2910 qemu_mutex_lock_iothread();
2912 case MIGRATION_STATUS_COMPLETED
:
2913 migration_calculate_complete(s
);
2916 case MIGRATION_STATUS_ACTIVE
:
2917 case MIGRATION_STATUS_FAILED
:
2918 case MIGRATION_STATUS_CANCELLED
:
2919 case MIGRATION_STATUS_CANCELLING
:
2923 /* Should not reach here, but if so, forgive the VM. */
2924 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2928 migrate_fd_cleanup_schedule(s
);
2929 qemu_mutex_unlock_iothread();
2933 * Return true if continue to the next iteration directly, false
2936 static MigIterateState
bg_migration_iteration_run(MigrationState
*s
)
2940 res
= qemu_savevm_state_iterate(s
->to_dst_file
, false);
2942 bg_migration_completion(s
);
2943 return MIG_ITERATE_BREAK
;
2946 return MIG_ITERATE_RESUME
;
2949 void migration_make_urgent_request(void)
2951 qemu_sem_post(&migrate_get_current()->rate_limit_sem
);
2954 void migration_consume_urgent_request(void)
2956 qemu_sem_wait(&migrate_get_current()->rate_limit_sem
);
2959 /* Returns true if the rate limiting was broken by an urgent request */
2960 bool migration_rate_limit(void)
2962 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2963 MigrationState
*s
= migrate_get_current();
2965 bool urgent
= false;
2966 migration_update_counters(s
, now
);
2967 if (migration_rate_exceeded(s
->to_dst_file
)) {
2969 if (qemu_file_get_error(s
->to_dst_file
)) {
2973 * Wait for a delay to do rate limiting OR
2974 * something urgent to post the semaphore.
2976 int ms
= s
->iteration_start_time
+ BUFFER_DELAY
- now
;
2977 trace_migration_rate_limit_pre(ms
);
2978 if (qemu_sem_timedwait(&s
->rate_limit_sem
, ms
) == 0) {
2980 * We were woken by one or more urgent things but
2981 * the timedwait will have consumed one of them.
2982 * The service routine for the urgent wake will dec
2983 * the semaphore itself for each item it consumes,
2984 * so add this one we just eat back.
2986 qemu_sem_post(&s
->rate_limit_sem
);
2989 trace_migration_rate_limit_post(urgent
);
2995 * if failover devices are present, wait they are completely
2999 static void qemu_savevm_wait_unplug(MigrationState
*s
, int old_state
,
3002 if (qemu_savevm_state_guest_unplug_pending()) {
3003 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_WAIT_UNPLUG
);
3005 while (s
->state
== MIGRATION_STATUS_WAIT_UNPLUG
&&
3006 qemu_savevm_state_guest_unplug_pending()) {
3007 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3009 if (s
->state
!= MIGRATION_STATUS_WAIT_UNPLUG
) {
3010 int timeout
= 120; /* 30 seconds */
3012 * migration has been canceled
3013 * but as we have started an unplug we must wait the end
3014 * to be able to plug back the card
3016 while (timeout
-- && qemu_savevm_state_guest_unplug_pending()) {
3017 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3019 if (qemu_savevm_state_guest_unplug_pending() &&
3021 warn_report("migration: partially unplugged device on "
3026 migrate_set_state(&s
->state
, MIGRATION_STATUS_WAIT_UNPLUG
, new_state
);
3028 migrate_set_state(&s
->state
, old_state
, new_state
);
3033 * Master migration thread on the source VM.
3034 * It drives the migration and pumps the data down the outgoing channel.
3036 static void *migration_thread(void *opaque
)
3038 MigrationState
*s
= opaque
;
3039 MigrationThread
*thread
= NULL
;
3040 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3041 MigThrError thr_error
;
3042 bool urgent
= false;
3044 thread
= migration_threads_add("live_migration", qemu_get_thread_id());
3046 rcu_register_thread();
3048 object_ref(OBJECT(s
));
3049 update_iteration_initial_status(s
);
3051 qemu_mutex_lock_iothread();
3052 qemu_savevm_state_header(s
->to_dst_file
);
3053 qemu_mutex_unlock_iothread();
3056 * If we opened the return path, we need to make sure dst has it
3059 if (s
->rp_state
.rp_thread_created
) {
3060 /* Now tell the dest that it should open its end so it can reply */
3061 qemu_savevm_send_open_return_path(s
->to_dst_file
);
3063 /* And do a ping that will make stuff easier to debug */
3064 qemu_savevm_send_ping(s
->to_dst_file
, 1);
3067 if (migrate_postcopy()) {
3069 * Tell the destination that we *might* want to do postcopy later;
3070 * if the other end can't do postcopy it should fail now, nice and
3073 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
3076 if (migrate_colo()) {
3077 /* Notify migration destination that we enable COLO */
3078 qemu_savevm_send_colo_enable(s
->to_dst_file
);
3081 qemu_mutex_lock_iothread();
3082 qemu_savevm_state_setup(s
->to_dst_file
);
3083 qemu_mutex_unlock_iothread();
3085 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3086 MIGRATION_STATUS_ACTIVE
);
3088 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3090 trace_migration_thread_setup_complete();
3092 while (migration_is_active(s
)) {
3093 if (urgent
|| !migration_rate_exceeded(s
->to_dst_file
)) {
3094 MigIterateState iter_state
= migration_iteration_run(s
);
3095 if (iter_state
== MIG_ITERATE_SKIP
) {
3097 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3103 * Try to detect any kind of failures, and see whether we
3104 * should stop the migration now.
3106 thr_error
= migration_detect_error(s
);
3107 if (thr_error
== MIG_THR_ERR_FATAL
) {
3108 /* Stop migration */
3110 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
3112 * Just recovered from a e.g. network failure, reset all
3113 * the local variables. This is important to avoid
3114 * breaking transferred_bytes and bandwidth calculation
3116 update_iteration_initial_status(s
);
3119 urgent
= migration_rate_limit();
3122 trace_migration_thread_after_loop();
3123 migration_iteration_finish(s
);
3124 object_unref(OBJECT(s
));
3125 rcu_unregister_thread();
3126 migration_threads_remove(thread
);
3130 static void bg_migration_vm_start_bh(void *opaque
)
3132 MigrationState
*s
= opaque
;
3134 qemu_bh_delete(s
->vm_start_bh
);
3135 s
->vm_start_bh
= NULL
;
3138 s
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - s
->downtime_start
;
3142 * Background snapshot thread, based on live migration code.
3143 * This is an alternative implementation of live migration mechanism
3144 * introduced specifically to support background snapshots.
3146 * It takes advantage of userfault_fd write protection mechanism introduced
3147 * in v5.7 kernel. Compared to existing dirty page logging migration much
3148 * lesser stream traffic is produced resulting in smaller snapshot images,
3149 * simply cause of no page duplicates can get into the stream.
3151 * Another key point is that generated vmstate stream reflects machine state
3152 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3153 * mechanism, which effectively results in that saved snapshot is the state of VM
3154 * at the end of the process.
3156 static void *bg_migration_thread(void *opaque
)
3158 MigrationState
*s
= opaque
;
3159 int64_t setup_start
;
3160 MigThrError thr_error
;
3162 bool early_fail
= true;
3164 rcu_register_thread();
3165 object_ref(OBJECT(s
));
3167 migration_rate_set(RATE_LIMIT_DISABLED
);
3169 setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3171 * We want to save vmstate for the moment when migration has been
3172 * initiated but also we want to save RAM content while VM is running.
3173 * The RAM content should appear first in the vmstate. So, we first
3174 * stash the non-RAM part of the vmstate to the temporary buffer,
3175 * then write RAM part of the vmstate to the migration stream
3176 * with vCPUs running and, finally, write stashed non-RAM part of
3177 * the vmstate from the buffer to the migration stream.
3179 s
->bioc
= qio_channel_buffer_new(512 * 1024);
3180 qio_channel_set_name(QIO_CHANNEL(s
->bioc
), "vmstate-buffer");
3181 fb
= qemu_file_new_output(QIO_CHANNEL(s
->bioc
));
3182 object_unref(OBJECT(s
->bioc
));
3184 update_iteration_initial_status(s
);
3187 * Prepare for tracking memory writes with UFFD-WP - populate
3188 * RAM pages before protecting.
3191 ram_write_tracking_prepare();
3194 qemu_mutex_lock_iothread();
3195 qemu_savevm_state_header(s
->to_dst_file
);
3196 qemu_savevm_state_setup(s
->to_dst_file
);
3197 qemu_mutex_unlock_iothread();
3199 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3200 MIGRATION_STATUS_ACTIVE
);
3202 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3204 trace_migration_thread_setup_complete();
3205 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3207 qemu_mutex_lock_iothread();
3210 * If VM is currently in suspended state, then, to make a valid runstate
3211 * transition in vm_stop_force_state() we need to wakeup it up.
3213 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
3214 s
->vm_old_state
= runstate_get();
3216 global_state_store();
3217 /* Forcibly stop VM before saving state of vCPUs and devices */
3218 if (vm_stop_force_state(RUN_STATE_PAUSED
)) {
3222 * Put vCPUs in sync with shadow context structures, then
3223 * save their state to channel-buffer along with devices.
3225 cpu_synchronize_all_states();
3226 if (qemu_savevm_state_complete_precopy_non_iterable(fb
, false, false)) {
3230 * Since we are going to get non-iterable state data directly
3231 * from s->bioc->data, explicit flush is needed here.
3235 /* Now initialize UFFD context and start tracking RAM writes */
3236 if (ram_write_tracking_start()) {
3242 * Start VM from BH handler to avoid write-fault lock here.
3243 * UFFD-WP protection for the whole RAM is already enabled so
3244 * calling VM state change notifiers from vm_start() would initiate
3245 * writes to virtio VQs memory which is in write-protected region.
3247 s
->vm_start_bh
= qemu_bh_new(bg_migration_vm_start_bh
, s
);
3248 qemu_bh_schedule(s
->vm_start_bh
);
3250 qemu_mutex_unlock_iothread();
3252 while (migration_is_active(s
)) {
3253 MigIterateState iter_state
= bg_migration_iteration_run(s
);
3254 if (iter_state
== MIG_ITERATE_SKIP
) {
3256 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3261 * Try to detect any kind of failures, and see whether we
3262 * should stop the migration now.
3264 thr_error
= migration_detect_error(s
);
3265 if (thr_error
== MIG_THR_ERR_FATAL
) {
3266 /* Stop migration */
3270 migration_update_counters(s
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
));
3273 trace_migration_thread_after_loop();
3277 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
3278 MIGRATION_STATUS_FAILED
);
3279 qemu_mutex_unlock_iothread();
3282 bg_migration_iteration_finish(s
);
3285 object_unref(OBJECT(s
));
3286 rcu_unregister_thread();
3291 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
3293 Error
*local_err
= NULL
;
3294 uint64_t rate_limit
;
3295 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
3298 * If there's a previous error, free it and prepare for another one.
3299 * Meanwhile if migration completes successfully, there won't have an error
3300 * dumped when calling migrate_fd_cleanup().
3302 migrate_error_free(s
);
3304 s
->expected_downtime
= migrate_downtime_limit();
3306 assert(s
->cleanup_bh
);
3308 assert(!s
->cleanup_bh
);
3309 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup_bh
, s
);
3312 migrate_fd_error(s
, error_in
);
3315 * Don't do cleanup for resume if channel is invalid, but only dump
3316 * the error. We wait for another channel connect from the user.
3317 * The error_report still gives HMP user a hint on what failed.
3318 * It's normally done in migrate_fd_cleanup(), but call it here
3321 error_report_err(error_copy(s
->error
));
3323 migrate_fd_cleanup(s
);
3329 /* This is a resumed migration */
3330 rate_limit
= migrate_max_postcopy_bandwidth();
3332 /* This is a fresh new migration */
3333 rate_limit
= migrate_max_bandwidth();
3335 /* Notify before starting migration thread */
3336 migration_call_notifiers(s
);
3339 migration_rate_set(rate_limit
);
3340 qemu_file_set_blocking(s
->to_dst_file
, true);
3343 * Open the return path. For postcopy, it is used exclusively. For
3344 * precopy, only if user specified "return-path" capability would
3345 * QEMU uses the return path.
3347 if (migrate_postcopy_ram() || migrate_return_path()) {
3348 if (open_return_path_on_source(s
)) {
3349 error_setg(&local_err
, "Unable to open return-path for postcopy");
3350 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
3351 migrate_set_error(s
, local_err
);
3352 error_report_err(local_err
);
3353 migrate_fd_cleanup(s
);
3359 * This needs to be done before resuming a postcopy. Note: for newer
3360 * QEMUs we will delay the channel creation until postcopy_start(), to
3361 * avoid disorder of channel creations.
3363 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
3364 postcopy_preempt_setup(s
);
3368 /* Wakeup the main migration thread to do the recovery */
3369 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
3370 MIGRATION_STATUS_POSTCOPY_RECOVER
);
3371 qemu_sem_post(&s
->postcopy_pause_sem
);
3375 if (multifd_save_setup(&local_err
) != 0) {
3376 migrate_set_error(s
, local_err
);
3377 error_report_err(local_err
);
3378 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
3379 MIGRATION_STATUS_FAILED
);
3380 migrate_fd_cleanup(s
);
3384 if (migrate_background_snapshot()) {
3385 qemu_thread_create(&s
->thread
, "bg_snapshot",
3386 bg_migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3388 qemu_thread_create(&s
->thread
, "live_migration",
3389 migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3391 s
->migration_thread_running
= true;
3394 static void migration_class_init(ObjectClass
*klass
, void *data
)
3396 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3398 dc
->user_creatable
= false;
3399 device_class_set_props(dc
, migration_properties
);
3402 static void migration_instance_finalize(Object
*obj
)
3404 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3406 qemu_mutex_destroy(&ms
->error_mutex
);
3407 qemu_mutex_destroy(&ms
->qemu_file_lock
);
3408 qemu_sem_destroy(&ms
->wait_unplug_sem
);
3409 qemu_sem_destroy(&ms
->rate_limit_sem
);
3410 qemu_sem_destroy(&ms
->pause_sem
);
3411 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
3412 qemu_sem_destroy(&ms
->rp_state
.rp_sem
);
3413 qemu_sem_destroy(&ms
->rp_state
.rp_pong_acks
);
3414 qemu_sem_destroy(&ms
->postcopy_qemufile_src_sem
);
3415 error_free(ms
->error
);
3418 static void migration_instance_init(Object
*obj
)
3420 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3422 ms
->state
= MIGRATION_STATUS_NONE
;
3424 ms
->pages_per_second
= -1;
3425 qemu_sem_init(&ms
->pause_sem
, 0);
3426 qemu_mutex_init(&ms
->error_mutex
);
3428 migrate_params_init(&ms
->parameters
);
3430 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
3431 qemu_sem_init(&ms
->rp_state
.rp_sem
, 0);
3432 qemu_sem_init(&ms
->rp_state
.rp_pong_acks
, 0);
3433 qemu_sem_init(&ms
->rate_limit_sem
, 0);
3434 qemu_sem_init(&ms
->wait_unplug_sem
, 0);
3435 qemu_sem_init(&ms
->postcopy_qemufile_src_sem
, 0);
3436 qemu_mutex_init(&ms
->qemu_file_lock
);
3440 * Return true if check pass, false otherwise. Error will be put
3441 * inside errp if provided.
3443 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
3445 /* Assuming all off */
3446 bool old_caps
[MIGRATION_CAPABILITY__MAX
] = { 0 };
3448 if (!migrate_params_check(&ms
->parameters
, errp
)) {
3452 return migrate_caps_check(old_caps
, ms
->capabilities
, errp
);
3455 static const TypeInfo migration_type
= {
3456 .name
= TYPE_MIGRATION
,
3458 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3459 * not created using qdev_new(), it is not attached to the qdev
3460 * device tree, and it is never realized.
3462 * TODO: Make this TYPE_OBJECT once QOM provides something like
3463 * TYPE_DEVICE's "-global" properties.
3465 .parent
= TYPE_DEVICE
,
3466 .class_init
= migration_class_init
,
3467 .class_size
= sizeof(MigrationClass
),
3468 .instance_size
= sizeof(MigrationState
),
3469 .instance_init
= migration_instance_init
,
3470 .instance_finalize
= migration_instance_finalize
,
3473 static void register_migration_types(void)
3475 type_register_static(&migration_type
);
3478 type_init(register_migration_types
);