4 * Copyright IBM, Corp. 2008
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "qemu/main-loop.h"
20 #include "migration/blocker.h"
25 #include "sysemu/runstate.h"
26 #include "sysemu/sysemu.h"
27 #include "sysemu/cpu-throttle.h"
30 #include "ram-compress.h"
31 #include "migration/global_state.h"
32 #include "migration/misc.h"
33 #include "migration.h"
34 #include "migration-stats.h"
36 #include "qemu-file.h"
38 #include "migration/vmstate.h"
39 #include "block/block.h"
40 #include "qapi/error.h"
41 #include "qapi/clone-visitor.h"
42 #include "qapi/qapi-visit-migration.h"
43 #include "qapi/qapi-visit-sockets.h"
44 #include "qapi/qapi-commands-migration.h"
45 #include "qapi/qapi-events-migration.h"
46 #include "qapi/qmp/qerror.h"
47 #include "qapi/qmp/qnull.h"
50 #include "postcopy-ram.h"
51 #include "qemu/thread.h"
53 #include "exec/target_page.h"
54 #include "io/channel-buffer.h"
55 #include "io/channel-tls.h"
56 #include "migration/colo.h"
57 #include "hw/boards.h"
58 #include "monitor/monitor.h"
59 #include "net/announce.h"
60 #include "qemu/queue.h"
62 #include "threadinfo.h"
63 #include "qemu/yank.h"
64 #include "sysemu/cpus.h"
65 #include "yank_functions.h"
66 #include "sysemu/qtest.h"
68 #include "sysemu/dirtylimit.h"
69 #include "qemu/sockets.h"
70 #include "sysemu/kvm.h"
72 #define NOTIFIER_ELEM_INIT(array, elem) \
73 [elem] = NOTIFIER_WITH_RETURN_LIST_INITIALIZER((array)[elem])
75 static NotifierWithReturnList migration_state_notifiers
[] = {
76 NOTIFIER_ELEM_INIT(migration_state_notifiers
, MIG_MODE_NORMAL
),
77 NOTIFIER_ELEM_INIT(migration_state_notifiers
, MIG_MODE_CPR_REBOOT
),
80 /* Messages sent on the return path from destination to source */
81 enum mig_rp_message_type
{
82 MIG_RP_MSG_INVALID
= 0, /* Must be 0 */
83 MIG_RP_MSG_SHUT
, /* sibling will not send any more RP messages */
84 MIG_RP_MSG_PONG
, /* Response to a PING; data (seq: be32 ) */
86 MIG_RP_MSG_REQ_PAGES_ID
, /* data (start: be64, len: be32, id: string) */
87 MIG_RP_MSG_REQ_PAGES
, /* data (start: be64, len: be32) */
88 MIG_RP_MSG_RECV_BITMAP
, /* send recved_bitmap back to source */
89 MIG_RP_MSG_RESUME_ACK
, /* tell source that we are ready to resume */
90 MIG_RP_MSG_SWITCHOVER_ACK
, /* Tell source it's OK to do switchover */
95 /* When we add fault tolerance, we could have several
96 migrations at once. For now we don't need to add
97 dynamic creation of migration */
99 static MigrationState
*current_migration
;
100 static MigrationIncomingState
*current_incoming
;
102 static GSList
*migration_blockers
[MIG_MODE__MAX
];
104 static bool migration_object_check(MigrationState
*ms
, Error
**errp
);
105 static int migration_maybe_pause(MigrationState
*s
,
106 int *current_active_state
,
108 static void migrate_fd_cancel(MigrationState
*s
);
109 static bool close_return_path_on_source(MigrationState
*s
);
110 static void migration_completion_end(MigrationState
*s
);
112 static void migration_downtime_start(MigrationState
*s
)
114 trace_vmstate_downtime_checkpoint("src-downtime-start");
115 s
->downtime_start
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
118 static void migration_downtime_end(MigrationState
*s
)
120 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
123 * If downtime already set, should mean that postcopy already set it,
124 * then that should be the real downtime already.
127 s
->downtime
= now
- s
->downtime_start
;
130 trace_vmstate_downtime_checkpoint("src-downtime-end");
133 static bool migration_needs_multiple_sockets(void)
135 return migrate_multifd() || migrate_postcopy_preempt();
138 static bool transport_supports_multi_channels(MigrationAddress
*addr
)
140 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
141 SocketAddress
*saddr
= &addr
->u
.socket
;
143 if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
144 return migrate_mapped_ram();
147 return (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
148 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
149 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
);
150 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
151 return migrate_mapped_ram();
157 static bool migration_needs_seekable_channel(void)
159 return migrate_mapped_ram();
162 static bool transport_supports_seeking(MigrationAddress
*addr
)
164 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
169 * At this point, the user might not yet have passed the file
170 * descriptor to QEMU, so we cannot know for sure whether it
171 * refers to a plain file or a socket. Let it through anyway.
173 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
174 return addr
->u
.socket
.type
== SOCKET_ADDRESS_TYPE_FD
;
181 migration_channels_and_transport_compatible(MigrationAddress
*addr
,
184 if (migration_needs_seekable_channel() &&
185 !transport_supports_seeking(addr
)) {
186 error_setg(errp
, "Migration requires seekable transport (e.g. file)");
190 if (migration_needs_multiple_sockets() &&
191 !transport_supports_multi_channels(addr
)) {
192 error_setg(errp
, "Migration requires multi-channel URIs (e.g. tcp)");
199 static gint
page_request_addr_cmp(gconstpointer ap
, gconstpointer bp
)
201 uintptr_t a
= (uintptr_t) ap
, b
= (uintptr_t) bp
;
203 return (a
> b
) - (a
< b
);
206 static int migration_stop_vm(MigrationState
*s
, RunState state
)
210 migration_downtime_start(s
);
212 s
->vm_old_state
= runstate_get();
213 global_state_store();
215 ret
= vm_stop_force_state(state
);
217 trace_vmstate_downtime_checkpoint("src-vm-stopped");
218 trace_migration_completion_vm_stop(ret
);
223 void migration_object_init(void)
225 /* This can only be called once. */
226 assert(!current_migration
);
227 current_migration
= MIGRATION_OBJ(object_new(TYPE_MIGRATION
));
230 * Init the migrate incoming object as well no matter whether
231 * we'll use it or not.
233 assert(!current_incoming
);
234 current_incoming
= g_new0(MigrationIncomingState
, 1);
235 current_incoming
->state
= MIGRATION_STATUS_NONE
;
236 current_incoming
->postcopy_remote_fds
=
237 g_array_new(FALSE
, TRUE
, sizeof(struct PostCopyFD
));
238 qemu_mutex_init(¤t_incoming
->rp_mutex
);
239 qemu_mutex_init(¤t_incoming
->postcopy_prio_thread_mutex
);
240 qemu_event_init(¤t_incoming
->main_thread_load_event
, false);
241 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_dst
, 0);
242 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fault
, 0);
243 qemu_sem_init(¤t_incoming
->postcopy_pause_sem_fast_load
, 0);
244 qemu_sem_init(¤t_incoming
->postcopy_qemufile_dst_done
, 0);
246 qemu_mutex_init(¤t_incoming
->page_request_mutex
);
247 qemu_cond_init(¤t_incoming
->page_request_cond
);
248 current_incoming
->page_requested
= g_tree_new(page_request_addr_cmp
);
250 migration_object_check(current_migration
, &error_fatal
);
254 dirty_bitmap_mig_init();
263 static void migration_bh_dispatch_bh(void *opaque
)
265 MigrationState
*s
= migrate_get_current();
266 MigrationBH
*migbh
= opaque
;
268 /* cleanup this BH */
269 qemu_bh_delete(migbh
->bh
);
272 /* dispatch the other one */
273 migbh
->cb(migbh
->opaque
);
274 object_unref(OBJECT(s
));
279 void migration_bh_schedule(QEMUBHFunc
*cb
, void *opaque
)
281 MigrationState
*s
= migrate_get_current();
282 MigrationBH
*migbh
= g_new0(MigrationBH
, 1);
283 QEMUBH
*bh
= qemu_bh_new(migration_bh_dispatch_bh
, migbh
);
285 /* Store these to dispatch when the BH runs */
288 migbh
->opaque
= opaque
;
291 * Ref the state for bh, because it may be called when
292 * there're already no other refs
294 object_ref(OBJECT(s
));
295 qemu_bh_schedule(bh
);
298 void migration_cancel(const Error
*error
)
301 migrate_set_error(current_migration
, error
);
303 if (migrate_dirty_limit()) {
304 qmp_cancel_vcpu_dirty_limit(false, -1, NULL
);
306 migrate_fd_cancel(current_migration
);
309 void migration_shutdown(void)
312 * When the QEMU main thread exit, the COLO thread
313 * may wait a semaphore. So, we should wakeup the
314 * COLO thread before migration shutdown.
318 * Cancel the current migration - that will (eventually)
319 * stop the migration using this structure
321 migration_cancel(NULL
);
322 object_unref(OBJECT(current_migration
));
325 * Cancel outgoing migration of dirty bitmaps. It should
326 * at least unref used block nodes.
328 dirty_bitmap_mig_cancel_outgoing();
331 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
332 * are non-critical data, and their loss never considered as
335 dirty_bitmap_mig_cancel_incoming();
339 MigrationState
*migrate_get_current(void)
341 /* This can only be called after the object created. */
342 assert(current_migration
);
343 return current_migration
;
346 MigrationIncomingState
*migration_incoming_get_current(void)
348 assert(current_incoming
);
349 return current_incoming
;
352 void migration_incoming_transport_cleanup(MigrationIncomingState
*mis
)
354 if (mis
->socket_address_list
) {
355 qapi_free_SocketAddressList(mis
->socket_address_list
);
356 mis
->socket_address_list
= NULL
;
359 if (mis
->transport_cleanup
) {
360 mis
->transport_cleanup(mis
->transport_data
);
361 mis
->transport_data
= mis
->transport_cleanup
= NULL
;
365 void migration_incoming_state_destroy(void)
367 struct MigrationIncomingState
*mis
= migration_incoming_get_current();
369 multifd_recv_cleanup();
370 compress_threads_load_cleanup();
372 if (mis
->to_src_file
) {
373 /* Tell source that we are done */
374 migrate_send_rp_shut(mis
, qemu_file_get_error(mis
->from_src_file
) != 0);
375 qemu_fclose(mis
->to_src_file
);
376 mis
->to_src_file
= NULL
;
379 if (mis
->from_src_file
) {
380 migration_ioc_unregister_yank_from_file(mis
->from_src_file
);
381 qemu_fclose(mis
->from_src_file
);
382 mis
->from_src_file
= NULL
;
384 if (mis
->postcopy_remote_fds
) {
385 g_array_free(mis
->postcopy_remote_fds
, TRUE
);
386 mis
->postcopy_remote_fds
= NULL
;
389 migration_incoming_transport_cleanup(mis
);
390 qemu_event_reset(&mis
->main_thread_load_event
);
392 if (mis
->page_requested
) {
393 g_tree_destroy(mis
->page_requested
);
394 mis
->page_requested
= NULL
;
397 if (mis
->postcopy_qemufile_dst
) {
398 migration_ioc_unregister_yank_from_file(mis
->postcopy_qemufile_dst
);
399 qemu_fclose(mis
->postcopy_qemufile_dst
);
400 mis
->postcopy_qemufile_dst
= NULL
;
403 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
406 static void migrate_generate_event(int new_state
)
408 if (migrate_events()) {
409 qapi_event_send_migration(new_state
);
414 * Send a message on the return channel back to the source
417 static int migrate_send_rp_message(MigrationIncomingState
*mis
,
418 enum mig_rp_message_type message_type
,
419 uint16_t len
, void *data
)
423 trace_migrate_send_rp_message((int)message_type
, len
);
424 QEMU_LOCK_GUARD(&mis
->rp_mutex
);
427 * It's possible that the file handle got lost due to network
430 if (!mis
->to_src_file
) {
435 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
436 qemu_put_be16(mis
->to_src_file
, len
);
437 qemu_put_buffer(mis
->to_src_file
, data
, len
);
438 return qemu_fflush(mis
->to_src_file
);
441 /* Request one page from the source VM at the given start address.
442 * rb: the RAMBlock to request the page in
443 * Start: Address offset within the RB
444 * Len: Length in bytes required - must be a multiple of pagesize
446 int migrate_send_rp_message_req_pages(MigrationIncomingState
*mis
,
447 RAMBlock
*rb
, ram_addr_t start
)
449 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
450 size_t msglen
= 12; /* start + len */
451 size_t len
= qemu_ram_pagesize(rb
);
452 enum mig_rp_message_type msg_type
;
456 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
457 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
460 * We maintain the last ramblock that we requested for page. Note that we
461 * don't need locking because this function will only be called within the
462 * postcopy ram fault thread.
464 if (rb
!= mis
->last_rb
) {
467 rbname
= qemu_ram_get_idstr(rb
);
468 rbname_len
= strlen(rbname
);
470 assert(rbname_len
< 256);
472 bufc
[msglen
++] = rbname_len
;
473 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
474 msglen
+= rbname_len
;
475 msg_type
= MIG_RP_MSG_REQ_PAGES_ID
;
477 msg_type
= MIG_RP_MSG_REQ_PAGES
;
480 return migrate_send_rp_message(mis
, msg_type
, msglen
, bufc
);
483 int migrate_send_rp_req_pages(MigrationIncomingState
*mis
,
484 RAMBlock
*rb
, ram_addr_t start
, uint64_t haddr
)
486 void *aligned
= (void *)(uintptr_t)ROUND_DOWN(haddr
, qemu_ram_pagesize(rb
));
487 bool received
= false;
489 WITH_QEMU_LOCK_GUARD(&mis
->page_request_mutex
) {
490 received
= ramblock_recv_bitmap_test_byte_offset(rb
, start
);
491 if (!received
&& !g_tree_lookup(mis
->page_requested
, aligned
)) {
493 * The page has not been received, and it's not yet in the page
494 * request list. Queue it. Set the value of element to 1, so that
495 * things like g_tree_lookup() will return TRUE (1) when found.
497 g_tree_insert(mis
->page_requested
, aligned
, (gpointer
)1);
498 qatomic_inc(&mis
->page_requested_count
);
499 trace_postcopy_page_req_add(aligned
, mis
->page_requested_count
);
504 * If the page is there, skip sending the message. We don't even need the
505 * lock because as long as the page arrived, it'll be there forever.
511 return migrate_send_rp_message_req_pages(mis
, rb
, start
);
514 static bool migration_colo_enabled
;
515 bool migration_incoming_colo_enabled(void)
517 return migration_colo_enabled
;
520 void migration_incoming_disable_colo(void)
522 ram_block_discard_disable(false);
523 migration_colo_enabled
= false;
526 int migration_incoming_enable_colo(void)
528 #ifndef CONFIG_REPLICATION
529 error_report("ENABLE_COLO command come in migration stream, but COLO "
530 "module is not built in");
534 if (!migrate_colo()) {
535 error_report("ENABLE_COLO command come in migration stream, but c-colo "
536 "capability is not set");
540 if (ram_block_discard_disable(true)) {
541 error_report("COLO: cannot disable RAM discard");
544 migration_colo_enabled
= true;
548 void migrate_add_address(SocketAddress
*address
)
550 MigrationIncomingState
*mis
= migration_incoming_get_current();
552 QAPI_LIST_PREPEND(mis
->socket_address_list
,
553 QAPI_CLONE(SocketAddress
, address
));
556 bool migrate_uri_parse(const char *uri
, MigrationChannel
**channel
,
559 g_autoptr(MigrationChannel
) val
= g_new0(MigrationChannel
, 1);
560 g_autoptr(MigrationAddress
) addr
= g_new0(MigrationAddress
, 1);
561 InetSocketAddress
*isock
= &addr
->u
.rdma
;
562 strList
**tail
= &addr
->u
.exec
.args
;
564 if (strstart(uri
, "exec:", NULL
)) {
565 addr
->transport
= MIGRATION_ADDRESS_TYPE_EXEC
;
567 QAPI_LIST_APPEND(tail
, g_strdup(exec_get_cmd_path()));
568 QAPI_LIST_APPEND(tail
, g_strdup("/c"));
570 QAPI_LIST_APPEND(tail
, g_strdup("/bin/sh"));
571 QAPI_LIST_APPEND(tail
, g_strdup("-c"));
573 QAPI_LIST_APPEND(tail
, g_strdup(uri
+ strlen("exec:")));
574 } else if (strstart(uri
, "rdma:", NULL
)) {
575 if (inet_parse(isock
, uri
+ strlen("rdma:"), errp
)) {
576 qapi_free_InetSocketAddress(isock
);
579 addr
->transport
= MIGRATION_ADDRESS_TYPE_RDMA
;
580 } else if (strstart(uri
, "tcp:", NULL
) ||
581 strstart(uri
, "unix:", NULL
) ||
582 strstart(uri
, "vsock:", NULL
) ||
583 strstart(uri
, "fd:", NULL
)) {
584 addr
->transport
= MIGRATION_ADDRESS_TYPE_SOCKET
;
585 SocketAddress
*saddr
= socket_parse(uri
, errp
);
589 addr
->u
.socket
.type
= saddr
->type
;
590 addr
->u
.socket
.u
= saddr
->u
;
591 /* Don't free the objects inside; their ownership moved to "addr" */
593 } else if (strstart(uri
, "file:", NULL
)) {
594 addr
->transport
= MIGRATION_ADDRESS_TYPE_FILE
;
595 addr
->u
.file
.filename
= g_strdup(uri
+ strlen("file:"));
596 if (file_parse_offset(addr
->u
.file
.filename
, &addr
->u
.file
.offset
,
601 error_setg(errp
, "unknown migration protocol: %s", uri
);
605 val
->channel_type
= MIGRATION_CHANNEL_TYPE_MAIN
;
606 val
->addr
= g_steal_pointer(&addr
);
607 *channel
= g_steal_pointer(&val
);
611 static void qemu_start_incoming_migration(const char *uri
, bool has_channels
,
612 MigrationChannelList
*channels
,
615 g_autoptr(MigrationChannel
) channel
= NULL
;
616 MigrationAddress
*addr
= NULL
;
617 MigrationIncomingState
*mis
= migration_incoming_get_current();
620 * Having preliminary checks for uri and channel
622 if (!uri
== !channels
) {
623 error_setg(errp
, "need either 'uri' or 'channels' argument");
628 /* To verify that Migrate channel list has only item */
629 if (channels
->next
) {
630 error_setg(errp
, "Channel list has more than one entries");
633 addr
= channels
->value
->addr
;
637 /* caller uses the old URI syntax */
638 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
641 addr
= channel
->addr
;
644 /* transport mechanism not suitable for migration? */
645 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
649 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
650 MIGRATION_STATUS_SETUP
);
652 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
653 SocketAddress
*saddr
= &addr
->u
.socket
;
654 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
655 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
656 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
657 socket_start_incoming_migration(saddr
, errp
);
658 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
659 fd_start_incoming_migration(saddr
->u
.fd
.str
, errp
);
662 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
663 if (migrate_compress()) {
664 error_setg(errp
, "RDMA and compression can't be used together");
667 if (migrate_xbzrle()) {
668 error_setg(errp
, "RDMA and XBZRLE can't be used together");
671 if (migrate_multifd()) {
672 error_setg(errp
, "RDMA and multifd can't be used together");
675 rdma_start_incoming_migration(&addr
->u
.rdma
, errp
);
677 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
678 exec_start_incoming_migration(addr
->u
.exec
.args
, errp
);
679 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
680 file_start_incoming_migration(&addr
->u
.file
, errp
);
682 error_setg(errp
, "unknown migration protocol: %s", uri
);
686 static void process_incoming_migration_bh(void *opaque
)
688 Error
*local_err
= NULL
;
689 MigrationIncomingState
*mis
= opaque
;
691 trace_vmstate_downtime_checkpoint("dst-precopy-bh-enter");
693 /* If capability late_block_activate is set:
694 * Only fire up the block code now if we're going to restart the
695 * VM, else 'cont' will do it.
696 * This causes file locking to happen; so we don't want it to happen
697 * unless we really are starting the VM.
699 if (!migrate_late_block_activate() ||
700 (autostart
&& (!global_state_received() ||
701 runstate_is_live(global_state_get_runstate())))) {
702 /* Make sure all file formats throw away their mutable metadata.
703 * If we get an error here, just don't restart the VM yet. */
704 bdrv_activate_all(&local_err
);
706 error_report_err(local_err
);
713 * This must happen after all error conditions are dealt with and
714 * we're sure the VM is going to be running on this host.
716 qemu_announce_self(&mis
->announce_timer
, migrate_announce_params());
718 trace_vmstate_downtime_checkpoint("dst-precopy-bh-announced");
720 multifd_recv_shutdown();
722 dirty_bitmap_mig_before_vm_start();
724 if (!global_state_received() ||
725 runstate_is_live(global_state_get_runstate())) {
729 runstate_set(RUN_STATE_PAUSED
);
731 } else if (migration_incoming_colo_enabled()) {
732 migration_incoming_disable_colo();
735 runstate_set(global_state_get_runstate());
737 trace_vmstate_downtime_checkpoint("dst-precopy-bh-vm-started");
739 * This must happen after any state changes since as soon as an external
740 * observer sees this event they might start to prod at the VM assuming
743 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
744 MIGRATION_STATUS_COMPLETED
);
745 migration_incoming_state_destroy();
748 static void coroutine_fn
749 process_incoming_migration_co(void *opaque
)
751 MigrationIncomingState
*mis
= migration_incoming_get_current();
755 assert(mis
->from_src_file
);
757 if (compress_threads_load_setup(mis
->from_src_file
)) {
758 error_report("Failed to setup decompress threads");
762 mis
->largest_page_size
= qemu_ram_pagesize_largest();
763 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
764 migrate_set_state(&mis
->state
, MIGRATION_STATUS_SETUP
,
765 MIGRATION_STATUS_ACTIVE
);
767 mis
->loadvm_co
= qemu_coroutine_self();
768 ret
= qemu_loadvm_state(mis
->from_src_file
);
769 mis
->loadvm_co
= NULL
;
771 trace_vmstate_downtime_checkpoint("dst-precopy-loadvm-completed");
773 ps
= postcopy_state_get();
774 trace_process_incoming_migration_co_end(ret
, ps
);
775 if (ps
!= POSTCOPY_INCOMING_NONE
) {
776 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
778 * Where a migration had postcopy enabled (and thus went to advise)
779 * but managed to complete within the precopy period, we can use
782 postcopy_ram_incoming_cleanup(mis
);
783 } else if (ret
>= 0) {
785 * Postcopy was started, cleanup should happen at the end of the
788 trace_process_incoming_migration_co_postcopy_end_main();
791 /* Else if something went wrong then just fall out of the normal exit */
795 MigrationState
*s
= migrate_get_current();
797 if (migrate_has_error(s
)) {
798 WITH_QEMU_LOCK_GUARD(&s
->error_mutex
) {
799 error_report_err(s
->error
);
802 error_report("load of migration failed: %s", strerror(-ret
));
806 if (colo_incoming_co() < 0) {
810 migration_bh_schedule(process_incoming_migration_bh
, mis
);
813 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
814 MIGRATION_STATUS_FAILED
);
815 qemu_fclose(mis
->from_src_file
);
817 multifd_recv_cleanup();
818 compress_threads_load_cleanup();
824 * migration_incoming_setup: Setup incoming migration
825 * @f: file for main migration channel
827 static void migration_incoming_setup(QEMUFile
*f
)
829 MigrationIncomingState
*mis
= migration_incoming_get_current();
831 if (!mis
->from_src_file
) {
832 mis
->from_src_file
= f
;
834 qemu_file_set_blocking(f
, false);
837 void migration_incoming_process(void)
839 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
, NULL
);
840 qemu_coroutine_enter(co
);
843 /* Returns true if recovered from a paused migration, otherwise false */
844 static bool postcopy_try_recover(void)
846 MigrationIncomingState
*mis
= migration_incoming_get_current();
848 if (mis
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
849 /* Resumed from a paused postcopy migration */
851 /* This should be set already in migration_incoming_setup() */
852 assert(mis
->from_src_file
);
853 /* Postcopy has standalone thread to do vm load */
854 qemu_file_set_blocking(mis
->from_src_file
, true);
856 /* Re-configure the return path */
857 mis
->to_src_file
= qemu_file_get_return_path(mis
->from_src_file
);
859 migrate_set_state(&mis
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
860 MIGRATION_STATUS_POSTCOPY_RECOVER
);
863 * Here, we only wake up the main loading thread (while the
864 * rest threads will still be waiting), so that we can receive
865 * commands from source now, and answer it if needed. The
866 * rest threads will be woken up afterwards until we are sure
867 * that source is ready to reply to page requests.
869 qemu_sem_post(&mis
->postcopy_pause_sem_dst
);
876 void migration_fd_process_incoming(QEMUFile
*f
)
878 migration_incoming_setup(f
);
879 if (postcopy_try_recover()) {
882 migration_incoming_process();
886 * Returns true when we want to start a new incoming migration process,
889 static bool migration_should_start_incoming(bool main_channel
)
891 /* Multifd doesn't start unless all channels are established */
892 if (migrate_multifd()) {
893 return migration_has_all_channels();
896 /* Preempt channel only starts when the main channel is created */
897 if (migrate_postcopy_preempt()) {
902 * For all the rest types of migration, we should only reach here when
903 * it's the main channel that's being created, and we should always
904 * proceed with this channel.
906 assert(main_channel
);
910 void migration_ioc_process_incoming(QIOChannel
*ioc
, Error
**errp
)
912 MigrationIncomingState
*mis
= migration_incoming_get_current();
913 Error
*local_err
= NULL
;
915 bool default_channel
= true;
916 uint32_t channel_magic
= 0;
919 if (migrate_multifd() && !migrate_mapped_ram() &&
920 !migrate_postcopy_ram() &&
921 qio_channel_has_feature(ioc
, QIO_CHANNEL_FEATURE_READ_MSG_PEEK
)) {
923 * With multiple channels, it is possible that we receive channels
924 * out of order on destination side, causing incorrect mapping of
925 * source channels on destination side. Check channel MAGIC to
926 * decide type of channel. Please note this is best effort, postcopy
927 * preempt channel does not send any magic number so avoid it for
928 * postcopy live migration. Also tls live migration already does
929 * tls handshake while initializing main channel so with tls this
930 * issue is not possible.
932 ret
= migration_channel_read_peek(ioc
, (void *)&channel_magic
,
933 sizeof(channel_magic
), errp
);
939 default_channel
= (channel_magic
== cpu_to_be32(QEMU_VM_FILE_MAGIC
));
941 default_channel
= !mis
->from_src_file
;
944 if (multifd_recv_setup(errp
) != 0) {
948 if (default_channel
) {
949 f
= qemu_file_new_input(ioc
);
950 migration_incoming_setup(f
);
952 /* Multiple connections */
953 assert(migration_needs_multiple_sockets());
954 if (migrate_multifd()) {
955 multifd_recv_new_channel(ioc
, &local_err
);
957 assert(migrate_postcopy_preempt());
958 f
= qemu_file_new_input(ioc
);
959 postcopy_preempt_new_channel(mis
, f
);
962 error_propagate(errp
, local_err
);
967 if (migration_should_start_incoming(default_channel
)) {
968 /* If it's a recovery, we're done */
969 if (postcopy_try_recover()) {
972 migration_incoming_process();
977 * @migration_has_all_channels: We have received all channels that we need
979 * Returns true when we have got connections to all the channels that
980 * we need for migration.
982 bool migration_has_all_channels(void)
984 MigrationIncomingState
*mis
= migration_incoming_get_current();
986 if (!mis
->from_src_file
) {
990 if (migrate_multifd()) {
991 return multifd_recv_all_channels_created();
994 if (migrate_postcopy_preempt()) {
995 return mis
->postcopy_qemufile_dst
!= NULL
;
1001 int migrate_send_rp_switchover_ack(MigrationIncomingState
*mis
)
1003 return migrate_send_rp_message(mis
, MIG_RP_MSG_SWITCHOVER_ACK
, 0, NULL
);
1007 * Send a 'SHUT' message on the return channel with the given value
1008 * to indicate that we've finished with the RP. Non-0 value indicates
1011 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
1016 buf
= cpu_to_be32(value
);
1017 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
1021 * Send a 'PONG' message on the return channel with the given value
1022 * (normally in response to a 'PING')
1024 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
1029 buf
= cpu_to_be32(value
);
1030 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
1033 void migrate_send_rp_recv_bitmap(MigrationIncomingState
*mis
,
1041 * First, we send the header part. It contains only the len of
1042 * idstr, and the idstr itself.
1044 len
= strlen(block_name
);
1046 memcpy(buf
+ 1, block_name
, len
);
1048 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_RECOVER
) {
1049 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
1054 migrate_send_rp_message(mis
, MIG_RP_MSG_RECV_BITMAP
, len
+ 1, buf
);
1057 * Next, we dump the received bitmap to the stream.
1059 * TODO: currently we are safe since we are the only one that is
1060 * using the to_src_file handle (fault thread is still paused),
1061 * and it's ok even not taking the mutex. However the best way is
1062 * to take the lock before sending the message header, and release
1063 * the lock after sending the bitmap.
1065 qemu_mutex_lock(&mis
->rp_mutex
);
1066 res
= ramblock_recv_bitmap_send(mis
->to_src_file
, block_name
);
1067 qemu_mutex_unlock(&mis
->rp_mutex
);
1069 trace_migrate_send_rp_recv_bitmap(block_name
, res
);
1072 void migrate_send_rp_resume_ack(MigrationIncomingState
*mis
, uint32_t value
)
1076 buf
= cpu_to_be32(value
);
1077 migrate_send_rp_message(mis
, MIG_RP_MSG_RESUME_ACK
, sizeof(buf
), &buf
);
1081 * Return true if we're already in the middle of a migration
1082 * (i.e. any of the active or setup states)
1084 bool migration_is_setup_or_active(int state
)
1087 case MIGRATION_STATUS_ACTIVE
:
1088 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1089 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1090 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1091 case MIGRATION_STATUS_SETUP
:
1092 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1093 case MIGRATION_STATUS_DEVICE
:
1094 case MIGRATION_STATUS_WAIT_UNPLUG
:
1095 case MIGRATION_STATUS_COLO
:
1104 bool migration_is_running(int state
)
1107 case MIGRATION_STATUS_ACTIVE
:
1108 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1109 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1110 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1111 case MIGRATION_STATUS_SETUP
:
1112 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1113 case MIGRATION_STATUS_DEVICE
:
1114 case MIGRATION_STATUS_WAIT_UNPLUG
:
1115 case MIGRATION_STATUS_CANCELLING
:
1124 static bool migrate_show_downtime(MigrationState
*s
)
1126 return (s
->state
== MIGRATION_STATUS_COMPLETED
) || migration_in_postcopy();
1129 static void populate_time_info(MigrationInfo
*info
, MigrationState
*s
)
1131 info
->has_status
= true;
1132 info
->has_setup_time
= true;
1133 info
->setup_time
= s
->setup_time
;
1135 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1136 info
->has_total_time
= true;
1137 info
->total_time
= s
->total_time
;
1139 info
->has_total_time
= true;
1140 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) -
1144 if (migrate_show_downtime(s
)) {
1145 info
->has_downtime
= true;
1146 info
->downtime
= s
->downtime
;
1148 info
->has_expected_downtime
= true;
1149 info
->expected_downtime
= s
->expected_downtime
;
1153 static void populate_ram_info(MigrationInfo
*info
, MigrationState
*s
)
1155 size_t page_size
= qemu_target_page_size();
1157 info
->ram
= g_malloc0(sizeof(*info
->ram
));
1158 info
->ram
->transferred
= migration_transferred_bytes();
1159 info
->ram
->total
= ram_bytes_total();
1160 info
->ram
->duplicate
= stat64_get(&mig_stats
.zero_pages
);
1161 /* legacy value. It is not used anymore */
1162 info
->ram
->skipped
= 0;
1163 info
->ram
->normal
= stat64_get(&mig_stats
.normal_pages
);
1164 info
->ram
->normal_bytes
= info
->ram
->normal
* page_size
;
1165 info
->ram
->mbps
= s
->mbps
;
1166 info
->ram
->dirty_sync_count
=
1167 stat64_get(&mig_stats
.dirty_sync_count
);
1168 info
->ram
->dirty_sync_missed_zero_copy
=
1169 stat64_get(&mig_stats
.dirty_sync_missed_zero_copy
);
1170 info
->ram
->postcopy_requests
=
1171 stat64_get(&mig_stats
.postcopy_requests
);
1172 info
->ram
->page_size
= page_size
;
1173 info
->ram
->multifd_bytes
= stat64_get(&mig_stats
.multifd_bytes
);
1174 info
->ram
->pages_per_second
= s
->pages_per_second
;
1175 info
->ram
->precopy_bytes
= stat64_get(&mig_stats
.precopy_bytes
);
1176 info
->ram
->downtime_bytes
= stat64_get(&mig_stats
.downtime_bytes
);
1177 info
->ram
->postcopy_bytes
= stat64_get(&mig_stats
.postcopy_bytes
);
1179 if (migrate_xbzrle()) {
1180 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
1181 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
1182 info
->xbzrle_cache
->bytes
= xbzrle_counters
.bytes
;
1183 info
->xbzrle_cache
->pages
= xbzrle_counters
.pages
;
1184 info
->xbzrle_cache
->cache_miss
= xbzrle_counters
.cache_miss
;
1185 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_counters
.cache_miss_rate
;
1186 info
->xbzrle_cache
->encoding_rate
= xbzrle_counters
.encoding_rate
;
1187 info
->xbzrle_cache
->overflow
= xbzrle_counters
.overflow
;
1190 populate_compress(info
);
1192 if (cpu_throttle_active()) {
1193 info
->has_cpu_throttle_percentage
= true;
1194 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
1197 if (s
->state
!= MIGRATION_STATUS_COMPLETED
) {
1198 info
->ram
->remaining
= ram_bytes_remaining();
1199 info
->ram
->dirty_pages_rate
=
1200 stat64_get(&mig_stats
.dirty_pages_rate
);
1203 if (migrate_dirty_limit() && dirtylimit_in_service()) {
1204 info
->has_dirty_limit_throttle_time_per_round
= true;
1205 info
->dirty_limit_throttle_time_per_round
=
1206 dirtylimit_throttle_time_per_round();
1208 info
->has_dirty_limit_ring_full_time
= true;
1209 info
->dirty_limit_ring_full_time
= dirtylimit_ring_full_time();
1213 static void populate_disk_info(MigrationInfo
*info
)
1215 if (blk_mig_active()) {
1216 info
->disk
= g_malloc0(sizeof(*info
->disk
));
1217 info
->disk
->transferred
= blk_mig_bytes_transferred();
1218 info
->disk
->remaining
= blk_mig_bytes_remaining();
1219 info
->disk
->total
= blk_mig_bytes_total();
1223 static void fill_source_migration_info(MigrationInfo
*info
)
1225 MigrationState
*s
= migrate_get_current();
1226 int state
= qatomic_read(&s
->state
);
1227 GSList
*cur_blocker
= migration_blockers
[migrate_mode()];
1229 info
->blocked_reasons
= NULL
;
1232 * There are two types of reasons a migration might be blocked;
1233 * a) devices marked in VMState as non-migratable, and
1234 * b) Explicit migration blockers
1235 * We need to add both of them here.
1237 qemu_savevm_non_migratable_list(&info
->blocked_reasons
);
1239 while (cur_blocker
) {
1240 QAPI_LIST_PREPEND(info
->blocked_reasons
,
1241 g_strdup(error_get_pretty(cur_blocker
->data
)));
1242 cur_blocker
= g_slist_next(cur_blocker
);
1244 info
->has_blocked_reasons
= info
->blocked_reasons
!= NULL
;
1247 case MIGRATION_STATUS_NONE
:
1248 /* no migration has happened ever */
1249 /* do not overwrite destination migration status */
1251 case MIGRATION_STATUS_SETUP
:
1252 info
->has_status
= true;
1253 info
->has_total_time
= false;
1255 case MIGRATION_STATUS_ACTIVE
:
1256 case MIGRATION_STATUS_CANCELLING
:
1257 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1258 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1259 case MIGRATION_STATUS_DEVICE
:
1260 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1261 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1262 /* TODO add some postcopy stats */
1263 populate_time_info(info
, s
);
1264 populate_ram_info(info
, s
);
1265 populate_disk_info(info
);
1266 migration_populate_vfio_info(info
);
1268 case MIGRATION_STATUS_COLO
:
1269 info
->has_status
= true;
1270 /* TODO: display COLO specific information (checkpoint info etc.) */
1272 case MIGRATION_STATUS_COMPLETED
:
1273 populate_time_info(info
, s
);
1274 populate_ram_info(info
, s
);
1275 migration_populate_vfio_info(info
);
1277 case MIGRATION_STATUS_FAILED
:
1278 info
->has_status
= true;
1280 case MIGRATION_STATUS_CANCELLED
:
1281 info
->has_status
= true;
1283 case MIGRATION_STATUS_WAIT_UNPLUG
:
1284 info
->has_status
= true;
1287 info
->status
= state
;
1289 QEMU_LOCK_GUARD(&s
->error_mutex
);
1291 info
->error_desc
= g_strdup(error_get_pretty(s
->error
));
1295 static void fill_destination_migration_info(MigrationInfo
*info
)
1297 MigrationIncomingState
*mis
= migration_incoming_get_current();
1299 if (mis
->socket_address_list
) {
1300 info
->has_socket_address
= true;
1301 info
->socket_address
=
1302 QAPI_CLONE(SocketAddressList
, mis
->socket_address_list
);
1305 switch (mis
->state
) {
1306 case MIGRATION_STATUS_NONE
:
1308 case MIGRATION_STATUS_SETUP
:
1309 case MIGRATION_STATUS_CANCELLING
:
1310 case MIGRATION_STATUS_CANCELLED
:
1311 case MIGRATION_STATUS_ACTIVE
:
1312 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1313 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1314 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1315 case MIGRATION_STATUS_FAILED
:
1316 case MIGRATION_STATUS_COLO
:
1317 info
->has_status
= true;
1319 case MIGRATION_STATUS_COMPLETED
:
1320 info
->has_status
= true;
1321 fill_destination_postcopy_migration_info(info
);
1324 info
->status
= mis
->state
;
1327 MigrationInfo
*qmp_query_migrate(Error
**errp
)
1329 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
1331 fill_destination_migration_info(info
);
1332 fill_source_migration_info(info
);
1337 void qmp_migrate_start_postcopy(Error
**errp
)
1339 MigrationState
*s
= migrate_get_current();
1341 if (!migrate_postcopy()) {
1342 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
1343 " the start of migration");
1347 if (s
->state
== MIGRATION_STATUS_NONE
) {
1348 error_setg(errp
, "Postcopy must be started after migration has been"
1353 * we don't error if migration has finished since that would be racy
1354 * with issuing this command.
1356 qatomic_set(&s
->start_postcopy
, true);
1359 /* shared migration helpers */
1361 void migrate_set_state(int *state
, int old_state
, int new_state
)
1363 assert(new_state
< MIGRATION_STATUS__MAX
);
1364 if (qatomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
1365 trace_migrate_set_state(MigrationStatus_str(new_state
));
1366 migrate_generate_event(new_state
);
1370 static void migrate_fd_cleanup(MigrationState
*s
)
1372 MigrationEventType type
;
1374 g_free(s
->hostname
);
1376 json_writer_free(s
->vmdesc
);
1379 qemu_savevm_state_cleanup();
1381 close_return_path_on_source(s
);
1383 if (s
->to_dst_file
) {
1386 trace_migrate_fd_cleanup();
1388 if (s
->migration_thread_running
) {
1389 qemu_thread_join(&s
->thread
);
1390 s
->migration_thread_running
= false;
1394 multifd_send_shutdown();
1395 qemu_mutex_lock(&s
->qemu_file_lock
);
1396 tmp
= s
->to_dst_file
;
1397 s
->to_dst_file
= NULL
;
1398 qemu_mutex_unlock(&s
->qemu_file_lock
);
1400 * Close the file handle without the lock to make sure the
1401 * critical section won't block for long.
1403 migration_ioc_unregister_yank_from_file(tmp
);
1407 assert(!migration_is_active(s
));
1409 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1410 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
1411 MIGRATION_STATUS_CANCELLED
);
1415 /* It is used on info migrate. We can't free it */
1416 error_report_err(error_copy(s
->error
));
1418 type
= migration_has_failed(s
) ? MIG_EVENT_PRECOPY_FAILED
:
1419 MIG_EVENT_PRECOPY_DONE
;
1420 migration_call_notifiers(s
, type
, NULL
);
1421 block_cleanup_parameters();
1422 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1425 static void migrate_fd_cleanup_bh(void *opaque
)
1427 migrate_fd_cleanup(opaque
);
1430 void migrate_set_error(MigrationState
*s
, const Error
*error
)
1432 QEMU_LOCK_GUARD(&s
->error_mutex
);
1434 s
->error
= error_copy(error
);
1438 bool migrate_has_error(MigrationState
*s
)
1440 /* The lock is not helpful here, but still follow the rule */
1441 QEMU_LOCK_GUARD(&s
->error_mutex
);
1442 return qatomic_read(&s
->error
);
1445 static void migrate_error_free(MigrationState
*s
)
1447 QEMU_LOCK_GUARD(&s
->error_mutex
);
1449 error_free(s
->error
);
1454 static void migrate_fd_error(MigrationState
*s
, const Error
*error
)
1456 trace_migrate_fd_error(error_get_pretty(error
));
1457 assert(s
->to_dst_file
== NULL
);
1458 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1459 MIGRATION_STATUS_FAILED
);
1460 migrate_set_error(s
, error
);
1463 static void migrate_fd_cancel(MigrationState
*s
)
1467 trace_migrate_fd_cancel();
1469 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1470 if (s
->rp_state
.from_dst_file
) {
1471 /* shutdown the rp socket, so causing the rp thread to shutdown */
1472 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
1477 old_state
= s
->state
;
1478 if (!migration_is_running(old_state
)) {
1481 /* If the migration is paused, kick it out of the pause */
1482 if (old_state
== MIGRATION_STATUS_PRE_SWITCHOVER
) {
1483 qemu_sem_post(&s
->pause_sem
);
1485 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
1486 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
1489 * If we're unlucky the migration code might be stuck somewhere in a
1490 * send/write while the network has failed and is waiting to timeout;
1491 * if we've got shutdown(2) available then we can force it to quit.
1493 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
1494 WITH_QEMU_LOCK_GUARD(&s
->qemu_file_lock
) {
1495 if (s
->to_dst_file
) {
1496 qemu_file_shutdown(s
->to_dst_file
);
1500 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& s
->block_inactive
) {
1501 Error
*local_err
= NULL
;
1503 bdrv_activate_all(&local_err
);
1505 error_report_err(local_err
);
1507 s
->block_inactive
= false;
1512 void migration_add_notifier_mode(NotifierWithReturn
*notify
,
1513 MigrationNotifyFunc func
, MigMode mode
)
1515 notify
->notify
= (NotifierWithReturnFunc
)func
;
1516 notifier_with_return_list_add(&migration_state_notifiers
[mode
], notify
);
1519 void migration_add_notifier(NotifierWithReturn
*notify
,
1520 MigrationNotifyFunc func
)
1522 migration_add_notifier_mode(notify
, func
, MIG_MODE_NORMAL
);
1525 void migration_remove_notifier(NotifierWithReturn
*notify
)
1527 if (notify
->notify
) {
1528 notifier_with_return_remove(notify
);
1529 notify
->notify
= NULL
;
1533 int migration_call_notifiers(MigrationState
*s
, MigrationEventType type
,
1536 MigMode mode
= s
->parameters
.mode
;
1541 ret
= notifier_with_return_list_notify(&migration_state_notifiers
[mode
],
1543 assert(!ret
|| type
== MIG_EVENT_PRECOPY_SETUP
);
1547 bool migration_in_setup(MigrationState
*s
)
1549 return s
->state
== MIGRATION_STATUS_SETUP
;
1552 bool migration_has_finished(MigrationState
*s
)
1554 return s
->state
== MIGRATION_STATUS_COMPLETED
;
1557 bool migration_has_failed(MigrationState
*s
)
1559 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
1560 s
->state
== MIGRATION_STATUS_FAILED
);
1563 bool migration_in_postcopy(void)
1565 MigrationState
*s
= migrate_get_current();
1568 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1569 case MIGRATION_STATUS_POSTCOPY_PAUSED
:
1570 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1577 bool migration_postcopy_is_alive(int state
)
1580 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1581 case MIGRATION_STATUS_POSTCOPY_RECOVER
:
1588 bool migration_in_incoming_postcopy(void)
1590 PostcopyState ps
= postcopy_state_get();
1592 return ps
>= POSTCOPY_INCOMING_DISCARD
&& ps
< POSTCOPY_INCOMING_END
;
1595 bool migration_incoming_postcopy_advised(void)
1597 PostcopyState ps
= postcopy_state_get();
1599 return ps
>= POSTCOPY_INCOMING_ADVISE
&& ps
< POSTCOPY_INCOMING_END
;
1602 bool migration_in_bg_snapshot(void)
1604 MigrationState
*s
= migrate_get_current();
1606 return migrate_background_snapshot() &&
1607 migration_is_setup_or_active(s
->state
);
1610 bool migration_is_idle(void)
1612 MigrationState
*s
= current_migration
;
1619 case MIGRATION_STATUS_NONE
:
1620 case MIGRATION_STATUS_CANCELLED
:
1621 case MIGRATION_STATUS_COMPLETED
:
1622 case MIGRATION_STATUS_FAILED
:
1624 case MIGRATION_STATUS_SETUP
:
1625 case MIGRATION_STATUS_CANCELLING
:
1626 case MIGRATION_STATUS_ACTIVE
:
1627 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
1628 case MIGRATION_STATUS_COLO
:
1629 case MIGRATION_STATUS_PRE_SWITCHOVER
:
1630 case MIGRATION_STATUS_DEVICE
:
1631 case MIGRATION_STATUS_WAIT_UNPLUG
:
1633 case MIGRATION_STATUS__MAX
:
1634 g_assert_not_reached();
1640 bool migration_is_active(MigrationState
*s
)
1642 return (s
->state
== MIGRATION_STATUS_ACTIVE
||
1643 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1646 bool migrate_mode_is_cpr(MigrationState
*s
)
1648 return s
->parameters
.mode
== MIG_MODE_CPR_REBOOT
;
1651 int migrate_init(MigrationState
*s
, Error
**errp
)
1655 ret
= qemu_savevm_state_prepare(errp
);
1661 * Reinitialise all migration state, except
1662 * parameters/capabilities that the user set, and
1665 s
->to_dst_file
= NULL
;
1666 s
->state
= MIGRATION_STATUS_NONE
;
1667 s
->rp_state
.from_dst_file
= NULL
;
1669 s
->pages_per_second
= 0.0;
1671 s
->expected_downtime
= 0;
1673 s
->start_postcopy
= false;
1674 s
->migration_thread_running
= false;
1675 error_free(s
->error
);
1679 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
1681 s
->start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1683 s
->vm_old_state
= -1;
1684 s
->iteration_initial_bytes
= 0;
1685 s
->threshold_size
= 0;
1686 s
->switchover_acked
= false;
1687 s
->rdma_migration
= false;
1689 * set mig_stats memory to zero for a new migration
1691 memset(&mig_stats
, 0, sizeof(mig_stats
));
1692 migration_reset_vfio_bytes_transferred();
1697 static bool is_busy(Error
**reasonp
, Error
**errp
)
1701 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1702 if (runstate_check(RUN_STATE_SAVE_VM
) || !migration_is_idle()) {
1703 error_propagate_prepend(errp
, *reasonp
,
1704 "disallowing migration blocker "
1705 "(migration/snapshot in progress) for: ");
1712 static bool is_only_migratable(Error
**reasonp
, Error
**errp
, int modes
)
1716 if (only_migratable
&& (modes
& BIT(MIG_MODE_NORMAL
))) {
1717 error_propagate_prepend(errp
, *reasonp
,
1718 "disallowing migration blocker "
1719 "(--only-migratable) for: ");
1726 static int get_modes(MigMode mode
, va_list ap
)
1730 while (mode
!= -1 && mode
!= MIG_MODE_ALL
) {
1731 assert(mode
>= MIG_MODE_NORMAL
&& mode
< MIG_MODE__MAX
);
1733 mode
= va_arg(ap
, MigMode
);
1735 if (mode
== MIG_MODE_ALL
) {
1736 modes
= BIT(MIG_MODE__MAX
) - 1;
1741 static int add_blockers(Error
**reasonp
, Error
**errp
, int modes
)
1743 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1744 if (modes
& BIT(mode
)) {
1745 migration_blockers
[mode
] = g_slist_prepend(migration_blockers
[mode
],
1752 int migrate_add_blocker(Error
**reasonp
, Error
**errp
)
1754 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_ALL
);
1757 int migrate_add_blocker_normal(Error
**reasonp
, Error
**errp
)
1759 return migrate_add_blocker_modes(reasonp
, errp
, MIG_MODE_NORMAL
, -1);
1762 int migrate_add_blocker_modes(Error
**reasonp
, Error
**errp
, MigMode mode
, ...)
1768 modes
= get_modes(mode
, ap
);
1771 if (is_only_migratable(reasonp
, errp
, modes
)) {
1773 } else if (is_busy(reasonp
, errp
)) {
1776 return add_blockers(reasonp
, errp
, modes
);
1779 int migrate_add_blocker_internal(Error
**reasonp
, Error
**errp
)
1781 int modes
= BIT(MIG_MODE__MAX
) - 1;
1783 if (is_busy(reasonp
, errp
)) {
1786 return add_blockers(reasonp
, errp
, modes
);
1789 void migrate_del_blocker(Error
**reasonp
)
1792 for (MigMode mode
= 0; mode
< MIG_MODE__MAX
; mode
++) {
1793 migration_blockers
[mode
] = g_slist_remove(migration_blockers
[mode
],
1796 error_free(*reasonp
);
1801 void qmp_migrate_incoming(const char *uri
, bool has_channels
,
1802 MigrationChannelList
*channels
, Error
**errp
)
1804 Error
*local_err
= NULL
;
1805 static bool once
= true;
1808 error_setg(errp
, "The incoming migration has already been started");
1811 if (!runstate_check(RUN_STATE_INMIGRATE
)) {
1812 error_setg(errp
, "'-incoming' was not specified on the command line");
1816 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
1820 qemu_start_incoming_migration(uri
, has_channels
, channels
, &local_err
);
1823 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
1824 error_propagate(errp
, local_err
);
1831 void qmp_migrate_recover(const char *uri
, Error
**errp
)
1833 MigrationIncomingState
*mis
= migration_incoming_get_current();
1836 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1837 * callers (no one should ignore a recover failure); if there is, it's a
1838 * programming error.
1842 if (mis
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1843 error_setg(errp
, "Migrate recover can only be run "
1844 "when postcopy is paused.");
1848 /* If there's an existing transport, release it */
1849 migration_incoming_transport_cleanup(mis
);
1852 * Note that this call will never start a real migration; it will
1853 * only re-setup the migration stream and poke existing migration
1854 * to continue using that newly established channel.
1856 qemu_start_incoming_migration(uri
, false, NULL
, errp
);
1859 void qmp_migrate_pause(Error
**errp
)
1861 MigrationState
*ms
= migrate_get_current();
1862 MigrationIncomingState
*mis
= migration_incoming_get_current();
1865 if (migration_postcopy_is_alive(ms
->state
)) {
1866 /* Source side, during postcopy */
1867 Error
*error
= NULL
;
1869 /* Tell the core migration that we're pausing */
1870 error_setg(&error
, "Postcopy migration is paused by the user");
1871 migrate_set_error(ms
, error
);
1874 qemu_mutex_lock(&ms
->qemu_file_lock
);
1875 if (ms
->to_dst_file
) {
1876 ret
= qemu_file_shutdown(ms
->to_dst_file
);
1878 qemu_mutex_unlock(&ms
->qemu_file_lock
);
1880 error_setg(errp
, "Failed to pause source migration");
1884 * Kick the migration thread out of any waiting windows (on behalf
1885 * of the rp thread).
1887 migration_rp_kick(ms
);
1892 if (migration_postcopy_is_alive(mis
->state
)) {
1893 ret
= qemu_file_shutdown(mis
->from_src_file
);
1895 error_setg(errp
, "Failed to pause destination migration");
1900 error_setg(errp
, "migrate-pause is currently only supported "
1901 "during postcopy-active or postcopy-recover state");
1904 bool migration_is_blocked(Error
**errp
)
1906 GSList
*blockers
= migration_blockers
[migrate_mode()];
1908 if (qemu_savevm_state_blocked(errp
)) {
1913 error_propagate(errp
, error_copy(blockers
->data
));
1920 /* Returns true if continue to migrate, or false if error detected */
1921 static bool migrate_prepare(MigrationState
*s
, bool blk
, bool blk_inc
,
1922 bool resume
, Error
**errp
)
1925 warn_report("parameter 'inc' is deprecated;"
1926 " use blockdev-mirror with NBD instead");
1930 warn_report("parameter 'blk' is deprecated;"
1931 " use blockdev-mirror with NBD instead");
1935 if (s
->state
!= MIGRATION_STATUS_POSTCOPY_PAUSED
) {
1936 error_setg(errp
, "Cannot resume if there is no "
1937 "paused migration");
1942 * Postcopy recovery won't work well with release-ram
1943 * capability since release-ram will drop the page buffer as
1944 * long as the page is put into the send buffer. So if there
1945 * is a network failure happened, any page buffers that have
1946 * not yet reached the destination VM but have already been
1947 * sent from the source VM will be lost forever. Let's refuse
1948 * the client from resuming such a postcopy migration.
1949 * Luckily release-ram was designed to only be used when src
1950 * and destination VMs are on the same host, so it should be
1953 if (migrate_release_ram()) {
1954 error_setg(errp
, "Postcopy recovery cannot work "
1955 "when release-ram capability is set");
1959 /* This is a resume, skip init status */
1963 if (migration_is_running(s
->state
)) {
1964 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1968 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1969 error_setg(errp
, "Guest is waiting for an incoming migration");
1973 if (runstate_check(RUN_STATE_POSTMIGRATE
)) {
1974 error_setg(errp
, "Can't migrate the vm that was paused due to "
1975 "previous migration");
1979 if (kvm_hwpoisoned_mem()) {
1980 error_setg(errp
, "Can't migrate this vm with hardware poisoned memory, "
1981 "please reboot the vm and try again");
1985 if (migration_is_blocked(errp
)) {
1989 if (migrate_mapped_ram()) {
1990 if (migrate_tls()) {
1991 error_setg(errp
, "Cannot use TLS with mapped-ram");
1995 if (migrate_multifd_compression()) {
1996 error_setg(errp
, "Cannot use compression with mapped-ram");
2001 if (migrate_mode_is_cpr(s
)) {
2002 const char *conflict
= NULL
;
2004 if (migrate_postcopy()) {
2005 conflict
= "postcopy";
2006 } else if (migrate_background_snapshot()) {
2007 conflict
= "background snapshot";
2008 } else if (migrate_colo()) {
2013 error_setg(errp
, "Cannot use %s with CPR", conflict
);
2018 if (blk
|| blk_inc
) {
2019 if (migrate_colo()) {
2020 error_setg(errp
, "No disk migration is required in COLO mode");
2023 if (migrate_block() || migrate_block_incremental()) {
2024 error_setg(errp
, "Command options are incompatible with "
2025 "current migration capabilities");
2028 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK
, true, errp
)) {
2031 s
->must_remove_block_options
= true;
2035 migrate_set_block_incremental(true);
2038 if (migrate_init(s
, errp
)) {
2045 void qmp_migrate(const char *uri
, bool has_channels
,
2046 MigrationChannelList
*channels
, bool has_blk
, bool blk
,
2047 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
2048 bool has_resume
, bool resume
, Error
**errp
)
2050 bool resume_requested
;
2051 Error
*local_err
= NULL
;
2052 MigrationState
*s
= migrate_get_current();
2053 g_autoptr(MigrationChannel
) channel
= NULL
;
2054 MigrationAddress
*addr
= NULL
;
2057 * Having preliminary checks for uri and channel
2059 if (!uri
== !channels
) {
2060 error_setg(errp
, "need either 'uri' or 'channels' argument");
2065 /* To verify that Migrate channel list has only item */
2066 if (channels
->next
) {
2067 error_setg(errp
, "Channel list has more than one entries");
2070 addr
= channels
->value
->addr
;
2074 /* caller uses the old URI syntax */
2075 if (!migrate_uri_parse(uri
, &channel
, errp
)) {
2078 addr
= channel
->addr
;
2081 /* transport mechanism not suitable for migration? */
2082 if (!migration_channels_and_transport_compatible(addr
, errp
)) {
2086 resume_requested
= has_resume
&& resume
;
2087 if (!migrate_prepare(s
, has_blk
&& blk
, has_inc
&& inc
,
2088 resume_requested
, errp
)) {
2089 /* Error detected, put into errp */
2093 if (!resume_requested
) {
2094 if (!yank_register_instance(MIGRATION_YANK_INSTANCE
, errp
)) {
2099 if (addr
->transport
== MIGRATION_ADDRESS_TYPE_SOCKET
) {
2100 SocketAddress
*saddr
= &addr
->u
.socket
;
2101 if (saddr
->type
== SOCKET_ADDRESS_TYPE_INET
||
2102 saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
||
2103 saddr
->type
== SOCKET_ADDRESS_TYPE_VSOCK
) {
2104 socket_start_outgoing_migration(s
, saddr
, &local_err
);
2105 } else if (saddr
->type
== SOCKET_ADDRESS_TYPE_FD
) {
2106 fd_start_outgoing_migration(s
, saddr
->u
.fd
.str
, &local_err
);
2109 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_RDMA
) {
2110 rdma_start_outgoing_migration(s
, &addr
->u
.rdma
, &local_err
);
2112 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_EXEC
) {
2113 exec_start_outgoing_migration(s
, addr
->u
.exec
.args
, &local_err
);
2114 } else if (addr
->transport
== MIGRATION_ADDRESS_TYPE_FILE
) {
2115 file_start_outgoing_migration(s
, &addr
->u
.file
, &local_err
);
2117 error_setg(&local_err
, QERR_INVALID_PARAMETER_VALUE
, "uri",
2118 "a valid migration protocol");
2119 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
2120 MIGRATION_STATUS_FAILED
);
2121 block_cleanup_parameters();
2125 if (!resume_requested
) {
2126 yank_unregister_instance(MIGRATION_YANK_INSTANCE
);
2128 migrate_fd_error(s
, local_err
);
2129 error_propagate(errp
, local_err
);
2134 void qmp_migrate_cancel(Error
**errp
)
2136 migration_cancel(NULL
);
2139 void qmp_migrate_continue(MigrationStatus state
, Error
**errp
)
2141 MigrationState
*s
= migrate_get_current();
2142 if (s
->state
!= state
) {
2143 error_setg(errp
, "Migration not in expected state: %s",
2144 MigrationStatus_str(s
->state
));
2147 qemu_sem_post(&s
->pause_sem
);
2150 int migration_rp_wait(MigrationState
*s
)
2152 /* If migration has failure already, ignore the wait */
2153 if (migrate_has_error(s
)) {
2157 qemu_sem_wait(&s
->rp_state
.rp_sem
);
2159 /* After wait, double check that there's no failure */
2160 if (migrate_has_error(s
)) {
2167 void migration_rp_kick(MigrationState
*s
)
2169 qemu_sem_post(&s
->rp_state
.rp_sem
);
2172 static struct rp_cmd_args
{
2173 ssize_t len
; /* -1 = variable */
2176 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
2177 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
2178 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
2179 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
2180 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
2181 [MIG_RP_MSG_RECV_BITMAP
] = { .len
= -1, .name
= "RECV_BITMAP" },
2182 [MIG_RP_MSG_RESUME_ACK
] = { .len
= 4, .name
= "RESUME_ACK" },
2183 [MIG_RP_MSG_SWITCHOVER_ACK
] = { .len
= 0, .name
= "SWITCHOVER_ACK" },
2184 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
2188 * Process a request for pages received on the return path,
2189 * We're allowed to send more than requested (e.g. to round to our page size)
2190 * and we don't need to send pages that have already been sent.
2193 migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
2194 ram_addr_t start
, size_t len
, Error
**errp
)
2196 long our_host_ps
= qemu_real_host_page_size();
2198 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
2201 * Since we currently insist on matching page sizes, just sanity check
2202 * we're being asked for whole host pages.
2204 if (!QEMU_IS_ALIGNED(start
, our_host_ps
) ||
2205 !QEMU_IS_ALIGNED(len
, our_host_ps
)) {
2206 error_setg(errp
, "MIG_RP_MSG_REQ_PAGES: Misaligned page request, start:"
2207 RAM_ADDR_FMT
" len: %zd", start
, len
);
2211 ram_save_queue_pages(rbname
, start
, len
, errp
);
2214 static bool migrate_handle_rp_recv_bitmap(MigrationState
*s
, char *block_name
,
2217 RAMBlock
*block
= qemu_ram_block_by_name(block_name
);
2220 error_setg(errp
, "MIG_RP_MSG_RECV_BITMAP has invalid block name '%s'",
2225 /* Fetch the received bitmap and refresh the dirty bitmap */
2226 return ram_dirty_bitmap_reload(s
, block
, errp
);
2229 static bool migrate_handle_rp_resume_ack(MigrationState
*s
,
2230 uint32_t value
, Error
**errp
)
2232 trace_source_return_path_thread_resume_ack(value
);
2234 if (value
!= MIGRATION_RESUME_ACK_VALUE
) {
2235 error_setg(errp
, "illegal resume_ack value %"PRIu32
, value
);
2239 /* Now both sides are active. */
2240 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_RECOVER
,
2241 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2243 /* Notify send thread that time to continue send pages */
2244 migration_rp_kick(s
);
2250 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2251 * existed) in a safe way.
2253 static void migration_release_dst_files(MigrationState
*ms
)
2257 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2259 * Reset the from_dst_file pointer first before releasing it, as we
2260 * can't block within lock section
2262 file
= ms
->rp_state
.from_dst_file
;
2263 ms
->rp_state
.from_dst_file
= NULL
;
2267 * Do the same to postcopy fast path socket too if there is. No
2268 * locking needed because this qemufile should only be managed by
2269 * return path thread.
2271 if (ms
->postcopy_qemufile_src
) {
2272 migration_ioc_unregister_yank_from_file(ms
->postcopy_qemufile_src
);
2273 qemu_file_shutdown(ms
->postcopy_qemufile_src
);
2274 qemu_fclose(ms
->postcopy_qemufile_src
);
2275 ms
->postcopy_qemufile_src
= NULL
;
2282 * Handles messages sent on the return path towards the source VM
2285 static void *source_return_path_thread(void *opaque
)
2287 MigrationState
*ms
= opaque
;
2288 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
2289 uint16_t header_len
, header_type
;
2291 uint32_t tmp32
, sibling_error
;
2292 ram_addr_t start
= 0; /* =0 to silence warning */
2293 size_t len
= 0, expected_len
;
2297 trace_source_return_path_thread_entry();
2298 rcu_register_thread();
2300 while (migration_is_setup_or_active(ms
->state
)) {
2301 trace_source_return_path_thread_loop_top();
2303 header_type
= qemu_get_be16(rp
);
2304 header_len
= qemu_get_be16(rp
);
2306 if (qemu_file_get_error(rp
)) {
2307 qemu_file_get_error_obj(rp
, &err
);
2311 if (header_type
>= MIG_RP_MSG_MAX
||
2312 header_type
== MIG_RP_MSG_INVALID
) {
2313 error_setg(&err
, "Received invalid message 0x%04x length 0x%04x",
2314 header_type
, header_len
);
2318 if ((rp_cmd_args
[header_type
].len
!= -1 &&
2319 header_len
!= rp_cmd_args
[header_type
].len
) ||
2320 header_len
> sizeof(buf
)) {
2321 error_setg(&err
, "Received '%s' message (0x%04x) with"
2322 "incorrect length %d expecting %zu",
2323 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
2324 (size_t)rp_cmd_args
[header_type
].len
);
2328 /* We know we've got a valid header by this point */
2329 res
= qemu_get_buffer(rp
, buf
, header_len
);
2330 if (res
!= header_len
) {
2331 error_setg(&err
, "Failed reading data for message 0x%04x"
2332 " read %d expected %d",
2333 header_type
, res
, header_len
);
2337 /* OK, we have the message and the data */
2338 switch (header_type
) {
2339 case MIG_RP_MSG_SHUT
:
2340 sibling_error
= ldl_be_p(buf
);
2341 trace_source_return_path_thread_shut(sibling_error
);
2342 if (sibling_error
) {
2343 error_setg(&err
, "Sibling indicated error %d", sibling_error
);
2346 * We'll let the main thread deal with closing the RP
2347 * we could do a shutdown(2) on it, but we're the only user
2348 * anyway, so there's nothing gained.
2352 case MIG_RP_MSG_PONG
:
2353 tmp32
= ldl_be_p(buf
);
2354 trace_source_return_path_thread_pong(tmp32
);
2355 qemu_sem_post(&ms
->rp_state
.rp_pong_acks
);
2358 case MIG_RP_MSG_REQ_PAGES
:
2359 start
= ldq_be_p(buf
);
2360 len
= ldl_be_p(buf
+ 8);
2361 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
, &err
);
2367 case MIG_RP_MSG_REQ_PAGES_ID
:
2368 expected_len
= 12 + 1; /* header + termination */
2370 if (header_len
>= expected_len
) {
2371 start
= ldq_be_p(buf
);
2372 len
= ldl_be_p(buf
+ 8);
2373 /* Now we expect an idstr */
2374 tmp32
= buf
[12]; /* Length of the following idstr */
2375 buf
[13 + tmp32
] = '\0';
2376 expected_len
+= tmp32
;
2378 if (header_len
!= expected_len
) {
2379 error_setg(&err
, "Req_Page_id with length %d expecting %zd",
2380 header_len
, expected_len
);
2383 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
,
2390 case MIG_RP_MSG_RECV_BITMAP
:
2391 if (header_len
< 1) {
2392 error_setg(&err
, "MIG_RP_MSG_RECV_BITMAP missing block name");
2395 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2396 buf
[buf
[0] + 1] = '\0';
2397 if (!migrate_handle_rp_recv_bitmap(ms
, (char *)(buf
+ 1), &err
)) {
2402 case MIG_RP_MSG_RESUME_ACK
:
2403 tmp32
= ldl_be_p(buf
);
2404 if (!migrate_handle_rp_resume_ack(ms
, tmp32
, &err
)) {
2409 case MIG_RP_MSG_SWITCHOVER_ACK
:
2410 ms
->switchover_acked
= true;
2411 trace_source_return_path_thread_switchover_acked();
2421 migrate_set_error(ms
, err
);
2423 trace_source_return_path_thread_bad_end();
2426 if (ms
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2428 * this will be extremely unlikely: that we got yet another network
2429 * issue during recovering of the 1st network failure.. during this
2430 * period the main migration thread can be waiting on rp_sem for
2431 * this thread to sync with the other side.
2433 * When this happens, explicitly kick the migration thread out of
2434 * RECOVER stage and back to PAUSED, so the admin can try
2437 migration_rp_kick(ms
);
2440 trace_source_return_path_thread_end();
2441 rcu_unregister_thread();
2446 static int open_return_path_on_source(MigrationState
*ms
)
2448 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
2449 if (!ms
->rp_state
.from_dst_file
) {
2453 trace_open_return_path_on_source();
2455 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
2456 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
2457 ms
->rp_state
.rp_thread_created
= true;
2459 trace_open_return_path_on_source_continue();
2464 /* Return true if error detected, or false otherwise */
2465 static bool close_return_path_on_source(MigrationState
*ms
)
2467 if (!ms
->rp_state
.rp_thread_created
) {
2471 trace_migration_return_path_end_before();
2474 * If this is a normal exit then the destination will send a SHUT
2475 * and the rp_thread will exit, however if there's an error we
2476 * need to cause it to exit. shutdown(2), if we have it, will
2477 * cause it to unblock if it's stuck waiting for the destination.
2479 WITH_QEMU_LOCK_GUARD(&ms
->qemu_file_lock
) {
2480 if (migrate_has_error(ms
) && ms
->rp_state
.from_dst_file
) {
2481 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
2485 qemu_thread_join(&ms
->rp_state
.rp_thread
);
2486 ms
->rp_state
.rp_thread_created
= false;
2487 migration_release_dst_files(ms
);
2488 trace_migration_return_path_end_after();
2490 /* Return path will persist the error in MigrationState when quit */
2491 return migrate_has_error(ms
);
2495 migration_wait_main_channel(MigrationState
*ms
)
2497 /* Wait until one PONG message received */
2498 qemu_sem_wait(&ms
->rp_state
.rp_pong_acks
);
2502 * Switch from normal iteration to postcopy
2503 * Returns non-0 on error
2505 static int postcopy_start(MigrationState
*ms
, Error
**errp
)
2508 QIOChannelBuffer
*bioc
;
2510 uint64_t bandwidth
= migrate_max_postcopy_bandwidth();
2511 bool restart_block
= false;
2512 int cur_state
= MIGRATION_STATUS_ACTIVE
;
2514 if (migrate_postcopy_preempt()) {
2515 migration_wait_main_channel(ms
);
2516 if (postcopy_preempt_establish_channel(ms
)) {
2517 migrate_set_state(&ms
->state
, ms
->state
, MIGRATION_STATUS_FAILED
);
2522 if (!migrate_pause_before_switchover()) {
2523 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
2524 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2527 trace_postcopy_start();
2529 trace_postcopy_start_set_run();
2531 ret
= migration_stop_vm(ms
, RUN_STATE_FINISH_MIGRATE
);
2536 ret
= migration_maybe_pause(ms
, &cur_state
,
2537 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2542 ret
= bdrv_inactivate_all();
2546 restart_block
= true;
2549 * Cause any non-postcopiable, but iterative devices to
2550 * send out their final data.
2552 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true, false);
2555 * in Finish migrate and with the io-lock held everything should
2556 * be quiet, but we've potentially still got dirty pages and we
2557 * need to tell the destination to throw any pages it's already received
2560 if (migrate_postcopy_ram()) {
2561 ram_postcopy_send_discard_bitmap(ms
);
2565 * send rest of state - note things that are doing postcopy
2566 * will notice we're in POSTCOPY_ACTIVE and not actually
2567 * wrap their state up here
2569 migration_rate_set(bandwidth
);
2570 if (migrate_postcopy_ram()) {
2571 /* Ping just for debugging, helps line traces up */
2572 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
2576 * While loading the device state we may trigger page transfer
2577 * requests and the fd must be free to process those, and thus
2578 * the destination must read the whole device state off the fd before
2579 * it starts processing it. Unfortunately the ad-hoc migration format
2580 * doesn't allow the destination to know the size to read without fully
2581 * parsing it through each devices load-state code (especially the open
2582 * coded devices that use get/put).
2583 * So we wrap the device state up in a package with a length at the start;
2584 * to do this we use a qemu_buf to hold the whole of the device state.
2586 bioc
= qio_channel_buffer_new(4096);
2587 qio_channel_set_name(QIO_CHANNEL(bioc
), "migration-postcopy-buffer");
2588 fb
= qemu_file_new_output(QIO_CHANNEL(bioc
));
2589 object_unref(OBJECT(bioc
));
2592 * Make sure the receiver can get incoming pages before we send the rest
2595 qemu_savevm_send_postcopy_listen(fb
);
2597 qemu_savevm_state_complete_precopy(fb
, false, false);
2598 if (migrate_postcopy_ram()) {
2599 qemu_savevm_send_ping(fb
, 3);
2602 qemu_savevm_send_postcopy_run(fb
);
2604 /* <><> end of stuff going into the package */
2606 /* Last point of recovery; as soon as we send the package the destination
2607 * can open devices and potentially start running.
2608 * Lets just check again we've not got any errors.
2610 ret
= qemu_file_get_error(ms
->to_dst_file
);
2612 error_setg(errp
, "postcopy_start: Migration stream errored (pre package)");
2616 restart_block
= false;
2618 /* Now send that blob */
2619 if (qemu_savevm_send_packaged(ms
->to_dst_file
, bioc
->data
, bioc
->usage
)) {
2624 /* Send a notify to give a chance for anything that needs to happen
2625 * at the transition to postcopy and after the device state; in particular
2626 * spice needs to trigger a transition now
2628 migration_call_notifiers(ms
, MIG_EVENT_PRECOPY_DONE
, NULL
);
2630 migration_downtime_end(ms
);
2634 if (migrate_postcopy_ram()) {
2636 * Although this ping is just for debug, it could potentially be
2637 * used for getting a better measurement of downtime at the source.
2639 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
2642 if (migrate_release_ram()) {
2643 ram_postcopy_migrated_memory_release(ms
);
2646 ret
= qemu_file_get_error(ms
->to_dst_file
);
2648 error_setg_errno(errp
, -ret
, "postcopy_start: Migration stream error");
2652 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2659 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
2660 MIGRATION_STATUS_FAILED
);
2661 if (restart_block
) {
2662 /* A failure happened early enough that we know the destination hasn't
2663 * accessed block devices, so we're safe to recover.
2665 Error
*local_err
= NULL
;
2667 bdrv_activate_all(&local_err
);
2669 error_report_err(local_err
);
2672 migration_call_notifiers(ms
, MIG_EVENT_PRECOPY_FAILED
, NULL
);
2678 * migration_maybe_pause: Pause if required to by
2679 * migrate_pause_before_switchover called with the BQL locked
2680 * Returns: 0 on success
2682 static int migration_maybe_pause(MigrationState
*s
,
2683 int *current_active_state
,
2686 if (!migrate_pause_before_switchover()) {
2690 /* Since leaving this state is not atomic with posting the semaphore
2691 * it's possible that someone could have issued multiple migrate_continue
2692 * and the semaphore is incorrectly positive at this point;
2693 * the docs say it's undefined to reinit a semaphore that's already
2694 * init'd, so use timedwait to eat up any existing posts.
2696 while (qemu_sem_timedwait(&s
->pause_sem
, 1) == 0) {
2697 /* This block intentionally left blank */
2701 * If the migration is cancelled when it is in the completion phase,
2702 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2703 * So we don't need to wait a semaphore, otherwise we would always
2704 * wait for the 'pause_sem' semaphore.
2706 if (s
->state
!= MIGRATION_STATUS_CANCELLING
) {
2708 migrate_set_state(&s
->state
, *current_active_state
,
2709 MIGRATION_STATUS_PRE_SWITCHOVER
);
2710 qemu_sem_wait(&s
->pause_sem
);
2711 migrate_set_state(&s
->state
, MIGRATION_STATUS_PRE_SWITCHOVER
,
2713 *current_active_state
= new_state
;
2717 return s
->state
== new_state
? 0 : -EINVAL
;
2720 static int migration_completion_precopy(MigrationState
*s
,
2721 int *current_active_state
)
2727 if (!migrate_mode_is_cpr(s
)) {
2728 ret
= migration_stop_vm(s
, RUN_STATE_FINISH_MIGRATE
);
2734 ret
= migration_maybe_pause(s
, current_active_state
,
2735 MIGRATION_STATUS_DEVICE
);
2741 * Inactivate disks except in COLO, and track that we have done so in order
2742 * to remember to reactivate them if migration fails or is cancelled.
2744 s
->block_inactive
= !migrate_colo();
2745 migration_rate_set(RATE_LIMIT_DISABLED
);
2746 ret
= qemu_savevm_state_complete_precopy(s
->to_dst_file
, false,
2753 static void migration_completion_postcopy(MigrationState
*s
)
2755 trace_migration_completion_postcopy_end();
2758 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
2762 * Shutdown the postcopy fast path thread. This is only needed when dest
2763 * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
2765 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
2766 postcopy_preempt_shutdown_file(s
);
2769 trace_migration_completion_postcopy_end_after_complete();
2772 static void migration_completion_failed(MigrationState
*s
,
2773 int current_active_state
)
2775 if (s
->block_inactive
&& (s
->state
== MIGRATION_STATUS_ACTIVE
||
2776 s
->state
== MIGRATION_STATUS_DEVICE
)) {
2778 * If not doing postcopy, vm_start() will be called: let's
2779 * regain control on images.
2781 Error
*local_err
= NULL
;
2784 bdrv_activate_all(&local_err
);
2786 error_report_err(local_err
);
2788 s
->block_inactive
= false;
2793 migrate_set_state(&s
->state
, current_active_state
,
2794 MIGRATION_STATUS_FAILED
);
2798 * migration_completion: Used by migration_thread when there's not much left.
2799 * The caller 'breaks' the loop when this returns.
2801 * @s: Current migration state
2803 static void migration_completion(MigrationState
*s
)
2806 int current_active_state
= s
->state
;
2808 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2809 ret
= migration_completion_precopy(s
, ¤t_active_state
);
2810 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2811 migration_completion_postcopy(s
);
2820 if (close_return_path_on_source(s
)) {
2824 if (qemu_file_get_error(s
->to_dst_file
)) {
2825 trace_migration_completion_file_err();
2829 if (migrate_colo() && s
->state
== MIGRATION_STATUS_ACTIVE
) {
2830 /* COLO does not support postcopy */
2831 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
2832 MIGRATION_STATUS_COLO
);
2834 migration_completion_end(s
);
2840 migration_completion_failed(s
, current_active_state
);
2844 * bg_migration_completion: Used by bg_migration_thread when after all the
2845 * RAM has been saved. The caller 'breaks' the loop when this returns.
2847 * @s: Current migration state
2849 static void bg_migration_completion(MigrationState
*s
)
2851 int current_active_state
= s
->state
;
2853 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
2855 * By this moment we have RAM content saved into the migration stream.
2856 * The next step is to flush the non-RAM content (device state)
2857 * right after the ram content. The device state has been stored into
2858 * the temporary buffer before RAM saving started.
2860 qemu_put_buffer(s
->to_dst_file
, s
->bioc
->data
, s
->bioc
->usage
);
2861 qemu_fflush(s
->to_dst_file
);
2862 } else if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
2866 if (qemu_file_get_error(s
->to_dst_file
)) {
2867 trace_migration_completion_file_err();
2871 migration_completion_end(s
);
2875 migrate_set_state(&s
->state
, current_active_state
,
2876 MIGRATION_STATUS_FAILED
);
2879 typedef enum MigThrError
{
2880 /* No error detected */
2881 MIG_THR_ERR_NONE
= 0,
2882 /* Detected error, but resumed successfully */
2883 MIG_THR_ERR_RECOVERED
= 1,
2884 /* Detected fatal error, need to exit */
2885 MIG_THR_ERR_FATAL
= 2,
2888 static int postcopy_resume_handshake(MigrationState
*s
)
2890 qemu_savevm_send_postcopy_resume(s
->to_dst_file
);
2892 while (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
2893 if (migration_rp_wait(s
)) {
2898 if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
2905 /* Return zero if success, or <0 for error */
2906 static int postcopy_do_resume(MigrationState
*s
)
2911 * Call all the resume_prepare() hooks, so that modules can be
2912 * ready for the migration resume.
2914 ret
= qemu_savevm_state_resume_prepare(s
);
2916 error_report("%s: resume_prepare() failure detected: %d",
2922 * If preempt is enabled, re-establish the preempt channel. Note that
2923 * we do it after resume prepare to make sure the main channel will be
2924 * created before the preempt channel. E.g. with weak network, the
2925 * dest QEMU may get messed up with the preempt and main channels on
2926 * the order of connection setup. This guarantees the correct order.
2928 ret
= postcopy_preempt_establish_channel(s
);
2930 error_report("%s: postcopy_preempt_establish_channel(): %d",
2936 * Last handshake with destination on the resume (destination will
2937 * switch to postcopy-active afterwards)
2939 ret
= postcopy_resume_handshake(s
);
2941 error_report("%s: handshake failed: %d", __func__
, ret
);
2949 * We don't return until we are in a safe state to continue current
2950 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2951 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2953 static MigThrError
postcopy_pause(MigrationState
*s
)
2955 assert(s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
2961 * We're already pausing, so ignore any errors on the return
2962 * path and just wait for the thread to finish. It will be
2963 * re-created when we resume.
2965 close_return_path_on_source(s
);
2968 * Current channel is possibly broken. Release it. Note that this is
2969 * guaranteed even without lock because to_dst_file should only be
2970 * modified by the migration thread. That also guarantees that the
2971 * unregister of yank is safe too without the lock. It should be safe
2972 * even to be within the qemu_file_lock, but we didn't do that to avoid
2973 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2974 * the qemu_file_lock critical section as small as possible.
2976 assert(s
->to_dst_file
);
2977 migration_ioc_unregister_yank_from_file(s
->to_dst_file
);
2978 qemu_mutex_lock(&s
->qemu_file_lock
);
2979 file
= s
->to_dst_file
;
2980 s
->to_dst_file
= NULL
;
2981 qemu_mutex_unlock(&s
->qemu_file_lock
);
2983 qemu_file_shutdown(file
);
2986 migrate_set_state(&s
->state
, s
->state
,
2987 MIGRATION_STATUS_POSTCOPY_PAUSED
);
2989 error_report("Detected IO failure for postcopy. "
2990 "Migration paused.");
2993 * We wait until things fixed up. Then someone will setup the
2994 * status back for us.
2996 while (s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
) {
2997 qemu_sem_wait(&s
->postcopy_pause_sem
);
3000 if (s
->state
== MIGRATION_STATUS_POSTCOPY_RECOVER
) {
3001 /* Woken up by a recover procedure. Give it a shot */
3003 /* Do the resume logic */
3004 if (postcopy_do_resume(s
) == 0) {
3005 /* Let's continue! */
3006 trace_postcopy_pause_continued();
3007 return MIG_THR_ERR_RECOVERED
;
3010 * Something wrong happened during the recovery, let's
3011 * pause again. Pause is always better than throwing
3017 /* This is not right... Time to quit. */
3018 return MIG_THR_ERR_FATAL
;
3023 static MigThrError
migration_detect_error(MigrationState
*s
)
3026 int state
= s
->state
;
3027 Error
*local_error
= NULL
;
3029 if (state
== MIGRATION_STATUS_CANCELLING
||
3030 state
== MIGRATION_STATUS_CANCELLED
) {
3031 /* End the migration, but don't set the state to failed */
3032 return MIG_THR_ERR_FATAL
;
3036 * Try to detect any file errors. Note that postcopy_qemufile_src will
3037 * be NULL when postcopy preempt is not enabled.
3039 ret
= qemu_file_get_error_obj_any(s
->to_dst_file
,
3040 s
->postcopy_qemufile_src
,
3043 /* Everything is fine */
3044 assert(!local_error
);
3045 return MIG_THR_ERR_NONE
;
3049 migrate_set_error(s
, local_error
);
3050 error_free(local_error
);
3053 if (state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
&& ret
) {
3055 * For postcopy, we allow the network to be down for a
3056 * while. After that, it can be continued by a
3059 return postcopy_pause(s
);
3062 * For precopy (or postcopy with error outside IO), we fail
3065 migrate_set_state(&s
->state
, state
, MIGRATION_STATUS_FAILED
);
3066 trace_migration_thread_file_err();
3068 /* Time to stop the migration, now. */
3069 return MIG_THR_ERR_FATAL
;
3073 static void migration_completion_end(MigrationState
*s
)
3075 uint64_t bytes
= migration_transferred_bytes();
3076 int64_t end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3077 int64_t transfer_time
;
3080 * Take the BQL here so that query-migrate on the QMP thread sees:
3081 * - atomic update of s->total_time and s->mbps;
3082 * - correct ordering of s->mbps update vs. s->state;
3085 migration_downtime_end(s
);
3086 s
->total_time
= end_time
- s
->start_time
;
3087 transfer_time
= s
->total_time
- s
->setup_time
;
3088 if (transfer_time
) {
3089 s
->mbps
= ((double) bytes
* 8.0) / transfer_time
/ 1000;
3092 migrate_set_state(&s
->state
, s
->state
,
3093 MIGRATION_STATUS_COMPLETED
);
3097 static void update_iteration_initial_status(MigrationState
*s
)
3100 * Update these three fields at the same time to avoid mismatch info lead
3101 * wrong speed calculation.
3103 s
->iteration_start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3104 s
->iteration_initial_bytes
= migration_transferred_bytes();
3105 s
->iteration_initial_pages
= ram_get_total_transferred_pages();
3108 static void migration_update_counters(MigrationState
*s
,
3109 int64_t current_time
)
3111 uint64_t transferred
, transferred_pages
, time_spent
;
3112 uint64_t current_bytes
; /* bytes transferred since the beginning */
3113 uint64_t switchover_bw
;
3114 /* Expected bandwidth when switching over to destination QEMU */
3115 double expected_bw_per_ms
;
3118 if (current_time
< s
->iteration_start_time
+ BUFFER_DELAY
) {
3122 switchover_bw
= migrate_avail_switchover_bandwidth();
3123 current_bytes
= migration_transferred_bytes();
3124 transferred
= current_bytes
- s
->iteration_initial_bytes
;
3125 time_spent
= current_time
- s
->iteration_start_time
;
3126 bandwidth
= (double)transferred
/ time_spent
;
3128 if (switchover_bw
) {
3130 * If the user specified a switchover bandwidth, let's trust the
3131 * user so that can be more accurate than what we estimated.
3133 expected_bw_per_ms
= switchover_bw
/ 1000;
3135 /* If the user doesn't specify bandwidth, we use the estimated */
3136 expected_bw_per_ms
= bandwidth
;
3139 s
->threshold_size
= expected_bw_per_ms
* migrate_downtime_limit();
3141 s
->mbps
= (((double) transferred
* 8.0) /
3142 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
3144 transferred_pages
= ram_get_total_transferred_pages() -
3145 s
->iteration_initial_pages
;
3146 s
->pages_per_second
= (double) transferred_pages
/
3147 (((double) time_spent
/ 1000.0));
3150 * if we haven't sent anything, we don't want to
3151 * recalculate. 10000 is a small enough number for our purposes
3153 if (stat64_get(&mig_stats
.dirty_pages_rate
) &&
3154 transferred
> 10000) {
3155 s
->expected_downtime
=
3156 stat64_get(&mig_stats
.dirty_bytes_last_sync
) / expected_bw_per_ms
;
3159 migration_rate_reset();
3161 update_iteration_initial_status(s
);
3163 trace_migrate_transferred(transferred
, time_spent
,
3164 /* Both in unit bytes/ms */
3165 bandwidth
, switchover_bw
/ 1000,
3169 static bool migration_can_switchover(MigrationState
*s
)
3171 if (!migrate_switchover_ack()) {
3175 /* No reason to wait for switchover ACK if VM is stopped */
3176 if (!runstate_is_running()) {
3180 return s
->switchover_acked
;
3183 /* Migration thread iteration status */
3185 MIG_ITERATE_RESUME
, /* Resume current iteration */
3186 MIG_ITERATE_SKIP
, /* Skip current iteration */
3187 MIG_ITERATE_BREAK
, /* Break the loop */
3191 * Return true if continue to the next iteration directly, false
3194 static MigIterateState
migration_iteration_run(MigrationState
*s
)
3196 uint64_t must_precopy
, can_postcopy
;
3197 Error
*local_err
= NULL
;
3198 bool in_postcopy
= s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
;
3199 bool can_switchover
= migration_can_switchover(s
);
3201 qemu_savevm_state_pending_estimate(&must_precopy
, &can_postcopy
);
3202 uint64_t pending_size
= must_precopy
+ can_postcopy
;
3204 trace_migrate_pending_estimate(pending_size
, must_precopy
, can_postcopy
);
3206 if (must_precopy
<= s
->threshold_size
) {
3207 qemu_savevm_state_pending_exact(&must_precopy
, &can_postcopy
);
3208 pending_size
= must_precopy
+ can_postcopy
;
3209 trace_migrate_pending_exact(pending_size
, must_precopy
, can_postcopy
);
3212 if ((!pending_size
|| pending_size
< s
->threshold_size
) && can_switchover
) {
3213 trace_migration_thread_low_pending(pending_size
);
3214 migration_completion(s
);
3215 return MIG_ITERATE_BREAK
;
3218 /* Still a significant amount to transfer */
3219 if (!in_postcopy
&& must_precopy
<= s
->threshold_size
&& can_switchover
&&
3220 qatomic_read(&s
->start_postcopy
)) {
3221 if (postcopy_start(s
, &local_err
)) {
3222 migrate_set_error(s
, local_err
);
3223 error_report_err(local_err
);
3225 return MIG_ITERATE_SKIP
;
3228 /* Just another iteration step */
3229 qemu_savevm_state_iterate(s
->to_dst_file
, in_postcopy
);
3230 return MIG_ITERATE_RESUME
;
3233 static void migration_iteration_finish(MigrationState
*s
)
3235 /* If we enabled cpu throttling for auto-converge, turn it off. */
3236 cpu_throttle_stop();
3240 case MIGRATION_STATUS_COMPLETED
:
3241 runstate_set(RUN_STATE_POSTMIGRATE
);
3243 case MIGRATION_STATUS_COLO
:
3244 assert(migrate_colo());
3245 migrate_start_colo_process(s
);
3246 s
->vm_old_state
= RUN_STATE_RUNNING
;
3248 case MIGRATION_STATUS_FAILED
:
3249 case MIGRATION_STATUS_CANCELLED
:
3250 case MIGRATION_STATUS_CANCELLING
:
3251 if (runstate_is_live(s
->vm_old_state
)) {
3252 if (!runstate_check(RUN_STATE_SHUTDOWN
)) {
3256 if (runstate_check(RUN_STATE_FINISH_MIGRATE
)) {
3257 runstate_set(s
->vm_old_state
);
3263 /* Should not reach here, but if so, forgive the VM. */
3264 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3268 migration_bh_schedule(migrate_fd_cleanup_bh
, s
);
3272 static void bg_migration_iteration_finish(MigrationState
*s
)
3275 * Stop tracking RAM writes - un-protect memory, un-register UFFD
3276 * memory ranges, flush kernel wait queues and wake up threads
3277 * waiting for write fault to be resolved.
3279 ram_write_tracking_stop();
3283 case MIGRATION_STATUS_COMPLETED
:
3284 case MIGRATION_STATUS_ACTIVE
:
3285 case MIGRATION_STATUS_FAILED
:
3286 case MIGRATION_STATUS_CANCELLED
:
3287 case MIGRATION_STATUS_CANCELLING
:
3291 /* Should not reach here, but if so, forgive the VM. */
3292 error_report("%s: Unknown ending state %d", __func__
, s
->state
);
3296 migration_bh_schedule(migrate_fd_cleanup_bh
, s
);
3301 * Return true if continue to the next iteration directly, false
3304 static MigIterateState
bg_migration_iteration_run(MigrationState
*s
)
3308 res
= qemu_savevm_state_iterate(s
->to_dst_file
, false);
3310 bg_migration_completion(s
);
3311 return MIG_ITERATE_BREAK
;
3314 return MIG_ITERATE_RESUME
;
3317 void migration_make_urgent_request(void)
3319 qemu_sem_post(&migrate_get_current()->rate_limit_sem
);
3322 void migration_consume_urgent_request(void)
3324 qemu_sem_wait(&migrate_get_current()->rate_limit_sem
);
3327 /* Returns true if the rate limiting was broken by an urgent request */
3328 bool migration_rate_limit(void)
3330 int64_t now
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
3331 MigrationState
*s
= migrate_get_current();
3333 bool urgent
= false;
3334 migration_update_counters(s
, now
);
3335 if (migration_rate_exceeded(s
->to_dst_file
)) {
3337 if (qemu_file_get_error(s
->to_dst_file
)) {
3341 * Wait for a delay to do rate limiting OR
3342 * something urgent to post the semaphore.
3344 int ms
= s
->iteration_start_time
+ BUFFER_DELAY
- now
;
3345 trace_migration_rate_limit_pre(ms
);
3346 if (qemu_sem_timedwait(&s
->rate_limit_sem
, ms
) == 0) {
3348 * We were woken by one or more urgent things but
3349 * the timedwait will have consumed one of them.
3350 * The service routine for the urgent wake will dec
3351 * the semaphore itself for each item it consumes,
3352 * so add this one we just eat back.
3354 qemu_sem_post(&s
->rate_limit_sem
);
3357 trace_migration_rate_limit_post(urgent
);
3363 * if failover devices are present, wait they are completely
3367 static void qemu_savevm_wait_unplug(MigrationState
*s
, int old_state
,
3370 if (qemu_savevm_state_guest_unplug_pending()) {
3371 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_WAIT_UNPLUG
);
3373 while (s
->state
== MIGRATION_STATUS_WAIT_UNPLUG
&&
3374 qemu_savevm_state_guest_unplug_pending()) {
3375 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3377 if (s
->state
!= MIGRATION_STATUS_WAIT_UNPLUG
) {
3378 int timeout
= 120; /* 30 seconds */
3380 * migration has been canceled
3381 * but as we have started an unplug we must wait the end
3382 * to be able to plug back the card
3384 while (timeout
-- && qemu_savevm_state_guest_unplug_pending()) {
3385 qemu_sem_timedwait(&s
->wait_unplug_sem
, 250);
3387 if (qemu_savevm_state_guest_unplug_pending() &&
3389 warn_report("migration: partially unplugged device on "
3394 migrate_set_state(&s
->state
, MIGRATION_STATUS_WAIT_UNPLUG
, new_state
);
3396 migrate_set_state(&s
->state
, old_state
, new_state
);
3401 * Master migration thread on the source VM.
3402 * It drives the migration and pumps the data down the outgoing channel.
3404 static void *migration_thread(void *opaque
)
3406 MigrationState
*s
= opaque
;
3407 MigrationThread
*thread
= NULL
;
3408 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3409 MigThrError thr_error
;
3410 bool urgent
= false;
3412 thread
= migration_threads_add("live_migration", qemu_get_thread_id());
3414 rcu_register_thread();
3416 object_ref(OBJECT(s
));
3417 update_iteration_initial_status(s
);
3419 if (!multifd_send_setup()) {
3424 qemu_savevm_state_header(s
->to_dst_file
);
3428 * If we opened the return path, we need to make sure dst has it
3431 if (s
->rp_state
.rp_thread_created
) {
3432 /* Now tell the dest that it should open its end so it can reply */
3433 qemu_savevm_send_open_return_path(s
->to_dst_file
);
3435 /* And do a ping that will make stuff easier to debug */
3436 qemu_savevm_send_ping(s
->to_dst_file
, 1);
3439 if (migrate_postcopy()) {
3441 * Tell the destination that we *might* want to do postcopy later;
3442 * if the other end can't do postcopy it should fail now, nice and
3445 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
3448 if (migrate_colo()) {
3449 /* Notify migration destination that we enable COLO */
3450 qemu_savevm_send_colo_enable(s
->to_dst_file
);
3454 qemu_savevm_state_setup(s
->to_dst_file
);
3457 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3458 MIGRATION_STATUS_ACTIVE
);
3460 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3462 trace_migration_thread_setup_complete();
3464 while (migration_is_active(s
)) {
3465 if (urgent
|| !migration_rate_exceeded(s
->to_dst_file
)) {
3466 MigIterateState iter_state
= migration_iteration_run(s
);
3467 if (iter_state
== MIG_ITERATE_SKIP
) {
3469 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3475 * Try to detect any kind of failures, and see whether we
3476 * should stop the migration now.
3478 thr_error
= migration_detect_error(s
);
3479 if (thr_error
== MIG_THR_ERR_FATAL
) {
3480 /* Stop migration */
3482 } else if (thr_error
== MIG_THR_ERR_RECOVERED
) {
3484 * Just recovered from a e.g. network failure, reset all
3485 * the local variables. This is important to avoid
3486 * breaking transferred_bytes and bandwidth calculation
3488 update_iteration_initial_status(s
);
3491 urgent
= migration_rate_limit();
3495 trace_migration_thread_after_loop();
3496 migration_iteration_finish(s
);
3497 object_unref(OBJECT(s
));
3498 rcu_unregister_thread();
3499 migration_threads_remove(thread
);
3503 static void bg_migration_vm_start_bh(void *opaque
)
3505 MigrationState
*s
= opaque
;
3507 vm_resume(s
->vm_old_state
);
3508 migration_downtime_end(s
);
3512 * Background snapshot thread, based on live migration code.
3513 * This is an alternative implementation of live migration mechanism
3514 * introduced specifically to support background snapshots.
3516 * It takes advantage of userfault_fd write protection mechanism introduced
3517 * in v5.7 kernel. Compared to existing dirty page logging migration much
3518 * lesser stream traffic is produced resulting in smaller snapshot images,
3519 * simply cause of no page duplicates can get into the stream.
3521 * Another key point is that generated vmstate stream reflects machine state
3522 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3523 * mechanism, which effectively results in that saved snapshot is the state of VM
3524 * at the end of the process.
3526 static void *bg_migration_thread(void *opaque
)
3528 MigrationState
*s
= opaque
;
3529 int64_t setup_start
;
3530 MigThrError thr_error
;
3532 bool early_fail
= true;
3534 rcu_register_thread();
3535 object_ref(OBJECT(s
));
3537 migration_rate_set(RATE_LIMIT_DISABLED
);
3539 setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
3541 * We want to save vmstate for the moment when migration has been
3542 * initiated but also we want to save RAM content while VM is running.
3543 * The RAM content should appear first in the vmstate. So, we first
3544 * stash the non-RAM part of the vmstate to the temporary buffer,
3545 * then write RAM part of the vmstate to the migration stream
3546 * with vCPUs running and, finally, write stashed non-RAM part of
3547 * the vmstate from the buffer to the migration stream.
3549 s
->bioc
= qio_channel_buffer_new(512 * 1024);
3550 qio_channel_set_name(QIO_CHANNEL(s
->bioc
), "vmstate-buffer");
3551 fb
= qemu_file_new_output(QIO_CHANNEL(s
->bioc
));
3552 object_unref(OBJECT(s
->bioc
));
3554 update_iteration_initial_status(s
);
3557 * Prepare for tracking memory writes with UFFD-WP - populate
3558 * RAM pages before protecting.
3561 ram_write_tracking_prepare();
3565 qemu_savevm_state_header(s
->to_dst_file
);
3566 qemu_savevm_state_setup(s
->to_dst_file
);
3569 qemu_savevm_wait_unplug(s
, MIGRATION_STATUS_SETUP
,
3570 MIGRATION_STATUS_ACTIVE
);
3572 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
3574 trace_migration_thread_setup_complete();
3578 if (migration_stop_vm(s
, RUN_STATE_PAUSED
)) {
3582 * Put vCPUs in sync with shadow context structures, then
3583 * save their state to channel-buffer along with devices.
3585 cpu_synchronize_all_states();
3586 if (qemu_savevm_state_complete_precopy_non_iterable(fb
, false, false)) {
3590 * Since we are going to get non-iterable state data directly
3591 * from s->bioc->data, explicit flush is needed here.
3595 /* Now initialize UFFD context and start tracking RAM writes */
3596 if (ram_write_tracking_start()) {
3602 * Start VM from BH handler to avoid write-fault lock here.
3603 * UFFD-WP protection for the whole RAM is already enabled so
3604 * calling VM state change notifiers from vm_start() would initiate
3605 * writes to virtio VQs memory which is in write-protected region.
3607 migration_bh_schedule(bg_migration_vm_start_bh
, s
);
3610 while (migration_is_active(s
)) {
3611 MigIterateState iter_state
= bg_migration_iteration_run(s
);
3612 if (iter_state
== MIG_ITERATE_SKIP
) {
3614 } else if (iter_state
== MIG_ITERATE_BREAK
) {
3619 * Try to detect any kind of failures, and see whether we
3620 * should stop the migration now.
3622 thr_error
= migration_detect_error(s
);
3623 if (thr_error
== MIG_THR_ERR_FATAL
) {
3624 /* Stop migration */
3628 migration_update_counters(s
, qemu_clock_get_ms(QEMU_CLOCK_REALTIME
));
3631 trace_migration_thread_after_loop();
3635 migrate_set_state(&s
->state
, MIGRATION_STATUS_ACTIVE
,
3636 MIGRATION_STATUS_FAILED
);
3640 bg_migration_iteration_finish(s
);
3643 object_unref(OBJECT(s
));
3644 rcu_unregister_thread();
3649 void migrate_fd_connect(MigrationState
*s
, Error
*error_in
)
3651 Error
*local_err
= NULL
;
3652 uint64_t rate_limit
;
3653 bool resume
= s
->state
== MIGRATION_STATUS_POSTCOPY_PAUSED
;
3657 * If there's a previous error, free it and prepare for another one.
3658 * Meanwhile if migration completes successfully, there won't have an error
3659 * dumped when calling migrate_fd_cleanup().
3661 migrate_error_free(s
);
3663 s
->expected_downtime
= migrate_downtime_limit();
3665 migrate_fd_error(s
, error_in
);
3668 * Don't do cleanup for resume if channel is invalid, but only dump
3669 * the error. We wait for another channel connect from the user.
3670 * The error_report still gives HMP user a hint on what failed.
3671 * It's normally done in migrate_fd_cleanup(), but call it here
3674 error_report_err(error_copy(s
->error
));
3676 migrate_fd_cleanup(s
);
3682 /* This is a resumed migration */
3683 rate_limit
= migrate_max_postcopy_bandwidth();
3685 /* This is a fresh new migration */
3686 rate_limit
= migrate_max_bandwidth();
3688 /* Notify before starting migration thread */
3689 if (migration_call_notifiers(s
, MIG_EVENT_PRECOPY_SETUP
, &local_err
)) {
3694 migration_rate_set(rate_limit
);
3695 qemu_file_set_blocking(s
->to_dst_file
, true);
3698 * Open the return path. For postcopy, it is used exclusively. For
3699 * precopy, only if user specified "return-path" capability would
3700 * QEMU uses the return path.
3702 if (migrate_postcopy_ram() || migrate_return_path()) {
3703 if (open_return_path_on_source(s
)) {
3704 error_setg(&local_err
, "Unable to open return-path for postcopy");
3710 * This needs to be done before resuming a postcopy. Note: for newer
3711 * QEMUs we will delay the channel creation until postcopy_start(), to
3712 * avoid disorder of channel creations.
3714 if (migrate_postcopy_preempt() && s
->preempt_pre_7_2
) {
3715 postcopy_preempt_setup(s
);
3719 /* Wakeup the main migration thread to do the recovery */
3720 migrate_set_state(&s
->state
, MIGRATION_STATUS_POSTCOPY_PAUSED
,
3721 MIGRATION_STATUS_POSTCOPY_RECOVER
);
3722 qemu_sem_post(&s
->postcopy_pause_sem
);
3726 if (migrate_mode_is_cpr(s
)) {
3727 ret
= migration_stop_vm(s
, RUN_STATE_FINISH_MIGRATE
);
3729 error_setg(&local_err
, "migration_stop_vm failed, error %d", -ret
);
3734 if (migrate_background_snapshot()) {
3735 qemu_thread_create(&s
->thread
, "bg_snapshot",
3736 bg_migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3738 qemu_thread_create(&s
->thread
, "live_migration",
3739 migration_thread
, s
, QEMU_THREAD_JOINABLE
);
3741 s
->migration_thread_running
= true;
3745 migrate_set_error(s
, local_err
);
3746 migrate_set_state(&s
->state
, s
->state
, MIGRATION_STATUS_FAILED
);
3747 error_report_err(local_err
);
3748 migrate_fd_cleanup(s
);
3751 static void migration_class_init(ObjectClass
*klass
, void *data
)
3753 DeviceClass
*dc
= DEVICE_CLASS(klass
);
3755 dc
->user_creatable
= false;
3756 device_class_set_props(dc
, migration_properties
);
3759 static void migration_instance_finalize(Object
*obj
)
3761 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3763 qemu_mutex_destroy(&ms
->error_mutex
);
3764 qemu_mutex_destroy(&ms
->qemu_file_lock
);
3765 qemu_sem_destroy(&ms
->wait_unplug_sem
);
3766 qemu_sem_destroy(&ms
->rate_limit_sem
);
3767 qemu_sem_destroy(&ms
->pause_sem
);
3768 qemu_sem_destroy(&ms
->postcopy_pause_sem
);
3769 qemu_sem_destroy(&ms
->rp_state
.rp_sem
);
3770 qemu_sem_destroy(&ms
->rp_state
.rp_pong_acks
);
3771 qemu_sem_destroy(&ms
->postcopy_qemufile_src_sem
);
3772 error_free(ms
->error
);
3775 static void migration_instance_init(Object
*obj
)
3777 MigrationState
*ms
= MIGRATION_OBJ(obj
);
3779 ms
->state
= MIGRATION_STATUS_NONE
;
3781 ms
->pages_per_second
= -1;
3782 qemu_sem_init(&ms
->pause_sem
, 0);
3783 qemu_mutex_init(&ms
->error_mutex
);
3785 migrate_params_init(&ms
->parameters
);
3787 qemu_sem_init(&ms
->postcopy_pause_sem
, 0);
3788 qemu_sem_init(&ms
->rp_state
.rp_sem
, 0);
3789 qemu_sem_init(&ms
->rp_state
.rp_pong_acks
, 0);
3790 qemu_sem_init(&ms
->rate_limit_sem
, 0);
3791 qemu_sem_init(&ms
->wait_unplug_sem
, 0);
3792 qemu_sem_init(&ms
->postcopy_qemufile_src_sem
, 0);
3793 qemu_mutex_init(&ms
->qemu_file_lock
);
3797 * Return true if check pass, false otherwise. Error will be put
3798 * inside errp if provided.
3800 static bool migration_object_check(MigrationState
*ms
, Error
**errp
)
3802 /* Assuming all off */
3803 bool old_caps
[MIGRATION_CAPABILITY__MAX
] = { 0 };
3805 if (!migrate_params_check(&ms
->parameters
, errp
)) {
3809 return migrate_caps_check(old_caps
, ms
->capabilities
, errp
);
3812 static const TypeInfo migration_type
= {
3813 .name
= TYPE_MIGRATION
,
3815 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3816 * not created using qdev_new(), it is not attached to the qdev
3817 * device tree, and it is never realized.
3819 * TODO: Make this TYPE_OBJECT once QOM provides something like
3820 * TYPE_DEVICE's "-global" properties.
3822 .parent
= TYPE_DEVICE
,
3823 .class_init
= migration_class_init
,
3824 .class_size
= sizeof(MigrationClass
),
3825 .instance_size
= sizeof(MigrationState
),
3826 .instance_init
= migration_instance_init
,
3827 .instance_finalize
= migration_instance_finalize
,
3830 static void register_migration_types(void)
3832 type_register_static(&migration_type
);
3835 type_init(register_migration_types
);