4 * Copyright IBM, Corp. 2008
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "qemu/main-loop.h"
20 #include "migration/blocker.h"
24 #include "sysemu/runstate.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/cpu-throttle.h"
29 #include "ram-compress.h"
30 #include "migration/global_state.h"
31 #include "migration/misc.h"
32 #include "migration.h"
33 #include "migration-stats.h"
35 #include "qemu-file.h"
37 #include "migration/vmstate.h"
38 #include "block/block.h"
39 #include "qapi/error.h"
40 #include "qapi/clone-visitor.h"
41 #include "qapi/qapi-visit-migration.h"
42 #include "qapi/qapi-visit-sockets.h"
43 #include "qapi/qapi-commands-migration.h"
44 #include "qapi/qapi-events-migration.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qmp/qnull.h"
49 #include "postcopy-ram.h"
50 #include "qemu/thread.h"
52 #include "exec/target_page.h"
53 #include "io/channel-buffer.h"
54 #include "io/channel-tls.h"
55 #include "migration/colo.h"
56 #include "hw/boards.h"
57 #include "monitor/monitor.h"
58 #include "net/announce.h"
59 #include "qemu/queue.h"
61 #include "threadinfo.h"
62 #include "qemu/yank.h"
63 #include "sysemu/cpus.h"
64 #include "yank_functions.h"
65 #include "sysemu/qtest.h"
67 #include "sysemu/dirtylimit.h"
69 static NotifierList migration_state_notifiers
=
70 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
72 /* Messages sent on the return path from destination to source */
73 enum mig_rp_message_type
{
74 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
75 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
76 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
78 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
79 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
80 MIG_RP_MSG_RECV_BITMAP
, /* send recved_bitmap back to source */
81 MIG_RP_MSG_RESUME_ACK
, /* tell source that we are ready to resume */
82 MIG_RP_MSG_SWITCHOVER_ACK
, /* Tell source it's OK to do switchover */
87 /* When we add fault tolerance, we could have several
88 migrations at once. For now we don't need to add
89 dynamic creation of migration */
91 static MigrationState
*current_migration
;
92 static MigrationIncomingState
*current_incoming
;
94 static GSList
*migration_blockers
;
96 static bool migration_object_check(MigrationState
*ms
, Error
**errp
);
97 static int migration_maybe_pause(MigrationState
*s
,
98 int *current_active_state
,
100 static void migrate_fd_cancel(MigrationState
*s
);
102 static bool migration_needs_multiple_sockets(void)
104 return migrate_multifd() || migrate_postcopy_preempt();
107 static bool uri_supports_multi_channels(const char *uri
)
109 return strstart(uri
, "tcp:", NULL
) || strstart(uri
, "unix:", NULL
) ||
110 strstart(uri
, "vsock:", NULL
);
114 migration_channels_and_uri_compatible(const char *uri
, Error
**errp
)
116 if (migration_needs_multiple_sockets() &&
117 !uri_supports_multi_channels(uri
)) {
118 error_setg(errp
, "Migration requires multi-channel URIs (e.g. tcp)");
125 static gint
page_request_addr_cmp(gconstpointer ap
, gconstpointer bp
)
127 uintptr_t a
= (uintptr_t) ap
, b
= (uintptr_t) bp
;
129 return (a
> b
) - (a
< b
);
132 void migration_object_init(void)
134 /* This can only be called once. */
135 assert(!current_migration
);
136 current_migration
= MIGRATION_OBJ(object_new(TYPE_MIGRATION
));
139 * Init the migrate incoming object as well no matter whether
140 * we'll use it or not.
142 assert(!current_incoming
);
143 current_incoming
= g_new0(MigrationIncomingState
, 1);
144 current_incoming
->state
= MIGRATION_STATUS_NONE
;
145 current_incoming
->postcopy_remote_fds
=
146 g_array_new(FALSE
, TRUE
, sizeof(struct PostCopyFD
));
147 qemu_mutex_init(¤t_incoming
->rp_mutex
);
148 qemu_mutex_init(¤t_incoming
->postcopy_prio_thread_mutex
);
149 qemu_event_init(¤t_incoming
->main_thread_load_event
, false);
150 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_dst
, 0);
151 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fault
, 0);
152 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fast_load
, 0);
153 qemu_sem_init(¤t_incoming
->postcopy_qemufile_dst_done
, 0);
155 qemu_mutex_init(¤t_incoming
->page_request_mutex
);
156 qemu_cond_init(¤t_incoming
->page_request_cond
);
157 current_incoming
->page_requested
= g_tree_new(page_request_addr_cmp
);
159 migration_object_check(current_migration
, &error_fatal
);
163 dirty_bitmap_mig_init();
166 void migration_cancel(const Error
*error
)
169 migrate_set_error(current_migration
, error
);
171 if (migrate_dirty_limit()) {
172 qmp_cancel_vcpu_dirty_limit(false, -1, NULL
);
174 migrate_fd_cancel(current_migration
);
177 void migration_shutdown(void)
180 * When the QEMU main thread exit, the COLO thread
181 * may wait a semaphore. So, we should wakeup the
182 * COLO thread before migration shutdown.
186 * Cancel the current migration - that will (eventually)
187 * stop the migration using this structure
189 migration_cancel(NULL
);
190 object_unref(OBJECT(current_migration
));
193 * Cancel outgoing migration of dirty bitmaps. It should
194 * at least unref used block nodes.
196 dirty_bitmap_mig_cancel_outgoing();
199 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
200 * are non-critical data, and their loss never considered as
203 dirty_bitmap_mig_cancel_incoming();
207 MigrationState
*migrate_get_current(void)
209 /* This can only be called after the object created. */
210 assert(current_migration
);
211 return current_migration
;
214 MigrationIncomingState
*migration_incoming_get_current(void)
216 assert(current_incoming
);
217 return current_incoming
;
220 void migration_incoming_transport_cleanup(MigrationIncomingState
*mis
)
222 if (mis
->socket_address_list
) {
223 qapi_free_SocketAddressList(mis
->socket_address_list
);
224 mis
->socket_address_list
= NULL
;
227 if (mis
->transport_cleanup
) {
228 mis
->transport_cleanup(mis
->transport_data
);
229 mis
->transport_data
= mis
->transport_cleanup
= NULL
;
233 void migration_incoming_state_destroy(void)
235 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
237 multifd_load_cleanup();
238 compress_threads_load_cleanup();
240 if (mis
->to_src_file
) {
241 /* Tell source that we are done */
242 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
243 qemu_fclose(mis
->to_src_file
);
244 mis
->to_src_file
= NULL
;
247 if (mis
->from_src_file
) {
248 migration_ioc_unregister_yank_from_file(mis
->from_src_file
);
249 qemu_fclose(mis
->from_src_file
);
250 mis
->from_src_file
= NULL
;
252 if (mis
->postcopy_remote_fds
) {
253 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
254 mis
->postcopy_remote_fds
= NULL
;
257 migration_incoming_transport_cleanup(mis
);
258 qemu_event_reset(&mis
->main_thread_load_event
);
260 if (mis
->page_requested
) {
261 g_tree_destroy(mis
->page_requested
);
262 mis
->page_requested
= NULL
;
265 if (mis
->postcopy_qemufile_dst
) {
266 migration_ioc_unregister_yank_from_file(mis
->postcopy_qemufile_dst
);
267 qemu_fclose(mis
->postcopy_qemufile_dst
);
268 mis
->postcopy_qemufile_dst
= NULL
;
271 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
274 static void migrate_generate_event(int new_state
)
276 if (migrate_events()) {
277 qapi_event_send_migration(new_state
);
282 * Send a message on the return channel back to the source
285 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
286 enum mig_rp_message_type message_type
,
287 uint16_t len
, void *data
)
291 trace_migrate_send_rp_message((int)message_type
, len
);
292 QEMU_LOCK_GUARD(&mis
->rp_mutex
);
295 * It's possible that the file handle got lost due to network
298 if (!mis
->to_src_file
) {
303 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
304 qemu_put_be16(mis
->to_src_file
, len
);
305 qemu_put_buffer(mis
->to_src_file
, data
, len
);
306 qemu_fflush(mis
->to_src_file
);
308 /* It's possible that qemu file got error during sending */
309 ret
= qemu_file_get_error(mis
->to_src_file
);
314 /* Request one page from the source VM at the given start address.
315 * rb: the RAMBlock to request the page in
316 * Start: Address offset within the RB
317 * Len: Length in bytes required - must be a multiple of pagesize
319 int migrate_send_rp_message_req_pages(MigrationIncomingState
*mis
,
320 RAMBlock
*rb
, ram_addr_t start
)
322 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
323 size_t msglen
= 12; /* start + len */
324 size_t len
= qemu_ram_pagesize(rb
);
325 enum mig_rp_message_type msg_type
;
329 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
330 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
333 * We maintain the last ramblock that we requested for page. Note that we
334 * don't need locking because this function will only be called within the
335 * postcopy ram fault thread.
337 if (rb
!= mis
->last_rb
) {
340 rbname
= qemu_ram_get_idstr(rb
);
341 rbname_len
= strlen(rbname
);
343 assert(rbname_len
< 256);
345 bufc
[msglen
++] = rbname_len
;
346 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
347 msglen
+= rbname_len
;
348 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
350 msg_type
= MIG_RP_MSG_REQ_PAGES
;
353 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
356 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
,
357 RAMBlock
*rb
, ram_addr_t start
, uint64_t haddr
)
359 void *aligned
= (void *)(uintptr_t)ROUND_DOWN(haddr
, qemu_ram_pagesize(rb
));
360 bool received
= false;
362 WITH_QEMU_LOCK_GUARD(&mis
->page_request_mutex
) {
363 received
= ramblock_recv_bitmap_test_byte_offset(rb
, start
);
364 if (!received
&& !g_tree_lookup(mis
->page_requested
, aligned
)) {
366 * The page has not been received, and it's not yet in the page
367 * request list. Queue it. Set the value of element to 1, so that
368 * things like g_tree_lookup() will return TRUE (1) when found.
370 g_tree_insert(mis
->page_requested
, aligned
, (gpointer
)1);
371 qatomic_inc(&mis
->page_requested_count
);
372 trace_postcopy_page_req_add(aligned
, mis
->page_requested_count
);
377 * If the page is there, skip sending the message. We don't even need the
378 * lock because as long as the page arrived, it'll be there forever.
384 return migrate_send_rp_message_req_pages(mis
, rb
, start
);
387 static bool migration_colo_enabled
;
388 bool migration_incoming_colo_enabled(void)
390 return migration_colo_enabled
;
393 void migration_incoming_disable_colo(void)
395 ram_block_discard_disable(false);
396 migration_colo_enabled
= false;
399 int migration_incoming_enable_colo(void)
401 #ifndef CONFIG_REPLICATION
402 error_report("ENABLE_COLO command come in migration stream, but COLO "
403 "module is not built in");
407 if (!migrate_colo()) {
408 error_report("ENABLE_COLO command come in migration stream, but c-colo "
409 "capability is not set");
413 if (ram_block_discard_disable(true)) {
414 error_report("COLO: cannot disable RAM discard");
417 migration_colo_enabled
= true;
421 void migrate_add_address(SocketAddress
*address
)
423 MigrationIncomingState
*mis
= migration_incoming_get_current();
425 QAPI_LIST_PREPEND(mis
->socket_address_list
,
426 QAPI_CLONE(SocketAddress
, address
));
429 static void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
431 const char *p
= NULL
;
433 /* URI is not suitable for migration? */
434 if (!migration_channels_and_uri_compatible(uri
, errp
)) {
438 qapi_event_send_migration(MIGRATION_STATUS_SETUP
);
439 if (strstart(uri
, "tcp:", &p
) ||
440 strstart(uri
, "unix:", NULL
) ||
441 strstart(uri
, "vsock:", NULL
)) {
442 socket_start_incoming_migration(p
? p
: uri
, errp
);
444 } else if (strstart(uri
, "rdma:", &p
)) {
445 rdma_start_incoming_migration(p
, errp
);
447 } else if (strstart(uri
, "exec:", &p
)) {
448 exec_start_incoming_migration(p
, errp
);
449 } else if (strstart(uri
, "fd:", &p
)) {
450 fd_start_incoming_migration(p
, errp
);
452 error_setg(errp
, "unknown migration protocol: %s", uri
);
456 static void process_incoming_migration_bh(void *opaque
)
458 Error
*local_err
= NULL
;
459 MigrationIncomingState
*mis
= opaque
;
461 /* If capability late_block_activate is set:
462 * Only fire up the block code now if we're going to restart the
463 * VM, else 'cont' will do it.
464 * This causes file locking to happen; so we don't want it to happen
465 * unless we really are starting the VM.
467 if (!migrate_late_block_activate() ||
468 (autostart
&& (!global_state_received() ||
469 global_state_get_runstate() == RUN_STATE_RUNNING
))) {
470 /* Make sure all file formats throw away their mutable metadata.
471 * If we get an error here, just don't restart the VM yet. */
472 bdrv_activate_all(&local_err
);
474 error_report_err(local_err
);
481 * This must happen after all error conditions are dealt with and
482 * we're sure the VM is going to be running on this host.
484 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
486 multifd_load_shutdown();
488 dirty_bitmap_mig_before_vm_start();
490 if (!global_state_received() ||
491 global_state_get_runstate() == RUN_STATE_RUNNING
) {
495 runstate_set(RUN_STATE_PAUSED
);
497 } else if (migration_incoming_colo_enabled()) {
498 migration_incoming_disable_colo();
501 runstate_set(global_state_get_runstate());
504 * This must happen after any state changes since as soon as an external
505 * observer sees this event they might start to prod at the VM assuming
508 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
509 MIGRATION_STATUS_COMPLETED
);
510 qemu_bh_delete(mis
->bh
);
511 migration_incoming_state_destroy();
514 static void coroutine_fn
515 process_incoming_migration_co(void *opaque
)
517 MigrationIncomingState
*mis
= migration_incoming_get_current();
521 assert(mis
->from_src_file
);
523 if (compress_threads_load_setup(mis
->from_src_file
)) {
524 error_report("Failed to setup decompress threads");
528 mis
->largest_page_size
= qemu_ram_pagesize_largest();
529 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
530 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
531 MIGRATION_STATUS_ACTIVE
);
533 mis
->loadvm_co
= qemu_coroutine_self();
534 ret
= qemu_loadvm_state(mis
->from_src_file
);
535 mis
->loadvm_co
= NULL
;
537 ps
= postcopy_state_get();
538 trace_process_incoming_migration_co_end(ret
, ps
);
539 if (ps
!= POSTCOPY_INCOMING_NONE
) {
540 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
542 * Where a migration had postcopy enabled (and thus went to advise)
543 * but managed to complete within the precopy period, we can use
546 postcopy_ram_incoming_cleanup(mis
);
547 } else if (ret
>= 0) {
549 * Postcopy was started, cleanup should happen at the end of the
552 trace_process_incoming_migration_co_postcopy_end_main();
555 /* Else if something went wrong then just fall out of the normal exit */
559 error_report("load of migration failed: %s", strerror(-ret
));
563 if (colo_incoming_co() < 0) {
567 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
568 qemu_bh_schedule(mis
->bh
);
571 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
572 MIGRATION_STATUS_FAILED
);
573 qemu_fclose(mis
->from_src_file
);
575 multifd_load_cleanup();
576 compress_threads_load_cleanup();
582 * migration_incoming_setup: Setup incoming migration
583 * @f: file for main migration channel
584 * @errp: where to put errors
586 * Returns: %true on success, %false on error.
588 static bool migration_incoming_setup(QEMUFile
*f
, Error
**errp
)
590 MigrationIncomingState
*mis
= migration_incoming_get_current();
592 if (!mis
->from_src_file
) {
593 mis
->from_src_file
= f
;
595 qemu_file_set_blocking(f
, false);
599 void migration_incoming_process(void)
601 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
602 qemu_coroutine_enter(co
);
605 /* Returns true if recovered from a paused migration, otherwise false */
606 static bool postcopy_try_recover(void)
608 MigrationIncomingState
*mis
= migration_incoming_get_current();
610 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
611 /* Resumed from a paused postcopy migration */
613 /* This should be set already in migration_incoming_setup() */
614 assert(mis
->from_src_file
);
615 /* Postcopy has standalone thread to do vm load */
616 qemu_file_set_blocking(mis
->from_src_file
, true);
618 /* Re-configure the return path */
619 mis
->to_src_file
= qemu_file_get_return_path(mis
->from_src_file
);
621 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
622 MIGRATION_STATUS_POSTCOPY_RECOVER
);
625 * Here, we only wake up the main loading thread (while the
626 * rest threads will still be waiting), so that we can receive
627 * commands from source now, and answer it if needed. The
628 * rest threads will be woken up afterwards until we are sure
629 * that source is ready to reply to page requests.
631 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
638 void migration_fd_process_incoming(QEMUFile
*f
, Error
**errp
)
640 if (!migration_incoming_setup(f
, errp
)) {
643 if (postcopy_try_recover()) {
646 migration_incoming_process();
650 * Returns true when we want to start a new incoming migration process,
653 static bool migration_should_start_incoming(bool main_channel
)
655 /* Multifd doesn't start unless all channels are established */
656 if (migrate_multifd()) {
657 return migration_has_all_channels();
660 /* Preempt channel only starts when the main channel is created */
661 if (migrate_postcopy_preempt()) {
666 * For all the rest types of migration, we should only reach here when
667 * it's the main channel that's being created, and we should always
668 * proceed with this channel.
670 assert(main_channel
);
674 void migration_ioc_process_incoming(QIOChannel
*ioc
, Error
**errp
)
676 MigrationIncomingState
*mis
= migration_incoming_get_current();
677 Error
*local_err
= NULL
;
679 bool default_channel
= true;
680 uint32_t channel_magic
= 0;
683 if (migrate_multifd() && !migrate_postcopy_ram() &&
684 qio_channel_has_feature(ioc
, QIO_CHANNEL_FEATURE_READ_MSG_PEEK
)) {
686 * With multiple channels, it is possible that we receive channels
687 * out of order on destination side, causing incorrect mapping of
688 * source channels on destination side. Check channel MAGIC to
689 * decide type of channel. Please note this is best effort, postcopy
690 * preempt channel does not send any magic number so avoid it for
691 * postcopy live migration. Also tls live migration already does
692 * tls handshake while initializing main channel so with tls this
693 * issue is not possible.
695 ret
= migration_channel_read_peek(ioc
, (void *)&channel_magic
,
696 sizeof(channel_magic
), &local_err
);
699 error_propagate(errp
, local_err
);
703 default_channel
= (channel_magic
== cpu_to_be32(QEMU_VM_FILE_MAGIC
));
705 default_channel
= !mis
->from_src_file
;
708 if (multifd_load_setup(errp
) != 0) {
709 error_setg(errp
, "Failed to setup multifd channels");
713 if (default_channel
) {
714 f
= qemu_file_new_input(ioc
);
716 if (!migration_incoming_setup(f
, errp
)) {
720 /* Multiple connections */
721 assert(migration_needs_multiple_sockets());
722 if (migrate_multifd()) {
723 multifd_recv_new_channel(ioc
, &local_err
);
725 assert(migrate_postcopy_preempt());
726 f
= qemu_file_new_input(ioc
);
727 postcopy_preempt_new_channel(mis
, f
);
730 error_propagate(errp
, local_err
);
735 if (migration_should_start_incoming(default_channel
)) {
736 /* If it's a recovery, we're done */
737 if (postcopy_try_recover()) {
740 migration_incoming_process();
745 * @migration_has_all_channels: We have received all channels that we need
747 * Returns true when we have got connections to all the channels that
748 * we need for migration.
750 bool migration_has_all_channels(void)
752 MigrationIncomingState
*mis
= migration_incoming_get_current();
754 if (!mis
->from_src_file
) {
758 if (migrate_multifd()) {
759 return multifd_recv_all_channels_created();
762 if (migrate_postcopy_preempt()) {
763 return mis
->postcopy_qemufile_dst
!= NULL
;
769 int migrate_send_rp_switchover_ack(MigrationIncomingState
*mis
)
771 return migrate_send_rp_message(mis
, MIG_RP_MSG_SWITCHOVER_ACK
, 0, NULL
);
775 * Send a 'SHUT' message on the return channel with the given value
776 * to indicate that we've finished with the RP. Non-0 value indicates
779 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
784 buf
= cpu_to_be32(value
);
785 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
789 * Send a 'PONG' message on the return channel with the given value
790 * (normally in response to a 'PING')
792 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
797 buf
= cpu_to_be32(value
);
798 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
801 void migrate_send_rp_recv_bitmap(MigrationIncomingState
*mis
,
809 * First, we send the header part. It contains only the len of
810 * idstr, and the idstr itself.
812 len
= strlen(block_name
);
814 memcpy(buf
+ 1, block_name
, len
);
816 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
817 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
822 migrate_send_rp_message(mis
, MIG_RP_MSG_RECV_BITMAP
, len
+ 1, buf
);
825 * Next, we dump the received bitmap to the stream.
827 * TODO: currently we are safe since we are the only one that is
828 * using the to_src_file handle (fault thread is still paused),
829 * and it's ok even not taking the mutex. However the best way is
830 * to take the lock before sending the message header, and release
831 * the lock after sending the bitmap.
833 qemu_mutex_lock(&mis
->rp_mutex
);
834 res
= ramblock_recv_bitmap_send(mis
->to_src_file
, block_name
);
835 qemu_mutex_unlock(&mis
->rp_mutex
);
837 trace_migrate_send_rp_recv_bitmap(block_name
, res
);
840 void migrate_send_rp_resume_ack(MigrationIncomingState
*mis
, uint32_t value
)
844 buf
= cpu_to_be32(value
);
845 migrate_send_rp_message(mis
, MIG_RP_MSG_RESUME_ACK
, sizeof(buf
), &buf
);
849 * Return true if we're already in the middle of a migration
850 * (i.e. any of the active or setup states)
852 bool migration_is_setup_or_active(int state
)
855 case MIGRATION_STATUS_ACTIVE
:
856 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
857 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
858 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
859 case MIGRATION_STATUS_SETUP
:
860 case MIGRATION_STATUS_PRE_SWITCHOVER
:
861 case MIGRATION_STATUS_DEVICE
:
862 case MIGRATION_STATUS_WAIT_UNPLUG
:
863 case MIGRATION_STATUS_COLO
:
872 bool migration_is_running(int state
)
875 case MIGRATION_STATUS_ACTIVE
:
876 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
877 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
878 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
879 case MIGRATION_STATUS_SETUP
:
880 case MIGRATION_STATUS_PRE_SWITCHOVER
:
881 case MIGRATION_STATUS_DEVICE
:
882 case MIGRATION_STATUS_WAIT_UNPLUG
:
883 case MIGRATION_STATUS_CANCELLING
:
892 static bool migrate_show_downtime(MigrationState
*s
)
894 return (s
->state
== MIGRATION_STATUS_COMPLETED
) || migration_in_postcopy();
897 static void populate_time_info(MigrationInfo
*info
, MigrationState
*s
)
899 info
->has_status
= true;
900 info
->has_setup_time
= true;
901 info
->setup_time
= s
->setup_time
;
903 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
904 info
->has_total_time
= true;
905 info
->total_time
= s
->total_time
;
907 info
->has_total_time
= true;
908 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) -
912 if (migrate_show_downtime(s
)) {
913 info
->has_downtime
= true;
914 info
->downtime
= s
->downtime
;
916 info
->has_expected_downtime
= true;
917 info
->expected_downtime
= s
->expected_downtime
;
921 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
923 size_t page_size
= qemu_target_page_size();
925 info
->ram
= g_malloc0(sizeof(*info
->ram
));
926 info
->ram
->transferred
= stat64_get(&mig_stats
.transferred
);
927 info
->ram
->total
= ram_bytes_total();
928 info
->ram
->duplicate
= stat64_get(&mig_stats
.zero_pages
);
929 /* legacy value. It is not used anymore */
930 info
->ram
->skipped
= 0;
931 info
->ram
->normal
= stat64_get(&mig_stats
.normal_pages
);
932 info
->ram
->normal_bytes
= info
->ram
->normal
* page_size
;
933 info
->ram
->mbps
= s
->mbps
;
934 info
->ram
->dirty_sync_count
=
935 stat64_get(&mig_stats
.dirty_sync_count
);
936 info
->ram
->dirty_sync_missed_zero_copy
=
937 stat64_get(&mig_stats
.dirty_sync_missed_zero_copy
);
938 info
->ram
->postcopy_requests
=
939 stat64_get(&mig_stats
.postcopy_requests
);
940 info
->ram
->page_size
= page_size
;
941 info
->ram
->multifd_bytes
= stat64_get(&mig_stats
.multifd_bytes
);
942 info
->ram
->pages_per_second
= s
->pages_per_second
;
943 info
->ram
->precopy_bytes
= stat64_get(&mig_stats
.precopy_bytes
);
944 info
->ram
->downtime_bytes
= stat64_get(&mig_stats
.downtime_bytes
);
945 info
->ram
->postcopy_bytes
= stat64_get(&mig_stats
.postcopy_bytes
);
947 if (migrate_xbzrle()) {
948 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
949 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
950 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
951 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
952 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
953 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
954 info
->xbzrle_cache
->encoding_rate
= xbzrle_counters
.encoding_rate
;
955 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
958 if (migrate_compress()) {
959 info
->compression
= g_malloc0(sizeof(*info
->compression
));
960 info
->compression
->pages
= compression_counters
.pages
;
961 info
->compression
->busy
= compression_counters
.busy
;
962 info
->compression
->busy_rate
= compression_counters
.busy_rate
;
963 info
->compression
->compressed_size
=
964 compression_counters
.compressed_size
;
965 info
->compression
->compression_rate
=
966 compression_counters
.compression_rate
;
969 if (cpu_throttle_active()) {
970 info
->has_cpu_throttle_percentage
= true;
971 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
974 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
975 info
->ram
->remaining
= ram_bytes_remaining();
976 info
->ram
->dirty_pages_rate
=
977 stat64_get(&mig_stats
.dirty_pages_rate
);
980 if (migrate_dirty_limit() && dirtylimit_in_service()) {
981 info
->has_dirty_limit_throttle_time_per_round
= true;
982 info
->dirty_limit_throttle_time_per_round
=
983 dirtylimit_throttle_time_per_round();
985 info
->has_dirty_limit_ring_full_time
= true;
986 info
->dirty_limit_ring_full_time
= dirtylimit_ring_full_time();
990 static void populate_disk_info(MigrationInfo
*info
)
992 if (blk_mig_active()) {
993 info
->disk
= g_malloc0(sizeof(*info
->disk
));
994 info
->disk
->transferred
= blk_mig_bytes_transferred();
995 info
->disk
->remaining
= blk_mig_bytes_remaining();
996 info
->disk
->total
= blk_mig_bytes_total();
1000 static void fill_source_migration_info(MigrationInfo
*info
)
1002 MigrationState
*s
= migrate_get_current();
1003 int state
= qatomic_read(&s
->state
);
1004 GSList
*cur_blocker
= migration_blockers
;
1006 info
->blocked_reasons
= NULL
;
1009 * There are two types of reasons a migration might be blocked;
1010 * a) devices marked in VMState as non-migratable, and
1011 * b) Explicit migration blockers
1012 * We need to add both of them here.
1014 qemu_savevm_non_migratable_list(&info
->blocked_reasons
);
1016 while (cur_blocker
) {
1017 QAPI_LIST_PREPEND(info
->blocked_reasons
,
1018 g_strdup(error_get_pretty(cur_blocker
->data
)));
1019 cur_blocker
= g_slist_next(cur_blocker
);
1021 info
->has_blocked_reasons
= info
->blocked_reasons
!= NULL
;
1024 case MIGRATION_STATUS_NONE
:
1025 /* no migration has happened ever */
1026 /* do not overwrite destination migration status */
1028 case MIGRATION_STATUS_SETUP
:
1029 info
->has_status
= true;
1030 info
->has_total_time
= false;
1032 case MIGRATION_STATUS_ACTIVE
:
1033 case MIGRATION_STATUS_CANCELLING
:
1034 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1035 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1036 case MIGRATION_STATUS_DEVICE
:
1037 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1038 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1039 /* TODO add some postcopy stats */
1040 populate_time_info(info
, s
);
1041 populate_ram_info(info
, s
);
1042 populate_disk_info(info
);
1043 migration_populate_vfio_info(info
);
1045 case MIGRATION_STATUS_COLO
:
1046 info
->has_status
= true;
1047 /* TODO: display COLO specific information (checkpoint info etc.) */
1049 case MIGRATION_STATUS_COMPLETED
:
1050 populate_time_info(info
, s
);
1051 populate_ram_info(info
, s
);
1052 migration_populate_vfio_info(info
);
1054 case MIGRATION_STATUS_FAILED
:
1055 info
->has_status
= true;
1057 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
1060 case MIGRATION_STATUS_CANCELLED
:
1061 info
->has_status
= true;
1063 case MIGRATION_STATUS_WAIT_UNPLUG
:
1064 info
->has_status
= true;
1067 info
->status
= state
;
1070 static void fill_destination_migration_info(MigrationInfo
*info
)
1072 MigrationIncomingState
*mis
= migration_incoming_get_current();
1074 if (mis
->socket_address_list
) {
1075 info
->has_socket_address
= true;
1076 info
->socket_address
=
1077 QAPI_CLONE(SocketAddressList
, mis
->socket_address_list
);
1080 switch (mis
->state
) {
1081 case MIGRATION_STATUS_NONE
:
1083 case MIGRATION_STATUS_SETUP
:
1084 case MIGRATION_STATUS_CANCELLING
:
1085 case MIGRATION_STATUS_CANCELLED
:
1086 case MIGRATION_STATUS_ACTIVE
:
1087 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1088 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1089 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1090 case MIGRATION_STATUS_FAILED
:
1091 case MIGRATION_STATUS_COLO
:
1092 info
->has_status
= true;
1094 case MIGRATION_STATUS_COMPLETED
:
1095 info
->has_status
= true;
1096 fill_destination_postcopy_migration_info(info
);
1099 info
->status
= mis
->state
;
1102 MigrationInfo
*qmp_query_migrate(Error
**errp
)
1104 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
1106 fill_destination_migration_info(info
);
1107 fill_source_migration_info(info
);
1112 void qmp_migrate_start_postcopy(Error
**errp
)
1114 MigrationState
*s
= migrate_get_current();
1116 if (!migrate_postcopy()) {
1117 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1118 " the start of migration");
1122 if (s
->state
== MIGRATION_STATUS_NONE
) {
1123 error_setg(errp
, "Postcopy must be started after migration has been"
1128 * we don't error if migration has finished since that would be racy
1129 * with issuing this command.
1131 qatomic_set(&s
->start_postcopy
, true);
1134 /* shared migration helpers */
1136 void migrate_set_state(int *state
, int old_state
, int new_state
)
1138 assert(new_state
< MIGRATION_STATUS__MAX
);
1139 if (qatomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1140 trace_migrate_set_state(MigrationStatus_str(new_state
));
1141 migrate_generate_event(new_state
);
1145 static void migrate_fd_cleanup(MigrationState
*s
)
1147 qemu_bh_delete(s
->cleanup_bh
);
1148 s
->cleanup_bh
= NULL
;
1150 g_free(s
->hostname
);
1152 json_writer_free(s
->vmdesc
);
1155 qemu_savevm_state_cleanup();
1157 if (s
->to_dst_file
) {
1160 trace_migrate_fd_cleanup();
1161 qemu_mutex_unlock_iothread();
1162 if (s
->migration_thread_running
) {
1163 qemu_thread_join(&s
->thread
);
1164 s
->migration_thread_running
= false;
1166 qemu_mutex_lock_iothread();
1168 multifd_save_cleanup();
1169 qemu_mutex_lock(&s
->qemu_file_lock
);
1170 tmp
= s
->to_dst_file
;
1171 s
->to_dst_file
= NULL
;
1172 qemu_mutex_unlock(&s
->qemu_file_lock
);
1174 * Close the file handle without the lock to make sure the
1175 * critical section won't block for long.
1177 migration_ioc_unregister_yank_from_file(tmp
);
1181 assert(!migration_is_active(s
));
1183 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1184 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1185 MIGRATION_STATUS_CANCELLED
);
1189 /* It is used on info migrate. We can't free it */
1190 error_report_err(error_copy(s
->error
));
1192 notifier_list_notify(&migration_state_notifiers
, s
);
1193 block_cleanup_parameters();
1194 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1197 static void migrate_fd_cleanup_schedule(MigrationState
*s
)
1200 * Ref the state for bh, because it may be called when
1201 * there're already no other refs
1203 object_ref(OBJECT(s
));
1204 qemu_bh_schedule(s
->cleanup_bh
);
1207 static void migrate_fd_cleanup_bh(void *opaque
)
1209 MigrationState
*s
= opaque
;
1210 migrate_fd_cleanup(s
);
1211 object_unref(OBJECT(s
));
1214 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1216 QEMU_LOCK_GUARD(&s
->error_mutex
);
1218 s
->error
= error_copy(error
);
1222 static void migrate_error_free(MigrationState
*s
)
1224 QEMU_LOCK_GUARD(&s
->error_mutex
);
1226 error_free(s
->error
);
1231 static void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1233 trace_migrate_fd_error(error_get_pretty(error
));
1234 assert(s
->to_dst_file
== NULL
);
1235 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1236 MIGRATION_STATUS_FAILED
);
1237 migrate_set_error(s
, error
);
1240 static void migrate_fd_cancel(MigrationState
*s
)
1244 trace_migrate_fd_cancel();
1246 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1247 if (s
->rp_state
.from_dst_file
) {
1248 /* shutdown the rp socket, so causing the rp thread to shutdown */
1249 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1254 old_state
= s
->state
;
1255 if (!migration_is_running(old_state
)) {
1258 /* If the migration is paused, kick it out of the pause */
1259 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1260 qemu_sem_post(&s
->pause_sem
);
1262 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1263 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1266 * If we're unlucky the migration code might be stuck somewhere in a
1267 * send/write while the network has failed and is waiting to timeout;
1268 * if we've got shutdown(2) available then we can force it to quit.
1270 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1271 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1272 if (s
->to_dst_file
) {
1273 qemu_file_shutdown(s
->to_dst_file
);
1277 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1278 Error
*local_err
= NULL
;
1280 bdrv_activate_all(&local_err
);
1282 error_report_err(local_err
);
1284 s
->block_inactive
= false;
1289 void add_migration_state_change_notifier(Notifier
*notify
)
1291 notifier_list_add(&migration_state_notifiers
, notify
);
1294 void remove_migration_state_change_notifier(Notifier
*notify
)
1296 notifier_remove(notify
);
1299 bool migration_in_setup(MigrationState
*s
)
1301 return s
->state
== MIGRATION_STATUS_SETUP
;
1304 bool migration_has_finished(MigrationState
*s
)
1306 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1309 bool migration_has_failed(MigrationState
*s
)
1311 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1312 s
->state
== MIGRATION_STATUS_FAILED
);
1315 bool migration_in_postcopy(void)
1317 MigrationState
*s
= migrate_get_current();
1320 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1321 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1322 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1329 bool migration_in_postcopy_after_devices(MigrationState
*s
)
1331 return migration_in_postcopy() && s
->postcopy_after_devices
;
1334 bool migration_in_incoming_postcopy(void)
1336 PostcopyState ps
= postcopy_state_get();
1338 return ps
>= POSTCOPY_INCOMING_DISCARD
&& ps
< POSTCOPY_INCOMING_END
;
1341 bool migration_incoming_postcopy_advised(void)
1343 PostcopyState ps
= postcopy_state_get();
1345 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
1348 bool migration_in_bg_snapshot(void)
1350 MigrationState
*s
= migrate_get_current();
1352 return migrate_background_snapshot() &&
1353 migration_is_setup_or_active(s
->state
);
1356 bool migration_is_idle(void)
1358 MigrationState
*s
= current_migration
;
1365 case MIGRATION_STATUS_NONE
:
1366 case MIGRATION_STATUS_CANCELLED
:
1367 case MIGRATION_STATUS_COMPLETED
:
1368 case MIGRATION_STATUS_FAILED
:
1370 case MIGRATION_STATUS_SETUP
:
1371 case MIGRATION_STATUS_CANCELLING
:
1372 case MIGRATION_STATUS_ACTIVE
:
1373 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1374 case MIGRATION_STATUS_COLO
:
1375 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1376 case MIGRATION_STATUS_DEVICE
:
1377 case MIGRATION_STATUS_WAIT_UNPLUG
:
1379 case MIGRATION_STATUS__MAX
:
1380 g_assert_not_reached();
1386 bool migration_is_active(MigrationState
*s
)
1388 return (s
->state
== MIGRATION_STATUS_ACTIVE
||
1389 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1392 int migrate_init(MigrationState
*s
, Error
**errp
)
1396 ret
= qemu_savevm_state_prepare(errp
);
1402 * Reinitialise all migration state, except
1403 * parameters/capabilities that the user set, and
1408 s
->to_dst_file
= NULL
;
1409 s
->state
= MIGRATION_STATUS_NONE
;
1410 s
->rp_state
.from_dst_file
= NULL
;
1411 s
->rp_state
.error
= false;
1413 s
->pages_per_second
= 0.0;
1415 s
->expected_downtime
= 0;
1417 s
->start_postcopy
= false;
1418 s
->postcopy_after_devices
= false;
1419 s
->migration_thread_running
= false;
1420 error_free(s
->error
);
1424 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1426 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1428 s
->vm_old_state
= -1;
1429 s
->iteration_initial_bytes
= 0;
1430 s
->threshold_size
= 0;
1431 s
->switchover_acked
= false;
1433 * set mig_stats compression_counters memory to zero for a
1436 memset(&mig_stats
, 0, sizeof(mig_stats
));
1437 memset(&compression_counters
, 0, sizeof(compression_counters
));
1438 migration_reset_vfio_bytes_transferred();
1443 int migrate_add_blocker_internal(Error
*reason
, Error
**errp
)
1445 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1446 if (runstate_check(RUN_STATE_SAVE_VM
) || !migration_is_idle()) {
1447 error_propagate_prepend(errp
, error_copy(reason
),
1448 "disallowing migration blocker "
1449 "(migration/snapshot in progress) for: ");
1453 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
1457 int migrate_add_blocker(Error
*reason
, Error
**errp
)
1459 if (only_migratable
) {
1460 error_propagate_prepend(errp
, error_copy(reason
),
1461 "disallowing migration blocker "
1462 "(--only-migratable) for: ");
1466 return migrate_add_blocker_internal(reason
, errp
);
1469 void migrate_del_blocker(Error
*reason
)
1471 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
1474 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
1476 Error
*local_err
= NULL
;
1477 static bool once
= true;
1480 error_setg(errp
, "The incoming migration has already been started");
1483 if (!runstate_check(RUN_STATE_INMIGRATE
)) {
1484 error_setg(errp
, "'-incoming' was not specified on the command line");
1488 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1492 qemu_start_incoming_migration(uri
, &local_err
);
1495 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1496 error_propagate(errp
, local_err
);
1503 void qmp_migrate_recover(const char *uri
, Error
**errp
)
1505 MigrationIncomingState
*mis
= migration_incoming_get_current();
1508 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1509 * callers (no one should ignore a recover failure); if there is, it's a
1510 * programming error.
1514 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1515 error_setg(errp
, "Migrate recover can only be run "
1516 "when postcopy is paused.");
1520 /* If there's an existing transport, release it */
1521 migration_incoming_transport_cleanup(mis
);
1524 * Note that this call will never start a real migration; it will
1525 * only re-setup the migration stream and poke existing migration
1526 * to continue using that newly established channel.
1528 qemu_start_incoming_migration(uri
, errp
);
1531 void qmp_migrate_pause(Error
**errp
)
1533 MigrationState
*ms
= migrate_get_current();
1534 MigrationIncomingState
*mis
= migration_incoming_get_current();
1537 if (ms
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1538 /* Source side, during postcopy */
1539 qemu_mutex_lock(&ms
->qemu_file_lock
);
1540 if (ms
->to_dst_file
) {
1541 ret
= qemu_file_shutdown(ms
->to_dst_file
);
1543 qemu_mutex_unlock(&ms
->qemu_file_lock
);
1545 error_setg(errp
, "Failed to pause source migration");
1550 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1551 ret
= qemu_file_shutdown(mis
->from_src_file
);
1553 error_setg(errp
, "Failed to pause destination migration");
1558 error_setg(errp
, "migrate-pause is currently only supported "
1559 "during postcopy-active state");
1562 bool migration_is_blocked(Error
**errp
)
1564 if (qemu_savevm_state_blocked(errp
)) {
1568 if (migration_blockers
) {
1569 error_propagate(errp
, error_copy(migration_blockers
->data
));
1576 /* Returns true if continue to migrate, or false if error detected */
1577 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1578 bool resume
, Error
**errp
)
1580 Error
*local_err
= NULL
;
1583 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1584 error_setg(errp
, "Cannot resume if there is no "
1585 "paused migration");
1590 * Postcopy recovery won't work well with release-ram
1591 * capability since release-ram will drop the page buffer as
1592 * long as the page is put into the send buffer. So if there
1593 * is a network failure happened, any page buffers that have
1594 * not yet reached the destination VM but have already been
1595 * sent from the source VM will be lost forever. Let's refuse
1596 * the client from resuming such a postcopy migration.
1597 * Luckily release-ram was designed to only be used when src
1598 * and destination VMs are on the same host, so it should be
1601 if (migrate_release_ram()) {
1602 error_setg(errp
, "Postcopy recovery cannot work "
1603 "when release-ram capability is set");
1607 /* This is a resume, skip init status */
1611 if (migration_is_running(s
->state
)) {
1612 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1616 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1617 error_setg(errp
, "Guest is waiting for an incoming migration");
1621 if (runstate_check(RUN_STATE_POSTMIGRATE
)) {
1622 error_setg(errp
, "Can't migrate the vm that was paused due to "
1623 "previous migration");
1627 if (migration_is_blocked(errp
)) {
1631 if (blk
|| blk_inc
) {
1632 if (migrate_colo()) {
1633 error_setg(errp
, "No disk migration is required in COLO mode");
1636 if (migrate_block() || migrate_block_incremental()) {
1637 error_setg(errp
, "Command options are incompatible with "
1638 "current migration capabilities");
1641 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK
, true, &local_err
)) {
1642 error_propagate(errp
, local_err
);
1645 s
->must_remove_block_options
= true;
1649 migrate_set_block_incremental(true);
1652 if (migrate_init(s
, errp
)) {
1659 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1660 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1661 bool has_resume
, bool resume
, Error
**errp
)
1663 bool resume_requested
;
1664 Error
*local_err
= NULL
;
1665 MigrationState
*s
= migrate_get_current();
1666 const char *p
= NULL
;
1668 /* URI is not suitable for migration? */
1669 if (!migration_channels_and_uri_compatible(uri
, errp
)) {
1673 resume_requested
= has_resume
&& resume
;
1674 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
1675 resume_requested
, errp
)) {
1676 /* Error detected, put into errp */
1680 if (!resume_requested
) {
1681 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1686 if (strstart(uri
, "tcp:", &p
) ||
1687 strstart(uri
, "unix:", NULL
) ||
1688 strstart(uri
, "vsock:", NULL
)) {
1689 socket_start_outgoing_migration(s
, p
? p
: uri
, &local_err
);
1691 } else if (strstart(uri
, "rdma:", &p
)) {
1692 rdma_start_outgoing_migration(s
, p
, &local_err
);
1694 } else if (strstart(uri
, "exec:", &p
)) {
1695 exec_start_outgoing_migration(s
, p
, &local_err
);
1696 } else if (strstart(uri
, "fd:", &p
)) {
1697 fd_start_outgoing_migration(s
, p
, &local_err
);
1699 if (!resume_requested
) {
1700 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1702 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1703 "a valid migration protocol");
1704 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1705 MIGRATION_STATUS_FAILED
);
1706 block_cleanup_parameters();
1711 if (!resume_requested
) {
1712 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1714 migrate_fd_error(s
, local_err
);
1715 error_propagate(errp
, local_err
);
1720 void qmp_migrate_cancel(Error
**errp
)
1722 migration_cancel(NULL
);
1725 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
1727 MigrationState
*s
= migrate_get_current();
1728 if (s
->state
!= state
) {
1729 error_setg(errp
, "Migration not in expected state: %s",
1730 MigrationStatus_str(s
->state
));
1733 qemu_sem_post(&s
->pause_sem
);
1736 /* migration thread support */
1738 * Something bad happened to the RP stream, mark an error
1739 * The caller shall print or trace something to indicate why
1741 static void mark_source_rp_bad(MigrationState
*s
)
1743 s
->rp_state
.error
= true;
1746 static struct rp_cmd_args
{
1747 ssize_t len
; /* -1 = variable */
1750 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1751 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1752 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1753 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1754 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1755 [MIG_RP_MSG_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
1756 [MIG_RP_MSG_RESUME_ACK
] = { .len
= 4, .name
= "RESUME_ACK" },
1757 [MIG_RP_MSG_SWITCHOVER_ACK
] = { .len
= 0, .name
= "SWITCHOVER_ACK" },
1758 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1762 * Process a request for pages received on the return path,
1763 * We're allowed to send more than requested (e.g. to round to our page size)
1764 * and we don't need to send pages that have already been sent.
1766 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1767 ram_addr_t start
, size_t len
)
1769 long our_host_ps
= qemu_real_host_page_size();
1771 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1774 * Since we currently insist on matching page sizes, just sanity check
1775 * we're being asked for whole host pages.
1777 if (!QEMU_IS_ALIGNED(start
, our_host_ps
) ||
1778 !QEMU_IS_ALIGNED(len
, our_host_ps
)) {
1779 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1780 " len: %zd", __func__
, start
, len
);
1781 mark_source_rp_bad(ms
);
1785 if (ram_save_queue_pages(rbname
, start
, len
)) {
1786 mark_source_rp_bad(ms
);
1790 /* Return true to retry, false to quit */
1791 static bool postcopy_pause_return_path_thread(MigrationState
*s
)
1793 trace_postcopy_pause_return_path();
1795 qemu_sem_wait(&s
->postcopy_pause_rp_sem
);
1797 trace_postcopy_pause_return_path_continued();
1802 static int migrate_handle_rp_recv_bitmap(MigrationState
*s
, char *block_name
)
1804 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
1807 error_report("%s: invalid block name '%s'", __func__
, block_name
);
1811 /* Fetch the received bitmap and refresh the dirty bitmap */
1812 return ram_dirty_bitmap_reload(s
, block
);
1815 static int migrate_handle_rp_resume_ack(MigrationState
*s
, uint32_t value
)
1817 trace_source_return_path_thread_resume_ack(value
);
1819 if (value
!= MIGRATION_RESUME_ACK_VALUE
) {
1820 error_report("%s: illegal resume_ack value %"PRIu32
,
1825 /* Now both sides are active. */
1826 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
1827 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1829 /* Notify send thread that time to continue send pages */
1830 qemu_sem_post(&s
->rp_state
.rp_sem
);
1836 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
1837 * existed) in a safe way.
1839 static void migration_release_dst_files(MigrationState
*ms
)
1843 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
1845 * Reset the from_dst_file pointer first before releasing it, as we
1846 * can't block within lock section
1848 file
= ms
->rp_state
.from_dst_file
;
1849 ms
->rp_state
.from_dst_file
= NULL
;
1853 * Do the same to postcopy fast path socket too if there is. No
1854 * locking needed because this qemufile should only be managed by
1855 * return path thread.
1857 if (ms
->postcopy_qemufile_src
) {
1858 migration_ioc_unregister_yank_from_file(ms
->postcopy_qemufile_src
);
1859 qemu_file_shutdown(ms
->postcopy_qemufile_src
);
1860 qemu_fclose(ms
->postcopy_qemufile_src
);
1861 ms
->postcopy_qemufile_src
= NULL
;
1868 * Handles messages sent on the return path towards the source VM
1871 static void *source_return_path_thread(void *opaque
)
1873 MigrationState
*ms
= opaque
;
1874 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1875 uint16_t header_len
, header_type
;
1877 uint32_t tmp32
, sibling_error
;
1878 ram_addr_t start
= 0; /* =0 to silence warning */
1879 size_t len
= 0, expected_len
;
1882 trace_source_return_path_thread_entry();
1883 rcu_register_thread();
1886 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1887 migration_is_setup_or_active(ms
->state
)) {
1888 trace_source_return_path_thread_loop_top();
1889 header_type
= qemu_get_be16(rp
);
1890 header_len
= qemu_get_be16(rp
);
1892 if (qemu_file_get_error(rp
)) {
1893 mark_source_rp_bad(ms
);
1897 if (header_type
>= MIG_RP_MSG_MAX
||
1898 header_type
== MIG_RP_MSG_INVALID
) {
1899 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1900 header_type
, header_len
);
1901 mark_source_rp_bad(ms
);
1905 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1906 header_len
!= rp_cmd_args
[header_type
].len
) ||
1907 header_len
> sizeof(buf
)) {
1908 error_report("RP: Received '%s' message (0x%04x) with"
1909 "incorrect length %d expecting %zu",
1910 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1911 (size_t)rp_cmd_args
[header_type
].len
);
1912 mark_source_rp_bad(ms
);
1916 /* We know we've got a valid header by this point */
1917 res
= qemu_get_buffer(rp
, buf
, header_len
);
1918 if (res
!= header_len
) {
1919 error_report("RP: Failed reading data for message 0x%04x"
1920 " read %d expected %d",
1921 header_type
, res
, header_len
);
1922 mark_source_rp_bad(ms
);
1926 /* OK, we have the message and the data */
1927 switch (header_type
) {
1928 case MIG_RP_MSG_SHUT
:
1929 sibling_error
= ldl_be_p(buf
);
1930 trace_source_return_path_thread_shut(sibling_error
);
1931 if (sibling_error
) {
1932 error_report("RP: Sibling indicated error %d", sibling_error
);
1933 mark_source_rp_bad(ms
);
1936 * We'll let the main thread deal with closing the RP
1937 * we could do a shutdown(2) on it, but we're the only user
1938 * anyway, so there's nothing gained.
1942 case MIG_RP_MSG_PONG
:
1943 tmp32
= ldl_be_p(buf
);
1944 trace_source_return_path_thread_pong(tmp32
);
1945 qemu_sem_post(&ms
->rp_state
.rp_pong_acks
);
1948 case MIG_RP_MSG_REQ_PAGES
:
1949 start
= ldq_be_p(buf
);
1950 len
= ldl_be_p(buf
+ 8);
1951 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1954 case MIG_RP_MSG_REQ_PAGES_ID
:
1955 expected_len
= 12 + 1; /* header + termination */
1957 if (header_len
>= expected_len
) {
1958 start
= ldq_be_p(buf
);
1959 len
= ldl_be_p(buf
+ 8);
1960 /* Now we expect an idstr */
1961 tmp32
= buf
[12]; /* Length of the following idstr */
1962 buf
[13 + tmp32
] = '\0';
1963 expected_len
+= tmp32
;
1965 if (header_len
!= expected_len
) {
1966 error_report("RP: Req_Page_id with length %d expecting %zd",
1967 header_len
, expected_len
);
1968 mark_source_rp_bad(ms
);
1971 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1974 case MIG_RP_MSG_RECV_BITMAP
:
1975 if (header_len
< 1) {
1976 error_report("%s: missing block name", __func__
);
1977 mark_source_rp_bad(ms
);
1980 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
1981 buf
[buf
[0] + 1] = '\0';
1982 if (migrate_handle_rp_recv_bitmap(ms
, (char *)(buf
+ 1))) {
1983 mark_source_rp_bad(ms
);
1988 case MIG_RP_MSG_RESUME_ACK
:
1989 tmp32
= ldl_be_p(buf
);
1990 if (migrate_handle_rp_resume_ack(ms
, tmp32
)) {
1991 mark_source_rp_bad(ms
);
1996 case MIG_RP_MSG_SWITCHOVER_ACK
:
1997 ms
->switchover_acked
= true;
1998 trace_source_return_path_thread_switchover_acked();
2007 res
= qemu_file_get_error(rp
);
2009 if (res
&& migration_in_postcopy()) {
2011 * Maybe there is something we can do: it looks like a
2012 * network down issue, and we pause for a recovery.
2014 migration_release_dst_files(ms
);
2016 if (postcopy_pause_return_path_thread(ms
)) {
2018 * Reload rp, reset the rest. Referencing it is safe since
2019 * it's reset only by us above, or when migration completes
2021 rp
= ms
->rp_state
.from_dst_file
;
2022 ms
->rp_state
.error
= false;
2027 trace_source_return_path_thread_bad_end();
2028 mark_source_rp_bad(ms
);
2031 trace_source_return_path_thread_end();
2032 migration_release_dst_files(ms
);
2033 rcu_unregister_thread();
2037 static int open_return_path_on_source(MigrationState
*ms
,
2040 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
2041 if (!ms
->rp_state
.from_dst_file
) {
2045 trace_open_return_path_on_source();
2047 if (!create_thread
) {
2052 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2053 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2054 ms
->rp_state
.rp_thread_created
= true;
2056 trace_open_return_path_on_source_continue();
2061 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2062 static int await_return_path_close_on_source(MigrationState
*ms
)
2066 if (!ms
->rp_state
.rp_thread_created
) {
2070 trace_migration_return_path_end_before();
2073 * If this is a normal exit then the destination will send a SHUT
2074 * and the rp_thread will exit, however if there's an error we
2075 * need to cause it to exit. shutdown(2), if we have it, will
2076 * cause it to unblock if it's stuck waiting for the destination.
2078 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2079 if (ms
->to_dst_file
&& ms
->rp_state
.from_dst_file
&&
2080 qemu_file_get_error(ms
->to_dst_file
)) {
2081 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2085 trace_await_return_path_close_on_source_joining();
2086 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2087 ms
->rp_state
.rp_thread_created
= false;
2088 trace_await_return_path_close_on_source_close();
2090 ret
= ms
->rp_state
.error
;
2091 trace_migration_return_path_end_after(ret
);
2096 migration_wait_main_channel(MigrationState
*ms
)
2098 /* Wait until one PONG message received */
2099 qemu_sem_wait(&ms
->rp_state
.rp_pong_acks
);
2103 * Switch from normal iteration to postcopy
2104 * Returns non-0 on error
2106 static int postcopy_start(MigrationState
*ms
, Error
**errp
)
2109 QIOChannelBuffer
*bioc
;
2111 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2112 uint64_t bandwidth
= migrate_max_postcopy_bandwidth();
2113 bool restart_block
= false;
2114 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2116 if (migrate_postcopy_preempt()) {
2117 migration_wait_main_channel(ms
);
2118 if (postcopy_preempt_establish_channel(ms
)) {
2119 migrate_set_state(&ms
->state
, ms
->state
, MIGRATION_STATUS_FAILED
);
2124 if (!migrate_pause_before_switchover()) {
2125 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2126 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2129 trace_postcopy_start();
2130 qemu_mutex_lock_iothread();
2131 trace_postcopy_start_set_run();
2133 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2134 global_state_store();
2135 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2140 ret
= migration_maybe_pause(ms
, &cur_state
,
2141 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2146 ret
= bdrv_inactivate_all();
2150 restart_block
= true;
2153 * Cause any non-postcopiable, but iterative devices to
2154 * send out their final data.
2156 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2159 * in Finish migrate and with the io-lock held everything should
2160 * be quiet, but we've potentially still got dirty pages and we
2161 * need to tell the destination to throw any pages it's already received
2164 if (migrate_postcopy_ram()) {
2165 ram_postcopy_send_discard_bitmap(ms
);
2169 * send rest of state - note things that are doing postcopy
2170 * will notice we're in POSTCOPY_ACTIVE and not actually
2171 * wrap their state up here
2173 migration_rate_set(bandwidth
);
2174 if (migrate_postcopy_ram()) {
2175 /* Ping just for debugging, helps line traces up */
2176 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2180 * While loading the device state we may trigger page transfer
2181 * requests and the fd must be free to process those, and thus
2182 * the destination must read the whole device state off the fd before
2183 * it starts processing it. Unfortunately the ad-hoc migration format
2184 * doesn't allow the destination to know the size to read without fully
2185 * parsing it through each devices load-state code (especially the open
2186 * coded devices that use get/put).
2187 * So we wrap the device state up in a package with a length at the start;
2188 * to do this we use a qemu_buf to hold the whole of the device state.
2190 bioc
= qio_channel_buffer_new(4096);
2191 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2192 fb
= qemu_file_new_output(QIO_CHANNEL(bioc
));
2193 object_unref(OBJECT(bioc
));
2196 * Make sure the receiver can get incoming pages before we send the rest
2199 qemu_savevm_send_postcopy_listen(fb
);
2201 qemu_savevm_state_complete_precopy(fb
, false, false);
2202 if (migrate_postcopy_ram()) {
2203 qemu_savevm_send_ping(fb
, 3);
2206 qemu_savevm_send_postcopy_run(fb
);
2208 /* <><> end of stuff going into the package */
2210 /* Last point of recovery; as soon as we send the package the destination
2211 * can open devices and potentially start running.
2212 * Lets just check again we've not got any errors.
2214 ret
= qemu_file_get_error(ms
->to_dst_file
);
2216 error_setg(errp
, "postcopy_start: Migration stream errored (pre package)");
2220 restart_block
= false;
2222 /* Now send that blob */
2223 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2228 /* Send a notify to give a chance for anything that needs to happen
2229 * at the transition to postcopy and after the device state; in particular
2230 * spice needs to trigger a transition now
2232 ms
->postcopy_after_devices
= true;
2233 notifier_list_notify(&migration_state_notifiers
, ms
);
2235 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
2237 qemu_mutex_unlock_iothread();
2239 if (migrate_postcopy_ram()) {
2241 * Although this ping is just for debug, it could potentially be
2242 * used for getting a better measurement of downtime at the source.
2244 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2247 if (migrate_release_ram()) {
2248 ram_postcopy_migrated_memory_release(ms
);
2251 ret
= qemu_file_get_error(ms
->to_dst_file
);
2253 error_setg(errp
, "postcopy_start: Migration stream errored");
2254 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2255 MIGRATION_STATUS_FAILED
);
2258 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2265 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2266 MIGRATION_STATUS_FAILED
);
2267 if (restart_block
) {
2268 /* A failure happened early enough that we know the destination hasn't
2269 * accessed block devices, so we're safe to recover.
2271 Error
*local_err
= NULL
;
2273 bdrv_activate_all(&local_err
);
2275 error_report_err(local_err
);
2278 qemu_mutex_unlock_iothread();
2283 * migration_maybe_pause: Pause if required to by
2284 * migrate_pause_before_switchover called with the iothread locked
2285 * Returns: 0 on success
2287 static int migration_maybe_pause(MigrationState
*s
,
2288 int *current_active_state
,
2291 if (!migrate_pause_before_switchover()) {
2295 /* Since leaving this state is not atomic with posting the semaphore
2296 * it's possible that someone could have issued multiple migrate_continue
2297 * and the semaphore is incorrectly positive at this point;
2298 * the docs say it's undefined to reinit a semaphore that's already
2299 * init'd, so use timedwait to eat up any existing posts.
2301 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2302 /* This block intentionally left blank */
2306 * If the migration is cancelled when it is in the completion phase,
2307 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2308 * So we don't need to wait a semaphore, otherwise we would always
2309 * wait for the 'pause_sem' semaphore.
2311 if (s
->state
!= MIGRATION_STATUS_CANCELLING
) {
2312 qemu_mutex_unlock_iothread();
2313 migrate_set_state(&s
->state
, *current_active_state
,
2314 MIGRATION_STATUS_PRE_SWITCHOVER
);
2315 qemu_sem_wait(&s
->pause_sem
);
2316 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2318 *current_active_state
= new_state
;
2319 qemu_mutex_lock_iothread();
2322 return s
->state
== new_state
? 0 : -EINVAL
;
2326 * migration_completion: Used by migration_thread when there's not much left.
2327 * The caller 'breaks' the loop when this returns.
2329 * @s: Current migration state
2331 static void migration_completion(MigrationState
*s
)
2334 int current_active_state
= s
->state
;
2336 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2337 qemu_mutex_lock_iothread();
2338 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2339 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
2341 s
->vm_old_state
= runstate_get();
2342 global_state_store();
2344 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
2345 trace_migration_completion_vm_stop(ret
);
2347 ret
= migration_maybe_pause(s
, ¤t_active_state
,
2348 MIGRATION_STATUS_DEVICE
);
2352 * Inactivate disks except in COLO, and track that we
2353 * have done so in order to remember to reactivate
2354 * them if migration fails or is cancelled.
2356 s
->block_inactive
= !migrate_colo();
2357 migration_rate_set(RATE_LIMIT_DISABLED
);
2358 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2362 qemu_mutex_unlock_iothread();
2367 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2368 trace_migration_completion_postcopy_end();
2370 qemu_mutex_lock_iothread();
2371 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2372 qemu_mutex_unlock_iothread();
2375 * Shutdown the postcopy fast path thread. This is only needed
2376 * when dest QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need
2379 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
2380 postcopy_preempt_shutdown_file(s
);
2383 trace_migration_completion_postcopy_end_after_complete();
2388 if (await_return_path_close_on_source(s
)) {
2392 if (qemu_file_get_error(s
->to_dst_file
)) {
2393 trace_migration_completion_file_err();
2397 if (migrate_colo() && s
->state
== MIGRATION_STATUS_ACTIVE
) {
2398 /* COLO does not support postcopy */
2399 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
2400 MIGRATION_STATUS_COLO
);
2402 migrate_set_state(&s
->state
, current_active_state
,
2403 MIGRATION_STATUS_COMPLETED
);
2409 if (s
->block_inactive
&& (s
->state
== MIGRATION_STATUS_ACTIVE
||
2410 s
->state
== MIGRATION_STATUS_DEVICE
)) {
2412 * If not doing postcopy, vm_start() will be called: let's
2413 * regain control on images.
2415 Error
*local_err
= NULL
;
2417 qemu_mutex_lock_iothread();
2418 bdrv_activate_all(&local_err
);
2420 error_report_err(local_err
);
2422 s
->block_inactive
= false;
2424 qemu_mutex_unlock_iothread();
2427 migrate_set_state(&s
->state
, current_active_state
,
2428 MIGRATION_STATUS_FAILED
);
2432 * bg_migration_completion: Used by bg_migration_thread when after all the
2433 * RAM has been saved. The caller 'breaks' the loop when this returns.
2435 * @s: Current migration state
2437 static void bg_migration_completion(MigrationState
*s
)
2439 int current_active_state
= s
->state
;
2441 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2443 * By this moment we have RAM content saved into the migration stream.
2444 * The next step is to flush the non-RAM content (device state)
2445 * right after the ram content. The device state has been stored into
2446 * the temporary buffer before RAM saving started.
2448 qemu_put_buffer(s
->to_dst_file
, s
->bioc
->data
, s
->bioc
->usage
);
2449 qemu_fflush(s
->to_dst_file
);
2450 } else if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
2454 if (qemu_file_get_error(s
->to_dst_file
)) {
2455 trace_migration_completion_file_err();
2459 migrate_set_state(&s
->state
, current_active_state
,
2460 MIGRATION_STATUS_COMPLETED
);
2464 migrate_set_state(&s
->state
, current_active_state
,
2465 MIGRATION_STATUS_FAILED
);
2468 typedef enum MigThrError
{
2469 /* No error detected */
2470 MIG_THR_ERR_NONE
= 0,
2471 /* Detected error, but resumed successfully */
2472 MIG_THR_ERR_RECOVERED
= 1,
2473 /* Detected fatal error, need to exit */
2474 MIG_THR_ERR_FATAL
= 2,
2477 static int postcopy_resume_handshake(MigrationState
*s
)
2479 qemu_savevm_send_postcopy_resume(s
->to_dst_file
);
2481 while (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2482 qemu_sem_wait(&s
->rp_state
.rp_sem
);
2485 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2492 /* Return zero if success, or <0 for error */
2493 static int postcopy_do_resume(MigrationState
*s
)
2498 * Call all the resume_prepare() hooks, so that modules can be
2499 * ready for the migration resume.
2501 ret
= qemu_savevm_state_resume_prepare(s
);
2503 error_report("%s: resume_prepare() failure detected: %d",
2509 * If preempt is enabled, re-establish the preempt channel. Note that
2510 * we do it after resume prepare to make sure the main channel will be
2511 * created before the preempt channel. E.g. with weak network, the
2512 * dest QEMU may get messed up with the preempt and main channels on
2513 * the order of connection setup. This guarantees the correct order.
2515 ret
= postcopy_preempt_establish_channel(s
);
2517 error_report("%s: postcopy_preempt_establish_channel(): %d",
2523 * Last handshake with destination on the resume (destination will
2524 * switch to postcopy-active afterwards)
2526 ret
= postcopy_resume_handshake(s
);
2528 error_report("%s: handshake failed: %d", __func__
, ret
);
2536 * We don't return until we are in a safe state to continue current
2537 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2538 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2540 static MigThrError
postcopy_pause(MigrationState
*s
)
2542 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2548 * Current channel is possibly broken. Release it. Note that this is
2549 * guaranteed even without lock because to_dst_file should only be
2550 * modified by the migration thread. That also guarantees that the
2551 * unregister of yank is safe too without the lock. It should be safe
2552 * even to be within the qemu_file_lock, but we didn't do that to avoid
2553 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2554 * the qemu_file_lock critical section as small as possible.
2556 assert(s
->to_dst_file
);
2557 migration_ioc_unregister_yank_from_file(s
->to_dst_file
);
2558 qemu_mutex_lock(&s
->qemu_file_lock
);
2559 file
= s
->to_dst_file
;
2560 s
->to_dst_file
= NULL
;
2561 qemu_mutex_unlock(&s
->qemu_file_lock
);
2563 qemu_file_shutdown(file
);
2566 migrate_set_state(&s
->state
, s
->state
,
2567 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2569 error_report("Detected IO failure for postcopy. "
2570 "Migration paused.");
2573 * We wait until things fixed up. Then someone will setup the
2574 * status back for us.
2576 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2577 qemu_sem_wait(&s
->postcopy_pause_sem
);
2580 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2581 /* Woken up by a recover procedure. Give it a shot */
2584 * Firstly, let's wake up the return path now, with a new
2585 * return path channel.
2587 qemu_sem_post(&s
->postcopy_pause_rp_sem
);
2589 /* Do the resume logic */
2590 if (postcopy_do_resume(s
) == 0) {
2591 /* Let's continue! */
2592 trace_postcopy_pause_continued();
2593 return MIG_THR_ERR_RECOVERED
;
2596 * Something wrong happened during the recovery, let's
2597 * pause again. Pause is always better than throwing
2603 /* This is not right... Time to quit. */
2604 return MIG_THR_ERR_FATAL
;
2609 static MigThrError
migration_detect_error(MigrationState
*s
)
2612 int state
= s
->state
;
2613 Error
*local_error
= NULL
;
2615 if (state
== MIGRATION_STATUS_CANCELLING
||
2616 state
== MIGRATION_STATUS_CANCELLED
) {
2617 /* End the migration, but don't set the state to failed */
2618 return MIG_THR_ERR_FATAL
;
2622 * Try to detect any file errors. Note that postcopy_qemufile_src will
2623 * be NULL when postcopy preempt is not enabled.
2625 ret
= qemu_file_get_error_obj_any(s
->to_dst_file
,
2626 s
->postcopy_qemufile_src
,
2629 /* Everything is fine */
2630 assert(!local_error
);
2631 return MIG_THR_ERR_NONE
;
2635 migrate_set_error(s
, local_error
);
2636 error_free(local_error
);
2639 if (state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
) {
2641 * For postcopy, we allow the network to be down for a
2642 * while. After that, it can be continued by a
2645 return postcopy_pause(s
);
2648 * For precopy (or postcopy with error outside IO), we fail
2651 migrate_set_state(&s
->state
, state
, MIGRATION_STATUS_FAILED
);
2652 trace_migration_thread_file_err();
2654 /* Time to stop the migration, now. */
2655 return MIG_THR_ERR_FATAL
;
2659 static void migration_calculate_complete(MigrationState
*s
)
2661 uint64_t bytes
= migration_transferred_bytes(s
->to_dst_file
);
2662 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2663 int64_t transfer_time
;
2665 s
->total_time
= end_time
- s
->start_time
;
2668 * It's still not set, so we are precopy migration. For
2669 * postcopy, downtime is calculated during postcopy_start().
2671 s
->downtime
= end_time
- s
->downtime_start
;
2674 transfer_time
= s
->total_time
- s
->setup_time
;
2675 if (transfer_time
) {
2676 s
->mbps
= ((double) bytes
* 8.0) / transfer_time
/ 1000;
2680 static void update_iteration_initial_status(MigrationState
*s
)
2683 * Update these three fields at the same time to avoid mismatch info lead
2684 * wrong speed calculation.
2686 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2687 s
->iteration_initial_bytes
= migration_transferred_bytes(s
->to_dst_file
);
2688 s
->iteration_initial_pages
= ram_get_total_transferred_pages();
2691 static void migration_update_counters(MigrationState
*s
,
2692 int64_t current_time
)
2694 uint64_t transferred
, transferred_pages
, time_spent
;
2695 uint64_t current_bytes
; /* bytes transferred since the beginning */
2698 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
2702 current_bytes
= migration_transferred_bytes(s
->to_dst_file
);
2703 transferred
= current_bytes
- s
->iteration_initial_bytes
;
2704 time_spent
= current_time
- s
->iteration_start_time
;
2705 bandwidth
= (double)transferred
/ time_spent
;
2706 s
->threshold_size
= bandwidth
* migrate_downtime_limit();
2708 s
->mbps
= (((double) transferred
* 8.0) /
2709 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
2711 transferred_pages
= ram_get_total_transferred_pages() -
2712 s
->iteration_initial_pages
;
2713 s
->pages_per_second
= (double) transferred_pages
/
2714 (((double) time_spent
/ 1000.0));
2717 * if we haven't sent anything, we don't want to
2718 * recalculate. 10000 is a small enough number for our purposes
2720 if (stat64_get(&mig_stats
.dirty_pages_rate
) &&
2721 transferred
> 10000) {
2722 s
->expected_downtime
=
2723 stat64_get(&mig_stats
.dirty_bytes_last_sync
) / bandwidth
;
2726 migration_rate_reset(s
->to_dst_file
);
2728 update_iteration_initial_status(s
);
2730 trace_migrate_transferred(transferred
, time_spent
,
2731 bandwidth
, s
->threshold_size
);
2734 static bool migration_can_switchover(MigrationState
*s
)
2736 if (!migrate_switchover_ack()) {
2740 /* No reason to wait for switchover ACK if VM is stopped */
2741 if (!runstate_is_running()) {
2745 return s
->switchover_acked
;
2748 /* Migration thread iteration status */
2750 MIG_ITERATE_RESUME
, /* Resume current iteration */
2751 MIG_ITERATE_SKIP
, /* Skip current iteration */
2752 MIG_ITERATE_BREAK
, /* Break the loop */
2756 * Return true if continue to the next iteration directly, false
2759 static MigIterateState
migration_iteration_run(MigrationState
*s
)
2761 uint64_t must_precopy
, can_postcopy
;
2762 Error
*local_err
= NULL
;
2763 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
2764 bool can_switchover
= migration_can_switchover(s
);
2766 qemu_savevm_state_pending_estimate(&must_precopy
, &can_postcopy
);
2767 uint64_t pending_size
= must_precopy
+ can_postcopy
;
2769 trace_migrate_pending_estimate(pending_size
, must_precopy
, can_postcopy
);
2771 if (must_precopy
<= s
->threshold_size
) {
2772 qemu_savevm_state_pending_exact(&must_precopy
, &can_postcopy
);
2773 pending_size
= must_precopy
+ can_postcopy
;
2774 trace_migrate_pending_exact(pending_size
, must_precopy
, can_postcopy
);
2777 if ((!pending_size
|| pending_size
< s
->threshold_size
) && can_switchover
) {
2778 trace_migration_thread_low_pending(pending_size
);
2779 migration_completion(s
);
2780 return MIG_ITERATE_BREAK
;
2783 /* Still a significant amount to transfer */
2784 if (!in_postcopy
&& must_precopy
<= s
->threshold_size
&& can_switchover
&&
2785 qatomic_read(&s
->start_postcopy
)) {
2786 if (postcopy_start(s
, &local_err
)) {
2787 migrate_set_error(s
, local_err
);
2788 error_report_err(local_err
);
2790 return MIG_ITERATE_SKIP
;
2793 /* Just another iteration step */
2794 qemu_savevm_state_iterate(s
->to_dst_file
, in_postcopy
);
2795 return MIG_ITERATE_RESUME
;
2798 static void migration_iteration_finish(MigrationState
*s
)
2800 /* If we enabled cpu throttling for auto-converge, turn it off. */
2801 cpu_throttle_stop();
2803 qemu_mutex_lock_iothread();
2805 case MIGRATION_STATUS_COMPLETED
:
2806 migration_calculate_complete(s
);
2807 runstate_set(RUN_STATE_POSTMIGRATE
);
2809 case MIGRATION_STATUS_COLO
:
2810 assert(migrate_colo());
2811 migrate_start_colo_process(s
);
2812 s
->vm_old_state
= RUN_STATE_RUNNING
;
2814 case MIGRATION_STATUS_FAILED
:
2815 case MIGRATION_STATUS_CANCELLED
:
2816 case MIGRATION_STATUS_CANCELLING
:
2817 if (s
->vm_old_state
== RUN_STATE_RUNNING
) {
2818 if (!runstate_check(RUN_STATE_SHUTDOWN
)) {
2822 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
2823 runstate_set(s
->vm_old_state
);
2829 /* Should not reach here, but if so, forgive the VM. */
2830 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2833 migrate_fd_cleanup_schedule(s
);
2834 qemu_mutex_unlock_iothread();
2837 static void bg_migration_iteration_finish(MigrationState
*s
)
2840 * Stop tracking RAM writes - un-protect memory, un-register UFFD
2841 * memory ranges, flush kernel wait queues and wake up threads
2842 * waiting for write fault to be resolved.
2844 ram_write_tracking_stop();
2846 qemu_mutex_lock_iothread();
2848 case MIGRATION_STATUS_COMPLETED
:
2849 migration_calculate_complete(s
);
2852 case MIGRATION_STATUS_ACTIVE
:
2853 case MIGRATION_STATUS_FAILED
:
2854 case MIGRATION_STATUS_CANCELLED
:
2855 case MIGRATION_STATUS_CANCELLING
:
2859 /* Should not reach here, but if so, forgive the VM. */
2860 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
2864 migrate_fd_cleanup_schedule(s
);
2865 qemu_mutex_unlock_iothread();
2869 * Return true if continue to the next iteration directly, false
2872 static MigIterateState
bg_migration_iteration_run(MigrationState
*s
)
2876 res
= qemu_savevm_state_iterate(s
->to_dst_file
, false);
2878 bg_migration_completion(s
);
2879 return MIG_ITERATE_BREAK
;
2882 return MIG_ITERATE_RESUME
;
2885 void migration_make_urgent_request(void)
2887 qemu_sem_post(&migrate_get_current()->rate_limit_sem
);
2890 void migration_consume_urgent_request(void)
2892 qemu_sem_wait(&migrate_get_current()->rate_limit_sem
);
2895 /* Returns true if the rate limiting was broken by an urgent request */
2896 bool migration_rate_limit(void)
2898 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
2899 MigrationState
*s
= migrate_get_current();
2901 bool urgent
= false;
2902 migration_update_counters(s
, now
);
2903 if (migration_rate_exceeded(s
->to_dst_file
)) {
2905 if (qemu_file_get_error(s
->to_dst_file
)) {
2909 * Wait for a delay to do rate limiting OR
2910 * something urgent to post the semaphore.
2912 int ms
= s
->iteration_start_time
+ BUFFER_DELAY
- now
;
2913 trace_migration_rate_limit_pre(ms
);
2914 if (qemu_sem_timedwait(&s
->rate_limit_sem
, ms
) == 0) {
2916 * We were woken by one or more urgent things but
2917 * the timedwait will have consumed one of them.
2918 * The service routine for the urgent wake will dec
2919 * the semaphore itself for each item it consumes,
2920 * so add this one we just eat back.
2922 qemu_sem_post(&s
->rate_limit_sem
);
2925 trace_migration_rate_limit_post(urgent
);
2931 * if failover devices are present, wait they are completely
2935 static void qemu_savevm_wait_unplug(MigrationState
*s
, int old_state
,
2938 if (qemu_savevm_state_guest_unplug_pending()) {
2939 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_WAIT_UNPLUG
);
2941 while (s
->state
== MIGRATION_STATUS_WAIT_UNPLUG
&&
2942 qemu_savevm_state_guest_unplug_pending()) {
2943 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
2945 if (s
->state
!= MIGRATION_STATUS_WAIT_UNPLUG
) {
2946 int timeout
= 120; /* 30 seconds */
2948 * migration has been canceled
2949 * but as we have started an unplug we must wait the end
2950 * to be able to plug back the card
2952 while (timeout
-- && qemu_savevm_state_guest_unplug_pending()) {
2953 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
2955 if (qemu_savevm_state_guest_unplug_pending() &&
2957 warn_report("migration: partially unplugged device on "
2962 migrate_set_state(&s
->state
, MIGRATION_STATUS_WAIT_UNPLUG
, new_state
);
2964 migrate_set_state(&s
->state
, old_state
, new_state
);
2969 * Master migration thread on the source VM.
2970 * It drives the migration and pumps the data down the outgoing channel.
2972 static void *migration_thread(void *opaque
)
2974 MigrationState
*s
= opaque
;
2975 MigrationThread
*thread
= NULL
;
2976 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
2977 MigThrError thr_error
;
2978 bool urgent
= false;
2980 thread
= migration_threads_add("live_migration", qemu_get_thread_id());
2982 rcu_register_thread();
2984 object_ref(OBJECT(s
));
2985 update_iteration_initial_status(s
);
2987 qemu_savevm_state_header(s
->to_dst_file
);
2990 * If we opened the return path, we need to make sure dst has it
2993 if (s
->rp_state
.rp_thread_created
) {
2994 /* Now tell the dest that it should open its end so it can reply */
2995 qemu_savevm_send_open_return_path(s
->to_dst_file
);
2997 /* And do a ping that will make stuff easier to debug */
2998 qemu_savevm_send_ping(s
->to_dst_file
, 1);
3001 if (migrate_postcopy()) {
3003 * Tell the destination that we *might* want to do postcopy later;
3004 * if the other end can't do postcopy it should fail now, nice and
3007 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
3010 if (migrate_colo()) {
3011 /* Notify migration destination that we enable COLO */
3012 qemu_savevm_send_colo_enable(s
->to_dst_file
);
3015 qemu_savevm_state_setup(s
->to_dst_file
);
3017 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3018 MIGRATION_STATUS_ACTIVE
);
3020 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3022 trace_migration_thread_setup_complete();
3024 while (migration_is_active(s
)) {
3025 if (urgent
|| !migration_rate_exceeded(s
->to_dst_file
)) {
3026 MigIterateState iter_state
= migration_iteration_run(s
);
3027 if (iter_state
== MIG_ITERATE_SKIP
) {
3029 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3035 * Try to detect any kind of failures, and see whether we
3036 * should stop the migration now.
3038 thr_error
= migration_detect_error(s
);
3039 if (thr_error
== MIG_THR_ERR_FATAL
) {
3040 /* Stop migration */
3042 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
3044 * Just recovered from a e.g. network failure, reset all
3045 * the local variables. This is important to avoid
3046 * breaking transferred_bytes and bandwidth calculation
3048 update_iteration_initial_status(s
);
3051 urgent
= migration_rate_limit();
3054 trace_migration_thread_after_loop();
3055 migration_iteration_finish(s
);
3056 object_unref(OBJECT(s
));
3057 rcu_unregister_thread();
3058 migration_threads_remove(thread
);
3062 static void bg_migration_vm_start_bh(void *opaque
)
3064 MigrationState
*s
= opaque
;
3066 qemu_bh_delete(s
->vm_start_bh
);
3067 s
->vm_start_bh
= NULL
;
3070 s
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - s
->downtime_start
;
3074 * Background snapshot thread, based on live migration code.
3075 * This is an alternative implementation of live migration mechanism
3076 * introduced specifically to support background snapshots.
3078 * It takes advantage of userfault_fd write protection mechanism introduced
3079 * in v5.7 kernel. Compared to existing dirty page logging migration much
3080 * lesser stream traffic is produced resulting in smaller snapshot images,
3081 * simply cause of no page duplicates can get into the stream.
3083 * Another key point is that generated vmstate stream reflects machine state
3084 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3085 * mechanism, which effectively results in that saved snapshot is the state of VM
3086 * at the end of the process.
3088 static void *bg_migration_thread(void *opaque
)
3090 MigrationState
*s
= opaque
;
3091 int64_t setup_start
;
3092 MigThrError thr_error
;
3094 bool early_fail
= true;
3096 rcu_register_thread();
3097 object_ref(OBJECT(s
));
3099 migration_rate_set(RATE_LIMIT_DISABLED
);
3101 setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3103 * We want to save vmstate for the moment when migration has been
3104 * initiated but also we want to save RAM content while VM is running.
3105 * The RAM content should appear first in the vmstate. So, we first
3106 * stash the non-RAM part of the vmstate to the temporary buffer,
3107 * then write RAM part of the vmstate to the migration stream
3108 * with vCPUs running and, finally, write stashed non-RAM part of
3109 * the vmstate from the buffer to the migration stream.
3111 s
->bioc
= qio_channel_buffer_new(512 * 1024);
3112 qio_channel_set_name(QIO_CHANNEL(s
->bioc
), "vmstate-buffer");
3113 fb
= qemu_file_new_output(QIO_CHANNEL(s
->bioc
));
3114 object_unref(OBJECT(s
->bioc
));
3116 update_iteration_initial_status(s
);
3119 * Prepare for tracking memory writes with UFFD-WP - populate
3120 * RAM pages before protecting.
3123 ram_write_tracking_prepare();
3126 qemu_savevm_state_header(s
->to_dst_file
);
3127 qemu_savevm_state_setup(s
->to_dst_file
);
3129 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3130 MIGRATION_STATUS_ACTIVE
);
3132 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3134 trace_migration_thread_setup_complete();
3135 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3137 qemu_mutex_lock_iothread();
3140 * If VM is currently in suspended state, then, to make a valid runstate
3141 * transition in vm_stop_force_state() we need to wakeup it up.
3143 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
, NULL
);
3144 s
->vm_old_state
= runstate_get();
3146 global_state_store();
3147 /* Forcibly stop VM before saving state of vCPUs and devices */
3148 if (vm_stop_force_state(RUN_STATE_PAUSED
)) {
3152 * Put vCPUs in sync with shadow context structures, then
3153 * save their state to channel-buffer along with devices.
3155 cpu_synchronize_all_states();
3156 if (qemu_savevm_state_complete_precopy_non_iterable(fb
, false, false)) {
3160 * Since we are going to get non-iterable state data directly
3161 * from s->bioc->data, explicit flush is needed here.
3165 /* Now initialize UFFD context and start tracking RAM writes */
3166 if (ram_write_tracking_start()) {
3172 * Start VM from BH handler to avoid write-fault lock here.
3173 * UFFD-WP protection for the whole RAM is already enabled so
3174 * calling VM state change notifiers from vm_start() would initiate
3175 * writes to virtio VQs memory which is in write-protected region.
3177 s
->vm_start_bh
= qemu_bh_new(bg_migration_vm_start_bh
, s
);
3178 qemu_bh_schedule(s
->vm_start_bh
);
3180 qemu_mutex_unlock_iothread();
3182 while (migration_is_active(s
)) {
3183 MigIterateState iter_state
= bg_migration_iteration_run(s
);
3184 if (iter_state
== MIG_ITERATE_SKIP
) {
3186 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3191 * Try to detect any kind of failures, and see whether we
3192 * should stop the migration now.
3194 thr_error
= migration_detect_error(s
);
3195 if (thr_error
== MIG_THR_ERR_FATAL
) {
3196 /* Stop migration */
3200 migration_update_counters(s
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
));
3203 trace_migration_thread_after_loop();
3207 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
3208 MIGRATION_STATUS_FAILED
);
3209 qemu_mutex_unlock_iothread();
3212 bg_migration_iteration_finish(s
);
3215 object_unref(OBJECT(s
));
3216 rcu_unregister_thread();
3221 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
3223 Error
*local_err
= NULL
;
3224 uint64_t rate_limit
;
3225 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
3228 * If there's a previous error, free it and prepare for another one.
3229 * Meanwhile if migration completes successfully, there won't have an error
3230 * dumped when calling migrate_fd_cleanup().
3232 migrate_error_free(s
);
3234 s
->expected_downtime
= migrate_downtime_limit();
3236 assert(s
->cleanup_bh
);
3238 assert(!s
->cleanup_bh
);
3239 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup_bh
, s
);
3242 migrate_fd_error(s
, error_in
);
3245 * Don't do cleanup for resume if channel is invalid, but only dump
3246 * the error. We wait for another channel connect from the user.
3247 * The error_report still gives HMP user a hint on what failed.
3248 * It's normally done in migrate_fd_cleanup(), but call it here
3251 error_report_err(error_copy(s
->error
));
3253 migrate_fd_cleanup(s
);
3259 /* This is a resumed migration */
3260 rate_limit
= migrate_max_postcopy_bandwidth();
3262 /* This is a fresh new migration */
3263 rate_limit
= migrate_max_bandwidth();
3265 /* Notify before starting migration thread */
3266 notifier_list_notify(&migration_state_notifiers
, s
);
3269 migration_rate_set(rate_limit
);
3270 qemu_file_set_blocking(s
->to_dst_file
, true);
3273 * Open the return path. For postcopy, it is used exclusively. For
3274 * precopy, only if user specified "return-path" capability would
3275 * QEMU uses the return path.
3277 if (migrate_postcopy_ram() || migrate_return_path()) {
3278 if (open_return_path_on_source(s
, !resume
)) {
3279 error_setg(&local_err
, "Unable to open return-path for postcopy");
3280 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
3281 migrate_set_error(s
, local_err
);
3282 error_report_err(local_err
);
3283 migrate_fd_cleanup(s
);
3289 * This needs to be done before resuming a postcopy. Note: for newer
3290 * QEMUs we will delay the channel creation until postcopy_start(), to
3291 * avoid disorder of channel creations.
3293 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
3294 postcopy_preempt_setup(s
);
3298 /* Wakeup the main migration thread to do the recovery */
3299 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
3300 MIGRATION_STATUS_POSTCOPY_RECOVER
);
3301 qemu_sem_post(&s
->postcopy_pause_sem
);
3305 if (multifd_save_setup(&local_err
) != 0) {
3306 migrate_set_error(s
, local_err
);
3307 error_report_err(local_err
);
3308 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
3309 MIGRATION_STATUS_FAILED
);
3310 migrate_fd_cleanup(s
);
3314 if (migrate_background_snapshot()) {
3315 qemu_thread_create(&s
->thread
, "bg_snapshot",
3316 bg_migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3318 qemu_thread_create(&s
->thread
, "live_migration",
3319 migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3321 s
->migration_thread_running
= true;
3324 static void migration_class_init(ObjectClass
*klass
, void *data
)
3326 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3328 dc
->user_creatable
= false;
3329 device_class_set_props(dc
, migration_properties
);
3332 static void migration_instance_finalize(Object
*obj
)
3334 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3336 qemu_mutex_destroy(&ms
->error_mutex
);
3337 qemu_mutex_destroy(&ms
->qemu_file_lock
);
3338 qemu_sem_destroy(&ms
->wait_unplug_sem
);
3339 qemu_sem_destroy(&ms
->rate_limit_sem
);
3340 qemu_sem_destroy(&ms
->pause_sem
);
3341 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
3342 qemu_sem_destroy(&ms
->postcopy_pause_rp_sem
);
3343 qemu_sem_destroy(&ms
->rp_state
.rp_sem
);
3344 qemu_sem_destroy(&ms
->rp_state
.rp_pong_acks
);
3345 qemu_sem_destroy(&ms
->postcopy_qemufile_src_sem
);
3346 error_free(ms
->error
);
3349 static void migration_instance_init(Object
*obj
)
3351 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3353 ms
->state
= MIGRATION_STATUS_NONE
;
3355 ms
->pages_per_second
= -1;
3356 qemu_sem_init(&ms
->pause_sem
, 0);
3357 qemu_mutex_init(&ms
->error_mutex
);
3359 migrate_params_init(&ms
->parameters
);
3361 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
3362 qemu_sem_init(&ms
->postcopy_pause_rp_sem
, 0);
3363 qemu_sem_init(&ms
->rp_state
.rp_sem
, 0);
3364 qemu_sem_init(&ms
->rp_state
.rp_pong_acks
, 0);
3365 qemu_sem_init(&ms
->rate_limit_sem
, 0);
3366 qemu_sem_init(&ms
->wait_unplug_sem
, 0);
3367 qemu_sem_init(&ms
->postcopy_qemufile_src_sem
, 0);
3368 qemu_mutex_init(&ms
->qemu_file_lock
);
3372 * Return true if check pass, false otherwise. Error will be put
3373 * inside errp if provided.
3375 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
3377 /* Assuming all off */
3378 bool old_caps
[MIGRATION_CAPABILITY__MAX
] = { 0 };
3380 if (!migrate_params_check(&ms
->parameters
, errp
)) {
3384 return migrate_caps_check(old_caps
, ms
->capabilities
, errp
);
3387 static const TypeInfo migration_type
= {
3388 .name
= TYPE_MIGRATION
,
3390 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3391 * not created using qdev_new(), it is not attached to the qdev
3392 * device tree, and it is never realized.
3394 * TODO: Make this TYPE_OBJECT once QOM provides something like
3395 * TYPE_DEVICE's "-global" properties.
3397 .parent
= TYPE_DEVICE
,
3398 .class_init
= migration_class_init
,
3399 .class_size
= sizeof(MigrationClass
),
3400 .instance_size
= sizeof(MigrationState
),
3401 .instance_init
= migration_instance_init
,
3402 .instance_finalize
= migration_instance_finalize
,
3405 static void register_migration_types(void)
3407 type_register_static(&migration_type
);
3410 type_init(register_migration_types
);