migration: Display error in query-migrate irrelevant of status
[qemu/kevin.git] / migration / migration.c
blob57f9e9ed0c3924b6687c7b8d41b7454ea9b4c591
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 "file.h"
24 #include "socket.h"
25 #include "sysemu/runstate.h"
26 #include "sysemu/sysemu.h"
27 #include "sysemu/cpu-throttle.h"
28 #include "rdma.h"
29 #include "ram.h"
30 #include "ram-compress.h"
31 #include "migration/global_state.h"
32 #include "migration/misc.h"
33 #include "migration.h"
34 #include "migration-stats.h"
35 #include "savevm.h"
36 #include "qemu-file.h"
37 #include "channel.h"
38 #include "migration/vmstate.h"
39 #include "block/block.h"
40 #include "qapi/error.h"
41 #include "qapi/clone-visitor.h"
42 #include "qapi/qapi-visit-migration.h"
43 #include "qapi/qapi-visit-sockets.h"
44 #include "qapi/qapi-commands-migration.h"
45 #include "qapi/qapi-events-migration.h"
46 #include "qapi/qmp/qerror.h"
47 #include "qapi/qmp/qnull.h"
48 #include "qemu/rcu.h"
49 #include "block.h"
50 #include "postcopy-ram.h"
51 #include "qemu/thread.h"
52 #include "trace.h"
53 #include "exec/target_page.h"
54 #include "io/channel-buffer.h"
55 #include "io/channel-tls.h"
56 #include "migration/colo.h"
57 #include "hw/boards.h"
58 #include "monitor/monitor.h"
59 #include "net/announce.h"
60 #include "qemu/queue.h"
61 #include "multifd.h"
62 #include "threadinfo.h"
63 #include "qemu/yank.h"
64 #include "sysemu/cpus.h"
65 #include "yank_functions.h"
66 #include "sysemu/qtest.h"
67 #include "options.h"
68 #include "sysemu/dirtylimit.h"
70 static NotifierList migration_state_notifiers =
71 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
73 /* Messages sent on the return path from destination to source */
74 enum mig_rp_message_type {
75 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
76 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
77 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
79 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
80 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
81 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
82 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
83 MIG_RP_MSG_SWITCHOVER_ACK, /* Tell source it's OK to do switchover */
85 MIG_RP_MSG_MAX
88 /* When we add fault tolerance, we could have several
89 migrations at once. For now we don't need to add
90 dynamic creation of migration */
92 static MigrationState *current_migration;
93 static MigrationIncomingState *current_incoming;
95 static GSList *migration_blockers;
97 static bool migration_object_check(MigrationState *ms, Error **errp);
98 static int migration_maybe_pause(MigrationState *s,
99 int *current_active_state,
100 int new_state);
101 static void migrate_fd_cancel(MigrationState *s);
102 static int await_return_path_close_on_source(MigrationState *s);
104 static bool migration_needs_multiple_sockets(void)
106 return migrate_multifd() || migrate_postcopy_preempt();
109 static bool uri_supports_multi_channels(const char *uri)
111 return strstart(uri, "tcp:", NULL) || strstart(uri, "unix:", NULL) ||
112 strstart(uri, "vsock:", NULL);
115 static bool
116 migration_channels_and_uri_compatible(const char *uri, Error **errp)
118 if (migration_needs_multiple_sockets() &&
119 !uri_supports_multi_channels(uri)) {
120 error_setg(errp, "Migration requires multi-channel URIs (e.g. tcp)");
121 return false;
124 return true;
127 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
129 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
131 return (a > b) - (a < b);
134 void migration_object_init(void)
136 /* This can only be called once. */
137 assert(!current_migration);
138 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
141 * Init the migrate incoming object as well no matter whether
142 * we'll use it or not.
144 assert(!current_incoming);
145 current_incoming = g_new0(MigrationIncomingState, 1);
146 current_incoming->state = MIGRATION_STATUS_NONE;
147 current_incoming->postcopy_remote_fds =
148 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
149 qemu_mutex_init(&current_incoming->rp_mutex);
150 qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
151 qemu_event_init(&current_incoming->main_thread_load_event, false);
152 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
153 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
154 qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
155 qemu_sem_init(&current_incoming->postcopy_qemufile_dst_done, 0);
157 qemu_mutex_init(&current_incoming->page_request_mutex);
158 qemu_cond_init(&current_incoming->page_request_cond);
159 current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
161 migration_object_check(current_migration, &error_fatal);
163 blk_mig_init();
164 ram_mig_init();
165 dirty_bitmap_mig_init();
168 void migration_cancel(const Error *error)
170 if (error) {
171 migrate_set_error(current_migration, error);
173 if (migrate_dirty_limit()) {
174 qmp_cancel_vcpu_dirty_limit(false, -1, NULL);
176 migrate_fd_cancel(current_migration);
179 void migration_shutdown(void)
182 * When the QEMU main thread exit, the COLO thread
183 * may wait a semaphore. So, we should wakeup the
184 * COLO thread before migration shutdown.
186 colo_shutdown();
188 * Cancel the current migration - that will (eventually)
189 * stop the migration using this structure
191 migration_cancel(NULL);
192 object_unref(OBJECT(current_migration));
195 * Cancel outgoing migration of dirty bitmaps. It should
196 * at least unref used block nodes.
198 dirty_bitmap_mig_cancel_outgoing();
201 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
202 * are non-critical data, and their loss never considered as
203 * something serious.
205 dirty_bitmap_mig_cancel_incoming();
208 /* For outgoing */
209 MigrationState *migrate_get_current(void)
211 /* This can only be called after the object created. */
212 assert(current_migration);
213 return current_migration;
216 MigrationIncomingState *migration_incoming_get_current(void)
218 assert(current_incoming);
219 return current_incoming;
222 void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
224 if (mis->socket_address_list) {
225 qapi_free_SocketAddressList(mis->socket_address_list);
226 mis->socket_address_list = NULL;
229 if (mis->transport_cleanup) {
230 mis->transport_cleanup(mis->transport_data);
231 mis->transport_data = mis->transport_cleanup = NULL;
235 void migration_incoming_state_destroy(void)
237 struct MigrationIncomingState *mis = migration_incoming_get_current();
239 multifd_load_cleanup();
240 compress_threads_load_cleanup();
242 if (mis->to_src_file) {
243 /* Tell source that we are done */
244 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
245 qemu_fclose(mis->to_src_file);
246 mis->to_src_file = NULL;
249 if (mis->from_src_file) {
250 migration_ioc_unregister_yank_from_file(mis->from_src_file);
251 qemu_fclose(mis->from_src_file);
252 mis->from_src_file = NULL;
254 if (mis->postcopy_remote_fds) {
255 g_array_free(mis->postcopy_remote_fds, TRUE);
256 mis->postcopy_remote_fds = NULL;
259 migration_incoming_transport_cleanup(mis);
260 qemu_event_reset(&mis->main_thread_load_event);
262 if (mis->page_requested) {
263 g_tree_destroy(mis->page_requested);
264 mis->page_requested = NULL;
267 if (mis->postcopy_qemufile_dst) {
268 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
269 qemu_fclose(mis->postcopy_qemufile_dst);
270 mis->postcopy_qemufile_dst = NULL;
273 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
276 static void migrate_generate_event(int new_state)
278 if (migrate_events()) {
279 qapi_event_send_migration(new_state);
284 * Send a message on the return channel back to the source
285 * of the migration.
287 static int migrate_send_rp_message(MigrationIncomingState *mis,
288 enum mig_rp_message_type message_type,
289 uint16_t len, void *data)
291 int ret = 0;
293 trace_migrate_send_rp_message((int)message_type, len);
294 QEMU_LOCK_GUARD(&mis->rp_mutex);
297 * It's possible that the file handle got lost due to network
298 * failures.
300 if (!mis->to_src_file) {
301 ret = -EIO;
302 return ret;
305 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
306 qemu_put_be16(mis->to_src_file, len);
307 qemu_put_buffer(mis->to_src_file, data, len);
308 qemu_fflush(mis->to_src_file);
310 /* It's possible that qemu file got error during sending */
311 ret = qemu_file_get_error(mis->to_src_file);
313 return ret;
316 /* Request one page from the source VM at the given start address.
317 * rb: the RAMBlock to request the page in
318 * Start: Address offset within the RB
319 * Len: Length in bytes required - must be a multiple of pagesize
321 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
322 RAMBlock *rb, ram_addr_t start)
324 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
325 size_t msglen = 12; /* start + len */
326 size_t len = qemu_ram_pagesize(rb);
327 enum mig_rp_message_type msg_type;
328 const char *rbname;
329 int rbname_len;
331 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
332 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
335 * We maintain the last ramblock that we requested for page. Note that we
336 * don't need locking because this function will only be called within the
337 * postcopy ram fault thread.
339 if (rb != mis->last_rb) {
340 mis->last_rb = rb;
342 rbname = qemu_ram_get_idstr(rb);
343 rbname_len = strlen(rbname);
345 assert(rbname_len < 256);
347 bufc[msglen++] = rbname_len;
348 memcpy(bufc + msglen, rbname, rbname_len);
349 msglen += rbname_len;
350 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
351 } else {
352 msg_type = MIG_RP_MSG_REQ_PAGES;
355 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
358 int migrate_send_rp_req_pages(MigrationIncomingState *mis,
359 RAMBlock *rb, ram_addr_t start, uint64_t haddr)
361 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
362 bool received = false;
364 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
365 received = ramblock_recv_bitmap_test_byte_offset(rb, start);
366 if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
368 * The page has not been received, and it's not yet in the page
369 * request list. Queue it. Set the value of element to 1, so that
370 * things like g_tree_lookup() will return TRUE (1) when found.
372 g_tree_insert(mis->page_requested, aligned, (gpointer)1);
373 qatomic_inc(&mis->page_requested_count);
374 trace_postcopy_page_req_add(aligned, mis->page_requested_count);
379 * If the page is there, skip sending the message. We don't even need the
380 * lock because as long as the page arrived, it'll be there forever.
382 if (received) {
383 return 0;
386 return migrate_send_rp_message_req_pages(mis, rb, start);
389 static bool migration_colo_enabled;
390 bool migration_incoming_colo_enabled(void)
392 return migration_colo_enabled;
395 void migration_incoming_disable_colo(void)
397 ram_block_discard_disable(false);
398 migration_colo_enabled = false;
401 int migration_incoming_enable_colo(void)
403 #ifndef CONFIG_REPLICATION
404 error_report("ENABLE_COLO command come in migration stream, but COLO "
405 "module is not built in");
406 return -ENOTSUP;
407 #endif
409 if (!migrate_colo()) {
410 error_report("ENABLE_COLO command come in migration stream, but c-colo "
411 "capability is not set");
412 return -EINVAL;
415 if (ram_block_discard_disable(true)) {
416 error_report("COLO: cannot disable RAM discard");
417 return -EBUSY;
419 migration_colo_enabled = true;
420 return 0;
423 void migrate_add_address(SocketAddress *address)
425 MigrationIncomingState *mis = migration_incoming_get_current();
427 QAPI_LIST_PREPEND(mis->socket_address_list,
428 QAPI_CLONE(SocketAddress, address));
431 static void qemu_start_incoming_migration(const char *uri, Error **errp)
433 const char *p = NULL;
434 MigrationIncomingState *mis = migration_incoming_get_current();
436 /* URI is not suitable for migration? */
437 if (!migration_channels_and_uri_compatible(uri, errp)) {
438 return;
441 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
442 MIGRATION_STATUS_SETUP);
444 if (strstart(uri, "tcp:", &p) ||
445 strstart(uri, "unix:", NULL) ||
446 strstart(uri, "vsock:", NULL)) {
447 socket_start_incoming_migration(p ? p : uri, errp);
448 #ifdef CONFIG_RDMA
449 } else if (strstart(uri, "rdma:", &p)) {
450 rdma_start_incoming_migration(p, errp);
451 #endif
452 } else if (strstart(uri, "exec:", &p)) {
453 exec_start_incoming_migration(p, errp);
454 } else if (strstart(uri, "fd:", &p)) {
455 fd_start_incoming_migration(p, errp);
456 } else if (strstart(uri, "file:", &p)) {
457 file_start_incoming_migration(p, errp);
458 } else {
459 error_setg(errp, "unknown migration protocol: %s", uri);
463 static void process_incoming_migration_bh(void *opaque)
465 Error *local_err = NULL;
466 MigrationIncomingState *mis = opaque;
468 /* If capability late_block_activate is set:
469 * Only fire up the block code now if we're going to restart the
470 * VM, else 'cont' will do it.
471 * This causes file locking to happen; so we don't want it to happen
472 * unless we really are starting the VM.
474 if (!migrate_late_block_activate() ||
475 (autostart && (!global_state_received() ||
476 global_state_get_runstate() == RUN_STATE_RUNNING))) {
477 /* Make sure all file formats throw away their mutable metadata.
478 * If we get an error here, just don't restart the VM yet. */
479 bdrv_activate_all(&local_err);
480 if (local_err) {
481 error_report_err(local_err);
482 local_err = NULL;
483 autostart = false;
488 * This must happen after all error conditions are dealt with and
489 * we're sure the VM is going to be running on this host.
491 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
493 multifd_load_shutdown();
495 dirty_bitmap_mig_before_vm_start();
497 if (!global_state_received() ||
498 global_state_get_runstate() == RUN_STATE_RUNNING) {
499 if (autostart) {
500 vm_start();
501 } else {
502 runstate_set(RUN_STATE_PAUSED);
504 } else if (migration_incoming_colo_enabled()) {
505 migration_incoming_disable_colo();
506 vm_start();
507 } else {
508 runstate_set(global_state_get_runstate());
511 * This must happen after any state changes since as soon as an external
512 * observer sees this event they might start to prod at the VM assuming
513 * it's ready to use.
515 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
516 MIGRATION_STATUS_COMPLETED);
517 qemu_bh_delete(mis->bh);
518 migration_incoming_state_destroy();
521 static void coroutine_fn
522 process_incoming_migration_co(void *opaque)
524 MigrationIncomingState *mis = migration_incoming_get_current();
525 PostcopyState ps;
526 int ret;
528 assert(mis->from_src_file);
530 if (compress_threads_load_setup(mis->from_src_file)) {
531 error_report("Failed to setup decompress threads");
532 goto fail;
535 mis->largest_page_size = qemu_ram_pagesize_largest();
536 postcopy_state_set(POSTCOPY_INCOMING_NONE);
537 migrate_set_state(&mis->state, MIGRATION_STATUS_SETUP,
538 MIGRATION_STATUS_ACTIVE);
540 mis->loadvm_co = qemu_coroutine_self();
541 ret = qemu_loadvm_state(mis->from_src_file);
542 mis->loadvm_co = NULL;
544 ps = postcopy_state_get();
545 trace_process_incoming_migration_co_end(ret, ps);
546 if (ps != POSTCOPY_INCOMING_NONE) {
547 if (ps == POSTCOPY_INCOMING_ADVISE) {
549 * Where a migration had postcopy enabled (and thus went to advise)
550 * but managed to complete within the precopy period, we can use
551 * the normal exit.
553 postcopy_ram_incoming_cleanup(mis);
554 } else if (ret >= 0) {
556 * Postcopy was started, cleanup should happen at the end of the
557 * postcopy thread.
559 trace_process_incoming_migration_co_postcopy_end_main();
560 return;
562 /* Else if something went wrong then just fall out of the normal exit */
565 if (ret < 0) {
566 error_report("load of migration failed: %s", strerror(-ret));
567 goto fail;
570 if (colo_incoming_co() < 0) {
571 goto fail;
574 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
575 qemu_bh_schedule(mis->bh);
576 return;
577 fail:
578 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
579 MIGRATION_STATUS_FAILED);
580 qemu_fclose(mis->from_src_file);
582 multifd_load_cleanup();
583 compress_threads_load_cleanup();
585 exit(EXIT_FAILURE);
589 * migration_incoming_setup: Setup incoming migration
590 * @f: file for main migration channel
591 * @errp: where to put errors
593 * Returns: %true on success, %false on error.
595 static bool migration_incoming_setup(QEMUFile *f, Error **errp)
597 MigrationIncomingState *mis = migration_incoming_get_current();
599 if (!mis->from_src_file) {
600 mis->from_src_file = f;
602 qemu_file_set_blocking(f, false);
603 return true;
606 void migration_incoming_process(void)
608 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
609 qemu_coroutine_enter(co);
612 /* Returns true if recovered from a paused migration, otherwise false */
613 static bool postcopy_try_recover(void)
615 MigrationIncomingState *mis = migration_incoming_get_current();
617 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
618 /* Resumed from a paused postcopy migration */
620 /* This should be set already in migration_incoming_setup() */
621 assert(mis->from_src_file);
622 /* Postcopy has standalone thread to do vm load */
623 qemu_file_set_blocking(mis->from_src_file, true);
625 /* Re-configure the return path */
626 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
628 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
629 MIGRATION_STATUS_POSTCOPY_RECOVER);
632 * Here, we only wake up the main loading thread (while the
633 * rest threads will still be waiting), so that we can receive
634 * commands from source now, and answer it if needed. The
635 * rest threads will be woken up afterwards until we are sure
636 * that source is ready to reply to page requests.
638 qemu_sem_post(&mis->postcopy_pause_sem_dst);
639 return true;
642 return false;
645 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
647 if (!migration_incoming_setup(f, errp)) {
648 return;
650 if (postcopy_try_recover()) {
651 return;
653 migration_incoming_process();
657 * Returns true when we want to start a new incoming migration process,
658 * false otherwise.
660 static bool migration_should_start_incoming(bool main_channel)
662 /* Multifd doesn't start unless all channels are established */
663 if (migrate_multifd()) {
664 return migration_has_all_channels();
667 /* Preempt channel only starts when the main channel is created */
668 if (migrate_postcopy_preempt()) {
669 return main_channel;
673 * For all the rest types of migration, we should only reach here when
674 * it's the main channel that's being created, and we should always
675 * proceed with this channel.
677 assert(main_channel);
678 return true;
681 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
683 MigrationIncomingState *mis = migration_incoming_get_current();
684 Error *local_err = NULL;
685 QEMUFile *f;
686 bool default_channel = true;
687 uint32_t channel_magic = 0;
688 int ret = 0;
690 if (migrate_multifd() && !migrate_postcopy_ram() &&
691 qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) {
693 * With multiple channels, it is possible that we receive channels
694 * out of order on destination side, causing incorrect mapping of
695 * source channels on destination side. Check channel MAGIC to
696 * decide type of channel. Please note this is best effort, postcopy
697 * preempt channel does not send any magic number so avoid it for
698 * postcopy live migration. Also tls live migration already does
699 * tls handshake while initializing main channel so with tls this
700 * issue is not possible.
702 ret = migration_channel_read_peek(ioc, (void *)&channel_magic,
703 sizeof(channel_magic), &local_err);
705 if (ret != 0) {
706 error_propagate(errp, local_err);
707 return;
710 default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC));
711 } else {
712 default_channel = !mis->from_src_file;
715 if (multifd_load_setup(errp) != 0) {
716 error_setg(errp, "Failed to setup multifd channels");
717 return;
720 if (default_channel) {
721 f = qemu_file_new_input(ioc);
723 if (!migration_incoming_setup(f, errp)) {
724 return;
726 } else {
727 /* Multiple connections */
728 assert(migration_needs_multiple_sockets());
729 if (migrate_multifd()) {
730 multifd_recv_new_channel(ioc, &local_err);
731 } else {
732 assert(migrate_postcopy_preempt());
733 f = qemu_file_new_input(ioc);
734 postcopy_preempt_new_channel(mis, f);
736 if (local_err) {
737 error_propagate(errp, local_err);
738 return;
742 if (migration_should_start_incoming(default_channel)) {
743 /* If it's a recovery, we're done */
744 if (postcopy_try_recover()) {
745 return;
747 migration_incoming_process();
752 * @migration_has_all_channels: We have received all channels that we need
754 * Returns true when we have got connections to all the channels that
755 * we need for migration.
757 bool migration_has_all_channels(void)
759 MigrationIncomingState *mis = migration_incoming_get_current();
761 if (!mis->from_src_file) {
762 return false;
765 if (migrate_multifd()) {
766 return multifd_recv_all_channels_created();
769 if (migrate_postcopy_preempt()) {
770 return mis->postcopy_qemufile_dst != NULL;
773 return true;
776 int migrate_send_rp_switchover_ack(MigrationIncomingState *mis)
778 return migrate_send_rp_message(mis, MIG_RP_MSG_SWITCHOVER_ACK, 0, NULL);
782 * Send a 'SHUT' message on the return channel with the given value
783 * to indicate that we've finished with the RP. Non-0 value indicates
784 * error.
786 void migrate_send_rp_shut(MigrationIncomingState *mis,
787 uint32_t value)
789 uint32_t buf;
791 buf = cpu_to_be32(value);
792 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
796 * Send a 'PONG' message on the return channel with the given value
797 * (normally in response to a 'PING')
799 void migrate_send_rp_pong(MigrationIncomingState *mis,
800 uint32_t value)
802 uint32_t buf;
804 buf = cpu_to_be32(value);
805 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
808 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
809 char *block_name)
811 char buf[512];
812 int len;
813 int64_t res;
816 * First, we send the header part. It contains only the len of
817 * idstr, and the idstr itself.
819 len = strlen(block_name);
820 buf[0] = len;
821 memcpy(buf + 1, block_name, len);
823 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
824 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
825 __func__);
826 return;
829 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
832 * Next, we dump the received bitmap to the stream.
834 * TODO: currently we are safe since we are the only one that is
835 * using the to_src_file handle (fault thread is still paused),
836 * and it's ok even not taking the mutex. However the best way is
837 * to take the lock before sending the message header, and release
838 * the lock after sending the bitmap.
840 qemu_mutex_lock(&mis->rp_mutex);
841 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
842 qemu_mutex_unlock(&mis->rp_mutex);
844 trace_migrate_send_rp_recv_bitmap(block_name, res);
847 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
849 uint32_t buf;
851 buf = cpu_to_be32(value);
852 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
856 * Return true if we're already in the middle of a migration
857 * (i.e. any of the active or setup states)
859 bool migration_is_setup_or_active(int state)
861 switch (state) {
862 case MIGRATION_STATUS_ACTIVE:
863 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
864 case MIGRATION_STATUS_POSTCOPY_PAUSED:
865 case MIGRATION_STATUS_POSTCOPY_RECOVER:
866 case MIGRATION_STATUS_SETUP:
867 case MIGRATION_STATUS_PRE_SWITCHOVER:
868 case MIGRATION_STATUS_DEVICE:
869 case MIGRATION_STATUS_WAIT_UNPLUG:
870 case MIGRATION_STATUS_COLO:
871 return true;
873 default:
874 return false;
879 bool migration_is_running(int state)
881 switch (state) {
882 case MIGRATION_STATUS_ACTIVE:
883 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
884 case MIGRATION_STATUS_POSTCOPY_PAUSED:
885 case MIGRATION_STATUS_POSTCOPY_RECOVER:
886 case MIGRATION_STATUS_SETUP:
887 case MIGRATION_STATUS_PRE_SWITCHOVER:
888 case MIGRATION_STATUS_DEVICE:
889 case MIGRATION_STATUS_WAIT_UNPLUG:
890 case MIGRATION_STATUS_CANCELLING:
891 return true;
893 default:
894 return false;
899 static bool migrate_show_downtime(MigrationState *s)
901 return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy();
904 static void populate_time_info(MigrationInfo *info, MigrationState *s)
906 info->has_status = true;
907 info->has_setup_time = true;
908 info->setup_time = s->setup_time;
910 if (s->state == MIGRATION_STATUS_COMPLETED) {
911 info->has_total_time = true;
912 info->total_time = s->total_time;
913 } else {
914 info->has_total_time = true;
915 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
916 s->start_time;
919 if (migrate_show_downtime(s)) {
920 info->has_downtime = true;
921 info->downtime = s->downtime;
922 } else {
923 info->has_expected_downtime = true;
924 info->expected_downtime = s->expected_downtime;
928 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
930 size_t page_size = qemu_target_page_size();
932 info->ram = g_malloc0(sizeof(*info->ram));
933 info->ram->transferred = stat64_get(&mig_stats.transferred);
934 info->ram->total = ram_bytes_total();
935 info->ram->duplicate = stat64_get(&mig_stats.zero_pages);
936 /* legacy value. It is not used anymore */
937 info->ram->skipped = 0;
938 info->ram->normal = stat64_get(&mig_stats.normal_pages);
939 info->ram->normal_bytes = info->ram->normal * page_size;
940 info->ram->mbps = s->mbps;
941 info->ram->dirty_sync_count =
942 stat64_get(&mig_stats.dirty_sync_count);
943 info->ram->dirty_sync_missed_zero_copy =
944 stat64_get(&mig_stats.dirty_sync_missed_zero_copy);
945 info->ram->postcopy_requests =
946 stat64_get(&mig_stats.postcopy_requests);
947 info->ram->page_size = page_size;
948 info->ram->multifd_bytes = stat64_get(&mig_stats.multifd_bytes);
949 info->ram->pages_per_second = s->pages_per_second;
950 info->ram->precopy_bytes = stat64_get(&mig_stats.precopy_bytes);
951 info->ram->downtime_bytes = stat64_get(&mig_stats.downtime_bytes);
952 info->ram->postcopy_bytes = stat64_get(&mig_stats.postcopy_bytes);
954 if (migrate_xbzrle()) {
955 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
956 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
957 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
958 info->xbzrle_cache->pages = xbzrle_counters.pages;
959 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
960 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
961 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
962 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
965 if (migrate_compress()) {
966 info->compression = g_malloc0(sizeof(*info->compression));
967 info->compression->pages = compression_counters.pages;
968 info->compression->busy = compression_counters.busy;
969 info->compression->busy_rate = compression_counters.busy_rate;
970 info->compression->compressed_size =
971 compression_counters.compressed_size;
972 info->compression->compression_rate =
973 compression_counters.compression_rate;
976 if (cpu_throttle_active()) {
977 info->has_cpu_throttle_percentage = true;
978 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
981 if (s->state != MIGRATION_STATUS_COMPLETED) {
982 info->ram->remaining = ram_bytes_remaining();
983 info->ram->dirty_pages_rate =
984 stat64_get(&mig_stats.dirty_pages_rate);
987 if (migrate_dirty_limit() && dirtylimit_in_service()) {
988 info->has_dirty_limit_throttle_time_per_round = true;
989 info->dirty_limit_throttle_time_per_round =
990 dirtylimit_throttle_time_per_round();
992 info->has_dirty_limit_ring_full_time = true;
993 info->dirty_limit_ring_full_time = dirtylimit_ring_full_time();
997 static void populate_disk_info(MigrationInfo *info)
999 if (blk_mig_active()) {
1000 info->disk = g_malloc0(sizeof(*info->disk));
1001 info->disk->transferred = blk_mig_bytes_transferred();
1002 info->disk->remaining = blk_mig_bytes_remaining();
1003 info->disk->total = blk_mig_bytes_total();
1007 static void fill_source_migration_info(MigrationInfo *info)
1009 MigrationState *s = migrate_get_current();
1010 int state = qatomic_read(&s->state);
1011 GSList *cur_blocker = migration_blockers;
1013 info->blocked_reasons = NULL;
1016 * There are two types of reasons a migration might be blocked;
1017 * a) devices marked in VMState as non-migratable, and
1018 * b) Explicit migration blockers
1019 * We need to add both of them here.
1021 qemu_savevm_non_migratable_list(&info->blocked_reasons);
1023 while (cur_blocker) {
1024 QAPI_LIST_PREPEND(info->blocked_reasons,
1025 g_strdup(error_get_pretty(cur_blocker->data)));
1026 cur_blocker = g_slist_next(cur_blocker);
1028 info->has_blocked_reasons = info->blocked_reasons != NULL;
1030 switch (state) {
1031 case MIGRATION_STATUS_NONE:
1032 /* no migration has happened ever */
1033 /* do not overwrite destination migration status */
1034 return;
1035 case MIGRATION_STATUS_SETUP:
1036 info->has_status = true;
1037 info->has_total_time = false;
1038 break;
1039 case MIGRATION_STATUS_ACTIVE:
1040 case MIGRATION_STATUS_CANCELLING:
1041 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1042 case MIGRATION_STATUS_PRE_SWITCHOVER:
1043 case MIGRATION_STATUS_DEVICE:
1044 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1045 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1046 /* TODO add some postcopy stats */
1047 populate_time_info(info, s);
1048 populate_ram_info(info, s);
1049 populate_disk_info(info);
1050 migration_populate_vfio_info(info);
1051 break;
1052 case MIGRATION_STATUS_COLO:
1053 info->has_status = true;
1054 /* TODO: display COLO specific information (checkpoint info etc.) */
1055 break;
1056 case MIGRATION_STATUS_COMPLETED:
1057 populate_time_info(info, s);
1058 populate_ram_info(info, s);
1059 migration_populate_vfio_info(info);
1060 break;
1061 case MIGRATION_STATUS_FAILED:
1062 info->has_status = true;
1063 break;
1064 case MIGRATION_STATUS_CANCELLED:
1065 info->has_status = true;
1066 break;
1067 case MIGRATION_STATUS_WAIT_UNPLUG:
1068 info->has_status = true;
1069 break;
1071 info->status = state;
1073 QEMU_LOCK_GUARD(&s->error_mutex);
1074 if (s->error) {
1075 info->error_desc = g_strdup(error_get_pretty(s->error));
1079 static void fill_destination_migration_info(MigrationInfo *info)
1081 MigrationIncomingState *mis = migration_incoming_get_current();
1083 if (mis->socket_address_list) {
1084 info->has_socket_address = true;
1085 info->socket_address =
1086 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1089 switch (mis->state) {
1090 case MIGRATION_STATUS_NONE:
1091 return;
1092 case MIGRATION_STATUS_SETUP:
1093 case MIGRATION_STATUS_CANCELLING:
1094 case MIGRATION_STATUS_CANCELLED:
1095 case MIGRATION_STATUS_ACTIVE:
1096 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1097 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1098 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1099 case MIGRATION_STATUS_FAILED:
1100 case MIGRATION_STATUS_COLO:
1101 info->has_status = true;
1102 break;
1103 case MIGRATION_STATUS_COMPLETED:
1104 info->has_status = true;
1105 fill_destination_postcopy_migration_info(info);
1106 break;
1108 info->status = mis->state;
1111 MigrationInfo *qmp_query_migrate(Error **errp)
1113 MigrationInfo *info = g_malloc0(sizeof(*info));
1115 fill_destination_migration_info(info);
1116 fill_source_migration_info(info);
1118 return info;
1121 void qmp_migrate_start_postcopy(Error **errp)
1123 MigrationState *s = migrate_get_current();
1125 if (!migrate_postcopy()) {
1126 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1127 " the start of migration");
1128 return;
1131 if (s->state == MIGRATION_STATUS_NONE) {
1132 error_setg(errp, "Postcopy must be started after migration has been"
1133 " started");
1134 return;
1137 * we don't error if migration has finished since that would be racy
1138 * with issuing this command.
1140 qatomic_set(&s->start_postcopy, true);
1143 /* shared migration helpers */
1145 void migrate_set_state(int *state, int old_state, int new_state)
1147 assert(new_state < MIGRATION_STATUS__MAX);
1148 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
1149 trace_migrate_set_state(MigrationStatus_str(new_state));
1150 migrate_generate_event(new_state);
1154 static void migrate_fd_cleanup(MigrationState *s)
1156 qemu_bh_delete(s->cleanup_bh);
1157 s->cleanup_bh = NULL;
1159 g_free(s->hostname);
1160 s->hostname = NULL;
1161 json_writer_free(s->vmdesc);
1162 s->vmdesc = NULL;
1164 qemu_savevm_state_cleanup();
1166 if (s->to_dst_file) {
1167 QEMUFile *tmp;
1169 trace_migrate_fd_cleanup();
1170 qemu_mutex_unlock_iothread();
1171 if (s->migration_thread_running) {
1172 qemu_thread_join(&s->thread);
1173 s->migration_thread_running = false;
1175 qemu_mutex_lock_iothread();
1177 multifd_save_cleanup();
1178 qemu_mutex_lock(&s->qemu_file_lock);
1179 tmp = s->to_dst_file;
1180 s->to_dst_file = NULL;
1181 qemu_mutex_unlock(&s->qemu_file_lock);
1183 * Close the file handle without the lock to make sure the
1184 * critical section won't block for long.
1186 migration_ioc_unregister_yank_from_file(tmp);
1187 qemu_fclose(tmp);
1191 * We already cleaned up to_dst_file, so errors from the return
1192 * path might be due to that, ignore them.
1194 await_return_path_close_on_source(s);
1196 assert(!migration_is_active(s));
1198 if (s->state == MIGRATION_STATUS_CANCELLING) {
1199 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1200 MIGRATION_STATUS_CANCELLED);
1203 if (s->error) {
1204 /* It is used on info migrate. We can't free it */
1205 error_report_err(error_copy(s->error));
1207 notifier_list_notify(&migration_state_notifiers, s);
1208 block_cleanup_parameters();
1209 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1212 static void migrate_fd_cleanup_schedule(MigrationState *s)
1215 * Ref the state for bh, because it may be called when
1216 * there're already no other refs
1218 object_ref(OBJECT(s));
1219 qemu_bh_schedule(s->cleanup_bh);
1222 static void migrate_fd_cleanup_bh(void *opaque)
1224 MigrationState *s = opaque;
1225 migrate_fd_cleanup(s);
1226 object_unref(OBJECT(s));
1229 void migrate_set_error(MigrationState *s, const Error *error)
1231 QEMU_LOCK_GUARD(&s->error_mutex);
1232 if (!s->error) {
1233 s->error = error_copy(error);
1237 static void migrate_error_free(MigrationState *s)
1239 QEMU_LOCK_GUARD(&s->error_mutex);
1240 if (s->error) {
1241 error_free(s->error);
1242 s->error = NULL;
1246 static void migrate_fd_error(MigrationState *s, const Error *error)
1248 trace_migrate_fd_error(error_get_pretty(error));
1249 assert(s->to_dst_file == NULL);
1250 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1251 MIGRATION_STATUS_FAILED);
1252 migrate_set_error(s, error);
1255 static void migrate_fd_cancel(MigrationState *s)
1257 int old_state ;
1259 trace_migrate_fd_cancel();
1261 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1262 if (s->rp_state.from_dst_file) {
1263 /* shutdown the rp socket, so causing the rp thread to shutdown */
1264 qemu_file_shutdown(s->rp_state.from_dst_file);
1268 do {
1269 old_state = s->state;
1270 if (!migration_is_running(old_state)) {
1271 break;
1273 /* If the migration is paused, kick it out of the pause */
1274 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1275 qemu_sem_post(&s->pause_sem);
1277 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1278 } while (s->state != MIGRATION_STATUS_CANCELLING);
1281 * If we're unlucky the migration code might be stuck somewhere in a
1282 * send/write while the network has failed and is waiting to timeout;
1283 * if we've got shutdown(2) available then we can force it to quit.
1285 if (s->state == MIGRATION_STATUS_CANCELLING) {
1286 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1287 if (s->to_dst_file) {
1288 qemu_file_shutdown(s->to_dst_file);
1292 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1293 Error *local_err = NULL;
1295 bdrv_activate_all(&local_err);
1296 if (local_err) {
1297 error_report_err(local_err);
1298 } else {
1299 s->block_inactive = false;
1304 void add_migration_state_change_notifier(Notifier *notify)
1306 notifier_list_add(&migration_state_notifiers, notify);
1309 void remove_migration_state_change_notifier(Notifier *notify)
1311 notifier_remove(notify);
1314 bool migration_in_setup(MigrationState *s)
1316 return s->state == MIGRATION_STATUS_SETUP;
1319 bool migration_has_finished(MigrationState *s)
1321 return s->state == MIGRATION_STATUS_COMPLETED;
1324 bool migration_has_failed(MigrationState *s)
1326 return (s->state == MIGRATION_STATUS_CANCELLED ||
1327 s->state == MIGRATION_STATUS_FAILED);
1330 bool migration_in_postcopy(void)
1332 MigrationState *s = migrate_get_current();
1334 switch (s->state) {
1335 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1336 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1337 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1338 return true;
1339 default:
1340 return false;
1344 bool migration_in_postcopy_after_devices(MigrationState *s)
1346 return migration_in_postcopy() && s->postcopy_after_devices;
1349 bool migration_in_incoming_postcopy(void)
1351 PostcopyState ps = postcopy_state_get();
1353 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
1356 bool migration_incoming_postcopy_advised(void)
1358 PostcopyState ps = postcopy_state_get();
1360 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
1363 bool migration_in_bg_snapshot(void)
1365 MigrationState *s = migrate_get_current();
1367 return migrate_background_snapshot() &&
1368 migration_is_setup_or_active(s->state);
1371 bool migration_is_idle(void)
1373 MigrationState *s = current_migration;
1375 if (!s) {
1376 return true;
1379 switch (s->state) {
1380 case MIGRATION_STATUS_NONE:
1381 case MIGRATION_STATUS_CANCELLED:
1382 case MIGRATION_STATUS_COMPLETED:
1383 case MIGRATION_STATUS_FAILED:
1384 return true;
1385 case MIGRATION_STATUS_SETUP:
1386 case MIGRATION_STATUS_CANCELLING:
1387 case MIGRATION_STATUS_ACTIVE:
1388 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1389 case MIGRATION_STATUS_COLO:
1390 case MIGRATION_STATUS_PRE_SWITCHOVER:
1391 case MIGRATION_STATUS_DEVICE:
1392 case MIGRATION_STATUS_WAIT_UNPLUG:
1393 return false;
1394 case MIGRATION_STATUS__MAX:
1395 g_assert_not_reached();
1398 return false;
1401 bool migration_is_active(MigrationState *s)
1403 return (s->state == MIGRATION_STATUS_ACTIVE ||
1404 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1407 int migrate_init(MigrationState *s, Error **errp)
1409 int ret;
1411 ret = qemu_savevm_state_prepare(errp);
1412 if (ret) {
1413 return ret;
1417 * Reinitialise all migration state, except
1418 * parameters/capabilities that the user set, and
1419 * locks.
1421 s->cleanup_bh = 0;
1422 s->vm_start_bh = 0;
1423 s->to_dst_file = NULL;
1424 s->state = MIGRATION_STATUS_NONE;
1425 s->rp_state.from_dst_file = NULL;
1426 s->rp_state.error = false;
1427 s->mbps = 0.0;
1428 s->pages_per_second = 0.0;
1429 s->downtime = 0;
1430 s->expected_downtime = 0;
1431 s->setup_time = 0;
1432 s->start_postcopy = false;
1433 s->postcopy_after_devices = false;
1434 s->migration_thread_running = false;
1435 error_free(s->error);
1436 s->error = NULL;
1437 s->hostname = NULL;
1439 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1441 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1442 s->total_time = 0;
1443 s->vm_old_state = -1;
1444 s->iteration_initial_bytes = 0;
1445 s->threshold_size = 0;
1446 s->switchover_acked = false;
1448 * set mig_stats compression_counters memory to zero for a
1449 * new migration
1451 memset(&mig_stats, 0, sizeof(mig_stats));
1452 memset(&compression_counters, 0, sizeof(compression_counters));
1453 migration_reset_vfio_bytes_transferred();
1455 return 0;
1458 int migrate_add_blocker_internal(Error *reason, Error **errp)
1460 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1461 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
1462 error_propagate_prepend(errp, error_copy(reason),
1463 "disallowing migration blocker "
1464 "(migration/snapshot in progress) for: ");
1465 return -EBUSY;
1468 migration_blockers = g_slist_prepend(migration_blockers, reason);
1469 return 0;
1472 int migrate_add_blocker(Error *reason, Error **errp)
1474 if (only_migratable) {
1475 error_propagate_prepend(errp, error_copy(reason),
1476 "disallowing migration blocker "
1477 "(--only-migratable) for: ");
1478 return -EACCES;
1481 return migrate_add_blocker_internal(reason, errp);
1484 void migrate_del_blocker(Error *reason)
1486 migration_blockers = g_slist_remove(migration_blockers, reason);
1489 void qmp_migrate_incoming(const char *uri, Error **errp)
1491 Error *local_err = NULL;
1492 static bool once = true;
1494 if (!once) {
1495 error_setg(errp, "The incoming migration has already been started");
1496 return;
1498 if (!runstate_check(RUN_STATE_INMIGRATE)) {
1499 error_setg(errp, "'-incoming' was not specified on the command line");
1500 return;
1503 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1504 return;
1507 qemu_start_incoming_migration(uri, &local_err);
1509 if (local_err) {
1510 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1511 error_propagate(errp, local_err);
1512 return;
1515 once = false;
1518 void qmp_migrate_recover(const char *uri, Error **errp)
1520 MigrationIncomingState *mis = migration_incoming_get_current();
1523 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1524 * callers (no one should ignore a recover failure); if there is, it's a
1525 * programming error.
1527 assert(errp);
1529 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1530 error_setg(errp, "Migrate recover can only be run "
1531 "when postcopy is paused.");
1532 return;
1535 /* If there's an existing transport, release it */
1536 migration_incoming_transport_cleanup(mis);
1539 * Note that this call will never start a real migration; it will
1540 * only re-setup the migration stream and poke existing migration
1541 * to continue using that newly established channel.
1543 qemu_start_incoming_migration(uri, errp);
1546 void qmp_migrate_pause(Error **errp)
1548 MigrationState *ms = migrate_get_current();
1549 MigrationIncomingState *mis = migration_incoming_get_current();
1550 int ret = 0;
1552 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1553 /* Source side, during postcopy */
1554 qemu_mutex_lock(&ms->qemu_file_lock);
1555 if (ms->to_dst_file) {
1556 ret = qemu_file_shutdown(ms->to_dst_file);
1558 qemu_mutex_unlock(&ms->qemu_file_lock);
1559 if (ret) {
1560 error_setg(errp, "Failed to pause source migration");
1562 return;
1565 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1566 ret = qemu_file_shutdown(mis->from_src_file);
1567 if (ret) {
1568 error_setg(errp, "Failed to pause destination migration");
1570 return;
1573 error_setg(errp, "migrate-pause is currently only supported "
1574 "during postcopy-active state");
1577 bool migration_is_blocked(Error **errp)
1579 if (qemu_savevm_state_blocked(errp)) {
1580 return true;
1583 if (migration_blockers) {
1584 error_propagate(errp, error_copy(migration_blockers->data));
1585 return true;
1588 return false;
1591 /* Returns true if continue to migrate, or false if error detected */
1592 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1593 bool resume, Error **errp)
1595 Error *local_err = NULL;
1597 if (resume) {
1598 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1599 error_setg(errp, "Cannot resume if there is no "
1600 "paused migration");
1601 return false;
1605 * Postcopy recovery won't work well with release-ram
1606 * capability since release-ram will drop the page buffer as
1607 * long as the page is put into the send buffer. So if there
1608 * is a network failure happened, any page buffers that have
1609 * not yet reached the destination VM but have already been
1610 * sent from the source VM will be lost forever. Let's refuse
1611 * the client from resuming such a postcopy migration.
1612 * Luckily release-ram was designed to only be used when src
1613 * and destination VMs are on the same host, so it should be
1614 * fine.
1616 if (migrate_release_ram()) {
1617 error_setg(errp, "Postcopy recovery cannot work "
1618 "when release-ram capability is set");
1619 return false;
1622 /* This is a resume, skip init status */
1623 return true;
1626 if (migration_is_running(s->state)) {
1627 error_setg(errp, QERR_MIGRATION_ACTIVE);
1628 return false;
1631 if (runstate_check(RUN_STATE_INMIGRATE)) {
1632 error_setg(errp, "Guest is waiting for an incoming migration");
1633 return false;
1636 if (runstate_check(RUN_STATE_POSTMIGRATE)) {
1637 error_setg(errp, "Can't migrate the vm that was paused due to "
1638 "previous migration");
1639 return false;
1642 if (migration_is_blocked(errp)) {
1643 return false;
1646 if (blk || blk_inc) {
1647 if (migrate_colo()) {
1648 error_setg(errp, "No disk migration is required in COLO mode");
1649 return false;
1651 if (migrate_block() || migrate_block_incremental()) {
1652 error_setg(errp, "Command options are incompatible with "
1653 "current migration capabilities");
1654 return false;
1656 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK, true, &local_err)) {
1657 error_propagate(errp, local_err);
1658 return false;
1660 s->must_remove_block_options = true;
1663 if (blk_inc) {
1664 migrate_set_block_incremental(true);
1667 if (migrate_init(s, errp)) {
1668 return false;
1671 return true;
1674 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1675 bool has_inc, bool inc, bool has_detach, bool detach,
1676 bool has_resume, bool resume, Error **errp)
1678 bool resume_requested;
1679 Error *local_err = NULL;
1680 MigrationState *s = migrate_get_current();
1681 const char *p = NULL;
1683 /* URI is not suitable for migration? */
1684 if (!migration_channels_and_uri_compatible(uri, errp)) {
1685 return;
1688 resume_requested = has_resume && resume;
1689 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1690 resume_requested, errp)) {
1691 /* Error detected, put into errp */
1692 return;
1695 if (!resume_requested) {
1696 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1697 return;
1701 if (strstart(uri, "tcp:", &p) ||
1702 strstart(uri, "unix:", NULL) ||
1703 strstart(uri, "vsock:", NULL)) {
1704 socket_start_outgoing_migration(s, p ? p : uri, &local_err);
1705 #ifdef CONFIG_RDMA
1706 } else if (strstart(uri, "rdma:", &p)) {
1707 rdma_start_outgoing_migration(s, p, &local_err);
1708 #endif
1709 } else if (strstart(uri, "exec:", &p)) {
1710 exec_start_outgoing_migration(s, p, &local_err);
1711 } else if (strstart(uri, "fd:", &p)) {
1712 fd_start_outgoing_migration(s, p, &local_err);
1713 } else if (strstart(uri, "file:", &p)) {
1714 file_start_outgoing_migration(s, p, &local_err);
1715 } else {
1716 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "uri",
1717 "a valid migration protocol");
1718 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1719 MIGRATION_STATUS_FAILED);
1720 block_cleanup_parameters();
1723 if (local_err) {
1724 if (!resume_requested) {
1725 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1727 migrate_fd_error(s, local_err);
1728 error_propagate(errp, local_err);
1729 return;
1733 void qmp_migrate_cancel(Error **errp)
1735 migration_cancel(NULL);
1738 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1740 MigrationState *s = migrate_get_current();
1741 if (s->state != state) {
1742 error_setg(errp, "Migration not in expected state: %s",
1743 MigrationStatus_str(s->state));
1744 return;
1746 qemu_sem_post(&s->pause_sem);
1749 /* migration thread support */
1751 * Something bad happened to the RP stream, mark an error
1752 * The caller shall print or trace something to indicate why
1754 static void mark_source_rp_bad(MigrationState *s)
1756 s->rp_state.error = true;
1759 static struct rp_cmd_args {
1760 ssize_t len; /* -1 = variable */
1761 const char *name;
1762 } rp_cmd_args[] = {
1763 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1764 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1765 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1766 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1767 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1768 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
1769 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
1770 [MIG_RP_MSG_SWITCHOVER_ACK] = { .len = 0, .name = "SWITCHOVER_ACK" },
1771 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1775 * Process a request for pages received on the return path,
1776 * We're allowed to send more than requested (e.g. to round to our page size)
1777 * and we don't need to send pages that have already been sent.
1779 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1780 ram_addr_t start, size_t len)
1782 long our_host_ps = qemu_real_host_page_size();
1784 trace_migrate_handle_rp_req_pages(rbname, start, len);
1787 * Since we currently insist on matching page sizes, just sanity check
1788 * we're being asked for whole host pages.
1790 if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
1791 !QEMU_IS_ALIGNED(len, our_host_ps)) {
1792 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1793 " len: %zd", __func__, start, len);
1794 mark_source_rp_bad(ms);
1795 return;
1798 if (ram_save_queue_pages(rbname, start, len)) {
1799 mark_source_rp_bad(ms);
1803 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
1805 RAMBlock *block = qemu_ram_block_by_name(block_name);
1807 if (!block) {
1808 error_report("%s: invalid block name '%s'", __func__, block_name);
1809 return -EINVAL;
1812 /* Fetch the received bitmap and refresh the dirty bitmap */
1813 return ram_dirty_bitmap_reload(s, block);
1816 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
1818 trace_source_return_path_thread_resume_ack(value);
1820 if (value != MIGRATION_RESUME_ACK_VALUE) {
1821 error_report("%s: illegal resume_ack value %"PRIu32,
1822 __func__, value);
1823 return -1;
1826 /* Now both sides are active. */
1827 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1828 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1830 /* Notify send thread that time to continue send pages */
1831 qemu_sem_post(&s->rp_state.rp_sem);
1833 return 0;
1837 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
1838 * existed) in a safe way.
1840 static void migration_release_dst_files(MigrationState *ms)
1842 QEMUFile *file;
1844 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
1846 * Reset the from_dst_file pointer first before releasing it, as we
1847 * can't block within lock section
1849 file = ms->rp_state.from_dst_file;
1850 ms->rp_state.from_dst_file = NULL;
1854 * Do the same to postcopy fast path socket too if there is. No
1855 * locking needed because this qemufile should only be managed by
1856 * return path thread.
1858 if (ms->postcopy_qemufile_src) {
1859 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
1860 qemu_file_shutdown(ms->postcopy_qemufile_src);
1861 qemu_fclose(ms->postcopy_qemufile_src);
1862 ms->postcopy_qemufile_src = NULL;
1865 qemu_fclose(file);
1869 * Handles messages sent on the return path towards the source VM
1872 static void *source_return_path_thread(void *opaque)
1874 MigrationState *ms = opaque;
1875 QEMUFile *rp = ms->rp_state.from_dst_file;
1876 uint16_t header_len, header_type;
1877 uint8_t buf[512];
1878 uint32_t tmp32, sibling_error;
1879 ram_addr_t start = 0; /* =0 to silence warning */
1880 size_t len = 0, expected_len;
1881 int res;
1883 trace_source_return_path_thread_entry();
1884 rcu_register_thread();
1886 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1887 migration_is_setup_or_active(ms->state)) {
1888 trace_source_return_path_thread_loop_top();
1889 header_type = qemu_get_be16(rp);
1890 header_len = qemu_get_be16(rp);
1892 if (qemu_file_get_error(rp)) {
1893 mark_source_rp_bad(ms);
1894 goto out;
1897 if (header_type >= MIG_RP_MSG_MAX ||
1898 header_type == MIG_RP_MSG_INVALID) {
1899 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1900 header_type, header_len);
1901 mark_source_rp_bad(ms);
1902 goto out;
1905 if ((rp_cmd_args[header_type].len != -1 &&
1906 header_len != rp_cmd_args[header_type].len) ||
1907 header_len > sizeof(buf)) {
1908 error_report("RP: Received '%s' message (0x%04x) with"
1909 "incorrect length %d expecting %zu",
1910 rp_cmd_args[header_type].name, header_type, header_len,
1911 (size_t)rp_cmd_args[header_type].len);
1912 mark_source_rp_bad(ms);
1913 goto out;
1916 /* We know we've got a valid header by this point */
1917 res = qemu_get_buffer(rp, buf, header_len);
1918 if (res != header_len) {
1919 error_report("RP: Failed reading data for message 0x%04x"
1920 " read %d expected %d",
1921 header_type, res, header_len);
1922 mark_source_rp_bad(ms);
1923 goto out;
1926 /* OK, we have the message and the data */
1927 switch (header_type) {
1928 case MIG_RP_MSG_SHUT:
1929 sibling_error = ldl_be_p(buf);
1930 trace_source_return_path_thread_shut(sibling_error);
1931 if (sibling_error) {
1932 error_report("RP: Sibling indicated error %d", sibling_error);
1933 mark_source_rp_bad(ms);
1936 * We'll let the main thread deal with closing the RP
1937 * we could do a shutdown(2) on it, but we're the only user
1938 * anyway, so there's nothing gained.
1940 goto out;
1942 case MIG_RP_MSG_PONG:
1943 tmp32 = ldl_be_p(buf);
1944 trace_source_return_path_thread_pong(tmp32);
1945 qemu_sem_post(&ms->rp_state.rp_pong_acks);
1946 break;
1948 case MIG_RP_MSG_REQ_PAGES:
1949 start = ldq_be_p(buf);
1950 len = ldl_be_p(buf + 8);
1951 migrate_handle_rp_req_pages(ms, NULL, start, len);
1952 break;
1954 case MIG_RP_MSG_REQ_PAGES_ID:
1955 expected_len = 12 + 1; /* header + termination */
1957 if (header_len >= expected_len) {
1958 start = ldq_be_p(buf);
1959 len = ldl_be_p(buf + 8);
1960 /* Now we expect an idstr */
1961 tmp32 = buf[12]; /* Length of the following idstr */
1962 buf[13 + tmp32] = '\0';
1963 expected_len += tmp32;
1965 if (header_len != expected_len) {
1966 error_report("RP: Req_Page_id with length %d expecting %zd",
1967 header_len, expected_len);
1968 mark_source_rp_bad(ms);
1969 goto out;
1971 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1972 break;
1974 case MIG_RP_MSG_RECV_BITMAP:
1975 if (header_len < 1) {
1976 error_report("%s: missing block name", __func__);
1977 mark_source_rp_bad(ms);
1978 goto out;
1980 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
1981 buf[buf[0] + 1] = '\0';
1982 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
1983 mark_source_rp_bad(ms);
1984 goto out;
1986 break;
1988 case MIG_RP_MSG_RESUME_ACK:
1989 tmp32 = ldl_be_p(buf);
1990 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
1991 mark_source_rp_bad(ms);
1992 goto out;
1994 break;
1996 case MIG_RP_MSG_SWITCHOVER_ACK:
1997 ms->switchover_acked = true;
1998 trace_source_return_path_thread_switchover_acked();
1999 break;
2001 default:
2002 break;
2006 out:
2007 if (qemu_file_get_error(rp)) {
2008 trace_source_return_path_thread_bad_end();
2009 mark_source_rp_bad(ms);
2012 trace_source_return_path_thread_end();
2013 rcu_unregister_thread();
2014 return NULL;
2017 static int open_return_path_on_source(MigrationState *ms)
2019 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2020 if (!ms->rp_state.from_dst_file) {
2021 return -1;
2024 trace_open_return_path_on_source();
2026 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2027 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2028 ms->rp_state.rp_thread_created = true;
2030 trace_open_return_path_on_source_continue();
2032 return 0;
2035 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2036 static int await_return_path_close_on_source(MigrationState *ms)
2038 int ret;
2040 if (!ms->rp_state.rp_thread_created) {
2041 return 0;
2044 trace_migration_return_path_end_before();
2047 * If this is a normal exit then the destination will send a SHUT
2048 * and the rp_thread will exit, however if there's an error we
2049 * need to cause it to exit. shutdown(2), if we have it, will
2050 * cause it to unblock if it's stuck waiting for the destination.
2052 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2053 if (ms->to_dst_file && ms->rp_state.from_dst_file &&
2054 qemu_file_get_error(ms->to_dst_file)) {
2055 qemu_file_shutdown(ms->rp_state.from_dst_file);
2059 trace_await_return_path_close_on_source_joining();
2060 qemu_thread_join(&ms->rp_state.rp_thread);
2061 ms->rp_state.rp_thread_created = false;
2062 trace_await_return_path_close_on_source_close();
2064 ret = ms->rp_state.error;
2065 ms->rp_state.error = false;
2067 migration_release_dst_files(ms);
2069 trace_migration_return_path_end_after(ret);
2070 return ret;
2073 static inline void
2074 migration_wait_main_channel(MigrationState *ms)
2076 /* Wait until one PONG message received */
2077 qemu_sem_wait(&ms->rp_state.rp_pong_acks);
2081 * Switch from normal iteration to postcopy
2082 * Returns non-0 on error
2084 static int postcopy_start(MigrationState *ms, Error **errp)
2086 int ret;
2087 QIOChannelBuffer *bioc;
2088 QEMUFile *fb;
2089 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2090 uint64_t bandwidth = migrate_max_postcopy_bandwidth();
2091 bool restart_block = false;
2092 int cur_state = MIGRATION_STATUS_ACTIVE;
2094 if (migrate_postcopy_preempt()) {
2095 migration_wait_main_channel(ms);
2096 if (postcopy_preempt_establish_channel(ms)) {
2097 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
2098 return -1;
2102 if (!migrate_pause_before_switchover()) {
2103 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2104 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2107 trace_postcopy_start();
2108 qemu_mutex_lock_iothread();
2109 trace_postcopy_start_set_run();
2111 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2112 global_state_store();
2113 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2114 if (ret < 0) {
2115 goto fail;
2118 ret = migration_maybe_pause(ms, &cur_state,
2119 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2120 if (ret < 0) {
2121 goto fail;
2124 ret = bdrv_inactivate_all();
2125 if (ret < 0) {
2126 goto fail;
2128 restart_block = true;
2131 * Cause any non-postcopiable, but iterative devices to
2132 * send out their final data.
2134 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2137 * in Finish migrate and with the io-lock held everything should
2138 * be quiet, but we've potentially still got dirty pages and we
2139 * need to tell the destination to throw any pages it's already received
2140 * that are dirty
2142 if (migrate_postcopy_ram()) {
2143 ram_postcopy_send_discard_bitmap(ms);
2147 * send rest of state - note things that are doing postcopy
2148 * will notice we're in POSTCOPY_ACTIVE and not actually
2149 * wrap their state up here
2151 migration_rate_set(bandwidth);
2152 if (migrate_postcopy_ram()) {
2153 /* Ping just for debugging, helps line traces up */
2154 qemu_savevm_send_ping(ms->to_dst_file, 2);
2158 * While loading the device state we may trigger page transfer
2159 * requests and the fd must be free to process those, and thus
2160 * the destination must read the whole device state off the fd before
2161 * it starts processing it. Unfortunately the ad-hoc migration format
2162 * doesn't allow the destination to know the size to read without fully
2163 * parsing it through each devices load-state code (especially the open
2164 * coded devices that use get/put).
2165 * So we wrap the device state up in a package with a length at the start;
2166 * to do this we use a qemu_buf to hold the whole of the device state.
2168 bioc = qio_channel_buffer_new(4096);
2169 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2170 fb = qemu_file_new_output(QIO_CHANNEL(bioc));
2171 object_unref(OBJECT(bioc));
2174 * Make sure the receiver can get incoming pages before we send the rest
2175 * of the state
2177 qemu_savevm_send_postcopy_listen(fb);
2179 qemu_savevm_state_complete_precopy(fb, false, false);
2180 if (migrate_postcopy_ram()) {
2181 qemu_savevm_send_ping(fb, 3);
2184 qemu_savevm_send_postcopy_run(fb);
2186 /* <><> end of stuff going into the package */
2188 /* Last point of recovery; as soon as we send the package the destination
2189 * can open devices and potentially start running.
2190 * Lets just check again we've not got any errors.
2192 ret = qemu_file_get_error(ms->to_dst_file);
2193 if (ret) {
2194 error_setg(errp, "postcopy_start: Migration stream errored (pre package)");
2195 goto fail_closefb;
2198 restart_block = false;
2200 /* Now send that blob */
2201 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2202 goto fail_closefb;
2204 qemu_fclose(fb);
2206 /* Send a notify to give a chance for anything that needs to happen
2207 * at the transition to postcopy and after the device state; in particular
2208 * spice needs to trigger a transition now
2210 ms->postcopy_after_devices = true;
2211 notifier_list_notify(&migration_state_notifiers, ms);
2213 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2215 qemu_mutex_unlock_iothread();
2217 if (migrate_postcopy_ram()) {
2219 * Although this ping is just for debug, it could potentially be
2220 * used for getting a better measurement of downtime at the source.
2222 qemu_savevm_send_ping(ms->to_dst_file, 4);
2225 if (migrate_release_ram()) {
2226 ram_postcopy_migrated_memory_release(ms);
2229 ret = qemu_file_get_error(ms->to_dst_file);
2230 if (ret) {
2231 error_setg(errp, "postcopy_start: Migration stream errored");
2232 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2233 MIGRATION_STATUS_FAILED);
2236 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2238 return ret;
2240 fail_closefb:
2241 qemu_fclose(fb);
2242 fail:
2243 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2244 MIGRATION_STATUS_FAILED);
2245 if (restart_block) {
2246 /* A failure happened early enough that we know the destination hasn't
2247 * accessed block devices, so we're safe to recover.
2249 Error *local_err = NULL;
2251 bdrv_activate_all(&local_err);
2252 if (local_err) {
2253 error_report_err(local_err);
2256 qemu_mutex_unlock_iothread();
2257 return -1;
2261 * migration_maybe_pause: Pause if required to by
2262 * migrate_pause_before_switchover called with the iothread locked
2263 * Returns: 0 on success
2265 static int migration_maybe_pause(MigrationState *s,
2266 int *current_active_state,
2267 int new_state)
2269 if (!migrate_pause_before_switchover()) {
2270 return 0;
2273 /* Since leaving this state is not atomic with posting the semaphore
2274 * it's possible that someone could have issued multiple migrate_continue
2275 * and the semaphore is incorrectly positive at this point;
2276 * the docs say it's undefined to reinit a semaphore that's already
2277 * init'd, so use timedwait to eat up any existing posts.
2279 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2280 /* This block intentionally left blank */
2284 * If the migration is cancelled when it is in the completion phase,
2285 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2286 * So we don't need to wait a semaphore, otherwise we would always
2287 * wait for the 'pause_sem' semaphore.
2289 if (s->state != MIGRATION_STATUS_CANCELLING) {
2290 qemu_mutex_unlock_iothread();
2291 migrate_set_state(&s->state, *current_active_state,
2292 MIGRATION_STATUS_PRE_SWITCHOVER);
2293 qemu_sem_wait(&s->pause_sem);
2294 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2295 new_state);
2296 *current_active_state = new_state;
2297 qemu_mutex_lock_iothread();
2300 return s->state == new_state ? 0 : -EINVAL;
2304 * migration_completion: Used by migration_thread when there's not much left.
2305 * The caller 'breaks' the loop when this returns.
2307 * @s: Current migration state
2309 static void migration_completion(MigrationState *s)
2311 int ret;
2312 int current_active_state = s->state;
2314 if (s->state == MIGRATION_STATUS_ACTIVE) {
2315 qemu_mutex_lock_iothread();
2316 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2317 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2319 s->vm_old_state = runstate_get();
2320 global_state_store();
2322 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2323 trace_migration_completion_vm_stop(ret);
2324 if (ret >= 0) {
2325 ret = migration_maybe_pause(s, &current_active_state,
2326 MIGRATION_STATUS_DEVICE);
2328 if (ret >= 0) {
2330 * Inactivate disks except in COLO, and track that we
2331 * have done so in order to remember to reactivate
2332 * them if migration fails or is cancelled.
2334 s->block_inactive = !migrate_colo();
2335 migration_rate_set(RATE_LIMIT_DISABLED);
2336 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2337 s->block_inactive);
2340 qemu_mutex_unlock_iothread();
2342 if (ret < 0) {
2343 goto fail;
2345 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2346 trace_migration_completion_postcopy_end();
2348 qemu_mutex_lock_iothread();
2349 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2350 qemu_mutex_unlock_iothread();
2353 * Shutdown the postcopy fast path thread. This is only needed
2354 * when dest QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need
2355 * this.
2357 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
2358 postcopy_preempt_shutdown_file(s);
2361 trace_migration_completion_postcopy_end_after_complete();
2362 } else {
2363 goto fail;
2366 if (await_return_path_close_on_source(s)) {
2367 goto fail;
2370 if (qemu_file_get_error(s->to_dst_file)) {
2371 trace_migration_completion_file_err();
2372 goto fail;
2375 if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
2376 /* COLO does not support postcopy */
2377 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
2378 MIGRATION_STATUS_COLO);
2379 } else {
2380 migrate_set_state(&s->state, current_active_state,
2381 MIGRATION_STATUS_COMPLETED);
2384 return;
2386 fail:
2387 if (s->block_inactive && (s->state == MIGRATION_STATUS_ACTIVE ||
2388 s->state == MIGRATION_STATUS_DEVICE)) {
2390 * If not doing postcopy, vm_start() will be called: let's
2391 * regain control on images.
2393 Error *local_err = NULL;
2395 qemu_mutex_lock_iothread();
2396 bdrv_activate_all(&local_err);
2397 if (local_err) {
2398 error_report_err(local_err);
2399 } else {
2400 s->block_inactive = false;
2402 qemu_mutex_unlock_iothread();
2405 migrate_set_state(&s->state, current_active_state,
2406 MIGRATION_STATUS_FAILED);
2410 * bg_migration_completion: Used by bg_migration_thread when after all the
2411 * RAM has been saved. The caller 'breaks' the loop when this returns.
2413 * @s: Current migration state
2415 static void bg_migration_completion(MigrationState *s)
2417 int current_active_state = s->state;
2419 if (s->state == MIGRATION_STATUS_ACTIVE) {
2421 * By this moment we have RAM content saved into the migration stream.
2422 * The next step is to flush the non-RAM content (device state)
2423 * right after the ram content. The device state has been stored into
2424 * the temporary buffer before RAM saving started.
2426 qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
2427 qemu_fflush(s->to_dst_file);
2428 } else if (s->state == MIGRATION_STATUS_CANCELLING) {
2429 goto fail;
2432 if (qemu_file_get_error(s->to_dst_file)) {
2433 trace_migration_completion_file_err();
2434 goto fail;
2437 migrate_set_state(&s->state, current_active_state,
2438 MIGRATION_STATUS_COMPLETED);
2439 return;
2441 fail:
2442 migrate_set_state(&s->state, current_active_state,
2443 MIGRATION_STATUS_FAILED);
2446 typedef enum MigThrError {
2447 /* No error detected */
2448 MIG_THR_ERR_NONE = 0,
2449 /* Detected error, but resumed successfully */
2450 MIG_THR_ERR_RECOVERED = 1,
2451 /* Detected fatal error, need to exit */
2452 MIG_THR_ERR_FATAL = 2,
2453 } MigThrError;
2455 static int postcopy_resume_handshake(MigrationState *s)
2457 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2459 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2460 qemu_sem_wait(&s->rp_state.rp_sem);
2463 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2464 return 0;
2467 return -1;
2470 /* Return zero if success, or <0 for error */
2471 static int postcopy_do_resume(MigrationState *s)
2473 int ret;
2476 * Call all the resume_prepare() hooks, so that modules can be
2477 * ready for the migration resume.
2479 ret = qemu_savevm_state_resume_prepare(s);
2480 if (ret) {
2481 error_report("%s: resume_prepare() failure detected: %d",
2482 __func__, ret);
2483 return ret;
2487 * If preempt is enabled, re-establish the preempt channel. Note that
2488 * we do it after resume prepare to make sure the main channel will be
2489 * created before the preempt channel. E.g. with weak network, the
2490 * dest QEMU may get messed up with the preempt and main channels on
2491 * the order of connection setup. This guarantees the correct order.
2493 ret = postcopy_preempt_establish_channel(s);
2494 if (ret) {
2495 error_report("%s: postcopy_preempt_establish_channel(): %d",
2496 __func__, ret);
2497 return ret;
2501 * Last handshake with destination on the resume (destination will
2502 * switch to postcopy-active afterwards)
2504 ret = postcopy_resume_handshake(s);
2505 if (ret) {
2506 error_report("%s: handshake failed: %d", __func__, ret);
2507 return ret;
2510 return 0;
2514 * We don't return until we are in a safe state to continue current
2515 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2516 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2518 static MigThrError postcopy_pause(MigrationState *s)
2520 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2522 while (true) {
2523 QEMUFile *file;
2526 * Current channel is possibly broken. Release it. Note that this is
2527 * guaranteed even without lock because to_dst_file should only be
2528 * modified by the migration thread. That also guarantees that the
2529 * unregister of yank is safe too without the lock. It should be safe
2530 * even to be within the qemu_file_lock, but we didn't do that to avoid
2531 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2532 * the qemu_file_lock critical section as small as possible.
2534 assert(s->to_dst_file);
2535 migration_ioc_unregister_yank_from_file(s->to_dst_file);
2536 qemu_mutex_lock(&s->qemu_file_lock);
2537 file = s->to_dst_file;
2538 s->to_dst_file = NULL;
2539 qemu_mutex_unlock(&s->qemu_file_lock);
2541 qemu_file_shutdown(file);
2542 qemu_fclose(file);
2545 * We're already pausing, so ignore any errors on the return
2546 * path and just wait for the thread to finish. It will be
2547 * re-created when we resume.
2549 await_return_path_close_on_source(s);
2551 migrate_set_state(&s->state, s->state,
2552 MIGRATION_STATUS_POSTCOPY_PAUSED);
2554 error_report("Detected IO failure for postcopy. "
2555 "Migration paused.");
2558 * We wait until things fixed up. Then someone will setup the
2559 * status back for us.
2561 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2562 qemu_sem_wait(&s->postcopy_pause_sem);
2565 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2566 /* Woken up by a recover procedure. Give it a shot */
2568 /* Do the resume logic */
2569 if (postcopy_do_resume(s) == 0) {
2570 /* Let's continue! */
2571 trace_postcopy_pause_continued();
2572 return MIG_THR_ERR_RECOVERED;
2573 } else {
2575 * Something wrong happened during the recovery, let's
2576 * pause again. Pause is always better than throwing
2577 * data away.
2579 continue;
2581 } else {
2582 /* This is not right... Time to quit. */
2583 return MIG_THR_ERR_FATAL;
2588 static MigThrError migration_detect_error(MigrationState *s)
2590 int ret;
2591 int state = s->state;
2592 Error *local_error = NULL;
2594 if (state == MIGRATION_STATUS_CANCELLING ||
2595 state == MIGRATION_STATUS_CANCELLED) {
2596 /* End the migration, but don't set the state to failed */
2597 return MIG_THR_ERR_FATAL;
2601 * Try to detect any file errors. Note that postcopy_qemufile_src will
2602 * be NULL when postcopy preempt is not enabled.
2604 ret = qemu_file_get_error_obj_any(s->to_dst_file,
2605 s->postcopy_qemufile_src,
2606 &local_error);
2607 if (!ret) {
2608 /* Everything is fine */
2609 assert(!local_error);
2610 return MIG_THR_ERR_NONE;
2613 if (local_error) {
2614 migrate_set_error(s, local_error);
2615 error_free(local_error);
2618 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
2620 * For postcopy, we allow the network to be down for a
2621 * while. After that, it can be continued by a
2622 * recovery phase.
2624 return postcopy_pause(s);
2625 } else {
2627 * For precopy (or postcopy with error outside IO), we fail
2628 * with no time.
2630 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
2631 trace_migration_thread_file_err();
2633 /* Time to stop the migration, now. */
2634 return MIG_THR_ERR_FATAL;
2638 static void migration_calculate_complete(MigrationState *s)
2640 uint64_t bytes = migration_transferred_bytes(s->to_dst_file);
2641 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2642 int64_t transfer_time;
2644 s->total_time = end_time - s->start_time;
2645 if (!s->downtime) {
2647 * It's still not set, so we are precopy migration. For
2648 * postcopy, downtime is calculated during postcopy_start().
2650 s->downtime = end_time - s->downtime_start;
2653 transfer_time = s->total_time - s->setup_time;
2654 if (transfer_time) {
2655 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
2659 static void update_iteration_initial_status(MigrationState *s)
2662 * Update these three fields at the same time to avoid mismatch info lead
2663 * wrong speed calculation.
2665 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2666 s->iteration_initial_bytes = migration_transferred_bytes(s->to_dst_file);
2667 s->iteration_initial_pages = ram_get_total_transferred_pages();
2670 static void migration_update_counters(MigrationState *s,
2671 int64_t current_time)
2673 uint64_t transferred, transferred_pages, time_spent;
2674 uint64_t current_bytes; /* bytes transferred since the beginning */
2675 double bandwidth;
2677 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2678 return;
2681 current_bytes = migration_transferred_bytes(s->to_dst_file);
2682 transferred = current_bytes - s->iteration_initial_bytes;
2683 time_spent = current_time - s->iteration_start_time;
2684 bandwidth = (double)transferred / time_spent;
2685 s->threshold_size = bandwidth * migrate_downtime_limit();
2687 s->mbps = (((double) transferred * 8.0) /
2688 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2690 transferred_pages = ram_get_total_transferred_pages() -
2691 s->iteration_initial_pages;
2692 s->pages_per_second = (double) transferred_pages /
2693 (((double) time_spent / 1000.0));
2696 * if we haven't sent anything, we don't want to
2697 * recalculate. 10000 is a small enough number for our purposes
2699 if (stat64_get(&mig_stats.dirty_pages_rate) &&
2700 transferred > 10000) {
2701 s->expected_downtime =
2702 stat64_get(&mig_stats.dirty_bytes_last_sync) / bandwidth;
2705 migration_rate_reset(s->to_dst_file);
2707 update_iteration_initial_status(s);
2709 trace_migrate_transferred(transferred, time_spent,
2710 bandwidth, s->threshold_size);
2713 static bool migration_can_switchover(MigrationState *s)
2715 if (!migrate_switchover_ack()) {
2716 return true;
2719 /* No reason to wait for switchover ACK if VM is stopped */
2720 if (!runstate_is_running()) {
2721 return true;
2724 return s->switchover_acked;
2727 /* Migration thread iteration status */
2728 typedef enum {
2729 MIG_ITERATE_RESUME, /* Resume current iteration */
2730 MIG_ITERATE_SKIP, /* Skip current iteration */
2731 MIG_ITERATE_BREAK, /* Break the loop */
2732 } MigIterateState;
2735 * Return true if continue to the next iteration directly, false
2736 * otherwise.
2738 static MigIterateState migration_iteration_run(MigrationState *s)
2740 uint64_t must_precopy, can_postcopy;
2741 Error *local_err = NULL;
2742 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2743 bool can_switchover = migration_can_switchover(s);
2745 qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
2746 uint64_t pending_size = must_precopy + can_postcopy;
2748 trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
2750 if (must_precopy <= s->threshold_size) {
2751 qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
2752 pending_size = must_precopy + can_postcopy;
2753 trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
2756 if ((!pending_size || pending_size < s->threshold_size) && can_switchover) {
2757 trace_migration_thread_low_pending(pending_size);
2758 migration_completion(s);
2759 return MIG_ITERATE_BREAK;
2762 /* Still a significant amount to transfer */
2763 if (!in_postcopy && must_precopy <= s->threshold_size && can_switchover &&
2764 qatomic_read(&s->start_postcopy)) {
2765 if (postcopy_start(s, &local_err)) {
2766 migrate_set_error(s, local_err);
2767 error_report_err(local_err);
2769 return MIG_ITERATE_SKIP;
2772 /* Just another iteration step */
2773 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
2774 return MIG_ITERATE_RESUME;
2777 static void migration_iteration_finish(MigrationState *s)
2779 /* If we enabled cpu throttling for auto-converge, turn it off. */
2780 cpu_throttle_stop();
2782 qemu_mutex_lock_iothread();
2783 switch (s->state) {
2784 case MIGRATION_STATUS_COMPLETED:
2785 migration_calculate_complete(s);
2786 runstate_set(RUN_STATE_POSTMIGRATE);
2787 break;
2788 case MIGRATION_STATUS_COLO:
2789 assert(migrate_colo());
2790 migrate_start_colo_process(s);
2791 s->vm_old_state = RUN_STATE_RUNNING;
2792 /* Fallthrough */
2793 case MIGRATION_STATUS_FAILED:
2794 case MIGRATION_STATUS_CANCELLED:
2795 case MIGRATION_STATUS_CANCELLING:
2796 if (s->vm_old_state == RUN_STATE_RUNNING) {
2797 if (!runstate_check(RUN_STATE_SHUTDOWN)) {
2798 vm_start();
2800 } else {
2801 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2802 runstate_set(s->vm_old_state);
2805 break;
2807 default:
2808 /* Should not reach here, but if so, forgive the VM. */
2809 error_report("%s: Unknown ending state %d", __func__, s->state);
2810 break;
2812 migrate_fd_cleanup_schedule(s);
2813 qemu_mutex_unlock_iothread();
2816 static void bg_migration_iteration_finish(MigrationState *s)
2819 * Stop tracking RAM writes - un-protect memory, un-register UFFD
2820 * memory ranges, flush kernel wait queues and wake up threads
2821 * waiting for write fault to be resolved.
2823 ram_write_tracking_stop();
2825 qemu_mutex_lock_iothread();
2826 switch (s->state) {
2827 case MIGRATION_STATUS_COMPLETED:
2828 migration_calculate_complete(s);
2829 break;
2831 case MIGRATION_STATUS_ACTIVE:
2832 case MIGRATION_STATUS_FAILED:
2833 case MIGRATION_STATUS_CANCELLED:
2834 case MIGRATION_STATUS_CANCELLING:
2835 break;
2837 default:
2838 /* Should not reach here, but if so, forgive the VM. */
2839 error_report("%s: Unknown ending state %d", __func__, s->state);
2840 break;
2843 migrate_fd_cleanup_schedule(s);
2844 qemu_mutex_unlock_iothread();
2848 * Return true if continue to the next iteration directly, false
2849 * otherwise.
2851 static MigIterateState bg_migration_iteration_run(MigrationState *s)
2853 int res;
2855 res = qemu_savevm_state_iterate(s->to_dst_file, false);
2856 if (res > 0) {
2857 bg_migration_completion(s);
2858 return MIG_ITERATE_BREAK;
2861 return MIG_ITERATE_RESUME;
2864 void migration_make_urgent_request(void)
2866 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
2869 void migration_consume_urgent_request(void)
2871 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
2874 /* Returns true if the rate limiting was broken by an urgent request */
2875 bool migration_rate_limit(void)
2877 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2878 MigrationState *s = migrate_get_current();
2880 bool urgent = false;
2881 migration_update_counters(s, now);
2882 if (migration_rate_exceeded(s->to_dst_file)) {
2884 if (qemu_file_get_error(s->to_dst_file)) {
2885 return false;
2888 * Wait for a delay to do rate limiting OR
2889 * something urgent to post the semaphore.
2891 int ms = s->iteration_start_time + BUFFER_DELAY - now;
2892 trace_migration_rate_limit_pre(ms);
2893 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
2895 * We were woken by one or more urgent things but
2896 * the timedwait will have consumed one of them.
2897 * The service routine for the urgent wake will dec
2898 * the semaphore itself for each item it consumes,
2899 * so add this one we just eat back.
2901 qemu_sem_post(&s->rate_limit_sem);
2902 urgent = true;
2904 trace_migration_rate_limit_post(urgent);
2906 return urgent;
2910 * if failover devices are present, wait they are completely
2911 * unplugged
2914 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
2915 int new_state)
2917 if (qemu_savevm_state_guest_unplug_pending()) {
2918 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
2920 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
2921 qemu_savevm_state_guest_unplug_pending()) {
2922 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
2924 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
2925 int timeout = 120; /* 30 seconds */
2927 * migration has been canceled
2928 * but as we have started an unplug we must wait the end
2929 * to be able to plug back the card
2931 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
2932 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
2934 if (qemu_savevm_state_guest_unplug_pending() &&
2935 !qtest_enabled()) {
2936 warn_report("migration: partially unplugged device on "
2937 "failure");
2941 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
2942 } else {
2943 migrate_set_state(&s->state, old_state, new_state);
2948 * Master migration thread on the source VM.
2949 * It drives the migration and pumps the data down the outgoing channel.
2951 static void *migration_thread(void *opaque)
2953 MigrationState *s = opaque;
2954 MigrationThread *thread = NULL;
2955 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2956 MigThrError thr_error;
2957 bool urgent = false;
2959 thread = migration_threads_add("live_migration", qemu_get_thread_id());
2961 rcu_register_thread();
2963 object_ref(OBJECT(s));
2964 update_iteration_initial_status(s);
2966 qemu_savevm_state_header(s->to_dst_file);
2969 * If we opened the return path, we need to make sure dst has it
2970 * opened as well.
2972 if (s->rp_state.rp_thread_created) {
2973 /* Now tell the dest that it should open its end so it can reply */
2974 qemu_savevm_send_open_return_path(s->to_dst_file);
2976 /* And do a ping that will make stuff easier to debug */
2977 qemu_savevm_send_ping(s->to_dst_file, 1);
2980 if (migrate_postcopy()) {
2982 * Tell the destination that we *might* want to do postcopy later;
2983 * if the other end can't do postcopy it should fail now, nice and
2984 * early.
2986 qemu_savevm_send_postcopy_advise(s->to_dst_file);
2989 if (migrate_colo()) {
2990 /* Notify migration destination that we enable COLO */
2991 qemu_savevm_send_colo_enable(s->to_dst_file);
2994 qemu_savevm_state_setup(s->to_dst_file);
2996 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
2997 MIGRATION_STATUS_ACTIVE);
2999 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3001 trace_migration_thread_setup_complete();
3003 while (migration_is_active(s)) {
3004 if (urgent || !migration_rate_exceeded(s->to_dst_file)) {
3005 MigIterateState iter_state = migration_iteration_run(s);
3006 if (iter_state == MIG_ITERATE_SKIP) {
3007 continue;
3008 } else if (iter_state == MIG_ITERATE_BREAK) {
3009 break;
3014 * Try to detect any kind of failures, and see whether we
3015 * should stop the migration now.
3017 thr_error = migration_detect_error(s);
3018 if (thr_error == MIG_THR_ERR_FATAL) {
3019 /* Stop migration */
3020 break;
3021 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3023 * Just recovered from a e.g. network failure, reset all
3024 * the local variables. This is important to avoid
3025 * breaking transferred_bytes and bandwidth calculation
3027 update_iteration_initial_status(s);
3030 urgent = migration_rate_limit();
3033 trace_migration_thread_after_loop();
3034 migration_iteration_finish(s);
3035 object_unref(OBJECT(s));
3036 rcu_unregister_thread();
3037 migration_threads_remove(thread);
3038 return NULL;
3041 static void bg_migration_vm_start_bh(void *opaque)
3043 MigrationState *s = opaque;
3045 qemu_bh_delete(s->vm_start_bh);
3046 s->vm_start_bh = NULL;
3048 vm_start();
3049 s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
3053 * Background snapshot thread, based on live migration code.
3054 * This is an alternative implementation of live migration mechanism
3055 * introduced specifically to support background snapshots.
3057 * It takes advantage of userfault_fd write protection mechanism introduced
3058 * in v5.7 kernel. Compared to existing dirty page logging migration much
3059 * lesser stream traffic is produced resulting in smaller snapshot images,
3060 * simply cause of no page duplicates can get into the stream.
3062 * Another key point is that generated vmstate stream reflects machine state
3063 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3064 * mechanism, which effectively results in that saved snapshot is the state of VM
3065 * at the end of the process.
3067 static void *bg_migration_thread(void *opaque)
3069 MigrationState *s = opaque;
3070 int64_t setup_start;
3071 MigThrError thr_error;
3072 QEMUFile *fb;
3073 bool early_fail = true;
3075 rcu_register_thread();
3076 object_ref(OBJECT(s));
3078 migration_rate_set(RATE_LIMIT_DISABLED);
3080 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3082 * We want to save vmstate for the moment when migration has been
3083 * initiated but also we want to save RAM content while VM is running.
3084 * The RAM content should appear first in the vmstate. So, we first
3085 * stash the non-RAM part of the vmstate to the temporary buffer,
3086 * then write RAM part of the vmstate to the migration stream
3087 * with vCPUs running and, finally, write stashed non-RAM part of
3088 * the vmstate from the buffer to the migration stream.
3090 s->bioc = qio_channel_buffer_new(512 * 1024);
3091 qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
3092 fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
3093 object_unref(OBJECT(s->bioc));
3095 update_iteration_initial_status(s);
3098 * Prepare for tracking memory writes with UFFD-WP - populate
3099 * RAM pages before protecting.
3101 #ifdef __linux__
3102 ram_write_tracking_prepare();
3103 #endif
3105 qemu_savevm_state_header(s->to_dst_file);
3106 qemu_savevm_state_setup(s->to_dst_file);
3108 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3109 MIGRATION_STATUS_ACTIVE);
3111 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3113 trace_migration_thread_setup_complete();
3114 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3116 qemu_mutex_lock_iothread();
3119 * If VM is currently in suspended state, then, to make a valid runstate
3120 * transition in vm_stop_force_state() we need to wakeup it up.
3122 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3123 s->vm_old_state = runstate_get();
3125 global_state_store();
3126 /* Forcibly stop VM before saving state of vCPUs and devices */
3127 if (vm_stop_force_state(RUN_STATE_PAUSED)) {
3128 goto fail;
3131 * Put vCPUs in sync with shadow context structures, then
3132 * save their state to channel-buffer along with devices.
3134 cpu_synchronize_all_states();
3135 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
3136 goto fail;
3139 * Since we are going to get non-iterable state data directly
3140 * from s->bioc->data, explicit flush is needed here.
3142 qemu_fflush(fb);
3144 /* Now initialize UFFD context and start tracking RAM writes */
3145 if (ram_write_tracking_start()) {
3146 goto fail;
3148 early_fail = false;
3151 * Start VM from BH handler to avoid write-fault lock here.
3152 * UFFD-WP protection for the whole RAM is already enabled so
3153 * calling VM state change notifiers from vm_start() would initiate
3154 * writes to virtio VQs memory which is in write-protected region.
3156 s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
3157 qemu_bh_schedule(s->vm_start_bh);
3159 qemu_mutex_unlock_iothread();
3161 while (migration_is_active(s)) {
3162 MigIterateState iter_state = bg_migration_iteration_run(s);
3163 if (iter_state == MIG_ITERATE_SKIP) {
3164 continue;
3165 } else if (iter_state == MIG_ITERATE_BREAK) {
3166 break;
3170 * Try to detect any kind of failures, and see whether we
3171 * should stop the migration now.
3173 thr_error = migration_detect_error(s);
3174 if (thr_error == MIG_THR_ERR_FATAL) {
3175 /* Stop migration */
3176 break;
3179 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
3182 trace_migration_thread_after_loop();
3184 fail:
3185 if (early_fail) {
3186 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3187 MIGRATION_STATUS_FAILED);
3188 qemu_mutex_unlock_iothread();
3191 bg_migration_iteration_finish(s);
3193 qemu_fclose(fb);
3194 object_unref(OBJECT(s));
3195 rcu_unregister_thread();
3197 return NULL;
3200 void migrate_fd_connect(MigrationState *s, Error *error_in)
3202 Error *local_err = NULL;
3203 uint64_t rate_limit;
3204 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3207 * If there's a previous error, free it and prepare for another one.
3208 * Meanwhile if migration completes successfully, there won't have an error
3209 * dumped when calling migrate_fd_cleanup().
3211 migrate_error_free(s);
3213 s->expected_downtime = migrate_downtime_limit();
3214 if (resume) {
3215 assert(s->cleanup_bh);
3216 } else {
3217 assert(!s->cleanup_bh);
3218 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
3220 if (error_in) {
3221 migrate_fd_error(s, error_in);
3222 if (resume) {
3224 * Don't do cleanup for resume if channel is invalid, but only dump
3225 * the error. We wait for another channel connect from the user.
3226 * The error_report still gives HMP user a hint on what failed.
3227 * It's normally done in migrate_fd_cleanup(), but call it here
3228 * explicitly.
3230 error_report_err(error_copy(s->error));
3231 } else {
3232 migrate_fd_cleanup(s);
3234 return;
3237 if (resume) {
3238 /* This is a resumed migration */
3239 rate_limit = migrate_max_postcopy_bandwidth();
3240 } else {
3241 /* This is a fresh new migration */
3242 rate_limit = migrate_max_bandwidth();
3244 /* Notify before starting migration thread */
3245 notifier_list_notify(&migration_state_notifiers, s);
3248 migration_rate_set(rate_limit);
3249 qemu_file_set_blocking(s->to_dst_file, true);
3252 * Open the return path. For postcopy, it is used exclusively. For
3253 * precopy, only if user specified "return-path" capability would
3254 * QEMU uses the return path.
3256 if (migrate_postcopy_ram() || migrate_return_path()) {
3257 if (open_return_path_on_source(s)) {
3258 error_setg(&local_err, "Unable to open return-path for postcopy");
3259 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3260 migrate_set_error(s, local_err);
3261 error_report_err(local_err);
3262 migrate_fd_cleanup(s);
3263 return;
3268 * This needs to be done before resuming a postcopy. Note: for newer
3269 * QEMUs we will delay the channel creation until postcopy_start(), to
3270 * avoid disorder of channel creations.
3272 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
3273 postcopy_preempt_setup(s);
3276 if (resume) {
3277 /* Wakeup the main migration thread to do the recovery */
3278 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3279 MIGRATION_STATUS_POSTCOPY_RECOVER);
3280 qemu_sem_post(&s->postcopy_pause_sem);
3281 return;
3284 if (multifd_save_setup(&local_err) != 0) {
3285 migrate_set_error(s, local_err);
3286 error_report_err(local_err);
3287 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3288 MIGRATION_STATUS_FAILED);
3289 migrate_fd_cleanup(s);
3290 return;
3293 if (migrate_background_snapshot()) {
3294 qemu_thread_create(&s->thread, "bg_snapshot",
3295 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
3296 } else {
3297 qemu_thread_create(&s->thread, "live_migration",
3298 migration_thread, s, QEMU_THREAD_JOINABLE);
3300 s->migration_thread_running = true;
3303 static void migration_class_init(ObjectClass *klass, void *data)
3305 DeviceClass *dc = DEVICE_CLASS(klass);
3307 dc->user_creatable = false;
3308 device_class_set_props(dc, migration_properties);
3311 static void migration_instance_finalize(Object *obj)
3313 MigrationState *ms = MIGRATION_OBJ(obj);
3315 qemu_mutex_destroy(&ms->error_mutex);
3316 qemu_mutex_destroy(&ms->qemu_file_lock);
3317 qemu_sem_destroy(&ms->wait_unplug_sem);
3318 qemu_sem_destroy(&ms->rate_limit_sem);
3319 qemu_sem_destroy(&ms->pause_sem);
3320 qemu_sem_destroy(&ms->postcopy_pause_sem);
3321 qemu_sem_destroy(&ms->rp_state.rp_sem);
3322 qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
3323 qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
3324 error_free(ms->error);
3327 static void migration_instance_init(Object *obj)
3329 MigrationState *ms = MIGRATION_OBJ(obj);
3331 ms->state = MIGRATION_STATUS_NONE;
3332 ms->mbps = -1;
3333 ms->pages_per_second = -1;
3334 qemu_sem_init(&ms->pause_sem, 0);
3335 qemu_mutex_init(&ms->error_mutex);
3337 migrate_params_init(&ms->parameters);
3339 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3340 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3341 qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
3342 qemu_sem_init(&ms->rate_limit_sem, 0);
3343 qemu_sem_init(&ms->wait_unplug_sem, 0);
3344 qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
3345 qemu_mutex_init(&ms->qemu_file_lock);
3349 * Return true if check pass, false otherwise. Error will be put
3350 * inside errp if provided.
3352 static bool migration_object_check(MigrationState *ms, Error **errp)
3354 /* Assuming all off */
3355 bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
3357 if (!migrate_params_check(&ms->parameters, errp)) {
3358 return false;
3361 return migrate_caps_check(old_caps, ms->capabilities, errp);
3364 static const TypeInfo migration_type = {
3365 .name = TYPE_MIGRATION,
3367 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3368 * not created using qdev_new(), it is not attached to the qdev
3369 * device tree, and it is never realized.
3371 * TODO: Make this TYPE_OBJECT once QOM provides something like
3372 * TYPE_DEVICE's "-global" properties.
3374 .parent = TYPE_DEVICE,
3375 .class_init = migration_class_init,
3376 .class_size = sizeof(MigrationClass),
3377 .instance_size = sizeof(MigrationState),
3378 .instance_init = migration_instance_init,
3379 .instance_finalize = migration_instance_finalize,
3382 static void register_migration_types(void)
3384 type_register_static(&migration_type);
3387 type_init(register_migration_types);