mirror: Require GRAPH_RDLOCK for accessing a node's parent list
[qemu/kevin.git] / migration / migration.c
blobf9f12a17b53763c43e15d10f41bc0cebf2f8518e
1 /*
2 * QEMU live migration
4 * Copyright IBM, Corp. 2008
6 * Authors:
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"
21 #include "exec.h"
22 #include "fd.h"
23 #include "socket.h"
24 #include "sysemu/runstate.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/cpu-throttle.h"
27 #include "rdma.h"
28 #include "ram.h"
29 #include "ram-compress.h"
30 #include "migration/global_state.h"
31 #include "migration/misc.h"
32 #include "migration.h"
33 #include "migration-stats.h"
34 #include "savevm.h"
35 #include "qemu-file.h"
36 #include "channel.h"
37 #include "migration/vmstate.h"
38 #include "block/block.h"
39 #include "qapi/error.h"
40 #include "qapi/clone-visitor.h"
41 #include "qapi/qapi-visit-migration.h"
42 #include "qapi/qapi-visit-sockets.h"
43 #include "qapi/qapi-commands-migration.h"
44 #include "qapi/qapi-events-migration.h"
45 #include "qapi/qmp/qerror.h"
46 #include "qapi/qmp/qnull.h"
47 #include "qemu/rcu.h"
48 #include "block.h"
49 #include "postcopy-ram.h"
50 #include "qemu/thread.h"
51 #include "trace.h"
52 #include "exec/target_page.h"
53 #include "io/channel-buffer.h"
54 #include "io/channel-tls.h"
55 #include "migration/colo.h"
56 #include "hw/boards.h"
57 #include "monitor/monitor.h"
58 #include "net/announce.h"
59 #include "qemu/queue.h"
60 #include "multifd.h"
61 #include "threadinfo.h"
62 #include "qemu/yank.h"
63 #include "sysemu/cpus.h"
64 #include "yank_functions.h"
65 #include "sysemu/qtest.h"
66 #include "options.h"
68 static NotifierList migration_state_notifiers =
69 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
71 /* Messages sent on the return path from destination to source */
72 enum mig_rp_message_type {
73 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
74 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
75 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
77 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
78 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
79 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
80 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
82 MIG_RP_MSG_MAX
85 /* When we add fault tolerance, we could have several
86 migrations at once. For now we don't need to add
87 dynamic creation of migration */
89 static MigrationState *current_migration;
90 static MigrationIncomingState *current_incoming;
92 static GSList *migration_blockers;
94 static bool migration_object_check(MigrationState *ms, Error **errp);
95 static int migration_maybe_pause(MigrationState *s,
96 int *current_active_state,
97 int new_state);
98 static void migrate_fd_cancel(MigrationState *s);
100 static bool migration_needs_multiple_sockets(void)
102 return migrate_multifd() || migrate_postcopy_preempt();
105 static bool uri_supports_multi_channels(const char *uri)
107 return strstart(uri, "tcp:", NULL) || strstart(uri, "unix:", NULL) ||
108 strstart(uri, "vsock:", NULL);
111 static bool
112 migration_channels_and_uri_compatible(const char *uri, Error **errp)
114 if (migration_needs_multiple_sockets() &&
115 !uri_supports_multi_channels(uri)) {
116 error_setg(errp, "Migration requires multi-channel URIs (e.g. tcp)");
117 return false;
120 return true;
123 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
125 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
127 return (a > b) - (a < b);
130 void migration_object_init(void)
132 /* This can only be called once. */
133 assert(!current_migration);
134 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
137 * Init the migrate incoming object as well no matter whether
138 * we'll use it or not.
140 assert(!current_incoming);
141 current_incoming = g_new0(MigrationIncomingState, 1);
142 current_incoming->state = MIGRATION_STATUS_NONE;
143 current_incoming->postcopy_remote_fds =
144 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
145 qemu_mutex_init(&current_incoming->rp_mutex);
146 qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
147 qemu_event_init(&current_incoming->main_thread_load_event, false);
148 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
149 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
150 qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
151 qemu_sem_init(&current_incoming->postcopy_qemufile_dst_done, 0);
153 qemu_mutex_init(&current_incoming->page_request_mutex);
154 current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
156 migration_object_check(current_migration, &error_fatal);
158 blk_mig_init();
159 ram_mig_init();
160 dirty_bitmap_mig_init();
163 void migration_cancel(const Error *error)
165 if (error) {
166 migrate_set_error(current_migration, error);
168 migrate_fd_cancel(current_migration);
171 void migration_shutdown(void)
174 * When the QEMU main thread exit, the COLO thread
175 * may wait a semaphore. So, we should wakeup the
176 * COLO thread before migration shutdown.
178 colo_shutdown();
180 * Cancel the current migration - that will (eventually)
181 * stop the migration using this structure
183 migration_cancel(NULL);
184 object_unref(OBJECT(current_migration));
187 * Cancel outgoing migration of dirty bitmaps. It should
188 * at least unref used block nodes.
190 dirty_bitmap_mig_cancel_outgoing();
193 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
194 * are non-critical data, and their loss never considered as
195 * something serious.
197 dirty_bitmap_mig_cancel_incoming();
200 /* For outgoing */
201 MigrationState *migrate_get_current(void)
203 /* This can only be called after the object created. */
204 assert(current_migration);
205 return current_migration;
208 MigrationIncomingState *migration_incoming_get_current(void)
210 assert(current_incoming);
211 return current_incoming;
214 void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
216 if (mis->socket_address_list) {
217 qapi_free_SocketAddressList(mis->socket_address_list);
218 mis->socket_address_list = NULL;
221 if (mis->transport_cleanup) {
222 mis->transport_cleanup(mis->transport_data);
223 mis->transport_data = mis->transport_cleanup = NULL;
227 void migration_incoming_state_destroy(void)
229 struct MigrationIncomingState *mis = migration_incoming_get_current();
231 multifd_load_cleanup();
232 compress_threads_load_cleanup();
234 if (mis->to_src_file) {
235 /* Tell source that we are done */
236 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
237 qemu_fclose(mis->to_src_file);
238 mis->to_src_file = NULL;
241 if (mis->from_src_file) {
242 migration_ioc_unregister_yank_from_file(mis->from_src_file);
243 qemu_fclose(mis->from_src_file);
244 mis->from_src_file = NULL;
246 if (mis->postcopy_remote_fds) {
247 g_array_free(mis->postcopy_remote_fds, TRUE);
248 mis->postcopy_remote_fds = NULL;
251 migration_incoming_transport_cleanup(mis);
252 qemu_event_reset(&mis->main_thread_load_event);
254 if (mis->page_requested) {
255 g_tree_destroy(mis->page_requested);
256 mis->page_requested = NULL;
259 if (mis->postcopy_qemufile_dst) {
260 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
261 qemu_fclose(mis->postcopy_qemufile_dst);
262 mis->postcopy_qemufile_dst = NULL;
265 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
268 static void migrate_generate_event(int new_state)
270 if (migrate_events()) {
271 qapi_event_send_migration(new_state);
276 * Send a message on the return channel back to the source
277 * of the migration.
279 static int migrate_send_rp_message(MigrationIncomingState *mis,
280 enum mig_rp_message_type message_type,
281 uint16_t len, void *data)
283 int ret = 0;
285 trace_migrate_send_rp_message((int)message_type, len);
286 QEMU_LOCK_GUARD(&mis->rp_mutex);
289 * It's possible that the file handle got lost due to network
290 * failures.
292 if (!mis->to_src_file) {
293 ret = -EIO;
294 return ret;
297 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
298 qemu_put_be16(mis->to_src_file, len);
299 qemu_put_buffer(mis->to_src_file, data, len);
300 qemu_fflush(mis->to_src_file);
302 /* It's possible that qemu file got error during sending */
303 ret = qemu_file_get_error(mis->to_src_file);
305 return ret;
308 /* Request one page from the source VM at the given start address.
309 * rb: the RAMBlock to request the page in
310 * Start: Address offset within the RB
311 * Len: Length in bytes required - must be a multiple of pagesize
313 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
314 RAMBlock *rb, ram_addr_t start)
316 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
317 size_t msglen = 12; /* start + len */
318 size_t len = qemu_ram_pagesize(rb);
319 enum mig_rp_message_type msg_type;
320 const char *rbname;
321 int rbname_len;
323 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
324 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
327 * We maintain the last ramblock that we requested for page. Note that we
328 * don't need locking because this function will only be called within the
329 * postcopy ram fault thread.
331 if (rb != mis->last_rb) {
332 mis->last_rb = rb;
334 rbname = qemu_ram_get_idstr(rb);
335 rbname_len = strlen(rbname);
337 assert(rbname_len < 256);
339 bufc[msglen++] = rbname_len;
340 memcpy(bufc + msglen, rbname, rbname_len);
341 msglen += rbname_len;
342 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
343 } else {
344 msg_type = MIG_RP_MSG_REQ_PAGES;
347 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
350 int migrate_send_rp_req_pages(MigrationIncomingState *mis,
351 RAMBlock *rb, ram_addr_t start, uint64_t haddr)
353 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
354 bool received = false;
356 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
357 received = ramblock_recv_bitmap_test_byte_offset(rb, start);
358 if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
360 * The page has not been received, and it's not yet in the page
361 * request list. Queue it. Set the value of element to 1, so that
362 * things like g_tree_lookup() will return TRUE (1) when found.
364 g_tree_insert(mis->page_requested, aligned, (gpointer)1);
365 mis->page_requested_count++;
366 trace_postcopy_page_req_add(aligned, mis->page_requested_count);
371 * If the page is there, skip sending the message. We don't even need the
372 * lock because as long as the page arrived, it'll be there forever.
374 if (received) {
375 return 0;
378 return migrate_send_rp_message_req_pages(mis, rb, start);
381 static bool migration_colo_enabled;
382 bool migration_incoming_colo_enabled(void)
384 return migration_colo_enabled;
387 void migration_incoming_disable_colo(void)
389 ram_block_discard_disable(false);
390 migration_colo_enabled = false;
393 int migration_incoming_enable_colo(void)
395 if (ram_block_discard_disable(true)) {
396 error_report("COLO: cannot disable RAM discard");
397 return -EBUSY;
399 migration_colo_enabled = true;
400 return 0;
403 void migrate_add_address(SocketAddress *address)
405 MigrationIncomingState *mis = migration_incoming_get_current();
407 QAPI_LIST_PREPEND(mis->socket_address_list,
408 QAPI_CLONE(SocketAddress, address));
411 static void qemu_start_incoming_migration(const char *uri, Error **errp)
413 const char *p = NULL;
415 /* URI is not suitable for migration? */
416 if (!migration_channels_and_uri_compatible(uri, errp)) {
417 return;
420 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
421 if (strstart(uri, "tcp:", &p) ||
422 strstart(uri, "unix:", NULL) ||
423 strstart(uri, "vsock:", NULL)) {
424 socket_start_incoming_migration(p ? p : uri, errp);
425 #ifdef CONFIG_RDMA
426 } else if (strstart(uri, "rdma:", &p)) {
427 rdma_start_incoming_migration(p, errp);
428 #endif
429 } else if (strstart(uri, "exec:", &p)) {
430 exec_start_incoming_migration(p, errp);
431 } else if (strstart(uri, "fd:", &p)) {
432 fd_start_incoming_migration(p, errp);
433 } else {
434 error_setg(errp, "unknown migration protocol: %s", uri);
438 static void process_incoming_migration_bh(void *opaque)
440 Error *local_err = NULL;
441 MigrationIncomingState *mis = opaque;
443 /* If capability late_block_activate is set:
444 * Only fire up the block code now if we're going to restart the
445 * VM, else 'cont' will do it.
446 * This causes file locking to happen; so we don't want it to happen
447 * unless we really are starting the VM.
449 if (!migrate_late_block_activate() ||
450 (autostart && (!global_state_received() ||
451 global_state_get_runstate() == RUN_STATE_RUNNING))) {
452 /* Make sure all file formats throw away their mutable metadata.
453 * If we get an error here, just don't restart the VM yet. */
454 bdrv_activate_all(&local_err);
455 if (local_err) {
456 error_report_err(local_err);
457 local_err = NULL;
458 autostart = false;
463 * This must happen after all error conditions are dealt with and
464 * we're sure the VM is going to be running on this host.
466 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
468 multifd_load_shutdown();
470 dirty_bitmap_mig_before_vm_start();
472 if (!global_state_received() ||
473 global_state_get_runstate() == RUN_STATE_RUNNING) {
474 if (autostart) {
475 vm_start();
476 } else {
477 runstate_set(RUN_STATE_PAUSED);
479 } else if (migration_incoming_colo_enabled()) {
480 migration_incoming_disable_colo();
481 vm_start();
482 } else {
483 runstate_set(global_state_get_runstate());
486 * This must happen after any state changes since as soon as an external
487 * observer sees this event they might start to prod at the VM assuming
488 * it's ready to use.
490 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
491 MIGRATION_STATUS_COMPLETED);
492 qemu_bh_delete(mis->bh);
493 migration_incoming_state_destroy();
496 static void coroutine_fn
497 process_incoming_migration_co(void *opaque)
499 MigrationIncomingState *mis = migration_incoming_get_current();
500 PostcopyState ps;
501 int ret;
502 Error *local_err = NULL;
504 assert(mis->from_src_file);
506 if (compress_threads_load_setup(mis->from_src_file)) {
507 error_report("Failed to setup decompress threads");
508 goto fail;
511 mis->migration_incoming_co = qemu_coroutine_self();
512 mis->largest_page_size = qemu_ram_pagesize_largest();
513 postcopy_state_set(POSTCOPY_INCOMING_NONE);
514 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
515 MIGRATION_STATUS_ACTIVE);
516 ret = qemu_loadvm_state(mis->from_src_file);
518 ps = postcopy_state_get();
519 trace_process_incoming_migration_co_end(ret, ps);
520 if (ps != POSTCOPY_INCOMING_NONE) {
521 if (ps == POSTCOPY_INCOMING_ADVISE) {
523 * Where a migration had postcopy enabled (and thus went to advise)
524 * but managed to complete within the precopy period, we can use
525 * the normal exit.
527 postcopy_ram_incoming_cleanup(mis);
528 } else if (ret >= 0) {
530 * Postcopy was started, cleanup should happen at the end of the
531 * postcopy thread.
533 trace_process_incoming_migration_co_postcopy_end_main();
534 return;
536 /* Else if something went wrong then just fall out of the normal exit */
539 /* we get COLO info, and know if we are in COLO mode */
540 if (!ret && migration_incoming_colo_enabled()) {
541 /* Make sure all file formats throw away their mutable metadata */
542 bdrv_activate_all(&local_err);
543 if (local_err) {
544 error_report_err(local_err);
545 goto fail;
548 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
549 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
550 mis->have_colo_incoming_thread = true;
551 qemu_coroutine_yield();
553 qemu_mutex_unlock_iothread();
554 /* Wait checkpoint incoming thread exit before free resource */
555 qemu_thread_join(&mis->colo_incoming_thread);
556 qemu_mutex_lock_iothread();
557 /* We hold the global iothread lock, so it is safe here */
558 colo_release_ram_cache();
561 if (ret < 0) {
562 error_report("load of migration failed: %s", strerror(-ret));
563 goto fail;
565 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
566 qemu_bh_schedule(mis->bh);
567 mis->migration_incoming_co = NULL;
568 return;
569 fail:
570 local_err = NULL;
571 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
572 MIGRATION_STATUS_FAILED);
573 qemu_fclose(mis->from_src_file);
575 multifd_load_cleanup();
576 compress_threads_load_cleanup();
578 exit(EXIT_FAILURE);
582 * migration_incoming_setup: Setup incoming migration
583 * @f: file for main migration channel
584 * @errp: where to put errors
586 * Returns: %true on success, %false on error.
588 static bool migration_incoming_setup(QEMUFile *f, Error **errp)
590 MigrationIncomingState *mis = migration_incoming_get_current();
592 if (!mis->from_src_file) {
593 mis->from_src_file = f;
595 qemu_file_set_blocking(f, false);
596 return true;
599 void migration_incoming_process(void)
601 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
602 qemu_coroutine_enter(co);
605 /* Returns true if recovered from a paused migration, otherwise false */
606 static bool postcopy_try_recover(void)
608 MigrationIncomingState *mis = migration_incoming_get_current();
610 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
611 /* Resumed from a paused postcopy migration */
613 /* This should be set already in migration_incoming_setup() */
614 assert(mis->from_src_file);
615 /* Postcopy has standalone thread to do vm load */
616 qemu_file_set_blocking(mis->from_src_file, true);
618 /* Re-configure the return path */
619 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
621 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
622 MIGRATION_STATUS_POSTCOPY_RECOVER);
625 * Here, we only wake up the main loading thread (while the
626 * rest threads will still be waiting), so that we can receive
627 * commands from source now, and answer it if needed. The
628 * rest threads will be woken up afterwards until we are sure
629 * that source is ready to reply to page requests.
631 qemu_sem_post(&mis->postcopy_pause_sem_dst);
632 return true;
635 return false;
638 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
640 if (!migration_incoming_setup(f, errp)) {
641 return;
643 if (postcopy_try_recover()) {
644 return;
646 migration_incoming_process();
650 * Returns true when we want to start a new incoming migration process,
651 * false otherwise.
653 static bool migration_should_start_incoming(bool main_channel)
655 /* Multifd doesn't start unless all channels are established */
656 if (migrate_multifd()) {
657 return migration_has_all_channels();
660 /* Preempt channel only starts when the main channel is created */
661 if (migrate_postcopy_preempt()) {
662 return main_channel;
666 * For all the rest types of migration, we should only reach here when
667 * it's the main channel that's being created, and we should always
668 * proceed with this channel.
670 assert(main_channel);
671 return true;
674 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
676 MigrationIncomingState *mis = migration_incoming_get_current();
677 Error *local_err = NULL;
678 QEMUFile *f;
679 bool default_channel = true;
680 uint32_t channel_magic = 0;
681 int ret = 0;
683 if (migrate_multifd() && !migrate_postcopy_ram() &&
684 qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) {
686 * With multiple channels, it is possible that we receive channels
687 * out of order on destination side, causing incorrect mapping of
688 * source channels on destination side. Check channel MAGIC to
689 * decide type of channel. Please note this is best effort, postcopy
690 * preempt channel does not send any magic number so avoid it for
691 * postcopy live migration. Also tls live migration already does
692 * tls handshake while initializing main channel so with tls this
693 * issue is not possible.
695 ret = migration_channel_read_peek(ioc, (void *)&channel_magic,
696 sizeof(channel_magic), &local_err);
698 if (ret != 0) {
699 error_propagate(errp, local_err);
700 return;
703 default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC));
704 } else {
705 default_channel = !mis->from_src_file;
708 if (multifd_load_setup(errp) != 0) {
709 error_setg(errp, "Failed to setup multifd channels");
710 return;
713 if (default_channel) {
714 f = qemu_file_new_input(ioc);
716 if (!migration_incoming_setup(f, errp)) {
717 return;
719 } else {
720 /* Multiple connections */
721 assert(migration_needs_multiple_sockets());
722 if (migrate_multifd()) {
723 multifd_recv_new_channel(ioc, &local_err);
724 } else {
725 assert(migrate_postcopy_preempt());
726 f = qemu_file_new_input(ioc);
727 postcopy_preempt_new_channel(mis, f);
729 if (local_err) {
730 error_propagate(errp, local_err);
731 return;
735 if (migration_should_start_incoming(default_channel)) {
736 /* If it's a recovery, we're done */
737 if (postcopy_try_recover()) {
738 return;
740 migration_incoming_process();
745 * @migration_has_all_channels: We have received all channels that we need
747 * Returns true when we have got connections to all the channels that
748 * we need for migration.
750 bool migration_has_all_channels(void)
752 MigrationIncomingState *mis = migration_incoming_get_current();
754 if (!mis->from_src_file) {
755 return false;
758 if (migrate_multifd()) {
759 return multifd_recv_all_channels_created();
762 if (migrate_postcopy_preempt()) {
763 return mis->postcopy_qemufile_dst != NULL;
766 return true;
770 * Send a 'SHUT' message on the return channel with the given value
771 * to indicate that we've finished with the RP. Non-0 value indicates
772 * error.
774 void migrate_send_rp_shut(MigrationIncomingState *mis,
775 uint32_t value)
777 uint32_t buf;
779 buf = cpu_to_be32(value);
780 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
784 * Send a 'PONG' message on the return channel with the given value
785 * (normally in response to a 'PING')
787 void migrate_send_rp_pong(MigrationIncomingState *mis,
788 uint32_t value)
790 uint32_t buf;
792 buf = cpu_to_be32(value);
793 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
796 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
797 char *block_name)
799 char buf[512];
800 int len;
801 int64_t res;
804 * First, we send the header part. It contains only the len of
805 * idstr, and the idstr itself.
807 len = strlen(block_name);
808 buf[0] = len;
809 memcpy(buf + 1, block_name, len);
811 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
812 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
813 __func__);
814 return;
817 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
820 * Next, we dump the received bitmap to the stream.
822 * TODO: currently we are safe since we are the only one that is
823 * using the to_src_file handle (fault thread is still paused),
824 * and it's ok even not taking the mutex. However the best way is
825 * to take the lock before sending the message header, and release
826 * the lock after sending the bitmap.
828 qemu_mutex_lock(&mis->rp_mutex);
829 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
830 qemu_mutex_unlock(&mis->rp_mutex);
832 trace_migrate_send_rp_recv_bitmap(block_name, res);
835 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
837 uint32_t buf;
839 buf = cpu_to_be32(value);
840 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
844 * Return true if we're already in the middle of a migration
845 * (i.e. any of the active or setup states)
847 bool migration_is_setup_or_active(int state)
849 switch (state) {
850 case MIGRATION_STATUS_ACTIVE:
851 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
852 case MIGRATION_STATUS_POSTCOPY_PAUSED:
853 case MIGRATION_STATUS_POSTCOPY_RECOVER:
854 case MIGRATION_STATUS_SETUP:
855 case MIGRATION_STATUS_PRE_SWITCHOVER:
856 case MIGRATION_STATUS_DEVICE:
857 case MIGRATION_STATUS_WAIT_UNPLUG:
858 case MIGRATION_STATUS_COLO:
859 return true;
861 default:
862 return false;
867 bool migration_is_running(int state)
869 switch (state) {
870 case MIGRATION_STATUS_ACTIVE:
871 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
872 case MIGRATION_STATUS_POSTCOPY_PAUSED:
873 case MIGRATION_STATUS_POSTCOPY_RECOVER:
874 case MIGRATION_STATUS_SETUP:
875 case MIGRATION_STATUS_PRE_SWITCHOVER:
876 case MIGRATION_STATUS_DEVICE:
877 case MIGRATION_STATUS_WAIT_UNPLUG:
878 case MIGRATION_STATUS_CANCELLING:
879 return true;
881 default:
882 return false;
887 static bool migrate_show_downtime(MigrationState *s)
889 return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy();
892 static void populate_time_info(MigrationInfo *info, MigrationState *s)
894 info->has_status = true;
895 info->has_setup_time = true;
896 info->setup_time = s->setup_time;
898 if (s->state == MIGRATION_STATUS_COMPLETED) {
899 info->has_total_time = true;
900 info->total_time = s->total_time;
901 } else {
902 info->has_total_time = true;
903 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
904 s->start_time;
907 if (migrate_show_downtime(s)) {
908 info->has_downtime = true;
909 info->downtime = s->downtime;
910 } else {
911 info->has_expected_downtime = true;
912 info->expected_downtime = s->expected_downtime;
916 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
918 size_t page_size = qemu_target_page_size();
920 info->ram = g_malloc0(sizeof(*info->ram));
921 info->ram->transferred = stat64_get(&mig_stats.transferred);
922 info->ram->total = ram_bytes_total();
923 info->ram->duplicate = stat64_get(&mig_stats.zero_pages);
924 /* legacy value. It is not used anymore */
925 info->ram->skipped = 0;
926 info->ram->normal = stat64_get(&mig_stats.normal_pages);
927 info->ram->normal_bytes = info->ram->normal * page_size;
928 info->ram->mbps = s->mbps;
929 info->ram->dirty_sync_count =
930 stat64_get(&mig_stats.dirty_sync_count);
931 info->ram->dirty_sync_missed_zero_copy =
932 stat64_get(&mig_stats.dirty_sync_missed_zero_copy);
933 info->ram->postcopy_requests =
934 stat64_get(&mig_stats.postcopy_requests);
935 info->ram->page_size = page_size;
936 info->ram->multifd_bytes = stat64_get(&mig_stats.multifd_bytes);
937 info->ram->pages_per_second = s->pages_per_second;
938 info->ram->precopy_bytes = stat64_get(&mig_stats.precopy_bytes);
939 info->ram->downtime_bytes = stat64_get(&mig_stats.downtime_bytes);
940 info->ram->postcopy_bytes = stat64_get(&mig_stats.postcopy_bytes);
942 if (migrate_xbzrle()) {
943 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
944 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
945 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
946 info->xbzrle_cache->pages = xbzrle_counters.pages;
947 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
948 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
949 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
950 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
953 if (migrate_compress()) {
954 info->compression = g_malloc0(sizeof(*info->compression));
955 info->compression->pages = compression_counters.pages;
956 info->compression->busy = compression_counters.busy;
957 info->compression->busy_rate = compression_counters.busy_rate;
958 info->compression->compressed_size =
959 compression_counters.compressed_size;
960 info->compression->compression_rate =
961 compression_counters.compression_rate;
964 if (cpu_throttle_active()) {
965 info->has_cpu_throttle_percentage = true;
966 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
969 if (s->state != MIGRATION_STATUS_COMPLETED) {
970 info->ram->remaining = ram_bytes_remaining();
971 info->ram->dirty_pages_rate =
972 stat64_get(&mig_stats.dirty_pages_rate);
976 static void populate_disk_info(MigrationInfo *info)
978 if (blk_mig_active()) {
979 info->disk = g_malloc0(sizeof(*info->disk));
980 info->disk->transferred = blk_mig_bytes_transferred();
981 info->disk->remaining = blk_mig_bytes_remaining();
982 info->disk->total = blk_mig_bytes_total();
986 static void fill_source_migration_info(MigrationInfo *info)
988 MigrationState *s = migrate_get_current();
989 int state = qatomic_read(&s->state);
990 GSList *cur_blocker = migration_blockers;
992 info->blocked_reasons = NULL;
995 * There are two types of reasons a migration might be blocked;
996 * a) devices marked in VMState as non-migratable, and
997 * b) Explicit migration blockers
998 * We need to add both of them here.
1000 qemu_savevm_non_migratable_list(&info->blocked_reasons);
1002 while (cur_blocker) {
1003 QAPI_LIST_PREPEND(info->blocked_reasons,
1004 g_strdup(error_get_pretty(cur_blocker->data)));
1005 cur_blocker = g_slist_next(cur_blocker);
1007 info->has_blocked_reasons = info->blocked_reasons != NULL;
1009 switch (state) {
1010 case MIGRATION_STATUS_NONE:
1011 /* no migration has happened ever */
1012 /* do not overwrite destination migration status */
1013 return;
1014 case MIGRATION_STATUS_SETUP:
1015 info->has_status = true;
1016 info->has_total_time = false;
1017 break;
1018 case MIGRATION_STATUS_ACTIVE:
1019 case MIGRATION_STATUS_CANCELLING:
1020 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1021 case MIGRATION_STATUS_PRE_SWITCHOVER:
1022 case MIGRATION_STATUS_DEVICE:
1023 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1024 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1025 /* TODO add some postcopy stats */
1026 populate_time_info(info, s);
1027 populate_ram_info(info, s);
1028 populate_disk_info(info);
1029 populate_vfio_info(info);
1030 break;
1031 case MIGRATION_STATUS_COLO:
1032 info->has_status = true;
1033 /* TODO: display COLO specific information (checkpoint info etc.) */
1034 break;
1035 case MIGRATION_STATUS_COMPLETED:
1036 populate_time_info(info, s);
1037 populate_ram_info(info, s);
1038 populate_vfio_info(info);
1039 break;
1040 case MIGRATION_STATUS_FAILED:
1041 info->has_status = true;
1042 if (s->error) {
1043 info->error_desc = g_strdup(error_get_pretty(s->error));
1045 break;
1046 case MIGRATION_STATUS_CANCELLED:
1047 info->has_status = true;
1048 break;
1049 case MIGRATION_STATUS_WAIT_UNPLUG:
1050 info->has_status = true;
1051 break;
1053 info->status = state;
1056 static void fill_destination_migration_info(MigrationInfo *info)
1058 MigrationIncomingState *mis = migration_incoming_get_current();
1060 if (mis->socket_address_list) {
1061 info->has_socket_address = true;
1062 info->socket_address =
1063 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1066 switch (mis->state) {
1067 case MIGRATION_STATUS_NONE:
1068 return;
1069 case MIGRATION_STATUS_SETUP:
1070 case MIGRATION_STATUS_CANCELLING:
1071 case MIGRATION_STATUS_CANCELLED:
1072 case MIGRATION_STATUS_ACTIVE:
1073 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1074 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1075 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1076 case MIGRATION_STATUS_FAILED:
1077 case MIGRATION_STATUS_COLO:
1078 info->has_status = true;
1079 break;
1080 case MIGRATION_STATUS_COMPLETED:
1081 info->has_status = true;
1082 fill_destination_postcopy_migration_info(info);
1083 break;
1085 info->status = mis->state;
1088 MigrationInfo *qmp_query_migrate(Error **errp)
1090 MigrationInfo *info = g_malloc0(sizeof(*info));
1092 fill_destination_migration_info(info);
1093 fill_source_migration_info(info);
1095 return info;
1098 void qmp_migrate_start_postcopy(Error **errp)
1100 MigrationState *s = migrate_get_current();
1102 if (!migrate_postcopy()) {
1103 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1104 " the start of migration");
1105 return;
1108 if (s->state == MIGRATION_STATUS_NONE) {
1109 error_setg(errp, "Postcopy must be started after migration has been"
1110 " started");
1111 return;
1114 * we don't error if migration has finished since that would be racy
1115 * with issuing this command.
1117 qatomic_set(&s->start_postcopy, true);
1120 /* shared migration helpers */
1122 void migrate_set_state(int *state, int old_state, int new_state)
1124 assert(new_state < MIGRATION_STATUS__MAX);
1125 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
1126 trace_migrate_set_state(MigrationStatus_str(new_state));
1127 migrate_generate_event(new_state);
1131 static void migrate_fd_cleanup(MigrationState *s)
1133 qemu_bh_delete(s->cleanup_bh);
1134 s->cleanup_bh = NULL;
1136 g_free(s->hostname);
1137 s->hostname = NULL;
1138 json_writer_free(s->vmdesc);
1139 s->vmdesc = NULL;
1141 qemu_savevm_state_cleanup();
1143 if (s->to_dst_file) {
1144 QEMUFile *tmp;
1146 trace_migrate_fd_cleanup();
1147 qemu_mutex_unlock_iothread();
1148 if (s->migration_thread_running) {
1149 qemu_thread_join(&s->thread);
1150 s->migration_thread_running = false;
1152 qemu_mutex_lock_iothread();
1154 multifd_save_cleanup();
1155 qemu_mutex_lock(&s->qemu_file_lock);
1156 tmp = s->to_dst_file;
1157 s->to_dst_file = NULL;
1158 qemu_mutex_unlock(&s->qemu_file_lock);
1160 * Close the file handle without the lock to make sure the
1161 * critical section won't block for long.
1163 migration_ioc_unregister_yank_from_file(tmp);
1164 qemu_fclose(tmp);
1167 if (s->postcopy_qemufile_src) {
1168 migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src);
1169 qemu_fclose(s->postcopy_qemufile_src);
1170 s->postcopy_qemufile_src = NULL;
1173 assert(!migration_is_active(s));
1175 if (s->state == MIGRATION_STATUS_CANCELLING) {
1176 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1177 MIGRATION_STATUS_CANCELLED);
1180 if (s->error) {
1181 /* It is used on info migrate. We can't free it */
1182 error_report_err(error_copy(s->error));
1184 notifier_list_notify(&migration_state_notifiers, s);
1185 block_cleanup_parameters();
1186 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1189 static void migrate_fd_cleanup_schedule(MigrationState *s)
1192 * Ref the state for bh, because it may be called when
1193 * there're already no other refs
1195 object_ref(OBJECT(s));
1196 qemu_bh_schedule(s->cleanup_bh);
1199 static void migrate_fd_cleanup_bh(void *opaque)
1201 MigrationState *s = opaque;
1202 migrate_fd_cleanup(s);
1203 object_unref(OBJECT(s));
1206 void migrate_set_error(MigrationState *s, const Error *error)
1208 QEMU_LOCK_GUARD(&s->error_mutex);
1209 if (!s->error) {
1210 s->error = error_copy(error);
1214 static void migrate_error_free(MigrationState *s)
1216 QEMU_LOCK_GUARD(&s->error_mutex);
1217 if (s->error) {
1218 error_free(s->error);
1219 s->error = NULL;
1223 void migrate_fd_error(MigrationState *s, const Error *error)
1225 trace_migrate_fd_error(error_get_pretty(error));
1226 assert(s->to_dst_file == NULL);
1227 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1228 MIGRATION_STATUS_FAILED);
1229 migrate_set_error(s, error);
1232 static void migrate_fd_cancel(MigrationState *s)
1234 int old_state ;
1235 QEMUFile *f = migrate_get_current()->to_dst_file;
1236 trace_migrate_fd_cancel();
1238 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1239 if (s->rp_state.from_dst_file) {
1240 /* shutdown the rp socket, so causing the rp thread to shutdown */
1241 qemu_file_shutdown(s->rp_state.from_dst_file);
1245 do {
1246 old_state = s->state;
1247 if (!migration_is_running(old_state)) {
1248 break;
1250 /* If the migration is paused, kick it out of the pause */
1251 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1252 qemu_sem_post(&s->pause_sem);
1254 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1255 } while (s->state != MIGRATION_STATUS_CANCELLING);
1258 * If we're unlucky the migration code might be stuck somewhere in a
1259 * send/write while the network has failed and is waiting to timeout;
1260 * if we've got shutdown(2) available then we can force it to quit.
1261 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1262 * called in a bh, so there is no race against this cancel.
1264 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1265 qemu_file_shutdown(f);
1267 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1268 Error *local_err = NULL;
1270 bdrv_activate_all(&local_err);
1271 if (local_err) {
1272 error_report_err(local_err);
1273 } else {
1274 s->block_inactive = false;
1279 void add_migration_state_change_notifier(Notifier *notify)
1281 notifier_list_add(&migration_state_notifiers, notify);
1284 void remove_migration_state_change_notifier(Notifier *notify)
1286 notifier_remove(notify);
1289 bool migration_in_setup(MigrationState *s)
1291 return s->state == MIGRATION_STATUS_SETUP;
1294 bool migration_has_finished(MigrationState *s)
1296 return s->state == MIGRATION_STATUS_COMPLETED;
1299 bool migration_has_failed(MigrationState *s)
1301 return (s->state == MIGRATION_STATUS_CANCELLED ||
1302 s->state == MIGRATION_STATUS_FAILED);
1305 bool migration_in_postcopy(void)
1307 MigrationState *s = migrate_get_current();
1309 switch (s->state) {
1310 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1311 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1312 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1313 return true;
1314 default:
1315 return false;
1319 bool migration_in_postcopy_after_devices(MigrationState *s)
1321 return migration_in_postcopy() && s->postcopy_after_devices;
1324 bool migration_in_incoming_postcopy(void)
1326 PostcopyState ps = postcopy_state_get();
1328 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
1331 bool migration_incoming_postcopy_advised(void)
1333 PostcopyState ps = postcopy_state_get();
1335 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
1338 bool migration_in_bg_snapshot(void)
1340 MigrationState *s = migrate_get_current();
1342 return migrate_background_snapshot() &&
1343 migration_is_setup_or_active(s->state);
1346 bool migration_is_idle(void)
1348 MigrationState *s = current_migration;
1350 if (!s) {
1351 return true;
1354 switch (s->state) {
1355 case MIGRATION_STATUS_NONE:
1356 case MIGRATION_STATUS_CANCELLED:
1357 case MIGRATION_STATUS_COMPLETED:
1358 case MIGRATION_STATUS_FAILED:
1359 return true;
1360 case MIGRATION_STATUS_SETUP:
1361 case MIGRATION_STATUS_CANCELLING:
1362 case MIGRATION_STATUS_ACTIVE:
1363 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1364 case MIGRATION_STATUS_COLO:
1365 case MIGRATION_STATUS_PRE_SWITCHOVER:
1366 case MIGRATION_STATUS_DEVICE:
1367 case MIGRATION_STATUS_WAIT_UNPLUG:
1368 return false;
1369 case MIGRATION_STATUS__MAX:
1370 g_assert_not_reached();
1373 return false;
1376 bool migration_is_active(MigrationState *s)
1378 return (s->state == MIGRATION_STATUS_ACTIVE ||
1379 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1382 void migrate_init(MigrationState *s)
1385 * Reinitialise all migration state, except
1386 * parameters/capabilities that the user set, and
1387 * locks.
1389 s->cleanup_bh = 0;
1390 s->vm_start_bh = 0;
1391 s->to_dst_file = NULL;
1392 s->state = MIGRATION_STATUS_NONE;
1393 s->rp_state.from_dst_file = NULL;
1394 s->rp_state.error = false;
1395 s->mbps = 0.0;
1396 s->pages_per_second = 0.0;
1397 s->downtime = 0;
1398 s->expected_downtime = 0;
1399 s->setup_time = 0;
1400 s->start_postcopy = false;
1401 s->postcopy_after_devices = false;
1402 s->migration_thread_running = false;
1403 error_free(s->error);
1404 s->error = NULL;
1405 s->hostname = NULL;
1407 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1409 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1410 s->total_time = 0;
1411 s->vm_was_running = false;
1412 s->iteration_initial_bytes = 0;
1413 s->threshold_size = 0;
1416 int migrate_add_blocker_internal(Error *reason, Error **errp)
1418 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1419 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
1420 error_propagate_prepend(errp, error_copy(reason),
1421 "disallowing migration blocker "
1422 "(migration/snapshot in progress) for: ");
1423 return -EBUSY;
1426 migration_blockers = g_slist_prepend(migration_blockers, reason);
1427 return 0;
1430 int migrate_add_blocker(Error *reason, Error **errp)
1432 if (only_migratable) {
1433 error_propagate_prepend(errp, error_copy(reason),
1434 "disallowing migration blocker "
1435 "(--only-migratable) for: ");
1436 return -EACCES;
1439 return migrate_add_blocker_internal(reason, errp);
1442 void migrate_del_blocker(Error *reason)
1444 migration_blockers = g_slist_remove(migration_blockers, reason);
1447 void qmp_migrate_incoming(const char *uri, Error **errp)
1449 Error *local_err = NULL;
1450 static bool once = true;
1452 if (!once) {
1453 error_setg(errp, "The incoming migration has already been started");
1454 return;
1456 if (!runstate_check(RUN_STATE_INMIGRATE)) {
1457 error_setg(errp, "'-incoming' was not specified on the command line");
1458 return;
1461 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1462 return;
1465 qemu_start_incoming_migration(uri, &local_err);
1467 if (local_err) {
1468 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1469 error_propagate(errp, local_err);
1470 return;
1473 once = false;
1476 void qmp_migrate_recover(const char *uri, Error **errp)
1478 MigrationIncomingState *mis = migration_incoming_get_current();
1481 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1482 * callers (no one should ignore a recover failure); if there is, it's a
1483 * programming error.
1485 assert(errp);
1487 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1488 error_setg(errp, "Migrate recover can only be run "
1489 "when postcopy is paused.");
1490 return;
1493 /* If there's an existing transport, release it */
1494 migration_incoming_transport_cleanup(mis);
1497 * Note that this call will never start a real migration; it will
1498 * only re-setup the migration stream and poke existing migration
1499 * to continue using that newly established channel.
1501 qemu_start_incoming_migration(uri, errp);
1504 void qmp_migrate_pause(Error **errp)
1506 MigrationState *ms = migrate_get_current();
1507 MigrationIncomingState *mis = migration_incoming_get_current();
1508 int ret;
1510 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1511 /* Source side, during postcopy */
1512 qemu_mutex_lock(&ms->qemu_file_lock);
1513 ret = qemu_file_shutdown(ms->to_dst_file);
1514 qemu_mutex_unlock(&ms->qemu_file_lock);
1515 if (ret) {
1516 error_setg(errp, "Failed to pause source migration");
1518 return;
1521 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1522 ret = qemu_file_shutdown(mis->from_src_file);
1523 if (ret) {
1524 error_setg(errp, "Failed to pause destination migration");
1526 return;
1529 error_setg(errp, "migrate-pause is currently only supported "
1530 "during postcopy-active state");
1533 bool migration_is_blocked(Error **errp)
1535 if (qemu_savevm_state_blocked(errp)) {
1536 return true;
1539 if (migration_blockers) {
1540 error_propagate(errp, error_copy(migration_blockers->data));
1541 return true;
1544 return false;
1547 /* Returns true if continue to migrate, or false if error detected */
1548 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1549 bool resume, Error **errp)
1551 Error *local_err = NULL;
1553 if (resume) {
1554 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1555 error_setg(errp, "Cannot resume if there is no "
1556 "paused migration");
1557 return false;
1561 * Postcopy recovery won't work well with release-ram
1562 * capability since release-ram will drop the page buffer as
1563 * long as the page is put into the send buffer. So if there
1564 * is a network failure happened, any page buffers that have
1565 * not yet reached the destination VM but have already been
1566 * sent from the source VM will be lost forever. Let's refuse
1567 * the client from resuming such a postcopy migration.
1568 * Luckily release-ram was designed to only be used when src
1569 * and destination VMs are on the same host, so it should be
1570 * fine.
1572 if (migrate_release_ram()) {
1573 error_setg(errp, "Postcopy recovery cannot work "
1574 "when release-ram capability is set");
1575 return false;
1578 /* This is a resume, skip init status */
1579 return true;
1582 if (migration_is_running(s->state)) {
1583 error_setg(errp, QERR_MIGRATION_ACTIVE);
1584 return false;
1587 if (runstate_check(RUN_STATE_INMIGRATE)) {
1588 error_setg(errp, "Guest is waiting for an incoming migration");
1589 return false;
1592 if (runstate_check(RUN_STATE_POSTMIGRATE)) {
1593 error_setg(errp, "Can't migrate the vm that was paused due to "
1594 "previous migration");
1595 return false;
1598 if (migration_is_blocked(errp)) {
1599 return false;
1602 if (blk || blk_inc) {
1603 if (migrate_colo()) {
1604 error_setg(errp, "No disk migration is required in COLO mode");
1605 return false;
1607 if (migrate_block() || migrate_block_incremental()) {
1608 error_setg(errp, "Command options are incompatible with "
1609 "current migration capabilities");
1610 return false;
1612 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK, true, &local_err)) {
1613 error_propagate(errp, local_err);
1614 return false;
1616 s->must_remove_block_options = true;
1619 if (blk_inc) {
1620 migrate_set_block_incremental(true);
1623 migrate_init(s);
1625 * set mig_stats compression_counters memory to zero for a
1626 * new migration
1628 memset(&mig_stats, 0, sizeof(mig_stats));
1629 memset(&compression_counters, 0, sizeof(compression_counters));
1631 return true;
1634 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1635 bool has_inc, bool inc, bool has_detach, bool detach,
1636 bool has_resume, bool resume, Error **errp)
1638 Error *local_err = NULL;
1639 MigrationState *s = migrate_get_current();
1640 const char *p = NULL;
1642 /* URI is not suitable for migration? */
1643 if (!migration_channels_and_uri_compatible(uri, errp)) {
1644 return;
1647 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1648 has_resume && resume, errp)) {
1649 /* Error detected, put into errp */
1650 return;
1653 if (!(has_resume && resume)) {
1654 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1655 return;
1659 if (strstart(uri, "tcp:", &p) ||
1660 strstart(uri, "unix:", NULL) ||
1661 strstart(uri, "vsock:", NULL)) {
1662 socket_start_outgoing_migration(s, p ? p : uri, &local_err);
1663 #ifdef CONFIG_RDMA
1664 } else if (strstart(uri, "rdma:", &p)) {
1665 rdma_start_outgoing_migration(s, p, &local_err);
1666 #endif
1667 } else if (strstart(uri, "exec:", &p)) {
1668 exec_start_outgoing_migration(s, p, &local_err);
1669 } else if (strstart(uri, "fd:", &p)) {
1670 fd_start_outgoing_migration(s, p, &local_err);
1671 } else {
1672 if (!(has_resume && resume)) {
1673 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1675 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1676 "a valid migration protocol");
1677 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1678 MIGRATION_STATUS_FAILED);
1679 block_cleanup_parameters();
1680 return;
1683 if (local_err) {
1684 if (!(has_resume && resume)) {
1685 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1687 migrate_fd_error(s, local_err);
1688 error_propagate(errp, local_err);
1689 return;
1693 void qmp_migrate_cancel(Error **errp)
1695 migration_cancel(NULL);
1698 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1700 MigrationState *s = migrate_get_current();
1701 if (s->state != state) {
1702 error_setg(errp, "Migration not in expected state: %s",
1703 MigrationStatus_str(s->state));
1704 return;
1706 qemu_sem_post(&s->pause_sem);
1709 /* migration thread support */
1711 * Something bad happened to the RP stream, mark an error
1712 * The caller shall print or trace something to indicate why
1714 static void mark_source_rp_bad(MigrationState *s)
1716 s->rp_state.error = true;
1719 static struct rp_cmd_args {
1720 ssize_t len; /* -1 = variable */
1721 const char *name;
1722 } rp_cmd_args[] = {
1723 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1724 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1725 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1726 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1727 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1728 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
1729 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
1730 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1734 * Process a request for pages received on the return path,
1735 * We're allowed to send more than requested (e.g. to round to our page size)
1736 * and we don't need to send pages that have already been sent.
1738 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1739 ram_addr_t start, size_t len)
1741 long our_host_ps = qemu_real_host_page_size();
1743 trace_migrate_handle_rp_req_pages(rbname, start, len);
1746 * Since we currently insist on matching page sizes, just sanity check
1747 * we're being asked for whole host pages.
1749 if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
1750 !QEMU_IS_ALIGNED(len, our_host_ps)) {
1751 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1752 " len: %zd", __func__, start, len);
1753 mark_source_rp_bad(ms);
1754 return;
1757 if (ram_save_queue_pages(rbname, start, len)) {
1758 mark_source_rp_bad(ms);
1762 /* Return true to retry, false to quit */
1763 static bool postcopy_pause_return_path_thread(MigrationState *s)
1765 trace_postcopy_pause_return_path();
1767 qemu_sem_wait(&s->postcopy_pause_rp_sem);
1769 trace_postcopy_pause_return_path_continued();
1771 return true;
1774 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
1776 RAMBlock *block = qemu_ram_block_by_name(block_name);
1778 if (!block) {
1779 error_report("%s: invalid block name '%s'", __func__, block_name);
1780 return -EINVAL;
1783 /* Fetch the received bitmap and refresh the dirty bitmap */
1784 return ram_dirty_bitmap_reload(s, block);
1787 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
1789 trace_source_return_path_thread_resume_ack(value);
1791 if (value != MIGRATION_RESUME_ACK_VALUE) {
1792 error_report("%s: illegal resume_ack value %"PRIu32,
1793 __func__, value);
1794 return -1;
1797 /* Now both sides are active. */
1798 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1799 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1801 /* Notify send thread that time to continue send pages */
1802 qemu_sem_post(&s->rp_state.rp_sem);
1804 return 0;
1808 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
1809 * existed) in a safe way.
1811 static void migration_release_dst_files(MigrationState *ms)
1813 QEMUFile *file;
1815 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
1817 * Reset the from_dst_file pointer first before releasing it, as we
1818 * can't block within lock section
1820 file = ms->rp_state.from_dst_file;
1821 ms->rp_state.from_dst_file = NULL;
1825 * Do the same to postcopy fast path socket too if there is. No
1826 * locking needed because this qemufile should only be managed by
1827 * return path thread.
1829 if (ms->postcopy_qemufile_src) {
1830 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
1831 qemu_file_shutdown(ms->postcopy_qemufile_src);
1832 qemu_fclose(ms->postcopy_qemufile_src);
1833 ms->postcopy_qemufile_src = NULL;
1836 qemu_fclose(file);
1840 * Handles messages sent on the return path towards the source VM
1843 static void *source_return_path_thread(void *opaque)
1845 MigrationState *ms = opaque;
1846 QEMUFile *rp = ms->rp_state.from_dst_file;
1847 uint16_t header_len, header_type;
1848 uint8_t buf[512];
1849 uint32_t tmp32, sibling_error;
1850 ram_addr_t start = 0; /* =0 to silence warning */
1851 size_t len = 0, expected_len;
1852 int res;
1854 trace_source_return_path_thread_entry();
1855 rcu_register_thread();
1857 retry:
1858 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1859 migration_is_setup_or_active(ms->state)) {
1860 trace_source_return_path_thread_loop_top();
1861 header_type = qemu_get_be16(rp);
1862 header_len = qemu_get_be16(rp);
1864 if (qemu_file_get_error(rp)) {
1865 mark_source_rp_bad(ms);
1866 goto out;
1869 if (header_type >= MIG_RP_MSG_MAX ||
1870 header_type == MIG_RP_MSG_INVALID) {
1871 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1872 header_type, header_len);
1873 mark_source_rp_bad(ms);
1874 goto out;
1877 if ((rp_cmd_args[header_type].len != -1 &&
1878 header_len != rp_cmd_args[header_type].len) ||
1879 header_len > sizeof(buf)) {
1880 error_report("RP: Received '%s' message (0x%04x) with"
1881 "incorrect length %d expecting %zu",
1882 rp_cmd_args[header_type].name, header_type, header_len,
1883 (size_t)rp_cmd_args[header_type].len);
1884 mark_source_rp_bad(ms);
1885 goto out;
1888 /* We know we've got a valid header by this point */
1889 res = qemu_get_buffer(rp, buf, header_len);
1890 if (res != header_len) {
1891 error_report("RP: Failed reading data for message 0x%04x"
1892 " read %d expected %d",
1893 header_type, res, header_len);
1894 mark_source_rp_bad(ms);
1895 goto out;
1898 /* OK, we have the message and the data */
1899 switch (header_type) {
1900 case MIG_RP_MSG_SHUT:
1901 sibling_error = ldl_be_p(buf);
1902 trace_source_return_path_thread_shut(sibling_error);
1903 if (sibling_error) {
1904 error_report("RP: Sibling indicated error %d", sibling_error);
1905 mark_source_rp_bad(ms);
1908 * We'll let the main thread deal with closing the RP
1909 * we could do a shutdown(2) on it, but we're the only user
1910 * anyway, so there's nothing gained.
1912 goto out;
1914 case MIG_RP_MSG_PONG:
1915 tmp32 = ldl_be_p(buf);
1916 trace_source_return_path_thread_pong(tmp32);
1917 qemu_sem_post(&ms->rp_state.rp_pong_acks);
1918 break;
1920 case MIG_RP_MSG_REQ_PAGES:
1921 start = ldq_be_p(buf);
1922 len = ldl_be_p(buf + 8);
1923 migrate_handle_rp_req_pages(ms, NULL, start, len);
1924 break;
1926 case MIG_RP_MSG_REQ_PAGES_ID:
1927 expected_len = 12 + 1; /* header + termination */
1929 if (header_len >= expected_len) {
1930 start = ldq_be_p(buf);
1931 len = ldl_be_p(buf + 8);
1932 /* Now we expect an idstr */
1933 tmp32 = buf[12]; /* Length of the following idstr */
1934 buf[13 + tmp32] = '\0';
1935 expected_len += tmp32;
1937 if (header_len != expected_len) {
1938 error_report("RP: Req_Page_id with length %d expecting %zd",
1939 header_len, expected_len);
1940 mark_source_rp_bad(ms);
1941 goto out;
1943 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1944 break;
1946 case MIG_RP_MSG_RECV_BITMAP:
1947 if (header_len < 1) {
1948 error_report("%s: missing block name", __func__);
1949 mark_source_rp_bad(ms);
1950 goto out;
1952 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
1953 buf[buf[0] + 1] = '\0';
1954 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
1955 mark_source_rp_bad(ms);
1956 goto out;
1958 break;
1960 case MIG_RP_MSG_RESUME_ACK:
1961 tmp32 = ldl_be_p(buf);
1962 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
1963 mark_source_rp_bad(ms);
1964 goto out;
1966 break;
1968 default:
1969 break;
1973 out:
1974 res = qemu_file_get_error(rp);
1975 if (res) {
1976 if (res && migration_in_postcopy()) {
1978 * Maybe there is something we can do: it looks like a
1979 * network down issue, and we pause for a recovery.
1981 migration_release_dst_files(ms);
1982 rp = NULL;
1983 if (postcopy_pause_return_path_thread(ms)) {
1985 * Reload rp, reset the rest. Referencing it is safe since
1986 * it's reset only by us above, or when migration completes
1988 rp = ms->rp_state.from_dst_file;
1989 ms->rp_state.error = false;
1990 goto retry;
1994 trace_source_return_path_thread_bad_end();
1995 mark_source_rp_bad(ms);
1998 trace_source_return_path_thread_end();
1999 migration_release_dst_files(ms);
2000 rcu_unregister_thread();
2001 return NULL;
2004 static int open_return_path_on_source(MigrationState *ms,
2005 bool create_thread)
2007 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2008 if (!ms->rp_state.from_dst_file) {
2009 return -1;
2012 trace_open_return_path_on_source();
2014 if (!create_thread) {
2015 /* We're done */
2016 return 0;
2019 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2020 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2021 ms->rp_state.rp_thread_created = true;
2023 trace_open_return_path_on_source_continue();
2025 return 0;
2028 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2029 static int await_return_path_close_on_source(MigrationState *ms)
2032 * If this is a normal exit then the destination will send a SHUT and the
2033 * rp_thread will exit, however if there's an error we need to cause
2034 * it to exit.
2036 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2038 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2039 * waiting for the destination.
2041 qemu_file_shutdown(ms->rp_state.from_dst_file);
2042 mark_source_rp_bad(ms);
2044 trace_await_return_path_close_on_source_joining();
2045 qemu_thread_join(&ms->rp_state.rp_thread);
2046 ms->rp_state.rp_thread_created = false;
2047 trace_await_return_path_close_on_source_close();
2048 return ms->rp_state.error;
2051 static inline void
2052 migration_wait_main_channel(MigrationState *ms)
2054 /* Wait until one PONG message received */
2055 qemu_sem_wait(&ms->rp_state.rp_pong_acks);
2059 * Switch from normal iteration to postcopy
2060 * Returns non-0 on error
2062 static int postcopy_start(MigrationState *ms)
2064 int ret;
2065 QIOChannelBuffer *bioc;
2066 QEMUFile *fb;
2067 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2068 uint64_t bandwidth = migrate_max_postcopy_bandwidth();
2069 bool restart_block = false;
2070 int cur_state = MIGRATION_STATUS_ACTIVE;
2072 if (migrate_postcopy_preempt()) {
2073 migration_wait_main_channel(ms);
2074 if (postcopy_preempt_establish_channel(ms)) {
2075 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
2076 return -1;
2080 if (!migrate_pause_before_switchover()) {
2081 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2082 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2085 trace_postcopy_start();
2086 qemu_mutex_lock_iothread();
2087 trace_postcopy_start_set_run();
2089 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2090 global_state_store();
2091 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2092 if (ret < 0) {
2093 goto fail;
2096 ret = migration_maybe_pause(ms, &cur_state,
2097 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2098 if (ret < 0) {
2099 goto fail;
2102 ret = bdrv_inactivate_all();
2103 if (ret < 0) {
2104 goto fail;
2106 restart_block = true;
2109 * Cause any non-postcopiable, but iterative devices to
2110 * send out their final data.
2112 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2115 * in Finish migrate and with the io-lock held everything should
2116 * be quiet, but we've potentially still got dirty pages and we
2117 * need to tell the destination to throw any pages it's already received
2118 * that are dirty
2120 if (migrate_postcopy_ram()) {
2121 ram_postcopy_send_discard_bitmap(ms);
2125 * send rest of state - note things that are doing postcopy
2126 * will notice we're in POSTCOPY_ACTIVE and not actually
2127 * wrap their state up here
2129 /* 0 max-postcopy-bandwidth means unlimited */
2130 if (!bandwidth) {
2131 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2132 } else {
2133 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2135 if (migrate_postcopy_ram()) {
2136 /* Ping just for debugging, helps line traces up */
2137 qemu_savevm_send_ping(ms->to_dst_file, 2);
2141 * While loading the device state we may trigger page transfer
2142 * requests and the fd must be free to process those, and thus
2143 * the destination must read the whole device state off the fd before
2144 * it starts processing it. Unfortunately the ad-hoc migration format
2145 * doesn't allow the destination to know the size to read without fully
2146 * parsing it through each devices load-state code (especially the open
2147 * coded devices that use get/put).
2148 * So we wrap the device state up in a package with a length at the start;
2149 * to do this we use a qemu_buf to hold the whole of the device state.
2151 bioc = qio_channel_buffer_new(4096);
2152 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2153 fb = qemu_file_new_output(QIO_CHANNEL(bioc));
2154 object_unref(OBJECT(bioc));
2157 * Make sure the receiver can get incoming pages before we send the rest
2158 * of the state
2160 qemu_savevm_send_postcopy_listen(fb);
2162 qemu_savevm_state_complete_precopy(fb, false, false);
2163 if (migrate_postcopy_ram()) {
2164 qemu_savevm_send_ping(fb, 3);
2167 qemu_savevm_send_postcopy_run(fb);
2169 /* <><> end of stuff going into the package */
2171 /* Last point of recovery; as soon as we send the package the destination
2172 * can open devices and potentially start running.
2173 * Lets just check again we've not got any errors.
2175 ret = qemu_file_get_error(ms->to_dst_file);
2176 if (ret) {
2177 error_report("postcopy_start: Migration stream errored (pre package)");
2178 goto fail_closefb;
2181 restart_block = false;
2183 /* Now send that blob */
2184 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2185 goto fail_closefb;
2187 qemu_fclose(fb);
2189 /* Send a notify to give a chance for anything that needs to happen
2190 * at the transition to postcopy and after the device state; in particular
2191 * spice needs to trigger a transition now
2193 ms->postcopy_after_devices = true;
2194 notifier_list_notify(&migration_state_notifiers, ms);
2196 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2198 qemu_mutex_unlock_iothread();
2200 if (migrate_postcopy_ram()) {
2202 * Although this ping is just for debug, it could potentially be
2203 * used for getting a better measurement of downtime at the source.
2205 qemu_savevm_send_ping(ms->to_dst_file, 4);
2208 if (migrate_release_ram()) {
2209 ram_postcopy_migrated_memory_release(ms);
2212 ret = qemu_file_get_error(ms->to_dst_file);
2213 if (ret) {
2214 error_report("postcopy_start: Migration stream errored");
2215 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2216 MIGRATION_STATUS_FAILED);
2219 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2221 return ret;
2223 fail_closefb:
2224 qemu_fclose(fb);
2225 fail:
2226 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2227 MIGRATION_STATUS_FAILED);
2228 if (restart_block) {
2229 /* A failure happened early enough that we know the destination hasn't
2230 * accessed block devices, so we're safe to recover.
2232 Error *local_err = NULL;
2234 bdrv_activate_all(&local_err);
2235 if (local_err) {
2236 error_report_err(local_err);
2239 qemu_mutex_unlock_iothread();
2240 return -1;
2244 * migration_maybe_pause: Pause if required to by
2245 * migrate_pause_before_switchover called with the iothread locked
2246 * Returns: 0 on success
2248 static int migration_maybe_pause(MigrationState *s,
2249 int *current_active_state,
2250 int new_state)
2252 if (!migrate_pause_before_switchover()) {
2253 return 0;
2256 /* Since leaving this state is not atomic with posting the semaphore
2257 * it's possible that someone could have issued multiple migrate_continue
2258 * and the semaphore is incorrectly positive at this point;
2259 * the docs say it's undefined to reinit a semaphore that's already
2260 * init'd, so use timedwait to eat up any existing posts.
2262 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2263 /* This block intentionally left blank */
2267 * If the migration is cancelled when it is in the completion phase,
2268 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2269 * So we don't need to wait a semaphore, otherwise we would always
2270 * wait for the 'pause_sem' semaphore.
2272 if (s->state != MIGRATION_STATUS_CANCELLING) {
2273 qemu_mutex_unlock_iothread();
2274 migrate_set_state(&s->state, *current_active_state,
2275 MIGRATION_STATUS_PRE_SWITCHOVER);
2276 qemu_sem_wait(&s->pause_sem);
2277 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2278 new_state);
2279 *current_active_state = new_state;
2280 qemu_mutex_lock_iothread();
2283 return s->state == new_state ? 0 : -EINVAL;
2287 * migration_completion: Used by migration_thread when there's not much left.
2288 * The caller 'breaks' the loop when this returns.
2290 * @s: Current migration state
2292 static void migration_completion(MigrationState *s)
2294 int ret;
2295 int current_active_state = s->state;
2297 if (s->state == MIGRATION_STATUS_ACTIVE) {
2298 qemu_mutex_lock_iothread();
2299 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2300 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2301 s->vm_was_running = runstate_is_running();
2302 ret = global_state_store();
2304 if (!ret) {
2305 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2306 trace_migration_completion_vm_stop(ret);
2307 if (ret >= 0) {
2308 ret = migration_maybe_pause(s, &current_active_state,
2309 MIGRATION_STATUS_DEVICE);
2311 if (ret >= 0) {
2313 * Inactivate disks except in COLO, and track that we
2314 * have done so in order to remember to reactivate
2315 * them if migration fails or is cancelled.
2317 s->block_inactive = !migrate_colo();
2318 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2319 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2320 s->block_inactive);
2323 qemu_mutex_unlock_iothread();
2325 if (ret < 0) {
2326 goto fail;
2328 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2329 trace_migration_completion_postcopy_end();
2331 qemu_mutex_lock_iothread();
2332 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2333 qemu_mutex_unlock_iothread();
2336 * Shutdown the postcopy fast path thread. This is only needed
2337 * when dest QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need
2338 * this.
2340 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
2341 postcopy_preempt_shutdown_file(s);
2344 trace_migration_completion_postcopy_end_after_complete();
2345 } else {
2346 goto fail;
2350 * If rp was opened we must clean up the thread before
2351 * cleaning everything else up (since if there are no failures
2352 * it will wait for the destination to send it's status in
2353 * a SHUT command).
2355 if (s->rp_state.rp_thread_created) {
2356 int rp_error;
2357 trace_migration_return_path_end_before();
2358 rp_error = await_return_path_close_on_source(s);
2359 trace_migration_return_path_end_after(rp_error);
2360 if (rp_error) {
2361 goto fail;
2365 if (qemu_file_get_error(s->to_dst_file)) {
2366 trace_migration_completion_file_err();
2367 goto fail;
2370 if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
2371 /* COLO does not support postcopy */
2372 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
2373 MIGRATION_STATUS_COLO);
2374 } else {
2375 migrate_set_state(&s->state, current_active_state,
2376 MIGRATION_STATUS_COMPLETED);
2379 return;
2381 fail:
2382 if (s->block_inactive && (s->state == MIGRATION_STATUS_ACTIVE ||
2383 s->state == MIGRATION_STATUS_DEVICE)) {
2385 * If not doing postcopy, vm_start() will be called: let's
2386 * regain control on images.
2388 Error *local_err = NULL;
2390 qemu_mutex_lock_iothread();
2391 bdrv_activate_all(&local_err);
2392 if (local_err) {
2393 error_report_err(local_err);
2394 } else {
2395 s->block_inactive = false;
2397 qemu_mutex_unlock_iothread();
2400 migrate_set_state(&s->state, current_active_state,
2401 MIGRATION_STATUS_FAILED);
2405 * bg_migration_completion: Used by bg_migration_thread when after all the
2406 * RAM has been saved. The caller 'breaks' the loop when this returns.
2408 * @s: Current migration state
2410 static void bg_migration_completion(MigrationState *s)
2412 int current_active_state = s->state;
2415 * Stop tracking RAM writes - un-protect memory, un-register UFFD
2416 * memory ranges, flush kernel wait queues and wake up threads
2417 * waiting for write fault to be resolved.
2419 ram_write_tracking_stop();
2421 if (s->state == MIGRATION_STATUS_ACTIVE) {
2423 * By this moment we have RAM content saved into the migration stream.
2424 * The next step is to flush the non-RAM content (device state)
2425 * right after the ram content. The device state has been stored into
2426 * the temporary buffer before RAM saving started.
2428 qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
2429 qemu_fflush(s->to_dst_file);
2430 } else if (s->state == MIGRATION_STATUS_CANCELLING) {
2431 goto fail;
2434 if (qemu_file_get_error(s->to_dst_file)) {
2435 trace_migration_completion_file_err();
2436 goto fail;
2439 migrate_set_state(&s->state, current_active_state,
2440 MIGRATION_STATUS_COMPLETED);
2441 return;
2443 fail:
2444 migrate_set_state(&s->state, current_active_state,
2445 MIGRATION_STATUS_FAILED);
2448 typedef enum MigThrError {
2449 /* No error detected */
2450 MIG_THR_ERR_NONE = 0,
2451 /* Detected error, but resumed successfully */
2452 MIG_THR_ERR_RECOVERED = 1,
2453 /* Detected fatal error, need to exit */
2454 MIG_THR_ERR_FATAL = 2,
2455 } MigThrError;
2457 static int postcopy_resume_handshake(MigrationState *s)
2459 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2461 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2462 qemu_sem_wait(&s->rp_state.rp_sem);
2465 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2466 return 0;
2469 return -1;
2472 /* Return zero if success, or <0 for error */
2473 static int postcopy_do_resume(MigrationState *s)
2475 int ret;
2478 * Call all the resume_prepare() hooks, so that modules can be
2479 * ready for the migration resume.
2481 ret = qemu_savevm_state_resume_prepare(s);
2482 if (ret) {
2483 error_report("%s: resume_prepare() failure detected: %d",
2484 __func__, ret);
2485 return ret;
2489 * If preempt is enabled, re-establish the preempt channel. Note that
2490 * we do it after resume prepare to make sure the main channel will be
2491 * created before the preempt channel. E.g. with weak network, the
2492 * dest QEMU may get messed up with the preempt and main channels on
2493 * the order of connection setup. This guarantees the correct order.
2495 ret = postcopy_preempt_establish_channel(s);
2496 if (ret) {
2497 error_report("%s: postcopy_preempt_establish_channel(): %d",
2498 __func__, ret);
2499 return ret;
2503 * Last handshake with destination on the resume (destination will
2504 * switch to postcopy-active afterwards)
2506 ret = postcopy_resume_handshake(s);
2507 if (ret) {
2508 error_report("%s: handshake failed: %d", __func__, ret);
2509 return ret;
2512 return 0;
2516 * We don't return until we are in a safe state to continue current
2517 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2518 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2520 static MigThrError postcopy_pause(MigrationState *s)
2522 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2524 while (true) {
2525 QEMUFile *file;
2528 * Current channel is possibly broken. Release it. Note that this is
2529 * guaranteed even without lock because to_dst_file should only be
2530 * modified by the migration thread. That also guarantees that the
2531 * unregister of yank is safe too without the lock. It should be safe
2532 * even to be within the qemu_file_lock, but we didn't do that to avoid
2533 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2534 * the qemu_file_lock critical section as small as possible.
2536 assert(s->to_dst_file);
2537 migration_ioc_unregister_yank_from_file(s->to_dst_file);
2538 qemu_mutex_lock(&s->qemu_file_lock);
2539 file = s->to_dst_file;
2540 s->to_dst_file = NULL;
2541 qemu_mutex_unlock(&s->qemu_file_lock);
2543 qemu_file_shutdown(file);
2544 qemu_fclose(file);
2546 migrate_set_state(&s->state, s->state,
2547 MIGRATION_STATUS_POSTCOPY_PAUSED);
2549 error_report("Detected IO failure for postcopy. "
2550 "Migration paused.");
2553 * We wait until things fixed up. Then someone will setup the
2554 * status back for us.
2556 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2557 qemu_sem_wait(&s->postcopy_pause_sem);
2560 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2561 /* Woken up by a recover procedure. Give it a shot */
2564 * Firstly, let's wake up the return path now, with a new
2565 * return path channel.
2567 qemu_sem_post(&s->postcopy_pause_rp_sem);
2569 /* Do the resume logic */
2570 if (postcopy_do_resume(s) == 0) {
2571 /* Let's continue! */
2572 trace_postcopy_pause_continued();
2573 return MIG_THR_ERR_RECOVERED;
2574 } else {
2576 * Something wrong happened during the recovery, let's
2577 * pause again. Pause is always better than throwing
2578 * data away.
2580 continue;
2582 } else {
2583 /* This is not right... Time to quit. */
2584 return MIG_THR_ERR_FATAL;
2589 static MigThrError migration_detect_error(MigrationState *s)
2591 int ret;
2592 int state = s->state;
2593 Error *local_error = NULL;
2595 if (state == MIGRATION_STATUS_CANCELLING ||
2596 state == MIGRATION_STATUS_CANCELLED) {
2597 /* End the migration, but don't set the state to failed */
2598 return MIG_THR_ERR_FATAL;
2602 * Try to detect any file errors. Note that postcopy_qemufile_src will
2603 * be NULL when postcopy preempt is not enabled.
2605 ret = qemu_file_get_error_obj_any(s->to_dst_file,
2606 s->postcopy_qemufile_src,
2607 &local_error);
2608 if (!ret) {
2609 /* Everything is fine */
2610 assert(!local_error);
2611 return MIG_THR_ERR_NONE;
2614 if (local_error) {
2615 migrate_set_error(s, local_error);
2616 error_free(local_error);
2619 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
2621 * For postcopy, we allow the network to be down for a
2622 * while. After that, it can be continued by a
2623 * recovery phase.
2625 return postcopy_pause(s);
2626 } else {
2628 * For precopy (or postcopy with error outside IO), we fail
2629 * with no time.
2631 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
2632 trace_migration_thread_file_err();
2634 /* Time to stop the migration, now. */
2635 return MIG_THR_ERR_FATAL;
2639 /* How many bytes have we transferred since the beginning of the migration */
2640 static uint64_t migration_total_bytes(MigrationState *s)
2642 return qemu_file_total_transferred(s->to_dst_file) +
2643 stat64_get(&mig_stats.multifd_bytes);
2646 static void migration_calculate_complete(MigrationState *s)
2648 uint64_t bytes = migration_total_bytes(s);
2649 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2650 int64_t transfer_time;
2652 s->total_time = end_time - s->start_time;
2653 if (!s->downtime) {
2655 * It's still not set, so we are precopy migration. For
2656 * postcopy, downtime is calculated during postcopy_start().
2658 s->downtime = end_time - s->downtime_start;
2661 transfer_time = s->total_time - s->setup_time;
2662 if (transfer_time) {
2663 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
2667 static void update_iteration_initial_status(MigrationState *s)
2670 * Update these three fields at the same time to avoid mismatch info lead
2671 * wrong speed calculation.
2673 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2674 s->iteration_initial_bytes = migration_total_bytes(s);
2675 s->iteration_initial_pages = ram_get_total_transferred_pages();
2678 static void migration_update_counters(MigrationState *s,
2679 int64_t current_time)
2681 uint64_t transferred, transferred_pages, time_spent;
2682 uint64_t current_bytes; /* bytes transferred since the beginning */
2683 double bandwidth;
2685 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2686 return;
2689 current_bytes = migration_total_bytes(s);
2690 transferred = current_bytes - s->iteration_initial_bytes;
2691 time_spent = current_time - s->iteration_start_time;
2692 bandwidth = (double)transferred / time_spent;
2693 s->threshold_size = bandwidth * migrate_downtime_limit();
2695 s->mbps = (((double) transferred * 8.0) /
2696 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2698 transferred_pages = ram_get_total_transferred_pages() -
2699 s->iteration_initial_pages;
2700 s->pages_per_second = (double) transferred_pages /
2701 (((double) time_spent / 1000.0));
2704 * if we haven't sent anything, we don't want to
2705 * recalculate. 10000 is a small enough number for our purposes
2707 if (stat64_get(&mig_stats.dirty_pages_rate) &&
2708 transferred > 10000) {
2709 s->expected_downtime =
2710 stat64_get(&mig_stats.dirty_bytes_last_sync) / bandwidth;
2713 qemu_file_reset_rate_limit(s->to_dst_file);
2715 update_iteration_initial_status(s);
2717 trace_migrate_transferred(transferred, time_spent,
2718 bandwidth, s->threshold_size);
2721 /* Migration thread iteration status */
2722 typedef enum {
2723 MIG_ITERATE_RESUME, /* Resume current iteration */
2724 MIG_ITERATE_SKIP, /* Skip current iteration */
2725 MIG_ITERATE_BREAK, /* Break the loop */
2726 } MigIterateState;
2729 * Return true if continue to the next iteration directly, false
2730 * otherwise.
2732 static MigIterateState migration_iteration_run(MigrationState *s)
2734 uint64_t must_precopy, can_postcopy;
2735 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2737 qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
2738 uint64_t pending_size = must_precopy + can_postcopy;
2740 trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
2742 if (must_precopy <= s->threshold_size) {
2743 qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
2744 pending_size = must_precopy + can_postcopy;
2745 trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
2748 if (!pending_size || pending_size < s->threshold_size) {
2749 trace_migration_thread_low_pending(pending_size);
2750 migration_completion(s);
2751 return MIG_ITERATE_BREAK;
2754 /* Still a significant amount to transfer */
2755 if (!in_postcopy && must_precopy <= s->threshold_size &&
2756 qatomic_read(&s->start_postcopy)) {
2757 if (postcopy_start(s)) {
2758 error_report("%s: postcopy failed to start", __func__);
2760 return MIG_ITERATE_SKIP;
2763 /* Just another iteration step */
2764 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
2765 return MIG_ITERATE_RESUME;
2768 static void migration_iteration_finish(MigrationState *s)
2770 /* If we enabled cpu throttling for auto-converge, turn it off. */
2771 cpu_throttle_stop();
2773 qemu_mutex_lock_iothread();
2774 switch (s->state) {
2775 case MIGRATION_STATUS_COMPLETED:
2776 migration_calculate_complete(s);
2777 runstate_set(RUN_STATE_POSTMIGRATE);
2778 break;
2779 case MIGRATION_STATUS_COLO:
2780 if (!migrate_colo()) {
2781 error_report("%s: critical error: calling COLO code without "
2782 "COLO enabled", __func__);
2784 migrate_start_colo_process(s);
2785 s->vm_was_running = true;
2786 /* Fallthrough */
2787 case MIGRATION_STATUS_FAILED:
2788 case MIGRATION_STATUS_CANCELLED:
2789 case MIGRATION_STATUS_CANCELLING:
2790 if (s->vm_was_running) {
2791 if (!runstate_check(RUN_STATE_SHUTDOWN)) {
2792 vm_start();
2794 } else {
2795 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2796 runstate_set(RUN_STATE_POSTMIGRATE);
2799 break;
2801 default:
2802 /* Should not reach here, but if so, forgive the VM. */
2803 error_report("%s: Unknown ending state %d", __func__, s->state);
2804 break;
2806 migrate_fd_cleanup_schedule(s);
2807 qemu_mutex_unlock_iothread();
2810 static void bg_migration_iteration_finish(MigrationState *s)
2812 qemu_mutex_lock_iothread();
2813 switch (s->state) {
2814 case MIGRATION_STATUS_COMPLETED:
2815 migration_calculate_complete(s);
2816 break;
2818 case MIGRATION_STATUS_ACTIVE:
2819 case MIGRATION_STATUS_FAILED:
2820 case MIGRATION_STATUS_CANCELLED:
2821 case MIGRATION_STATUS_CANCELLING:
2822 break;
2824 default:
2825 /* Should not reach here, but if so, forgive the VM. */
2826 error_report("%s: Unknown ending state %d", __func__, s->state);
2827 break;
2830 migrate_fd_cleanup_schedule(s);
2831 qemu_mutex_unlock_iothread();
2835 * Return true if continue to the next iteration directly, false
2836 * otherwise.
2838 static MigIterateState bg_migration_iteration_run(MigrationState *s)
2840 int res;
2842 res = qemu_savevm_state_iterate(s->to_dst_file, false);
2843 if (res > 0) {
2844 bg_migration_completion(s);
2845 return MIG_ITERATE_BREAK;
2848 return MIG_ITERATE_RESUME;
2851 void migration_make_urgent_request(void)
2853 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
2856 void migration_consume_urgent_request(void)
2858 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
2861 /* Returns true if the rate limiting was broken by an urgent request */
2862 bool migration_rate_limit(void)
2864 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2865 MigrationState *s = migrate_get_current();
2867 bool urgent = false;
2868 migration_update_counters(s, now);
2869 if (qemu_file_rate_limit(s->to_dst_file)) {
2871 if (qemu_file_get_error(s->to_dst_file)) {
2872 return false;
2875 * Wait for a delay to do rate limiting OR
2876 * something urgent to post the semaphore.
2878 int ms = s->iteration_start_time + BUFFER_DELAY - now;
2879 trace_migration_rate_limit_pre(ms);
2880 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
2882 * We were woken by one or more urgent things but
2883 * the timedwait will have consumed one of them.
2884 * The service routine for the urgent wake will dec
2885 * the semaphore itself for each item it consumes,
2886 * so add this one we just eat back.
2888 qemu_sem_post(&s->rate_limit_sem);
2889 urgent = true;
2891 trace_migration_rate_limit_post(urgent);
2893 return urgent;
2897 * if failover devices are present, wait they are completely
2898 * unplugged
2901 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
2902 int new_state)
2904 if (qemu_savevm_state_guest_unplug_pending()) {
2905 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
2907 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
2908 qemu_savevm_state_guest_unplug_pending()) {
2909 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
2911 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
2912 int timeout = 120; /* 30 seconds */
2914 * migration has been canceled
2915 * but as we have started an unplug we must wait the end
2916 * to be able to plug back the card
2918 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
2919 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
2921 if (qemu_savevm_state_guest_unplug_pending() &&
2922 !qtest_enabled()) {
2923 warn_report("migration: partially unplugged device on "
2924 "failure");
2928 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
2929 } else {
2930 migrate_set_state(&s->state, old_state, new_state);
2935 * Master migration thread on the source VM.
2936 * It drives the migration and pumps the data down the outgoing channel.
2938 static void *migration_thread(void *opaque)
2940 MigrationState *s = opaque;
2941 MigrationThread *thread = NULL;
2942 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2943 MigThrError thr_error;
2944 bool urgent = false;
2946 thread = MigrationThreadAdd("live_migration", qemu_get_thread_id());
2948 rcu_register_thread();
2950 object_ref(OBJECT(s));
2951 update_iteration_initial_status(s);
2953 qemu_savevm_state_header(s->to_dst_file);
2956 * If we opened the return path, we need to make sure dst has it
2957 * opened as well.
2959 if (s->rp_state.rp_thread_created) {
2960 /* Now tell the dest that it should open its end so it can reply */
2961 qemu_savevm_send_open_return_path(s->to_dst_file);
2963 /* And do a ping that will make stuff easier to debug */
2964 qemu_savevm_send_ping(s->to_dst_file, 1);
2967 if (migrate_postcopy()) {
2969 * Tell the destination that we *might* want to do postcopy later;
2970 * if the other end can't do postcopy it should fail now, nice and
2971 * early.
2973 qemu_savevm_send_postcopy_advise(s->to_dst_file);
2976 if (migrate_colo()) {
2977 /* Notify migration destination that we enable COLO */
2978 qemu_savevm_send_colo_enable(s->to_dst_file);
2981 qemu_savevm_state_setup(s->to_dst_file);
2983 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
2984 MIGRATION_STATUS_ACTIVE);
2986 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
2988 trace_migration_thread_setup_complete();
2990 while (migration_is_active(s)) {
2991 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
2992 MigIterateState iter_state = migration_iteration_run(s);
2993 if (iter_state == MIG_ITERATE_SKIP) {
2994 continue;
2995 } else if (iter_state == MIG_ITERATE_BREAK) {
2996 break;
3001 * Try to detect any kind of failures, and see whether we
3002 * should stop the migration now.
3004 thr_error = migration_detect_error(s);
3005 if (thr_error == MIG_THR_ERR_FATAL) {
3006 /* Stop migration */
3007 break;
3008 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3010 * Just recovered from a e.g. network failure, reset all
3011 * the local variables. This is important to avoid
3012 * breaking transferred_bytes and bandwidth calculation
3014 update_iteration_initial_status(s);
3017 urgent = migration_rate_limit();
3020 trace_migration_thread_after_loop();
3021 migration_iteration_finish(s);
3022 object_unref(OBJECT(s));
3023 rcu_unregister_thread();
3024 MigrationThreadDel(thread);
3025 return NULL;
3028 static void bg_migration_vm_start_bh(void *opaque)
3030 MigrationState *s = opaque;
3032 qemu_bh_delete(s->vm_start_bh);
3033 s->vm_start_bh = NULL;
3035 vm_start();
3036 s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
3040 * Background snapshot thread, based on live migration code.
3041 * This is an alternative implementation of live migration mechanism
3042 * introduced specifically to support background snapshots.
3044 * It takes advantage of userfault_fd write protection mechanism introduced
3045 * in v5.7 kernel. Compared to existing dirty page logging migration much
3046 * lesser stream traffic is produced resulting in smaller snapshot images,
3047 * simply cause of no page duplicates can get into the stream.
3049 * Another key point is that generated vmstate stream reflects machine state
3050 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3051 * mechanism, which effectively results in that saved snapshot is the state of VM
3052 * at the end of the process.
3054 static void *bg_migration_thread(void *opaque)
3056 MigrationState *s = opaque;
3057 int64_t setup_start;
3058 MigThrError thr_error;
3059 QEMUFile *fb;
3060 bool early_fail = true;
3062 rcu_register_thread();
3063 object_ref(OBJECT(s));
3065 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
3067 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3069 * We want to save vmstate for the moment when migration has been
3070 * initiated but also we want to save RAM content while VM is running.
3071 * The RAM content should appear first in the vmstate. So, we first
3072 * stash the non-RAM part of the vmstate to the temporary buffer,
3073 * then write RAM part of the vmstate to the migration stream
3074 * with vCPUs running and, finally, write stashed non-RAM part of
3075 * the vmstate from the buffer to the migration stream.
3077 s->bioc = qio_channel_buffer_new(512 * 1024);
3078 qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
3079 fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
3080 object_unref(OBJECT(s->bioc));
3082 update_iteration_initial_status(s);
3085 * Prepare for tracking memory writes with UFFD-WP - populate
3086 * RAM pages before protecting.
3088 #ifdef __linux__
3089 ram_write_tracking_prepare();
3090 #endif
3092 qemu_savevm_state_header(s->to_dst_file);
3093 qemu_savevm_state_setup(s->to_dst_file);
3095 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3096 MIGRATION_STATUS_ACTIVE);
3098 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3100 trace_migration_thread_setup_complete();
3101 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3103 qemu_mutex_lock_iothread();
3106 * If VM is currently in suspended state, then, to make a valid runstate
3107 * transition in vm_stop_force_state() we need to wakeup it up.
3109 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3110 s->vm_was_running = runstate_is_running();
3112 if (global_state_store()) {
3113 goto fail;
3115 /* Forcibly stop VM before saving state of vCPUs and devices */
3116 if (vm_stop_force_state(RUN_STATE_PAUSED)) {
3117 goto fail;
3120 * Put vCPUs in sync with shadow context structures, then
3121 * save their state to channel-buffer along with devices.
3123 cpu_synchronize_all_states();
3124 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
3125 goto fail;
3128 * Since we are going to get non-iterable state data directly
3129 * from s->bioc->data, explicit flush is needed here.
3131 qemu_fflush(fb);
3133 /* Now initialize UFFD context and start tracking RAM writes */
3134 if (ram_write_tracking_start()) {
3135 goto fail;
3137 early_fail = false;
3140 * Start VM from BH handler to avoid write-fault lock here.
3141 * UFFD-WP protection for the whole RAM is already enabled so
3142 * calling VM state change notifiers from vm_start() would initiate
3143 * writes to virtio VQs memory which is in write-protected region.
3145 s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
3146 qemu_bh_schedule(s->vm_start_bh);
3148 qemu_mutex_unlock_iothread();
3150 while (migration_is_active(s)) {
3151 MigIterateState iter_state = bg_migration_iteration_run(s);
3152 if (iter_state == MIG_ITERATE_SKIP) {
3153 continue;
3154 } else if (iter_state == MIG_ITERATE_BREAK) {
3155 break;
3159 * Try to detect any kind of failures, and see whether we
3160 * should stop the migration now.
3162 thr_error = migration_detect_error(s);
3163 if (thr_error == MIG_THR_ERR_FATAL) {
3164 /* Stop migration */
3165 break;
3168 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
3171 trace_migration_thread_after_loop();
3173 fail:
3174 if (early_fail) {
3175 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3176 MIGRATION_STATUS_FAILED);
3177 qemu_mutex_unlock_iothread();
3180 bg_migration_iteration_finish(s);
3182 qemu_fclose(fb);
3183 object_unref(OBJECT(s));
3184 rcu_unregister_thread();
3186 return NULL;
3189 void migrate_fd_connect(MigrationState *s, Error *error_in)
3191 Error *local_err = NULL;
3192 uint64_t rate_limit;
3193 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3196 * If there's a previous error, free it and prepare for another one.
3197 * Meanwhile if migration completes successfully, there won't have an error
3198 * dumped when calling migrate_fd_cleanup().
3200 migrate_error_free(s);
3202 s->expected_downtime = migrate_downtime_limit();
3203 if (resume) {
3204 assert(s->cleanup_bh);
3205 } else {
3206 assert(!s->cleanup_bh);
3207 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
3209 if (error_in) {
3210 migrate_fd_error(s, error_in);
3211 if (resume) {
3213 * Don't do cleanup for resume if channel is invalid, but only dump
3214 * the error. We wait for another channel connect from the user.
3215 * The error_report still gives HMP user a hint on what failed.
3216 * It's normally done in migrate_fd_cleanup(), but call it here
3217 * explicitly.
3219 error_report_err(error_copy(s->error));
3220 } else {
3221 migrate_fd_cleanup(s);
3223 return;
3226 if (resume) {
3227 /* This is a resumed migration */
3228 rate_limit = migrate_max_postcopy_bandwidth() /
3229 XFER_LIMIT_RATIO;
3230 } else {
3231 /* This is a fresh new migration */
3232 rate_limit = migrate_max_bandwidth() / XFER_LIMIT_RATIO;
3234 /* Notify before starting migration thread */
3235 notifier_list_notify(&migration_state_notifiers, s);
3238 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3239 qemu_file_set_blocking(s->to_dst_file, true);
3242 * Open the return path. For postcopy, it is used exclusively. For
3243 * precopy, only if user specified "return-path" capability would
3244 * QEMU uses the return path.
3246 if (migrate_postcopy_ram() || migrate_return_path()) {
3247 if (open_return_path_on_source(s, !resume)) {
3248 error_report("Unable to open return-path for postcopy");
3249 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3250 migrate_fd_cleanup(s);
3251 return;
3256 * This needs to be done before resuming a postcopy. Note: for newer
3257 * QEMUs we will delay the channel creation until postcopy_start(), to
3258 * avoid disorder of channel creations.
3260 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
3261 postcopy_preempt_setup(s);
3264 if (resume) {
3265 /* Wakeup the main migration thread to do the recovery */
3266 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3267 MIGRATION_STATUS_POSTCOPY_RECOVER);
3268 qemu_sem_post(&s->postcopy_pause_sem);
3269 return;
3272 if (multifd_save_setup(&local_err) != 0) {
3273 error_report_err(local_err);
3274 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3275 MIGRATION_STATUS_FAILED);
3276 migrate_fd_cleanup(s);
3277 return;
3280 if (migrate_background_snapshot()) {
3281 qemu_thread_create(&s->thread, "bg_snapshot",
3282 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
3283 } else {
3284 qemu_thread_create(&s->thread, "live_migration",
3285 migration_thread, s, QEMU_THREAD_JOINABLE);
3287 s->migration_thread_running = true;
3290 static void migration_class_init(ObjectClass *klass, void *data)
3292 DeviceClass *dc = DEVICE_CLASS(klass);
3294 dc->user_creatable = false;
3295 device_class_set_props(dc, migration_properties);
3298 static void migration_instance_finalize(Object *obj)
3300 MigrationState *ms = MIGRATION_OBJ(obj);
3302 qemu_mutex_destroy(&ms->error_mutex);
3303 qemu_mutex_destroy(&ms->qemu_file_lock);
3304 qemu_sem_destroy(&ms->wait_unplug_sem);
3305 qemu_sem_destroy(&ms->rate_limit_sem);
3306 qemu_sem_destroy(&ms->pause_sem);
3307 qemu_sem_destroy(&ms->postcopy_pause_sem);
3308 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3309 qemu_sem_destroy(&ms->rp_state.rp_sem);
3310 qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
3311 qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
3312 error_free(ms->error);
3315 static void migration_instance_init(Object *obj)
3317 MigrationState *ms = MIGRATION_OBJ(obj);
3319 ms->state = MIGRATION_STATUS_NONE;
3320 ms->mbps = -1;
3321 ms->pages_per_second = -1;
3322 qemu_sem_init(&ms->pause_sem, 0);
3323 qemu_mutex_init(&ms->error_mutex);
3325 migrate_params_init(&ms->parameters);
3327 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3328 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3329 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3330 qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
3331 qemu_sem_init(&ms->rate_limit_sem, 0);
3332 qemu_sem_init(&ms->wait_unplug_sem, 0);
3333 qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
3334 qemu_mutex_init(&ms->qemu_file_lock);
3338 * Return true if check pass, false otherwise. Error will be put
3339 * inside errp if provided.
3341 static bool migration_object_check(MigrationState *ms, Error **errp)
3343 /* Assuming all off */
3344 bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
3346 if (!migrate_params_check(&ms->parameters, errp)) {
3347 return false;
3350 return migrate_caps_check(old_caps, ms->capabilities, errp);
3353 static const TypeInfo migration_type = {
3354 .name = TYPE_MIGRATION,
3356 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3357 * not created using qdev_new(), it is not attached to the qdev
3358 * device tree, and it is never realized.
3360 * TODO: Make this TYPE_OBJECT once QOM provides something like
3361 * TYPE_DEVICE's "-global" properties.
3363 .parent = TYPE_DEVICE,
3364 .class_init = migration_class_init,
3365 .class_size = sizeof(MigrationClass),
3366 .instance_size = sizeof(MigrationState),
3367 .instance_init = migration_instance_init,
3368 .instance_finalize = migration_instance_finalize,
3371 static void register_migration_types(void)
3373 type_register_static(&migration_type);
3376 type_init(register_migration_types);