migration: check magic value for deciding the mapping of channels
[qemu/armbru.git] / migration / migration.c
blob66c74f8e173434158d390528c72cbca20882ba4a
1 /*
2 * QEMU live migration
4 * Copyright IBM, Corp. 2008
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "qemu/main-loop.h"
20 #include "migration/blocker.h"
21 #include "exec.h"
22 #include "fd.h"
23 #include "socket.h"
24 #include "sysemu/runstate.h"
25 #include "sysemu/sysemu.h"
26 #include "sysemu/cpu-throttle.h"
27 #include "rdma.h"
28 #include "ram.h"
29 #include "migration/global_state.h"
30 #include "migration/misc.h"
31 #include "migration.h"
32 #include "savevm.h"
33 #include "qemu-file.h"
34 #include "channel.h"
35 #include "migration/vmstate.h"
36 #include "block/block.h"
37 #include "qapi/error.h"
38 #include "qapi/clone-visitor.h"
39 #include "qapi/qapi-visit-migration.h"
40 #include "qapi/qapi-visit-sockets.h"
41 #include "qapi/qapi-commands-migration.h"
42 #include "qapi/qapi-events-migration.h"
43 #include "qapi/qmp/qerror.h"
44 #include "qapi/qmp/qnull.h"
45 #include "qemu/rcu.h"
46 #include "block.h"
47 #include "postcopy-ram.h"
48 #include "qemu/thread.h"
49 #include "trace.h"
50 #include "exec/target_page.h"
51 #include "io/channel-buffer.h"
52 #include "io/channel-tls.h"
53 #include "migration/colo.h"
54 #include "hw/boards.h"
55 #include "hw/qdev-properties.h"
56 #include "hw/qdev-properties-system.h"
57 #include "monitor/monitor.h"
58 #include "net/announce.h"
59 #include "qemu/queue.h"
60 #include "multifd.h"
61 #include "qemu/yank.h"
62 #include "sysemu/cpus.h"
63 #include "yank_functions.h"
64 #include "sysemu/qtest.h"
65 #include "ui/qemu-spice.h"
67 #define MAX_THROTTLE (128 << 20) /* Migration transfer speed throttling */
69 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
70 * data. */
71 #define BUFFER_DELAY 100
72 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
74 /* Time in milliseconds we are allowed to stop the source,
75 * for sending the last part */
76 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
78 /* Maximum migrate downtime set to 2000 seconds */
79 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
80 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
82 /* Default compression thread count */
83 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
84 /* Default decompression thread count, usually decompression is at
85 * least 4 times as fast as compression.*/
86 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
87 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
88 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
89 /* Define default autoconverge cpu throttle migration parameters */
90 #define DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD 50
91 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
92 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
93 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
95 /* Migration XBZRLE default cache size */
96 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
98 /* The delay time (in ms) between two COLO checkpoints */
99 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
100 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
101 #define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE
102 /* 0: means nocompress, 1: best speed, ... 9: best compress ratio */
103 #define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1
104 /* 0: means nocompress, 1: best speed, ... 20: best compress ratio */
105 #define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1
107 /* Background transfer rate for postcopy, 0 means unlimited, note
108 * that page requests can still exceed this limit.
110 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
113 * Parameters for self_announce_delay giving a stream of RARP/ARP
114 * packets after migration.
116 #define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50
117 #define DEFAULT_MIGRATE_ANNOUNCE_MAX 550
118 #define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5
119 #define DEFAULT_MIGRATE_ANNOUNCE_STEP 100
121 static NotifierList migration_state_notifiers =
122 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
124 /* Messages sent on the return path from destination to source */
125 enum mig_rp_message_type {
126 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
127 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
128 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
130 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
131 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
132 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
133 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
135 MIG_RP_MSG_MAX
138 /* Migration capabilities set */
139 struct MigrateCapsSet {
140 int size; /* Capability set size */
141 MigrationCapability caps[]; /* Variadic array of capabilities */
143 typedef struct MigrateCapsSet MigrateCapsSet;
145 /* Define and initialize MigrateCapsSet */
146 #define INITIALIZE_MIGRATE_CAPS_SET(_name, ...) \
147 MigrateCapsSet _name = { \
148 .size = sizeof((int []) { __VA_ARGS__ }) / sizeof(int), \
149 .caps = { __VA_ARGS__ } \
152 /* Background-snapshot compatibility check list */
153 static const
154 INITIALIZE_MIGRATE_CAPS_SET(check_caps_background_snapshot,
155 MIGRATION_CAPABILITY_POSTCOPY_RAM,
156 MIGRATION_CAPABILITY_DIRTY_BITMAPS,
157 MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME,
158 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE,
159 MIGRATION_CAPABILITY_RETURN_PATH,
160 MIGRATION_CAPABILITY_MULTIFD,
161 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER,
162 MIGRATION_CAPABILITY_AUTO_CONVERGE,
163 MIGRATION_CAPABILITY_RELEASE_RAM,
164 MIGRATION_CAPABILITY_RDMA_PIN_ALL,
165 MIGRATION_CAPABILITY_COMPRESS,
166 MIGRATION_CAPABILITY_XBZRLE,
167 MIGRATION_CAPABILITY_X_COLO,
168 MIGRATION_CAPABILITY_VALIDATE_UUID,
169 MIGRATION_CAPABILITY_ZERO_COPY_SEND);
171 /* When we add fault tolerance, we could have several
172 migrations at once. For now we don't need to add
173 dynamic creation of migration */
175 static MigrationState *current_migration;
176 static MigrationIncomingState *current_incoming;
178 static GSList *migration_blockers;
180 static bool migration_object_check(MigrationState *ms, Error **errp);
181 static int migration_maybe_pause(MigrationState *s,
182 int *current_active_state,
183 int new_state);
184 static void migrate_fd_cancel(MigrationState *s);
186 static bool migrate_allow_multi_channels = true;
188 void migrate_protocol_allow_multi_channels(bool allow)
190 migrate_allow_multi_channels = allow;
193 bool migrate_multi_channels_is_allowed(void)
195 return migrate_allow_multi_channels;
198 static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
200 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
202 return (a > b) - (a < b);
205 void migration_object_init(void)
207 /* This can only be called once. */
208 assert(!current_migration);
209 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
212 * Init the migrate incoming object as well no matter whether
213 * we'll use it or not.
215 assert(!current_incoming);
216 current_incoming = g_new0(MigrationIncomingState, 1);
217 current_incoming->state = MIGRATION_STATUS_NONE;
218 current_incoming->postcopy_remote_fds =
219 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
220 qemu_mutex_init(&current_incoming->rp_mutex);
221 qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
222 qemu_event_init(&current_incoming->main_thread_load_event, false);
223 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
224 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
225 qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
226 qemu_mutex_init(&current_incoming->page_request_mutex);
227 current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
229 migration_object_check(current_migration, &error_fatal);
231 blk_mig_init();
232 ram_mig_init();
233 dirty_bitmap_mig_init();
236 void migration_cancel(const Error *error)
238 if (error) {
239 migrate_set_error(current_migration, error);
241 migrate_fd_cancel(current_migration);
244 void migration_shutdown(void)
247 * When the QEMU main thread exit, the COLO thread
248 * may wait a semaphore. So, we should wakeup the
249 * COLO thread before migration shutdown.
251 colo_shutdown();
253 * Cancel the current migration - that will (eventually)
254 * stop the migration using this structure
256 migration_cancel(NULL);
257 object_unref(OBJECT(current_migration));
260 * Cancel outgoing migration of dirty bitmaps. It should
261 * at least unref used block nodes.
263 dirty_bitmap_mig_cancel_outgoing();
266 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
267 * are non-critical data, and their loss never considered as
268 * something serious.
270 dirty_bitmap_mig_cancel_incoming();
273 /* For outgoing */
274 MigrationState *migrate_get_current(void)
276 /* This can only be called after the object created. */
277 assert(current_migration);
278 return current_migration;
281 MigrationIncomingState *migration_incoming_get_current(void)
283 assert(current_incoming);
284 return current_incoming;
287 void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
289 if (mis->socket_address_list) {
290 qapi_free_SocketAddressList(mis->socket_address_list);
291 mis->socket_address_list = NULL;
294 if (mis->transport_cleanup) {
295 mis->transport_cleanup(mis->transport_data);
296 mis->transport_data = mis->transport_cleanup = NULL;
300 void migration_incoming_state_destroy(void)
302 struct MigrationIncomingState *mis = migration_incoming_get_current();
304 if (mis->to_src_file) {
305 /* Tell source that we are done */
306 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
307 qemu_fclose(mis->to_src_file);
308 mis->to_src_file = NULL;
311 if (mis->from_src_file) {
312 migration_ioc_unregister_yank_from_file(mis->from_src_file);
313 qemu_fclose(mis->from_src_file);
314 mis->from_src_file = NULL;
316 if (mis->postcopy_remote_fds) {
317 g_array_free(mis->postcopy_remote_fds, TRUE);
318 mis->postcopy_remote_fds = NULL;
321 migration_incoming_transport_cleanup(mis);
322 qemu_event_reset(&mis->main_thread_load_event);
324 if (mis->page_requested) {
325 g_tree_destroy(mis->page_requested);
326 mis->page_requested = NULL;
329 if (mis->postcopy_qemufile_dst) {
330 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
331 qemu_fclose(mis->postcopy_qemufile_dst);
332 mis->postcopy_qemufile_dst = NULL;
335 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
338 static void migrate_generate_event(int new_state)
340 if (migrate_use_events()) {
341 qapi_event_send_migration(new_state);
345 static bool migrate_late_block_activate(void)
347 MigrationState *s;
349 s = migrate_get_current();
351 return s->enabled_capabilities[
352 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
356 * Send a message on the return channel back to the source
357 * of the migration.
359 static int migrate_send_rp_message(MigrationIncomingState *mis,
360 enum mig_rp_message_type message_type,
361 uint16_t len, void *data)
363 int ret = 0;
365 trace_migrate_send_rp_message((int)message_type, len);
366 QEMU_LOCK_GUARD(&mis->rp_mutex);
369 * It's possible that the file handle got lost due to network
370 * failures.
372 if (!mis->to_src_file) {
373 ret = -EIO;
374 return ret;
377 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
378 qemu_put_be16(mis->to_src_file, len);
379 qemu_put_buffer(mis->to_src_file, data, len);
380 qemu_fflush(mis->to_src_file);
382 /* It's possible that qemu file got error during sending */
383 ret = qemu_file_get_error(mis->to_src_file);
385 return ret;
388 /* Request one page from the source VM at the given start address.
389 * rb: the RAMBlock to request the page in
390 * Start: Address offset within the RB
391 * Len: Length in bytes required - must be a multiple of pagesize
393 int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
394 RAMBlock *rb, ram_addr_t start)
396 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
397 size_t msglen = 12; /* start + len */
398 size_t len = qemu_ram_pagesize(rb);
399 enum mig_rp_message_type msg_type;
400 const char *rbname;
401 int rbname_len;
403 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
404 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
407 * We maintain the last ramblock that we requested for page. Note that we
408 * don't need locking because this function will only be called within the
409 * postcopy ram fault thread.
411 if (rb != mis->last_rb) {
412 mis->last_rb = rb;
414 rbname = qemu_ram_get_idstr(rb);
415 rbname_len = strlen(rbname);
417 assert(rbname_len < 256);
419 bufc[msglen++] = rbname_len;
420 memcpy(bufc + msglen, rbname, rbname_len);
421 msglen += rbname_len;
422 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
423 } else {
424 msg_type = MIG_RP_MSG_REQ_PAGES;
427 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
430 int migrate_send_rp_req_pages(MigrationIncomingState *mis,
431 RAMBlock *rb, ram_addr_t start, uint64_t haddr)
433 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
434 bool received = false;
436 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
437 received = ramblock_recv_bitmap_test_byte_offset(rb, start);
438 if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
440 * The page has not been received, and it's not yet in the page
441 * request list. Queue it. Set the value of element to 1, so that
442 * things like g_tree_lookup() will return TRUE (1) when found.
444 g_tree_insert(mis->page_requested, aligned, (gpointer)1);
445 mis->page_requested_count++;
446 trace_postcopy_page_req_add(aligned, mis->page_requested_count);
451 * If the page is there, skip sending the message. We don't even need the
452 * lock because as long as the page arrived, it'll be there forever.
454 if (received) {
455 return 0;
458 return migrate_send_rp_message_req_pages(mis, rb, start);
461 static bool migration_colo_enabled;
462 bool migration_incoming_colo_enabled(void)
464 return migration_colo_enabled;
467 void migration_incoming_disable_colo(void)
469 ram_block_discard_disable(false);
470 migration_colo_enabled = false;
473 int migration_incoming_enable_colo(void)
475 if (ram_block_discard_disable(true)) {
476 error_report("COLO: cannot disable RAM discard");
477 return -EBUSY;
479 migration_colo_enabled = true;
480 return 0;
483 void migrate_add_address(SocketAddress *address)
485 MigrationIncomingState *mis = migration_incoming_get_current();
487 QAPI_LIST_PREPEND(mis->socket_address_list,
488 QAPI_CLONE(SocketAddress, address));
491 static void qemu_start_incoming_migration(const char *uri, Error **errp)
493 const char *p = NULL;
495 migrate_protocol_allow_multi_channels(false); /* reset it anyway */
496 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
497 if (strstart(uri, "tcp:", &p) ||
498 strstart(uri, "unix:", NULL) ||
499 strstart(uri, "vsock:", NULL)) {
500 migrate_protocol_allow_multi_channels(true);
501 socket_start_incoming_migration(p ? p : uri, errp);
502 #ifdef CONFIG_RDMA
503 } else if (strstart(uri, "rdma:", &p)) {
504 rdma_start_incoming_migration(p, errp);
505 #endif
506 } else if (strstart(uri, "exec:", &p)) {
507 exec_start_incoming_migration(p, errp);
508 } else if (strstart(uri, "fd:", &p)) {
509 fd_start_incoming_migration(p, errp);
510 } else {
511 error_setg(errp, "unknown migration protocol: %s", uri);
515 static void process_incoming_migration_bh(void *opaque)
517 Error *local_err = NULL;
518 MigrationIncomingState *mis = opaque;
520 /* If capability late_block_activate is set:
521 * Only fire up the block code now if we're going to restart the
522 * VM, else 'cont' will do it.
523 * This causes file locking to happen; so we don't want it to happen
524 * unless we really are starting the VM.
526 if (!migrate_late_block_activate() ||
527 (autostart && (!global_state_received() ||
528 global_state_get_runstate() == RUN_STATE_RUNNING))) {
529 /* Make sure all file formats throw away their mutable metadata.
530 * If we get an error here, just don't restart the VM yet. */
531 bdrv_activate_all(&local_err);
532 if (local_err) {
533 error_report_err(local_err);
534 local_err = NULL;
535 autostart = false;
540 * This must happen after all error conditions are dealt with and
541 * we're sure the VM is going to be running on this host.
543 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
545 if (multifd_load_cleanup(&local_err) != 0) {
546 error_report_err(local_err);
547 autostart = false;
549 /* If global state section was not received or we are in running
550 state, we need to obey autostart. Any other state is set with
551 runstate_set. */
553 dirty_bitmap_mig_before_vm_start();
555 if (!global_state_received() ||
556 global_state_get_runstate() == RUN_STATE_RUNNING) {
557 if (autostart) {
558 vm_start();
559 } else {
560 runstate_set(RUN_STATE_PAUSED);
562 } else if (migration_incoming_colo_enabled()) {
563 migration_incoming_disable_colo();
564 vm_start();
565 } else {
566 runstate_set(global_state_get_runstate());
569 * This must happen after any state changes since as soon as an external
570 * observer sees this event they might start to prod at the VM assuming
571 * it's ready to use.
573 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
574 MIGRATION_STATUS_COMPLETED);
575 qemu_bh_delete(mis->bh);
576 migration_incoming_state_destroy();
579 static void coroutine_fn
580 process_incoming_migration_co(void *opaque)
582 MigrationIncomingState *mis = migration_incoming_get_current();
583 PostcopyState ps;
584 int ret;
585 Error *local_err = NULL;
587 assert(mis->from_src_file);
588 mis->migration_incoming_co = qemu_coroutine_self();
589 mis->largest_page_size = qemu_ram_pagesize_largest();
590 postcopy_state_set(POSTCOPY_INCOMING_NONE);
591 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
592 MIGRATION_STATUS_ACTIVE);
593 ret = qemu_loadvm_state(mis->from_src_file);
595 ps = postcopy_state_get();
596 trace_process_incoming_migration_co_end(ret, ps);
597 if (ps != POSTCOPY_INCOMING_NONE) {
598 if (ps == POSTCOPY_INCOMING_ADVISE) {
600 * Where a migration had postcopy enabled (and thus went to advise)
601 * but managed to complete within the precopy period, we can use
602 * the normal exit.
604 postcopy_ram_incoming_cleanup(mis);
605 } else if (ret >= 0) {
607 * Postcopy was started, cleanup should happen at the end of the
608 * postcopy thread.
610 trace_process_incoming_migration_co_postcopy_end_main();
611 return;
613 /* Else if something went wrong then just fall out of the normal exit */
616 /* we get COLO info, and know if we are in COLO mode */
617 if (!ret && migration_incoming_colo_enabled()) {
618 /* Make sure all file formats throw away their mutable metadata */
619 bdrv_activate_all(&local_err);
620 if (local_err) {
621 error_report_err(local_err);
622 goto fail;
625 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
626 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
627 mis->have_colo_incoming_thread = true;
628 qemu_coroutine_yield();
630 qemu_mutex_unlock_iothread();
631 /* Wait checkpoint incoming thread exit before free resource */
632 qemu_thread_join(&mis->colo_incoming_thread);
633 qemu_mutex_lock_iothread();
634 /* We hold the global iothread lock, so it is safe here */
635 colo_release_ram_cache();
638 if (ret < 0) {
639 error_report("load of migration failed: %s", strerror(-ret));
640 goto fail;
642 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
643 qemu_bh_schedule(mis->bh);
644 mis->migration_incoming_co = NULL;
645 return;
646 fail:
647 local_err = NULL;
648 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
649 MIGRATION_STATUS_FAILED);
650 qemu_fclose(mis->from_src_file);
651 if (multifd_load_cleanup(&local_err) != 0) {
652 error_report_err(local_err);
654 exit(EXIT_FAILURE);
658 * migration_incoming_setup: Setup incoming migration
659 * @f: file for main migration channel
660 * @errp: where to put errors
662 * Returns: %true on success, %false on error.
664 static bool migration_incoming_setup(QEMUFile *f, Error **errp)
666 MigrationIncomingState *mis = migration_incoming_get_current();
668 if (!mis->from_src_file) {
669 mis->from_src_file = f;
671 qemu_file_set_blocking(f, false);
672 return true;
675 void migration_incoming_process(void)
677 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
678 qemu_coroutine_enter(co);
681 /* Returns true if recovered from a paused migration, otherwise false */
682 static bool postcopy_try_recover(void)
684 MigrationIncomingState *mis = migration_incoming_get_current();
686 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
687 /* Resumed from a paused postcopy migration */
689 /* This should be set already in migration_incoming_setup() */
690 assert(mis->from_src_file);
691 /* Postcopy has standalone thread to do vm load */
692 qemu_file_set_blocking(mis->from_src_file, true);
694 /* Re-configure the return path */
695 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
697 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
698 MIGRATION_STATUS_POSTCOPY_RECOVER);
701 * Here, we only wake up the main loading thread (while the
702 * rest threads will still be waiting), so that we can receive
703 * commands from source now, and answer it if needed. The
704 * rest threads will be woken up afterwards until we are sure
705 * that source is ready to reply to page requests.
707 qemu_sem_post(&mis->postcopy_pause_sem_dst);
708 return true;
711 return false;
714 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
716 if (!migration_incoming_setup(f, errp)) {
717 return;
719 if (postcopy_try_recover()) {
720 return;
722 migration_incoming_process();
725 static bool migration_needs_multiple_sockets(void)
727 return migrate_use_multifd() || migrate_postcopy_preempt();
730 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
732 MigrationIncomingState *mis = migration_incoming_get_current();
733 Error *local_err = NULL;
734 QEMUFile *f;
735 bool default_channel = true;
736 uint32_t channel_magic = 0;
737 int ret = 0;
739 if (migrate_use_multifd() && !migrate_postcopy_ram() &&
740 qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) {
742 * With multiple channels, it is possible that we receive channels
743 * out of order on destination side, causing incorrect mapping of
744 * source channels on destination side. Check channel MAGIC to
745 * decide type of channel. Please note this is best effort, postcopy
746 * preempt channel does not send any magic number so avoid it for
747 * postcopy live migration. Also tls live migration already does
748 * tls handshake while initializing main channel so with tls this
749 * issue is not possible.
751 ret = migration_channel_read_peek(ioc, (void *)&channel_magic,
752 sizeof(channel_magic), &local_err);
754 if (ret != 0) {
755 error_propagate(errp, local_err);
756 return;
759 default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC));
760 } else {
761 default_channel = !mis->from_src_file;
764 if (multifd_load_setup(errp) != 0) {
765 error_setg(errp, "Failed to setup multifd channels");
766 return;
769 if (default_channel) {
770 f = qemu_file_new_input(ioc);
772 if (!migration_incoming_setup(f, errp)) {
773 return;
775 } else {
776 /* Multiple connections */
777 assert(migration_needs_multiple_sockets());
778 if (migrate_use_multifd()) {
779 multifd_recv_new_channel(ioc, &local_err);
780 } else {
781 assert(migrate_postcopy_preempt());
782 f = qemu_file_new_input(ioc);
783 postcopy_preempt_new_channel(mis, f);
785 if (local_err) {
786 error_propagate(errp, local_err);
787 return;
791 if (migration_has_all_channels()) {
792 /* If it's a recovery, we're done */
793 if (postcopy_try_recover()) {
794 return;
796 migration_incoming_process();
801 * @migration_has_all_channels: We have received all channels that we need
803 * Returns true when we have got connections to all the channels that
804 * we need for migration.
806 bool migration_has_all_channels(void)
808 MigrationIncomingState *mis = migration_incoming_get_current();
810 if (!mis->from_src_file) {
811 return false;
814 if (migrate_use_multifd()) {
815 return multifd_recv_all_channels_created();
818 if (migrate_postcopy_preempt()) {
819 return mis->postcopy_qemufile_dst != NULL;
822 return true;
826 * Send a 'SHUT' message on the return channel with the given value
827 * to indicate that we've finished with the RP. Non-0 value indicates
828 * error.
830 void migrate_send_rp_shut(MigrationIncomingState *mis,
831 uint32_t value)
833 uint32_t buf;
835 buf = cpu_to_be32(value);
836 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
840 * Send a 'PONG' message on the return channel with the given value
841 * (normally in response to a 'PING')
843 void migrate_send_rp_pong(MigrationIncomingState *mis,
844 uint32_t value)
846 uint32_t buf;
848 buf = cpu_to_be32(value);
849 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
852 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
853 char *block_name)
855 char buf[512];
856 int len;
857 int64_t res;
860 * First, we send the header part. It contains only the len of
861 * idstr, and the idstr itself.
863 len = strlen(block_name);
864 buf[0] = len;
865 memcpy(buf + 1, block_name, len);
867 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
868 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
869 __func__);
870 return;
873 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
876 * Next, we dump the received bitmap to the stream.
878 * TODO: currently we are safe since we are the only one that is
879 * using the to_src_file handle (fault thread is still paused),
880 * and it's ok even not taking the mutex. However the best way is
881 * to take the lock before sending the message header, and release
882 * the lock after sending the bitmap.
884 qemu_mutex_lock(&mis->rp_mutex);
885 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
886 qemu_mutex_unlock(&mis->rp_mutex);
888 trace_migrate_send_rp_recv_bitmap(block_name, res);
891 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
893 uint32_t buf;
895 buf = cpu_to_be32(value);
896 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
899 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
901 MigrationCapabilityStatusList *head = NULL, **tail = &head;
902 MigrationCapabilityStatus *caps;
903 MigrationState *s = migrate_get_current();
904 int i;
906 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
907 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
908 if (i == MIGRATION_CAPABILITY_BLOCK) {
909 continue;
911 #endif
912 caps = g_malloc0(sizeof(*caps));
913 caps->capability = i;
914 caps->state = s->enabled_capabilities[i];
915 QAPI_LIST_APPEND(tail, caps);
918 return head;
921 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
923 MigrationParameters *params;
924 MigrationState *s = migrate_get_current();
926 /* TODO use QAPI_CLONE() instead of duplicating it inline */
927 params = g_malloc0(sizeof(*params));
928 params->has_compress_level = true;
929 params->compress_level = s->parameters.compress_level;
930 params->has_compress_threads = true;
931 params->compress_threads = s->parameters.compress_threads;
932 params->has_compress_wait_thread = true;
933 params->compress_wait_thread = s->parameters.compress_wait_thread;
934 params->has_decompress_threads = true;
935 params->decompress_threads = s->parameters.decompress_threads;
936 params->has_throttle_trigger_threshold = true;
937 params->throttle_trigger_threshold = s->parameters.throttle_trigger_threshold;
938 params->has_cpu_throttle_initial = true;
939 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
940 params->has_cpu_throttle_increment = true;
941 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
942 params->has_cpu_throttle_tailslow = true;
943 params->cpu_throttle_tailslow = s->parameters.cpu_throttle_tailslow;
944 params->tls_creds = g_strdup(s->parameters.tls_creds);
945 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
946 params->tls_authz = g_strdup(s->parameters.tls_authz ?
947 s->parameters.tls_authz : "");
948 params->has_max_bandwidth = true;
949 params->max_bandwidth = s->parameters.max_bandwidth;
950 params->has_downtime_limit = true;
951 params->downtime_limit = s->parameters.downtime_limit;
952 params->has_x_checkpoint_delay = true;
953 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
954 params->has_block_incremental = true;
955 params->block_incremental = s->parameters.block_incremental;
956 params->has_multifd_channels = true;
957 params->multifd_channels = s->parameters.multifd_channels;
958 params->has_multifd_compression = true;
959 params->multifd_compression = s->parameters.multifd_compression;
960 params->has_multifd_zlib_level = true;
961 params->multifd_zlib_level = s->parameters.multifd_zlib_level;
962 params->has_multifd_zstd_level = true;
963 params->multifd_zstd_level = s->parameters.multifd_zstd_level;
964 params->has_xbzrle_cache_size = true;
965 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
966 params->has_max_postcopy_bandwidth = true;
967 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
968 params->has_max_cpu_throttle = true;
969 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
970 params->has_announce_initial = true;
971 params->announce_initial = s->parameters.announce_initial;
972 params->has_announce_max = true;
973 params->announce_max = s->parameters.announce_max;
974 params->has_announce_rounds = true;
975 params->announce_rounds = s->parameters.announce_rounds;
976 params->has_announce_step = true;
977 params->announce_step = s->parameters.announce_step;
979 if (s->parameters.has_block_bitmap_mapping) {
980 params->has_block_bitmap_mapping = true;
981 params->block_bitmap_mapping =
982 QAPI_CLONE(BitmapMigrationNodeAliasList,
983 s->parameters.block_bitmap_mapping);
986 return params;
989 void qmp_client_migrate_info(const char *protocol, const char *hostname,
990 bool has_port, int64_t port,
991 bool has_tls_port, int64_t tls_port,
992 const char *cert_subject,
993 Error **errp)
995 if (strcmp(protocol, "spice") == 0) {
996 if (!qemu_using_spice(errp)) {
997 return;
1000 if (!has_port && !has_tls_port) {
1001 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
1002 return;
1005 if (qemu_spice.migrate_info(hostname,
1006 has_port ? port : -1,
1007 has_tls_port ? tls_port : -1,
1008 cert_subject)) {
1009 error_setg(errp, "Could not set up display for migration");
1010 return;
1012 return;
1015 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "'spice'");
1018 AnnounceParameters *migrate_announce_params(void)
1020 static AnnounceParameters ap;
1022 MigrationState *s = migrate_get_current();
1024 ap.initial = s->parameters.announce_initial;
1025 ap.max = s->parameters.announce_max;
1026 ap.rounds = s->parameters.announce_rounds;
1027 ap.step = s->parameters.announce_step;
1029 return &ap;
1033 * Return true if we're already in the middle of a migration
1034 * (i.e. any of the active or setup states)
1036 bool migration_is_setup_or_active(int state)
1038 switch (state) {
1039 case MIGRATION_STATUS_ACTIVE:
1040 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1041 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1042 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1043 case MIGRATION_STATUS_SETUP:
1044 case MIGRATION_STATUS_PRE_SWITCHOVER:
1045 case MIGRATION_STATUS_DEVICE:
1046 case MIGRATION_STATUS_WAIT_UNPLUG:
1047 case MIGRATION_STATUS_COLO:
1048 return true;
1050 default:
1051 return false;
1056 bool migration_is_running(int state)
1058 switch (state) {
1059 case MIGRATION_STATUS_ACTIVE:
1060 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1061 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1062 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1063 case MIGRATION_STATUS_SETUP:
1064 case MIGRATION_STATUS_PRE_SWITCHOVER:
1065 case MIGRATION_STATUS_DEVICE:
1066 case MIGRATION_STATUS_WAIT_UNPLUG:
1067 case MIGRATION_STATUS_CANCELLING:
1068 return true;
1070 default:
1071 return false;
1076 static bool migrate_show_downtime(MigrationState *s)
1078 return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy();
1081 static void populate_time_info(MigrationInfo *info, MigrationState *s)
1083 info->has_status = true;
1084 info->has_setup_time = true;
1085 info->setup_time = s->setup_time;
1087 if (s->state == MIGRATION_STATUS_COMPLETED) {
1088 info->has_total_time = true;
1089 info->total_time = s->total_time;
1090 } else {
1091 info->has_total_time = true;
1092 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
1093 s->start_time;
1096 if (migrate_show_downtime(s)) {
1097 info->has_downtime = true;
1098 info->downtime = s->downtime;
1099 } else {
1100 info->has_expected_downtime = true;
1101 info->expected_downtime = s->expected_downtime;
1105 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
1107 size_t page_size = qemu_target_page_size();
1109 info->ram = g_malloc0(sizeof(*info->ram));
1110 info->ram->transferred = stat64_get(&ram_atomic_counters.transferred);
1111 info->ram->total = ram_bytes_total();
1112 info->ram->duplicate = stat64_get(&ram_atomic_counters.duplicate);
1113 /* legacy value. It is not used anymore */
1114 info->ram->skipped = 0;
1115 info->ram->normal = stat64_get(&ram_atomic_counters.normal);
1116 info->ram->normal_bytes = info->ram->normal * page_size;
1117 info->ram->mbps = s->mbps;
1118 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
1119 info->ram->dirty_sync_missed_zero_copy =
1120 ram_counters.dirty_sync_missed_zero_copy;
1121 info->ram->postcopy_requests = ram_counters.postcopy_requests;
1122 info->ram->page_size = page_size;
1123 info->ram->multifd_bytes = ram_counters.multifd_bytes;
1124 info->ram->pages_per_second = s->pages_per_second;
1125 info->ram->precopy_bytes = ram_counters.precopy_bytes;
1126 info->ram->downtime_bytes = ram_counters.downtime_bytes;
1127 info->ram->postcopy_bytes = stat64_get(&ram_atomic_counters.postcopy_bytes);
1129 if (migrate_use_xbzrle()) {
1130 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
1131 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
1132 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
1133 info->xbzrle_cache->pages = xbzrle_counters.pages;
1134 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
1135 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
1136 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
1137 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
1140 if (migrate_use_compression()) {
1141 info->compression = g_malloc0(sizeof(*info->compression));
1142 info->compression->pages = compression_counters.pages;
1143 info->compression->busy = compression_counters.busy;
1144 info->compression->busy_rate = compression_counters.busy_rate;
1145 info->compression->compressed_size =
1146 compression_counters.compressed_size;
1147 info->compression->compression_rate =
1148 compression_counters.compression_rate;
1151 if (cpu_throttle_active()) {
1152 info->has_cpu_throttle_percentage = true;
1153 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
1156 if (s->state != MIGRATION_STATUS_COMPLETED) {
1157 info->ram->remaining = ram_bytes_remaining();
1158 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
1162 static void populate_disk_info(MigrationInfo *info)
1164 if (blk_mig_active()) {
1165 info->disk = g_malloc0(sizeof(*info->disk));
1166 info->disk->transferred = blk_mig_bytes_transferred();
1167 info->disk->remaining = blk_mig_bytes_remaining();
1168 info->disk->total = blk_mig_bytes_total();
1172 static void fill_source_migration_info(MigrationInfo *info)
1174 MigrationState *s = migrate_get_current();
1175 int state = qatomic_read(&s->state);
1176 GSList *cur_blocker = migration_blockers;
1178 info->blocked_reasons = NULL;
1181 * There are two types of reasons a migration might be blocked;
1182 * a) devices marked in VMState as non-migratable, and
1183 * b) Explicit migration blockers
1184 * We need to add both of them here.
1186 qemu_savevm_non_migratable_list(&info->blocked_reasons);
1188 while (cur_blocker) {
1189 QAPI_LIST_PREPEND(info->blocked_reasons,
1190 g_strdup(error_get_pretty(cur_blocker->data)));
1191 cur_blocker = g_slist_next(cur_blocker);
1193 info->has_blocked_reasons = info->blocked_reasons != NULL;
1195 switch (state) {
1196 case MIGRATION_STATUS_NONE:
1197 /* no migration has happened ever */
1198 /* do not overwrite destination migration status */
1199 return;
1200 case MIGRATION_STATUS_SETUP:
1201 info->has_status = true;
1202 info->has_total_time = false;
1203 break;
1204 case MIGRATION_STATUS_ACTIVE:
1205 case MIGRATION_STATUS_CANCELLING:
1206 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1207 case MIGRATION_STATUS_PRE_SWITCHOVER:
1208 case MIGRATION_STATUS_DEVICE:
1209 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1210 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1211 /* TODO add some postcopy stats */
1212 populate_time_info(info, s);
1213 populate_ram_info(info, s);
1214 populate_disk_info(info);
1215 populate_vfio_info(info);
1216 break;
1217 case MIGRATION_STATUS_COLO:
1218 info->has_status = true;
1219 /* TODO: display COLO specific information (checkpoint info etc.) */
1220 break;
1221 case MIGRATION_STATUS_COMPLETED:
1222 populate_time_info(info, s);
1223 populate_ram_info(info, s);
1224 populate_vfio_info(info);
1225 break;
1226 case MIGRATION_STATUS_FAILED:
1227 info->has_status = true;
1228 if (s->error) {
1229 info->error_desc = g_strdup(error_get_pretty(s->error));
1231 break;
1232 case MIGRATION_STATUS_CANCELLED:
1233 info->has_status = true;
1234 break;
1235 case MIGRATION_STATUS_WAIT_UNPLUG:
1236 info->has_status = true;
1237 break;
1239 info->status = state;
1242 typedef enum WriteTrackingSupport {
1243 WT_SUPPORT_UNKNOWN = 0,
1244 WT_SUPPORT_ABSENT,
1245 WT_SUPPORT_AVAILABLE,
1246 WT_SUPPORT_COMPATIBLE
1247 } WriteTrackingSupport;
1249 static
1250 WriteTrackingSupport migrate_query_write_tracking(void)
1252 /* Check if kernel supports required UFFD features */
1253 if (!ram_write_tracking_available()) {
1254 return WT_SUPPORT_ABSENT;
1257 * Check if current memory configuration is
1258 * compatible with required UFFD features.
1260 if (!ram_write_tracking_compatible()) {
1261 return WT_SUPPORT_AVAILABLE;
1264 return WT_SUPPORT_COMPATIBLE;
1268 * @migration_caps_check - check capability validity
1270 * @cap_list: old capability list, array of bool
1271 * @params: new capabilities to be applied soon
1272 * @errp: set *errp if the check failed, with reason
1274 * Returns true if check passed, otherwise false.
1276 static bool migrate_caps_check(bool *cap_list,
1277 MigrationCapabilityStatusList *params,
1278 Error **errp)
1280 MigrationCapabilityStatusList *cap;
1281 bool old_postcopy_cap;
1282 MigrationIncomingState *mis = migration_incoming_get_current();
1284 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1286 for (cap = params; cap; cap = cap->next) {
1287 cap_list[cap->value->capability] = cap->value->state;
1290 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
1291 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
1292 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
1293 "block migration");
1294 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
1295 return false;
1297 #endif
1299 #ifndef CONFIG_REPLICATION
1300 if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
1301 error_setg(errp, "QEMU compiled without replication module"
1302 " can't enable COLO");
1303 error_append_hint(errp, "Please enable replication before COLO.\n");
1304 return false;
1306 #endif
1308 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1309 /* This check is reasonably expensive, so only when it's being
1310 * set the first time, also it's only the destination that needs
1311 * special support.
1313 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
1314 !postcopy_ram_supported_by_host(mis)) {
1315 /* postcopy_ram_supported_by_host will have emitted a more
1316 * detailed message
1318 error_setg(errp, "Postcopy is not supported");
1319 return false;
1322 if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1323 error_setg(errp, "Postcopy is not compatible with ignore-shared");
1324 return false;
1328 if (cap_list[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) {
1329 WriteTrackingSupport wt_support;
1330 int idx;
1332 * Check if 'background-snapshot' capability is supported by
1333 * host kernel and compatible with guest memory configuration.
1335 wt_support = migrate_query_write_tracking();
1336 if (wt_support < WT_SUPPORT_AVAILABLE) {
1337 error_setg(errp, "Background-snapshot is not supported by host kernel");
1338 return false;
1340 if (wt_support < WT_SUPPORT_COMPATIBLE) {
1341 error_setg(errp, "Background-snapshot is not compatible "
1342 "with guest memory configuration");
1343 return false;
1347 * Check if there are any migration capabilities
1348 * incompatible with 'background-snapshot'.
1350 for (idx = 0; idx < check_caps_background_snapshot.size; idx++) {
1351 int incomp_cap = check_caps_background_snapshot.caps[idx];
1352 if (cap_list[incomp_cap]) {
1353 error_setg(errp,
1354 "Background-snapshot is not compatible with %s",
1355 MigrationCapability_str(incomp_cap));
1356 return false;
1361 #ifdef CONFIG_LINUX
1362 if (cap_list[MIGRATION_CAPABILITY_ZERO_COPY_SEND] &&
1363 (!cap_list[MIGRATION_CAPABILITY_MULTIFD] ||
1364 cap_list[MIGRATION_CAPABILITY_COMPRESS] ||
1365 cap_list[MIGRATION_CAPABILITY_XBZRLE] ||
1366 migrate_multifd_compression() ||
1367 migrate_use_tls())) {
1368 error_setg(errp,
1369 "Zero copy only available for non-compressed non-TLS multifd migration");
1370 return false;
1372 #else
1373 if (cap_list[MIGRATION_CAPABILITY_ZERO_COPY_SEND]) {
1374 error_setg(errp,
1375 "Zero copy currently only available on Linux");
1376 return false;
1378 #endif
1381 /* incoming side only */
1382 if (runstate_check(RUN_STATE_INMIGRATE) &&
1383 !migrate_multi_channels_is_allowed() &&
1384 cap_list[MIGRATION_CAPABILITY_MULTIFD]) {
1385 error_setg(errp, "multifd is not supported by current protocol");
1386 return false;
1389 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT]) {
1390 if (!cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1391 error_setg(errp, "Postcopy preempt requires postcopy-ram");
1392 return false;
1396 * Preempt mode requires urgent pages to be sent in separate
1397 * channel, OTOH compression logic will disorder all pages into
1398 * different compression channels, which is not compatible with the
1399 * preempt assumptions on channel assignments.
1401 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
1402 error_setg(errp, "Postcopy preempt not compatible with compress");
1403 return false;
1407 if (cap_list[MIGRATION_CAPABILITY_MULTIFD]) {
1408 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
1409 error_setg(errp, "Multifd is not compatible with compress");
1410 return false;
1414 return true;
1417 static void fill_destination_migration_info(MigrationInfo *info)
1419 MigrationIncomingState *mis = migration_incoming_get_current();
1421 if (mis->socket_address_list) {
1422 info->has_socket_address = true;
1423 info->socket_address =
1424 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1427 switch (mis->state) {
1428 case MIGRATION_STATUS_NONE:
1429 return;
1430 case MIGRATION_STATUS_SETUP:
1431 case MIGRATION_STATUS_CANCELLING:
1432 case MIGRATION_STATUS_CANCELLED:
1433 case MIGRATION_STATUS_ACTIVE:
1434 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1435 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1436 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1437 case MIGRATION_STATUS_FAILED:
1438 case MIGRATION_STATUS_COLO:
1439 info->has_status = true;
1440 break;
1441 case MIGRATION_STATUS_COMPLETED:
1442 info->has_status = true;
1443 fill_destination_postcopy_migration_info(info);
1444 break;
1446 info->status = mis->state;
1449 MigrationInfo *qmp_query_migrate(Error **errp)
1451 MigrationInfo *info = g_malloc0(sizeof(*info));
1453 fill_destination_migration_info(info);
1454 fill_source_migration_info(info);
1456 return info;
1459 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1460 Error **errp)
1462 MigrationState *s = migrate_get_current();
1463 MigrationCapabilityStatusList *cap;
1464 bool cap_list[MIGRATION_CAPABILITY__MAX];
1466 if (migration_is_running(s->state)) {
1467 error_setg(errp, QERR_MIGRATION_ACTIVE);
1468 return;
1471 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1472 if (!migrate_caps_check(cap_list, params, errp)) {
1473 return;
1476 for (cap = params; cap; cap = cap->next) {
1477 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1482 * Check whether the parameters are valid. Error will be put into errp
1483 * (if provided). Return true if valid, otherwise false.
1485 static bool migrate_params_check(MigrationParameters *params, Error **errp)
1487 if (params->has_compress_level &&
1488 (params->compress_level > 9)) {
1489 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1490 "a value between 0 and 9");
1491 return false;
1494 if (params->has_compress_threads && (params->compress_threads < 1)) {
1495 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1496 "compress_threads",
1497 "a value between 1 and 255");
1498 return false;
1501 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1502 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1503 "decompress_threads",
1504 "a value between 1 and 255");
1505 return false;
1508 if (params->has_throttle_trigger_threshold &&
1509 (params->throttle_trigger_threshold < 1 ||
1510 params->throttle_trigger_threshold > 100)) {
1511 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1512 "throttle_trigger_threshold",
1513 "an integer in the range of 1 to 100");
1514 return false;
1517 if (params->has_cpu_throttle_initial &&
1518 (params->cpu_throttle_initial < 1 ||
1519 params->cpu_throttle_initial > 99)) {
1520 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1521 "cpu_throttle_initial",
1522 "an integer in the range of 1 to 99");
1523 return false;
1526 if (params->has_cpu_throttle_increment &&
1527 (params->cpu_throttle_increment < 1 ||
1528 params->cpu_throttle_increment > 99)) {
1529 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1530 "cpu_throttle_increment",
1531 "an integer in the range of 1 to 99");
1532 return false;
1535 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1536 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1537 "max_bandwidth",
1538 "an integer in the range of 0 to "stringify(SIZE_MAX)
1539 " bytes/second");
1540 return false;
1543 if (params->has_downtime_limit &&
1544 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1545 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1546 "downtime_limit",
1547 "an integer in the range of 0 to "
1548 stringify(MAX_MIGRATE_DOWNTIME)" ms");
1549 return false;
1552 /* x_checkpoint_delay is now always positive */
1554 if (params->has_multifd_channels && (params->multifd_channels < 1)) {
1555 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1556 "multifd_channels",
1557 "a value between 1 and 255");
1558 return false;
1561 if (params->has_multifd_zlib_level &&
1562 (params->multifd_zlib_level > 9)) {
1563 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level",
1564 "a value between 0 and 9");
1565 return false;
1568 if (params->has_multifd_zstd_level &&
1569 (params->multifd_zstd_level > 20)) {
1570 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level",
1571 "a value between 0 and 20");
1572 return false;
1575 if (params->has_xbzrle_cache_size &&
1576 (params->xbzrle_cache_size < qemu_target_page_size() ||
1577 !is_power_of_2(params->xbzrle_cache_size))) {
1578 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1579 "xbzrle_cache_size",
1580 "a power of two no less than the target page size");
1581 return false;
1584 if (params->has_max_cpu_throttle &&
1585 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1586 params->max_cpu_throttle > 99)) {
1587 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1588 "max_cpu_throttle",
1589 "an integer in the range of cpu_throttle_initial to 99");
1590 return false;
1593 if (params->has_announce_initial &&
1594 params->announce_initial > 100000) {
1595 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1596 "announce_initial",
1597 "a value between 0 and 100000");
1598 return false;
1600 if (params->has_announce_max &&
1601 params->announce_max > 100000) {
1602 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1603 "announce_max",
1604 "a value between 0 and 100000");
1605 return false;
1607 if (params->has_announce_rounds &&
1608 params->announce_rounds > 1000) {
1609 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1610 "announce_rounds",
1611 "a value between 0 and 1000");
1612 return false;
1614 if (params->has_announce_step &&
1615 (params->announce_step < 1 ||
1616 params->announce_step > 10000)) {
1617 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1618 "announce_step",
1619 "a value between 0 and 10000");
1620 return false;
1623 if (params->has_block_bitmap_mapping &&
1624 !check_dirty_bitmap_mig_alias_map(params->block_bitmap_mapping, errp)) {
1625 error_prepend(errp, "Invalid mapping given for block-bitmap-mapping: ");
1626 return false;
1629 #ifdef CONFIG_LINUX
1630 if (migrate_use_zero_copy_send() &&
1631 ((params->has_multifd_compression && params->multifd_compression) ||
1632 (params->tls_creds && *params->tls_creds))) {
1633 error_setg(errp,
1634 "Zero copy only available for non-compressed non-TLS multifd migration");
1635 return false;
1637 #endif
1639 return true;
1642 static void migrate_params_test_apply(MigrateSetParameters *params,
1643 MigrationParameters *dest)
1645 *dest = migrate_get_current()->parameters;
1647 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1649 if (params->has_compress_level) {
1650 dest->compress_level = params->compress_level;
1653 if (params->has_compress_threads) {
1654 dest->compress_threads = params->compress_threads;
1657 if (params->has_compress_wait_thread) {
1658 dest->compress_wait_thread = params->compress_wait_thread;
1661 if (params->has_decompress_threads) {
1662 dest->decompress_threads = params->decompress_threads;
1665 if (params->has_throttle_trigger_threshold) {
1666 dest->throttle_trigger_threshold = params->throttle_trigger_threshold;
1669 if (params->has_cpu_throttle_initial) {
1670 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1673 if (params->has_cpu_throttle_increment) {
1674 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1677 if (params->has_cpu_throttle_tailslow) {
1678 dest->cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1681 if (params->tls_creds) {
1682 assert(params->tls_creds->type == QTYPE_QSTRING);
1683 dest->tls_creds = params->tls_creds->u.s;
1686 if (params->tls_hostname) {
1687 assert(params->tls_hostname->type == QTYPE_QSTRING);
1688 dest->tls_hostname = params->tls_hostname->u.s;
1691 if (params->has_max_bandwidth) {
1692 dest->max_bandwidth = params->max_bandwidth;
1695 if (params->has_downtime_limit) {
1696 dest->downtime_limit = params->downtime_limit;
1699 if (params->has_x_checkpoint_delay) {
1700 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1703 if (params->has_block_incremental) {
1704 dest->block_incremental = params->block_incremental;
1706 if (params->has_multifd_channels) {
1707 dest->multifd_channels = params->multifd_channels;
1709 if (params->has_multifd_compression) {
1710 dest->multifd_compression = params->multifd_compression;
1712 if (params->has_xbzrle_cache_size) {
1713 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1715 if (params->has_max_postcopy_bandwidth) {
1716 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1718 if (params->has_max_cpu_throttle) {
1719 dest->max_cpu_throttle = params->max_cpu_throttle;
1721 if (params->has_announce_initial) {
1722 dest->announce_initial = params->announce_initial;
1724 if (params->has_announce_max) {
1725 dest->announce_max = params->announce_max;
1727 if (params->has_announce_rounds) {
1728 dest->announce_rounds = params->announce_rounds;
1730 if (params->has_announce_step) {
1731 dest->announce_step = params->announce_step;
1734 if (params->has_block_bitmap_mapping) {
1735 dest->has_block_bitmap_mapping = true;
1736 dest->block_bitmap_mapping = params->block_bitmap_mapping;
1740 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1742 MigrationState *s = migrate_get_current();
1744 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1746 if (params->has_compress_level) {
1747 s->parameters.compress_level = params->compress_level;
1750 if (params->has_compress_threads) {
1751 s->parameters.compress_threads = params->compress_threads;
1754 if (params->has_compress_wait_thread) {
1755 s->parameters.compress_wait_thread = params->compress_wait_thread;
1758 if (params->has_decompress_threads) {
1759 s->parameters.decompress_threads = params->decompress_threads;
1762 if (params->has_throttle_trigger_threshold) {
1763 s->parameters.throttle_trigger_threshold = params->throttle_trigger_threshold;
1766 if (params->has_cpu_throttle_initial) {
1767 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1770 if (params->has_cpu_throttle_increment) {
1771 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1774 if (params->has_cpu_throttle_tailslow) {
1775 s->parameters.cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1778 if (params->tls_creds) {
1779 g_free(s->parameters.tls_creds);
1780 assert(params->tls_creds->type == QTYPE_QSTRING);
1781 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1784 if (params->tls_hostname) {
1785 g_free(s->parameters.tls_hostname);
1786 assert(params->tls_hostname->type == QTYPE_QSTRING);
1787 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1790 if (params->tls_authz) {
1791 g_free(s->parameters.tls_authz);
1792 assert(params->tls_authz->type == QTYPE_QSTRING);
1793 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1796 if (params->has_max_bandwidth) {
1797 s->parameters.max_bandwidth = params->max_bandwidth;
1798 if (s->to_dst_file && !migration_in_postcopy()) {
1799 qemu_file_set_rate_limit(s->to_dst_file,
1800 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1804 if (params->has_downtime_limit) {
1805 s->parameters.downtime_limit = params->downtime_limit;
1808 if (params->has_x_checkpoint_delay) {
1809 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1810 if (migration_in_colo_state()) {
1811 colo_checkpoint_notify(s);
1815 if (params->has_block_incremental) {
1816 s->parameters.block_incremental = params->block_incremental;
1818 if (params->has_multifd_channels) {
1819 s->parameters.multifd_channels = params->multifd_channels;
1821 if (params->has_multifd_compression) {
1822 s->parameters.multifd_compression = params->multifd_compression;
1824 if (params->has_xbzrle_cache_size) {
1825 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1826 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1828 if (params->has_max_postcopy_bandwidth) {
1829 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1830 if (s->to_dst_file && migration_in_postcopy()) {
1831 qemu_file_set_rate_limit(s->to_dst_file,
1832 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1835 if (params->has_max_cpu_throttle) {
1836 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1838 if (params->has_announce_initial) {
1839 s->parameters.announce_initial = params->announce_initial;
1841 if (params->has_announce_max) {
1842 s->parameters.announce_max = params->announce_max;
1844 if (params->has_announce_rounds) {
1845 s->parameters.announce_rounds = params->announce_rounds;
1847 if (params->has_announce_step) {
1848 s->parameters.announce_step = params->announce_step;
1851 if (params->has_block_bitmap_mapping) {
1852 qapi_free_BitmapMigrationNodeAliasList(
1853 s->parameters.block_bitmap_mapping);
1855 s->parameters.has_block_bitmap_mapping = true;
1856 s->parameters.block_bitmap_mapping =
1857 QAPI_CLONE(BitmapMigrationNodeAliasList,
1858 params->block_bitmap_mapping);
1862 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1864 MigrationParameters tmp;
1866 /* TODO Rewrite "" to null instead */
1867 if (params->tls_creds
1868 && params->tls_creds->type == QTYPE_QNULL) {
1869 qobject_unref(params->tls_creds->u.n);
1870 params->tls_creds->type = QTYPE_QSTRING;
1871 params->tls_creds->u.s = strdup("");
1873 /* TODO Rewrite "" to null instead */
1874 if (params->tls_hostname
1875 && params->tls_hostname->type == QTYPE_QNULL) {
1876 qobject_unref(params->tls_hostname->u.n);
1877 params->tls_hostname->type = QTYPE_QSTRING;
1878 params->tls_hostname->u.s = strdup("");
1881 migrate_params_test_apply(params, &tmp);
1883 if (!migrate_params_check(&tmp, errp)) {
1884 /* Invalid parameter */
1885 return;
1888 migrate_params_apply(params, errp);
1892 void qmp_migrate_start_postcopy(Error **errp)
1894 MigrationState *s = migrate_get_current();
1896 if (!migrate_postcopy()) {
1897 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1898 " the start of migration");
1899 return;
1902 if (s->state == MIGRATION_STATUS_NONE) {
1903 error_setg(errp, "Postcopy must be started after migration has been"
1904 " started");
1905 return;
1908 * we don't error if migration has finished since that would be racy
1909 * with issuing this command.
1911 qatomic_set(&s->start_postcopy, true);
1914 /* shared migration helpers */
1916 void migrate_set_state(int *state, int old_state, int new_state)
1918 assert(new_state < MIGRATION_STATUS__MAX);
1919 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
1920 trace_migrate_set_state(MigrationStatus_str(new_state));
1921 migrate_generate_event(new_state);
1925 static MigrationCapabilityStatus *migrate_cap_add(MigrationCapability index,
1926 bool state)
1928 MigrationCapabilityStatus *cap;
1930 cap = g_new0(MigrationCapabilityStatus, 1);
1931 cap->capability = index;
1932 cap->state = state;
1934 return cap;
1937 void migrate_set_block_enabled(bool value, Error **errp)
1939 MigrationCapabilityStatusList *cap = NULL;
1941 QAPI_LIST_PREPEND(cap, migrate_cap_add(MIGRATION_CAPABILITY_BLOCK, value));
1942 qmp_migrate_set_capabilities(cap, errp);
1943 qapi_free_MigrationCapabilityStatusList(cap);
1946 static void migrate_set_block_incremental(MigrationState *s, bool value)
1948 s->parameters.block_incremental = value;
1951 static void block_cleanup_parameters(MigrationState *s)
1953 if (s->must_remove_block_options) {
1954 /* setting to false can never fail */
1955 migrate_set_block_enabled(false, &error_abort);
1956 migrate_set_block_incremental(s, false);
1957 s->must_remove_block_options = false;
1961 static void migrate_fd_cleanup(MigrationState *s)
1963 qemu_bh_delete(s->cleanup_bh);
1964 s->cleanup_bh = NULL;
1966 g_free(s->hostname);
1967 s->hostname = NULL;
1968 json_writer_free(s->vmdesc);
1969 s->vmdesc = NULL;
1971 qemu_savevm_state_cleanup();
1973 if (s->to_dst_file) {
1974 QEMUFile *tmp;
1976 trace_migrate_fd_cleanup();
1977 qemu_mutex_unlock_iothread();
1978 if (s->migration_thread_running) {
1979 qemu_thread_join(&s->thread);
1980 s->migration_thread_running = false;
1982 qemu_mutex_lock_iothread();
1984 multifd_save_cleanup();
1985 qemu_mutex_lock(&s->qemu_file_lock);
1986 tmp = s->to_dst_file;
1987 s->to_dst_file = NULL;
1988 qemu_mutex_unlock(&s->qemu_file_lock);
1990 * Close the file handle without the lock to make sure the
1991 * critical section won't block for long.
1993 migration_ioc_unregister_yank_from_file(tmp);
1994 qemu_fclose(tmp);
1997 if (s->postcopy_qemufile_src) {
1998 migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src);
1999 qemu_fclose(s->postcopy_qemufile_src);
2000 s->postcopy_qemufile_src = NULL;
2003 assert(!migration_is_active(s));
2005 if (s->state == MIGRATION_STATUS_CANCELLING) {
2006 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
2007 MIGRATION_STATUS_CANCELLED);
2010 if (s->error) {
2011 /* It is used on info migrate. We can't free it */
2012 error_report_err(error_copy(s->error));
2014 notifier_list_notify(&migration_state_notifiers, s);
2015 block_cleanup_parameters(s);
2016 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2019 static void migrate_fd_cleanup_schedule(MigrationState *s)
2022 * Ref the state for bh, because it may be called when
2023 * there're already no other refs
2025 object_ref(OBJECT(s));
2026 qemu_bh_schedule(s->cleanup_bh);
2029 static void migrate_fd_cleanup_bh(void *opaque)
2031 MigrationState *s = opaque;
2032 migrate_fd_cleanup(s);
2033 object_unref(OBJECT(s));
2036 void migrate_set_error(MigrationState *s, const Error *error)
2038 QEMU_LOCK_GUARD(&s->error_mutex);
2039 if (!s->error) {
2040 s->error = error_copy(error);
2044 static void migrate_error_free(MigrationState *s)
2046 QEMU_LOCK_GUARD(&s->error_mutex);
2047 if (s->error) {
2048 error_free(s->error);
2049 s->error = NULL;
2053 void migrate_fd_error(MigrationState *s, const Error *error)
2055 trace_migrate_fd_error(error_get_pretty(error));
2056 assert(s->to_dst_file == NULL);
2057 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2058 MIGRATION_STATUS_FAILED);
2059 migrate_set_error(s, error);
2062 static void migrate_fd_cancel(MigrationState *s)
2064 int old_state ;
2065 QEMUFile *f = migrate_get_current()->to_dst_file;
2066 trace_migrate_fd_cancel();
2068 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
2069 if (s->rp_state.from_dst_file) {
2070 /* shutdown the rp socket, so causing the rp thread to shutdown */
2071 qemu_file_shutdown(s->rp_state.from_dst_file);
2075 do {
2076 old_state = s->state;
2077 if (!migration_is_running(old_state)) {
2078 break;
2080 /* If the migration is paused, kick it out of the pause */
2081 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
2082 qemu_sem_post(&s->pause_sem);
2084 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
2085 } while (s->state != MIGRATION_STATUS_CANCELLING);
2088 * If we're unlucky the migration code might be stuck somewhere in a
2089 * send/write while the network has failed and is waiting to timeout;
2090 * if we've got shutdown(2) available then we can force it to quit.
2091 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
2092 * called in a bh, so there is no race against this cancel.
2094 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
2095 qemu_file_shutdown(f);
2097 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
2098 Error *local_err = NULL;
2100 bdrv_activate_all(&local_err);
2101 if (local_err) {
2102 error_report_err(local_err);
2103 } else {
2104 s->block_inactive = false;
2109 void add_migration_state_change_notifier(Notifier *notify)
2111 notifier_list_add(&migration_state_notifiers, notify);
2114 void remove_migration_state_change_notifier(Notifier *notify)
2116 notifier_remove(notify);
2119 bool migration_in_setup(MigrationState *s)
2121 return s->state == MIGRATION_STATUS_SETUP;
2124 bool migration_has_finished(MigrationState *s)
2126 return s->state == MIGRATION_STATUS_COMPLETED;
2129 bool migration_has_failed(MigrationState *s)
2131 return (s->state == MIGRATION_STATUS_CANCELLED ||
2132 s->state == MIGRATION_STATUS_FAILED);
2135 bool migration_in_postcopy(void)
2137 MigrationState *s = migrate_get_current();
2139 switch (s->state) {
2140 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2141 case MIGRATION_STATUS_POSTCOPY_PAUSED:
2142 case MIGRATION_STATUS_POSTCOPY_RECOVER:
2143 return true;
2144 default:
2145 return false;
2149 bool migration_in_postcopy_after_devices(MigrationState *s)
2151 return migration_in_postcopy() && s->postcopy_after_devices;
2154 bool migration_in_incoming_postcopy(void)
2156 PostcopyState ps = postcopy_state_get();
2158 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
2161 bool migration_incoming_postcopy_advised(void)
2163 PostcopyState ps = postcopy_state_get();
2165 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
2168 bool migration_in_bg_snapshot(void)
2170 MigrationState *s = migrate_get_current();
2172 return migrate_background_snapshot() &&
2173 migration_is_setup_or_active(s->state);
2176 bool migration_is_idle(void)
2178 MigrationState *s = current_migration;
2180 if (!s) {
2181 return true;
2184 switch (s->state) {
2185 case MIGRATION_STATUS_NONE:
2186 case MIGRATION_STATUS_CANCELLED:
2187 case MIGRATION_STATUS_COMPLETED:
2188 case MIGRATION_STATUS_FAILED:
2189 return true;
2190 case MIGRATION_STATUS_SETUP:
2191 case MIGRATION_STATUS_CANCELLING:
2192 case MIGRATION_STATUS_ACTIVE:
2193 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2194 case MIGRATION_STATUS_COLO:
2195 case MIGRATION_STATUS_PRE_SWITCHOVER:
2196 case MIGRATION_STATUS_DEVICE:
2197 case MIGRATION_STATUS_WAIT_UNPLUG:
2198 return false;
2199 case MIGRATION_STATUS__MAX:
2200 g_assert_not_reached();
2203 return false;
2206 bool migration_is_active(MigrationState *s)
2208 return (s->state == MIGRATION_STATUS_ACTIVE ||
2209 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2212 void migrate_init(MigrationState *s)
2215 * Reinitialise all migration state, except
2216 * parameters/capabilities that the user set, and
2217 * locks.
2219 s->cleanup_bh = 0;
2220 s->vm_start_bh = 0;
2221 s->to_dst_file = NULL;
2222 s->state = MIGRATION_STATUS_NONE;
2223 s->rp_state.from_dst_file = NULL;
2224 s->rp_state.error = false;
2225 s->mbps = 0.0;
2226 s->pages_per_second = 0.0;
2227 s->downtime = 0;
2228 s->expected_downtime = 0;
2229 s->setup_time = 0;
2230 s->start_postcopy = false;
2231 s->postcopy_after_devices = false;
2232 s->migration_thread_running = false;
2233 error_free(s->error);
2234 s->error = NULL;
2235 s->hostname = NULL;
2237 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
2239 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2240 s->total_time = 0;
2241 s->vm_was_running = false;
2242 s->iteration_initial_bytes = 0;
2243 s->threshold_size = 0;
2246 int migrate_add_blocker_internal(Error *reason, Error **errp)
2248 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
2249 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
2250 error_propagate_prepend(errp, error_copy(reason),
2251 "disallowing migration blocker "
2252 "(migration/snapshot in progress) for: ");
2253 return -EBUSY;
2256 migration_blockers = g_slist_prepend(migration_blockers, reason);
2257 return 0;
2260 int migrate_add_blocker(Error *reason, Error **errp)
2262 if (only_migratable) {
2263 error_propagate_prepend(errp, error_copy(reason),
2264 "disallowing migration blocker "
2265 "(--only-migratable) for: ");
2266 return -EACCES;
2269 return migrate_add_blocker_internal(reason, errp);
2272 void migrate_del_blocker(Error *reason)
2274 migration_blockers = g_slist_remove(migration_blockers, reason);
2277 void qmp_migrate_incoming(const char *uri, Error **errp)
2279 Error *local_err = NULL;
2280 static bool once = true;
2282 if (!once) {
2283 error_setg(errp, "The incoming migration has already been started");
2284 return;
2286 if (!runstate_check(RUN_STATE_INMIGRATE)) {
2287 error_setg(errp, "'-incoming' was not specified on the command line");
2288 return;
2291 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2292 return;
2295 qemu_start_incoming_migration(uri, &local_err);
2297 if (local_err) {
2298 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2299 error_propagate(errp, local_err);
2300 return;
2303 once = false;
2306 void qmp_migrate_recover(const char *uri, Error **errp)
2308 MigrationIncomingState *mis = migration_incoming_get_current();
2311 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
2312 * callers (no one should ignore a recover failure); if there is, it's a
2313 * programming error.
2315 assert(errp);
2317 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2318 error_setg(errp, "Migrate recover can only be run "
2319 "when postcopy is paused.");
2320 return;
2323 /* If there's an existing transport, release it */
2324 migration_incoming_transport_cleanup(mis);
2327 * Note that this call will never start a real migration; it will
2328 * only re-setup the migration stream and poke existing migration
2329 * to continue using that newly established channel.
2331 qemu_start_incoming_migration(uri, errp);
2334 void qmp_migrate_pause(Error **errp)
2336 MigrationState *ms = migrate_get_current();
2337 MigrationIncomingState *mis = migration_incoming_get_current();
2338 int ret;
2340 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2341 /* Source side, during postcopy */
2342 qemu_mutex_lock(&ms->qemu_file_lock);
2343 ret = qemu_file_shutdown(ms->to_dst_file);
2344 qemu_mutex_unlock(&ms->qemu_file_lock);
2345 if (ret) {
2346 error_setg(errp, "Failed to pause source migration");
2348 return;
2351 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2352 ret = qemu_file_shutdown(mis->from_src_file);
2353 if (ret) {
2354 error_setg(errp, "Failed to pause destination migration");
2356 return;
2359 error_setg(errp, "migrate-pause is currently only supported "
2360 "during postcopy-active state");
2363 bool migration_is_blocked(Error **errp)
2365 if (qemu_savevm_state_blocked(errp)) {
2366 return true;
2369 if (migration_blockers) {
2370 error_propagate(errp, error_copy(migration_blockers->data));
2371 return true;
2374 return false;
2377 /* Returns true if continue to migrate, or false if error detected */
2378 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
2379 bool resume, Error **errp)
2381 Error *local_err = NULL;
2383 if (resume) {
2384 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2385 error_setg(errp, "Cannot resume if there is no "
2386 "paused migration");
2387 return false;
2391 * Postcopy recovery won't work well with release-ram
2392 * capability since release-ram will drop the page buffer as
2393 * long as the page is put into the send buffer. So if there
2394 * is a network failure happened, any page buffers that have
2395 * not yet reached the destination VM but have already been
2396 * sent from the source VM will be lost forever. Let's refuse
2397 * the client from resuming such a postcopy migration.
2398 * Luckily release-ram was designed to only be used when src
2399 * and destination VMs are on the same host, so it should be
2400 * fine.
2402 if (migrate_release_ram()) {
2403 error_setg(errp, "Postcopy recovery cannot work "
2404 "when release-ram capability is set");
2405 return false;
2408 /* This is a resume, skip init status */
2409 return true;
2412 if (migration_is_running(s->state)) {
2413 error_setg(errp, QERR_MIGRATION_ACTIVE);
2414 return false;
2417 if (runstate_check(RUN_STATE_INMIGRATE)) {
2418 error_setg(errp, "Guest is waiting for an incoming migration");
2419 return false;
2422 if (runstate_check(RUN_STATE_POSTMIGRATE)) {
2423 error_setg(errp, "Can't migrate the vm that was paused due to "
2424 "previous migration");
2425 return false;
2428 if (migration_is_blocked(errp)) {
2429 return false;
2432 if (blk || blk_inc) {
2433 if (migrate_colo_enabled()) {
2434 error_setg(errp, "No disk migration is required in COLO mode");
2435 return false;
2437 if (migrate_use_block() || migrate_use_block_incremental()) {
2438 error_setg(errp, "Command options are incompatible with "
2439 "current migration capabilities");
2440 return false;
2442 migrate_set_block_enabled(true, &local_err);
2443 if (local_err) {
2444 error_propagate(errp, local_err);
2445 return false;
2447 s->must_remove_block_options = true;
2450 if (blk_inc) {
2451 migrate_set_block_incremental(s, true);
2454 migrate_init(s);
2456 * set ram_counters compression_counters memory to zero for a
2457 * new migration
2459 memset(&ram_counters, 0, sizeof(ram_counters));
2460 memset(&compression_counters, 0, sizeof(compression_counters));
2462 return true;
2465 void qmp_migrate(const char *uri, bool has_blk, bool blk,
2466 bool has_inc, bool inc, bool has_detach, bool detach,
2467 bool has_resume, bool resume, Error **errp)
2469 Error *local_err = NULL;
2470 MigrationState *s = migrate_get_current();
2471 const char *p = NULL;
2473 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2474 has_resume && resume, errp)) {
2475 /* Error detected, put into errp */
2476 return;
2479 if (!(has_resume && resume)) {
2480 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2481 return;
2485 migrate_protocol_allow_multi_channels(false);
2486 if (strstart(uri, "tcp:", &p) ||
2487 strstart(uri, "unix:", NULL) ||
2488 strstart(uri, "vsock:", NULL)) {
2489 migrate_protocol_allow_multi_channels(true);
2490 socket_start_outgoing_migration(s, p ? p : uri, &local_err);
2491 #ifdef CONFIG_RDMA
2492 } else if (strstart(uri, "rdma:", &p)) {
2493 rdma_start_outgoing_migration(s, p, &local_err);
2494 #endif
2495 } else if (strstart(uri, "exec:", &p)) {
2496 exec_start_outgoing_migration(s, p, &local_err);
2497 } else if (strstart(uri, "fd:", &p)) {
2498 fd_start_outgoing_migration(s, p, &local_err);
2499 } else {
2500 if (!(has_resume && resume)) {
2501 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2503 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2504 "a valid migration protocol");
2505 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2506 MIGRATION_STATUS_FAILED);
2507 block_cleanup_parameters(s);
2508 return;
2511 if (local_err) {
2512 if (!(has_resume && resume)) {
2513 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2515 migrate_fd_error(s, local_err);
2516 error_propagate(errp, local_err);
2517 return;
2521 void qmp_migrate_cancel(Error **errp)
2523 migration_cancel(NULL);
2526 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2528 MigrationState *s = migrate_get_current();
2529 if (s->state != state) {
2530 error_setg(errp, "Migration not in expected state: %s",
2531 MigrationStatus_str(s->state));
2532 return;
2534 qemu_sem_post(&s->pause_sem);
2537 bool migrate_release_ram(void)
2539 MigrationState *s;
2541 s = migrate_get_current();
2543 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2546 bool migrate_postcopy_ram(void)
2548 MigrationState *s;
2550 s = migrate_get_current();
2552 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
2555 bool migrate_postcopy(void)
2557 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
2560 bool migrate_auto_converge(void)
2562 MigrationState *s;
2564 s = migrate_get_current();
2566 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2569 bool migrate_zero_blocks(void)
2571 MigrationState *s;
2573 s = migrate_get_current();
2575 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2578 bool migrate_postcopy_blocktime(void)
2580 MigrationState *s;
2582 s = migrate_get_current();
2584 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2587 bool migrate_use_compression(void)
2589 MigrationState *s;
2591 s = migrate_get_current();
2593 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
2596 int migrate_compress_level(void)
2598 MigrationState *s;
2600 s = migrate_get_current();
2602 return s->parameters.compress_level;
2605 int migrate_compress_threads(void)
2607 MigrationState *s;
2609 s = migrate_get_current();
2611 return s->parameters.compress_threads;
2614 int migrate_compress_wait_thread(void)
2616 MigrationState *s;
2618 s = migrate_get_current();
2620 return s->parameters.compress_wait_thread;
2623 int migrate_decompress_threads(void)
2625 MigrationState *s;
2627 s = migrate_get_current();
2629 return s->parameters.decompress_threads;
2632 bool migrate_dirty_bitmaps(void)
2634 MigrationState *s;
2636 s = migrate_get_current();
2638 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2641 bool migrate_ignore_shared(void)
2643 MigrationState *s;
2645 s = migrate_get_current();
2647 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2650 bool migrate_validate_uuid(void)
2652 MigrationState *s;
2654 s = migrate_get_current();
2656 return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2659 bool migrate_use_events(void)
2661 MigrationState *s;
2663 s = migrate_get_current();
2665 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2668 bool migrate_use_multifd(void)
2670 MigrationState *s;
2672 s = migrate_get_current();
2674 return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
2677 bool migrate_pause_before_switchover(void)
2679 MigrationState *s;
2681 s = migrate_get_current();
2683 return s->enabled_capabilities[
2684 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2687 int migrate_multifd_channels(void)
2689 MigrationState *s;
2691 s = migrate_get_current();
2693 return s->parameters.multifd_channels;
2696 MultiFDCompression migrate_multifd_compression(void)
2698 MigrationState *s;
2700 s = migrate_get_current();
2702 assert(s->parameters.multifd_compression < MULTIFD_COMPRESSION__MAX);
2703 return s->parameters.multifd_compression;
2706 int migrate_multifd_zlib_level(void)
2708 MigrationState *s;
2710 s = migrate_get_current();
2712 return s->parameters.multifd_zlib_level;
2715 int migrate_multifd_zstd_level(void)
2717 MigrationState *s;
2719 s = migrate_get_current();
2721 return s->parameters.multifd_zstd_level;
2724 #ifdef CONFIG_LINUX
2725 bool migrate_use_zero_copy_send(void)
2727 MigrationState *s;
2729 s = migrate_get_current();
2731 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_COPY_SEND];
2733 #endif
2735 int migrate_use_tls(void)
2737 MigrationState *s;
2739 s = migrate_get_current();
2741 return s->parameters.tls_creds && *s->parameters.tls_creds;
2744 int migrate_use_xbzrle(void)
2746 MigrationState *s;
2748 s = migrate_get_current();
2750 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2753 uint64_t migrate_xbzrle_cache_size(void)
2755 MigrationState *s;
2757 s = migrate_get_current();
2759 return s->parameters.xbzrle_cache_size;
2762 static int64_t migrate_max_postcopy_bandwidth(void)
2764 MigrationState *s;
2766 s = migrate_get_current();
2768 return s->parameters.max_postcopy_bandwidth;
2771 bool migrate_use_block(void)
2773 MigrationState *s;
2775 s = migrate_get_current();
2777 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2780 bool migrate_use_return_path(void)
2782 MigrationState *s;
2784 s = migrate_get_current();
2786 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2789 bool migrate_use_block_incremental(void)
2791 MigrationState *s;
2793 s = migrate_get_current();
2795 return s->parameters.block_incremental;
2798 bool migrate_background_snapshot(void)
2800 MigrationState *s;
2802 s = migrate_get_current();
2804 return s->enabled_capabilities[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT];
2807 bool migrate_postcopy_preempt(void)
2809 MigrationState *s;
2811 s = migrate_get_current();
2813 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT];
2816 /* migration thread support */
2818 * Something bad happened to the RP stream, mark an error
2819 * The caller shall print or trace something to indicate why
2821 static void mark_source_rp_bad(MigrationState *s)
2823 s->rp_state.error = true;
2826 static struct rp_cmd_args {
2827 ssize_t len; /* -1 = variable */
2828 const char *name;
2829 } rp_cmd_args[] = {
2830 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2831 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2832 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2833 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2834 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2835 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2836 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2837 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2841 * Process a request for pages received on the return path,
2842 * We're allowed to send more than requested (e.g. to round to our page size)
2843 * and we don't need to send pages that have already been sent.
2845 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2846 ram_addr_t start, size_t len)
2848 long our_host_ps = qemu_real_host_page_size();
2850 trace_migrate_handle_rp_req_pages(rbname, start, len);
2853 * Since we currently insist on matching page sizes, just sanity check
2854 * we're being asked for whole host pages.
2856 if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2857 !QEMU_IS_ALIGNED(len, our_host_ps)) {
2858 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2859 " len: %zd", __func__, start, len);
2860 mark_source_rp_bad(ms);
2861 return;
2864 if (ram_save_queue_pages(rbname, start, len)) {
2865 mark_source_rp_bad(ms);
2869 /* Return true to retry, false to quit */
2870 static bool postcopy_pause_return_path_thread(MigrationState *s)
2872 trace_postcopy_pause_return_path();
2874 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2876 trace_postcopy_pause_return_path_continued();
2878 return true;
2881 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2883 RAMBlock *block = qemu_ram_block_by_name(block_name);
2885 if (!block) {
2886 error_report("%s: invalid block name '%s'", __func__, block_name);
2887 return -EINVAL;
2890 /* Fetch the received bitmap and refresh the dirty bitmap */
2891 return ram_dirty_bitmap_reload(s, block);
2894 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2896 trace_source_return_path_thread_resume_ack(value);
2898 if (value != MIGRATION_RESUME_ACK_VALUE) {
2899 error_report("%s: illegal resume_ack value %"PRIu32,
2900 __func__, value);
2901 return -1;
2904 /* Now both sides are active. */
2905 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2906 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2908 /* Notify send thread that time to continue send pages */
2909 qemu_sem_post(&s->rp_state.rp_sem);
2911 return 0;
2915 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2916 * existed) in a safe way.
2918 static void migration_release_dst_files(MigrationState *ms)
2920 QEMUFile *file;
2922 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2924 * Reset the from_dst_file pointer first before releasing it, as we
2925 * can't block within lock section
2927 file = ms->rp_state.from_dst_file;
2928 ms->rp_state.from_dst_file = NULL;
2932 * Do the same to postcopy fast path socket too if there is. No
2933 * locking needed because this qemufile should only be managed by
2934 * return path thread.
2936 if (ms->postcopy_qemufile_src) {
2937 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
2938 qemu_file_shutdown(ms->postcopy_qemufile_src);
2939 qemu_fclose(ms->postcopy_qemufile_src);
2940 ms->postcopy_qemufile_src = NULL;
2943 qemu_fclose(file);
2947 * Handles messages sent on the return path towards the source VM
2950 static void *source_return_path_thread(void *opaque)
2952 MigrationState *ms = opaque;
2953 QEMUFile *rp = ms->rp_state.from_dst_file;
2954 uint16_t header_len, header_type;
2955 uint8_t buf[512];
2956 uint32_t tmp32, sibling_error;
2957 ram_addr_t start = 0; /* =0 to silence warning */
2958 size_t len = 0, expected_len;
2959 int res;
2961 trace_source_return_path_thread_entry();
2962 rcu_register_thread();
2964 retry:
2965 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2966 migration_is_setup_or_active(ms->state)) {
2967 trace_source_return_path_thread_loop_top();
2968 header_type = qemu_get_be16(rp);
2969 header_len = qemu_get_be16(rp);
2971 if (qemu_file_get_error(rp)) {
2972 mark_source_rp_bad(ms);
2973 goto out;
2976 if (header_type >= MIG_RP_MSG_MAX ||
2977 header_type == MIG_RP_MSG_INVALID) {
2978 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2979 header_type, header_len);
2980 mark_source_rp_bad(ms);
2981 goto out;
2984 if ((rp_cmd_args[header_type].len != -1 &&
2985 header_len != rp_cmd_args[header_type].len) ||
2986 header_len > sizeof(buf)) {
2987 error_report("RP: Received '%s' message (0x%04x) with"
2988 "incorrect length %d expecting %zu",
2989 rp_cmd_args[header_type].name, header_type, header_len,
2990 (size_t)rp_cmd_args[header_type].len);
2991 mark_source_rp_bad(ms);
2992 goto out;
2995 /* We know we've got a valid header by this point */
2996 res = qemu_get_buffer(rp, buf, header_len);
2997 if (res != header_len) {
2998 error_report("RP: Failed reading data for message 0x%04x"
2999 " read %d expected %d",
3000 header_type, res, header_len);
3001 mark_source_rp_bad(ms);
3002 goto out;
3005 /* OK, we have the message and the data */
3006 switch (header_type) {
3007 case MIG_RP_MSG_SHUT:
3008 sibling_error = ldl_be_p(buf);
3009 trace_source_return_path_thread_shut(sibling_error);
3010 if (sibling_error) {
3011 error_report("RP: Sibling indicated error %d", sibling_error);
3012 mark_source_rp_bad(ms);
3015 * We'll let the main thread deal with closing the RP
3016 * we could do a shutdown(2) on it, but we're the only user
3017 * anyway, so there's nothing gained.
3019 goto out;
3021 case MIG_RP_MSG_PONG:
3022 tmp32 = ldl_be_p(buf);
3023 trace_source_return_path_thread_pong(tmp32);
3024 break;
3026 case MIG_RP_MSG_REQ_PAGES:
3027 start = ldq_be_p(buf);
3028 len = ldl_be_p(buf + 8);
3029 migrate_handle_rp_req_pages(ms, NULL, start, len);
3030 break;
3032 case MIG_RP_MSG_REQ_PAGES_ID:
3033 expected_len = 12 + 1; /* header + termination */
3035 if (header_len >= expected_len) {
3036 start = ldq_be_p(buf);
3037 len = ldl_be_p(buf + 8);
3038 /* Now we expect an idstr */
3039 tmp32 = buf[12]; /* Length of the following idstr */
3040 buf[13 + tmp32] = '\0';
3041 expected_len += tmp32;
3043 if (header_len != expected_len) {
3044 error_report("RP: Req_Page_id with length %d expecting %zd",
3045 header_len, expected_len);
3046 mark_source_rp_bad(ms);
3047 goto out;
3049 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
3050 break;
3052 case MIG_RP_MSG_RECV_BITMAP:
3053 if (header_len < 1) {
3054 error_report("%s: missing block name", __func__);
3055 mark_source_rp_bad(ms);
3056 goto out;
3058 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
3059 buf[buf[0] + 1] = '\0';
3060 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
3061 mark_source_rp_bad(ms);
3062 goto out;
3064 break;
3066 case MIG_RP_MSG_RESUME_ACK:
3067 tmp32 = ldl_be_p(buf);
3068 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
3069 mark_source_rp_bad(ms);
3070 goto out;
3072 break;
3074 default:
3075 break;
3079 out:
3080 res = qemu_file_get_error(rp);
3081 if (res) {
3082 if (res && migration_in_postcopy()) {
3084 * Maybe there is something we can do: it looks like a
3085 * network down issue, and we pause for a recovery.
3087 migration_release_dst_files(ms);
3088 rp = NULL;
3089 if (postcopy_pause_return_path_thread(ms)) {
3091 * Reload rp, reset the rest. Referencing it is safe since
3092 * it's reset only by us above, or when migration completes
3094 rp = ms->rp_state.from_dst_file;
3095 ms->rp_state.error = false;
3096 goto retry;
3100 trace_source_return_path_thread_bad_end();
3101 mark_source_rp_bad(ms);
3104 trace_source_return_path_thread_end();
3105 migration_release_dst_files(ms);
3106 rcu_unregister_thread();
3107 return NULL;
3110 static int open_return_path_on_source(MigrationState *ms,
3111 bool create_thread)
3113 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
3114 if (!ms->rp_state.from_dst_file) {
3115 return -1;
3118 trace_open_return_path_on_source();
3120 if (!create_thread) {
3121 /* We're done */
3122 return 0;
3125 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
3126 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
3127 ms->rp_state.rp_thread_created = true;
3129 trace_open_return_path_on_source_continue();
3131 return 0;
3134 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
3135 static int await_return_path_close_on_source(MigrationState *ms)
3138 * If this is a normal exit then the destination will send a SHUT and the
3139 * rp_thread will exit, however if there's an error we need to cause
3140 * it to exit.
3142 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
3144 * shutdown(2), if we have it, will cause it to unblock if it's stuck
3145 * waiting for the destination.
3147 qemu_file_shutdown(ms->rp_state.from_dst_file);
3148 mark_source_rp_bad(ms);
3150 trace_await_return_path_close_on_source_joining();
3151 qemu_thread_join(&ms->rp_state.rp_thread);
3152 ms->rp_state.rp_thread_created = false;
3153 trace_await_return_path_close_on_source_close();
3154 return ms->rp_state.error;
3158 * Switch from normal iteration to postcopy
3159 * Returns non-0 on error
3161 static int postcopy_start(MigrationState *ms)
3163 int ret;
3164 QIOChannelBuffer *bioc;
3165 QEMUFile *fb;
3166 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3167 int64_t bandwidth = migrate_max_postcopy_bandwidth();
3168 bool restart_block = false;
3169 int cur_state = MIGRATION_STATUS_ACTIVE;
3171 if (postcopy_preempt_wait_channel(ms)) {
3172 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
3173 return -1;
3176 if (!migrate_pause_before_switchover()) {
3177 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
3178 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3181 trace_postcopy_start();
3182 qemu_mutex_lock_iothread();
3183 trace_postcopy_start_set_run();
3185 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3186 global_state_store();
3187 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3188 if (ret < 0) {
3189 goto fail;
3192 ret = migration_maybe_pause(ms, &cur_state,
3193 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3194 if (ret < 0) {
3195 goto fail;
3198 ret = bdrv_inactivate_all();
3199 if (ret < 0) {
3200 goto fail;
3202 restart_block = true;
3205 * Cause any non-postcopiable, but iterative devices to
3206 * send out their final data.
3208 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
3211 * in Finish migrate and with the io-lock held everything should
3212 * be quiet, but we've potentially still got dirty pages and we
3213 * need to tell the destination to throw any pages it's already received
3214 * that are dirty
3216 if (migrate_postcopy_ram()) {
3217 ram_postcopy_send_discard_bitmap(ms);
3221 * send rest of state - note things that are doing postcopy
3222 * will notice we're in POSTCOPY_ACTIVE and not actually
3223 * wrap their state up here
3225 /* 0 max-postcopy-bandwidth means unlimited */
3226 if (!bandwidth) {
3227 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
3228 } else {
3229 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
3231 if (migrate_postcopy_ram()) {
3232 /* Ping just for debugging, helps line traces up */
3233 qemu_savevm_send_ping(ms->to_dst_file, 2);
3237 * While loading the device state we may trigger page transfer
3238 * requests and the fd must be free to process those, and thus
3239 * the destination must read the whole device state off the fd before
3240 * it starts processing it. Unfortunately the ad-hoc migration format
3241 * doesn't allow the destination to know the size to read without fully
3242 * parsing it through each devices load-state code (especially the open
3243 * coded devices that use get/put).
3244 * So we wrap the device state up in a package with a length at the start;
3245 * to do this we use a qemu_buf to hold the whole of the device state.
3247 bioc = qio_channel_buffer_new(4096);
3248 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
3249 fb = qemu_file_new_output(QIO_CHANNEL(bioc));
3250 object_unref(OBJECT(bioc));
3253 * Make sure the receiver can get incoming pages before we send the rest
3254 * of the state
3256 qemu_savevm_send_postcopy_listen(fb);
3258 qemu_savevm_state_complete_precopy(fb, false, false);
3259 if (migrate_postcopy_ram()) {
3260 qemu_savevm_send_ping(fb, 3);
3263 qemu_savevm_send_postcopy_run(fb);
3265 /* <><> end of stuff going into the package */
3267 /* Last point of recovery; as soon as we send the package the destination
3268 * can open devices and potentially start running.
3269 * Lets just check again we've not got any errors.
3271 ret = qemu_file_get_error(ms->to_dst_file);
3272 if (ret) {
3273 error_report("postcopy_start: Migration stream errored (pre package)");
3274 goto fail_closefb;
3277 restart_block = false;
3279 /* Now send that blob */
3280 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
3281 goto fail_closefb;
3283 qemu_fclose(fb);
3285 /* Send a notify to give a chance for anything that needs to happen
3286 * at the transition to postcopy and after the device state; in particular
3287 * spice needs to trigger a transition now
3289 ms->postcopy_after_devices = true;
3290 notifier_list_notify(&migration_state_notifiers, ms);
3292 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
3294 qemu_mutex_unlock_iothread();
3296 if (migrate_postcopy_ram()) {
3298 * Although this ping is just for debug, it could potentially be
3299 * used for getting a better measurement of downtime at the source.
3301 qemu_savevm_send_ping(ms->to_dst_file, 4);
3304 if (migrate_release_ram()) {
3305 ram_postcopy_migrated_memory_release(ms);
3308 ret = qemu_file_get_error(ms->to_dst_file);
3309 if (ret) {
3310 error_report("postcopy_start: Migration stream errored");
3311 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3312 MIGRATION_STATUS_FAILED);
3315 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
3317 return ret;
3319 fail_closefb:
3320 qemu_fclose(fb);
3321 fail:
3322 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
3323 MIGRATION_STATUS_FAILED);
3324 if (restart_block) {
3325 /* A failure happened early enough that we know the destination hasn't
3326 * accessed block devices, so we're safe to recover.
3328 Error *local_err = NULL;
3330 bdrv_activate_all(&local_err);
3331 if (local_err) {
3332 error_report_err(local_err);
3335 qemu_mutex_unlock_iothread();
3336 return -1;
3340 * migration_maybe_pause: Pause if required to by
3341 * migrate_pause_before_switchover called with the iothread locked
3342 * Returns: 0 on success
3344 static int migration_maybe_pause(MigrationState *s,
3345 int *current_active_state,
3346 int new_state)
3348 if (!migrate_pause_before_switchover()) {
3349 return 0;
3352 /* Since leaving this state is not atomic with posting the semaphore
3353 * it's possible that someone could have issued multiple migrate_continue
3354 * and the semaphore is incorrectly positive at this point;
3355 * the docs say it's undefined to reinit a semaphore that's already
3356 * init'd, so use timedwait to eat up any existing posts.
3358 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
3359 /* This block intentionally left blank */
3363 * If the migration is cancelled when it is in the completion phase,
3364 * the migration state is set to MIGRATION_STATUS_CANCELLING.
3365 * So we don't need to wait a semaphore, otherwise we would always
3366 * wait for the 'pause_sem' semaphore.
3368 if (s->state != MIGRATION_STATUS_CANCELLING) {
3369 qemu_mutex_unlock_iothread();
3370 migrate_set_state(&s->state, *current_active_state,
3371 MIGRATION_STATUS_PRE_SWITCHOVER);
3372 qemu_sem_wait(&s->pause_sem);
3373 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
3374 new_state);
3375 *current_active_state = new_state;
3376 qemu_mutex_lock_iothread();
3379 return s->state == new_state ? 0 : -EINVAL;
3383 * migration_completion: Used by migration_thread when there's not much left.
3384 * The caller 'breaks' the loop when this returns.
3386 * @s: Current migration state
3388 static void migration_completion(MigrationState *s)
3390 int ret;
3391 int current_active_state = s->state;
3393 if (s->state == MIGRATION_STATUS_ACTIVE) {
3394 qemu_mutex_lock_iothread();
3395 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3396 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
3397 s->vm_was_running = runstate_is_running();
3398 ret = global_state_store();
3400 if (!ret) {
3401 bool inactivate = !migrate_colo_enabled();
3402 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
3403 trace_migration_completion_vm_stop(ret);
3404 if (ret >= 0) {
3405 ret = migration_maybe_pause(s, &current_active_state,
3406 MIGRATION_STATUS_DEVICE);
3408 if (ret >= 0) {
3409 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
3410 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
3411 inactivate);
3413 if (inactivate && ret >= 0) {
3414 s->block_inactive = true;
3417 qemu_mutex_unlock_iothread();
3419 if (ret < 0) {
3420 goto fail;
3422 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3423 trace_migration_completion_postcopy_end();
3425 qemu_mutex_lock_iothread();
3426 qemu_savevm_state_complete_postcopy(s->to_dst_file);
3427 qemu_mutex_unlock_iothread();
3429 /* Shutdown the postcopy fast path thread */
3430 if (migrate_postcopy_preempt()) {
3431 postcopy_preempt_shutdown_file(s);
3434 trace_migration_completion_postcopy_end_after_complete();
3435 } else {
3436 goto fail;
3440 * If rp was opened we must clean up the thread before
3441 * cleaning everything else up (since if there are no failures
3442 * it will wait for the destination to send it's status in
3443 * a SHUT command).
3445 if (s->rp_state.rp_thread_created) {
3446 int rp_error;
3447 trace_migration_return_path_end_before();
3448 rp_error = await_return_path_close_on_source(s);
3449 trace_migration_return_path_end_after(rp_error);
3450 if (rp_error) {
3451 goto fail_invalidate;
3455 if (qemu_file_get_error(s->to_dst_file)) {
3456 trace_migration_completion_file_err();
3457 goto fail_invalidate;
3460 if (migrate_colo_enabled() && s->state == MIGRATION_STATUS_ACTIVE) {
3461 /* COLO does not support postcopy */
3462 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3463 MIGRATION_STATUS_COLO);
3464 } else {
3465 migrate_set_state(&s->state, current_active_state,
3466 MIGRATION_STATUS_COMPLETED);
3469 return;
3471 fail_invalidate:
3472 /* If not doing postcopy, vm_start() will be called: let's regain
3473 * control on images.
3475 if (s->state == MIGRATION_STATUS_ACTIVE ||
3476 s->state == MIGRATION_STATUS_DEVICE) {
3477 Error *local_err = NULL;
3479 qemu_mutex_lock_iothread();
3480 bdrv_activate_all(&local_err);
3481 if (local_err) {
3482 error_report_err(local_err);
3483 } else {
3484 s->block_inactive = false;
3486 qemu_mutex_unlock_iothread();
3489 fail:
3490 migrate_set_state(&s->state, current_active_state,
3491 MIGRATION_STATUS_FAILED);
3495 * bg_migration_completion: Used by bg_migration_thread when after all the
3496 * RAM has been saved. The caller 'breaks' the loop when this returns.
3498 * @s: Current migration state
3500 static void bg_migration_completion(MigrationState *s)
3502 int current_active_state = s->state;
3505 * Stop tracking RAM writes - un-protect memory, un-register UFFD
3506 * memory ranges, flush kernel wait queues and wake up threads
3507 * waiting for write fault to be resolved.
3509 ram_write_tracking_stop();
3511 if (s->state == MIGRATION_STATUS_ACTIVE) {
3513 * By this moment we have RAM content saved into the migration stream.
3514 * The next step is to flush the non-RAM content (device state)
3515 * right after the ram content. The device state has been stored into
3516 * the temporary buffer before RAM saving started.
3518 qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
3519 qemu_fflush(s->to_dst_file);
3520 } else if (s->state == MIGRATION_STATUS_CANCELLING) {
3521 goto fail;
3524 if (qemu_file_get_error(s->to_dst_file)) {
3525 trace_migration_completion_file_err();
3526 goto fail;
3529 migrate_set_state(&s->state, current_active_state,
3530 MIGRATION_STATUS_COMPLETED);
3531 return;
3533 fail:
3534 migrate_set_state(&s->state, current_active_state,
3535 MIGRATION_STATUS_FAILED);
3538 bool migrate_colo_enabled(void)
3540 MigrationState *s = migrate_get_current();
3541 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
3544 typedef enum MigThrError {
3545 /* No error detected */
3546 MIG_THR_ERR_NONE = 0,
3547 /* Detected error, but resumed successfully */
3548 MIG_THR_ERR_RECOVERED = 1,
3549 /* Detected fatal error, need to exit */
3550 MIG_THR_ERR_FATAL = 2,
3551 } MigThrError;
3553 static int postcopy_resume_handshake(MigrationState *s)
3555 qemu_savevm_send_postcopy_resume(s->to_dst_file);
3557 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3558 qemu_sem_wait(&s->rp_state.rp_sem);
3561 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3562 return 0;
3565 return -1;
3568 /* Return zero if success, or <0 for error */
3569 static int postcopy_do_resume(MigrationState *s)
3571 int ret;
3574 * Call all the resume_prepare() hooks, so that modules can be
3575 * ready for the migration resume.
3577 ret = qemu_savevm_state_resume_prepare(s);
3578 if (ret) {
3579 error_report("%s: resume_prepare() failure detected: %d",
3580 __func__, ret);
3581 return ret;
3585 * Last handshake with destination on the resume (destination will
3586 * switch to postcopy-active afterwards)
3588 ret = postcopy_resume_handshake(s);
3589 if (ret) {
3590 error_report("%s: handshake failed: %d", __func__, ret);
3591 return ret;
3594 return 0;
3598 * We don't return until we are in a safe state to continue current
3599 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
3600 * MIG_THR_ERR_FATAL if unrecovery failure happened.
3602 static MigThrError postcopy_pause(MigrationState *s)
3604 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3606 while (true) {
3607 QEMUFile *file;
3610 * Current channel is possibly broken. Release it. Note that this is
3611 * guaranteed even without lock because to_dst_file should only be
3612 * modified by the migration thread. That also guarantees that the
3613 * unregister of yank is safe too without the lock. It should be safe
3614 * even to be within the qemu_file_lock, but we didn't do that to avoid
3615 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
3616 * the qemu_file_lock critical section as small as possible.
3618 assert(s->to_dst_file);
3619 migration_ioc_unregister_yank_from_file(s->to_dst_file);
3620 qemu_mutex_lock(&s->qemu_file_lock);
3621 file = s->to_dst_file;
3622 s->to_dst_file = NULL;
3623 qemu_mutex_unlock(&s->qemu_file_lock);
3625 qemu_file_shutdown(file);
3626 qemu_fclose(file);
3628 migrate_set_state(&s->state, s->state,
3629 MIGRATION_STATUS_POSTCOPY_PAUSED);
3631 error_report("Detected IO failure for postcopy. "
3632 "Migration paused.");
3635 * We wait until things fixed up. Then someone will setup the
3636 * status back for us.
3638 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3639 qemu_sem_wait(&s->postcopy_pause_sem);
3642 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3643 /* Woken up by a recover procedure. Give it a shot */
3645 if (postcopy_preempt_wait_channel(s)) {
3647 * Preempt enabled, and new channel create failed; loop
3648 * back to wait for another recovery.
3650 continue;
3654 * Firstly, let's wake up the return path now, with a new
3655 * return path channel.
3657 qemu_sem_post(&s->postcopy_pause_rp_sem);
3659 /* Do the resume logic */
3660 if (postcopy_do_resume(s) == 0) {
3661 /* Let's continue! */
3662 trace_postcopy_pause_continued();
3663 return MIG_THR_ERR_RECOVERED;
3664 } else {
3666 * Something wrong happened during the recovery, let's
3667 * pause again. Pause is always better than throwing
3668 * data away.
3670 continue;
3672 } else {
3673 /* This is not right... Time to quit. */
3674 return MIG_THR_ERR_FATAL;
3679 static MigThrError migration_detect_error(MigrationState *s)
3681 int ret;
3682 int state = s->state;
3683 Error *local_error = NULL;
3685 if (state == MIGRATION_STATUS_CANCELLING ||
3686 state == MIGRATION_STATUS_CANCELLED) {
3687 /* End the migration, but don't set the state to failed */
3688 return MIG_THR_ERR_FATAL;
3692 * Try to detect any file errors. Note that postcopy_qemufile_src will
3693 * be NULL when postcopy preempt is not enabled.
3695 ret = qemu_file_get_error_obj_any(s->to_dst_file,
3696 s->postcopy_qemufile_src,
3697 &local_error);
3698 if (!ret) {
3699 /* Everything is fine */
3700 assert(!local_error);
3701 return MIG_THR_ERR_NONE;
3704 if (local_error) {
3705 migrate_set_error(s, local_error);
3706 error_free(local_error);
3709 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
3711 * For postcopy, we allow the network to be down for a
3712 * while. After that, it can be continued by a
3713 * recovery phase.
3715 return postcopy_pause(s);
3716 } else {
3718 * For precopy (or postcopy with error outside IO), we fail
3719 * with no time.
3721 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3722 trace_migration_thread_file_err();
3724 /* Time to stop the migration, now. */
3725 return MIG_THR_ERR_FATAL;
3729 /* How many bytes have we transferred since the beginning of the migration */
3730 static uint64_t migration_total_bytes(MigrationState *s)
3732 return qemu_file_total_transferred(s->to_dst_file) +
3733 ram_counters.multifd_bytes;
3736 static void migration_calculate_complete(MigrationState *s)
3738 uint64_t bytes = migration_total_bytes(s);
3739 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3740 int64_t transfer_time;
3742 s->total_time = end_time - s->start_time;
3743 if (!s->downtime) {
3745 * It's still not set, so we are precopy migration. For
3746 * postcopy, downtime is calculated during postcopy_start().
3748 s->downtime = end_time - s->downtime_start;
3751 transfer_time = s->total_time - s->setup_time;
3752 if (transfer_time) {
3753 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3757 static void update_iteration_initial_status(MigrationState *s)
3760 * Update these three fields at the same time to avoid mismatch info lead
3761 * wrong speed calculation.
3763 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3764 s->iteration_initial_bytes = migration_total_bytes(s);
3765 s->iteration_initial_pages = ram_get_total_transferred_pages();
3768 static void migration_update_counters(MigrationState *s,
3769 int64_t current_time)
3771 uint64_t transferred, transferred_pages, time_spent;
3772 uint64_t current_bytes; /* bytes transferred since the beginning */
3773 double bandwidth;
3775 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3776 return;
3779 current_bytes = migration_total_bytes(s);
3780 transferred = current_bytes - s->iteration_initial_bytes;
3781 time_spent = current_time - s->iteration_start_time;
3782 bandwidth = (double)transferred / time_spent;
3783 s->threshold_size = bandwidth * s->parameters.downtime_limit;
3785 s->mbps = (((double) transferred * 8.0) /
3786 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3788 transferred_pages = ram_get_total_transferred_pages() -
3789 s->iteration_initial_pages;
3790 s->pages_per_second = (double) transferred_pages /
3791 (((double) time_spent / 1000.0));
3794 * if we haven't sent anything, we don't want to
3795 * recalculate. 10000 is a small enough number for our purposes
3797 if (ram_counters.dirty_pages_rate && transferred > 10000) {
3798 s->expected_downtime = ram_counters.remaining / bandwidth;
3801 qemu_file_reset_rate_limit(s->to_dst_file);
3803 update_iteration_initial_status(s);
3805 trace_migrate_transferred(transferred, time_spent,
3806 bandwidth, s->threshold_size);
3809 /* Migration thread iteration status */
3810 typedef enum {
3811 MIG_ITERATE_RESUME, /* Resume current iteration */
3812 MIG_ITERATE_SKIP, /* Skip current iteration */
3813 MIG_ITERATE_BREAK, /* Break the loop */
3814 } MigIterateState;
3817 * Return true if continue to the next iteration directly, false
3818 * otherwise.
3820 static MigIterateState migration_iteration_run(MigrationState *s)
3822 uint64_t pend_pre, pend_compat, pend_post;
3823 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3825 qemu_savevm_state_pending_estimate(&pend_pre, &pend_compat, &pend_post);
3826 uint64_t pending_size = pend_pre + pend_compat + pend_post;
3828 trace_migrate_pending_estimate(pending_size,
3829 pend_pre, pend_compat, pend_post);
3831 if (pend_pre + pend_compat <= s->threshold_size) {
3832 qemu_savevm_state_pending_exact(&pend_pre, &pend_compat, &pend_post);
3833 pending_size = pend_pre + pend_compat + pend_post;
3834 trace_migrate_pending_exact(pending_size,
3835 pend_pre, pend_compat, pend_post);
3838 if (!pending_size || pending_size < s->threshold_size) {
3839 trace_migration_thread_low_pending(pending_size);
3840 migration_completion(s);
3841 return MIG_ITERATE_BREAK;
3844 /* Still a significant amount to transfer */
3845 if (!in_postcopy && pend_pre <= s->threshold_size &&
3846 qatomic_read(&s->start_postcopy)) {
3847 if (postcopy_start(s)) {
3848 error_report("%s: postcopy failed to start", __func__);
3850 return MIG_ITERATE_SKIP;
3853 /* Just another iteration step */
3854 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3855 return MIG_ITERATE_RESUME;
3858 static void migration_iteration_finish(MigrationState *s)
3860 /* If we enabled cpu throttling for auto-converge, turn it off. */
3861 cpu_throttle_stop();
3863 qemu_mutex_lock_iothread();
3864 switch (s->state) {
3865 case MIGRATION_STATUS_COMPLETED:
3866 migration_calculate_complete(s);
3867 runstate_set(RUN_STATE_POSTMIGRATE);
3868 break;
3869 case MIGRATION_STATUS_COLO:
3870 if (!migrate_colo_enabled()) {
3871 error_report("%s: critical error: calling COLO code without "
3872 "COLO enabled", __func__);
3874 migrate_start_colo_process(s);
3875 s->vm_was_running = true;
3876 /* Fallthrough */
3877 case MIGRATION_STATUS_FAILED:
3878 case MIGRATION_STATUS_CANCELLED:
3879 case MIGRATION_STATUS_CANCELLING:
3880 if (s->vm_was_running) {
3881 if (!runstate_check(RUN_STATE_SHUTDOWN)) {
3882 vm_start();
3884 } else {
3885 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3886 runstate_set(RUN_STATE_POSTMIGRATE);
3889 break;
3891 default:
3892 /* Should not reach here, but if so, forgive the VM. */
3893 error_report("%s: Unknown ending state %d", __func__, s->state);
3894 break;
3896 migrate_fd_cleanup_schedule(s);
3897 qemu_mutex_unlock_iothread();
3900 static void bg_migration_iteration_finish(MigrationState *s)
3902 qemu_mutex_lock_iothread();
3903 switch (s->state) {
3904 case MIGRATION_STATUS_COMPLETED:
3905 migration_calculate_complete(s);
3906 break;
3908 case MIGRATION_STATUS_ACTIVE:
3909 case MIGRATION_STATUS_FAILED:
3910 case MIGRATION_STATUS_CANCELLED:
3911 case MIGRATION_STATUS_CANCELLING:
3912 break;
3914 default:
3915 /* Should not reach here, but if so, forgive the VM. */
3916 error_report("%s: Unknown ending state %d", __func__, s->state);
3917 break;
3920 migrate_fd_cleanup_schedule(s);
3921 qemu_mutex_unlock_iothread();
3925 * Return true if continue to the next iteration directly, false
3926 * otherwise.
3928 static MigIterateState bg_migration_iteration_run(MigrationState *s)
3930 int res;
3932 res = qemu_savevm_state_iterate(s->to_dst_file, false);
3933 if (res > 0) {
3934 bg_migration_completion(s);
3935 return MIG_ITERATE_BREAK;
3938 return MIG_ITERATE_RESUME;
3941 void migration_make_urgent_request(void)
3943 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3946 void migration_consume_urgent_request(void)
3948 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3951 /* Returns true if the rate limiting was broken by an urgent request */
3952 bool migration_rate_limit(void)
3954 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3955 MigrationState *s = migrate_get_current();
3957 bool urgent = false;
3958 migration_update_counters(s, now);
3959 if (qemu_file_rate_limit(s->to_dst_file)) {
3961 if (qemu_file_get_error(s->to_dst_file)) {
3962 return false;
3965 * Wait for a delay to do rate limiting OR
3966 * something urgent to post the semaphore.
3968 int ms = s->iteration_start_time + BUFFER_DELAY - now;
3969 trace_migration_rate_limit_pre(ms);
3970 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3972 * We were woken by one or more urgent things but
3973 * the timedwait will have consumed one of them.
3974 * The service routine for the urgent wake will dec
3975 * the semaphore itself for each item it consumes,
3976 * so add this one we just eat back.
3978 qemu_sem_post(&s->rate_limit_sem);
3979 urgent = true;
3981 trace_migration_rate_limit_post(urgent);
3983 return urgent;
3987 * if failover devices are present, wait they are completely
3988 * unplugged
3991 static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3992 int new_state)
3994 if (qemu_savevm_state_guest_unplug_pending()) {
3995 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3997 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3998 qemu_savevm_state_guest_unplug_pending()) {
3999 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
4001 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
4002 int timeout = 120; /* 30 seconds */
4004 * migration has been canceled
4005 * but as we have started an unplug we must wait the end
4006 * to be able to plug back the card
4008 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
4009 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
4011 if (qemu_savevm_state_guest_unplug_pending() &&
4012 !qtest_enabled()) {
4013 warn_report("migration: partially unplugged device on "
4014 "failure");
4018 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
4019 } else {
4020 migrate_set_state(&s->state, old_state, new_state);
4025 * Master migration thread on the source VM.
4026 * It drives the migration and pumps the data down the outgoing channel.
4028 static void *migration_thread(void *opaque)
4030 MigrationState *s = opaque;
4031 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
4032 MigThrError thr_error;
4033 bool urgent = false;
4035 rcu_register_thread();
4037 object_ref(OBJECT(s));
4038 update_iteration_initial_status(s);
4040 qemu_savevm_state_header(s->to_dst_file);
4043 * If we opened the return path, we need to make sure dst has it
4044 * opened as well.
4046 if (s->rp_state.rp_thread_created) {
4047 /* Now tell the dest that it should open its end so it can reply */
4048 qemu_savevm_send_open_return_path(s->to_dst_file);
4050 /* And do a ping that will make stuff easier to debug */
4051 qemu_savevm_send_ping(s->to_dst_file, 1);
4054 if (migrate_postcopy()) {
4056 * Tell the destination that we *might* want to do postcopy later;
4057 * if the other end can't do postcopy it should fail now, nice and
4058 * early.
4060 qemu_savevm_send_postcopy_advise(s->to_dst_file);
4063 if (migrate_colo_enabled()) {
4064 /* Notify migration destination that we enable COLO */
4065 qemu_savevm_send_colo_enable(s->to_dst_file);
4068 qemu_savevm_state_setup(s->to_dst_file);
4070 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4071 MIGRATION_STATUS_ACTIVE);
4073 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
4075 trace_migration_thread_setup_complete();
4077 while (migration_is_active(s)) {
4078 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
4079 MigIterateState iter_state = migration_iteration_run(s);
4080 if (iter_state == MIG_ITERATE_SKIP) {
4081 continue;
4082 } else if (iter_state == MIG_ITERATE_BREAK) {
4083 break;
4088 * Try to detect any kind of failures, and see whether we
4089 * should stop the migration now.
4091 thr_error = migration_detect_error(s);
4092 if (thr_error == MIG_THR_ERR_FATAL) {
4093 /* Stop migration */
4094 break;
4095 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
4097 * Just recovered from a e.g. network failure, reset all
4098 * the local variables. This is important to avoid
4099 * breaking transferred_bytes and bandwidth calculation
4101 update_iteration_initial_status(s);
4104 urgent = migration_rate_limit();
4107 trace_migration_thread_after_loop();
4108 migration_iteration_finish(s);
4109 object_unref(OBJECT(s));
4110 rcu_unregister_thread();
4111 return NULL;
4114 static void bg_migration_vm_start_bh(void *opaque)
4116 MigrationState *s = opaque;
4118 qemu_bh_delete(s->vm_start_bh);
4119 s->vm_start_bh = NULL;
4121 vm_start();
4122 s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
4126 * Background snapshot thread, based on live migration code.
4127 * This is an alternative implementation of live migration mechanism
4128 * introduced specifically to support background snapshots.
4130 * It takes advantage of userfault_fd write protection mechanism introduced
4131 * in v5.7 kernel. Compared to existing dirty page logging migration much
4132 * lesser stream traffic is produced resulting in smaller snapshot images,
4133 * simply cause of no page duplicates can get into the stream.
4135 * Another key point is that generated vmstate stream reflects machine state
4136 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
4137 * mechanism, which effectively results in that saved snapshot is the state of VM
4138 * at the end of the process.
4140 static void *bg_migration_thread(void *opaque)
4142 MigrationState *s = opaque;
4143 int64_t setup_start;
4144 MigThrError thr_error;
4145 QEMUFile *fb;
4146 bool early_fail = true;
4148 rcu_register_thread();
4149 object_ref(OBJECT(s));
4151 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
4153 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
4155 * We want to save vmstate for the moment when migration has been
4156 * initiated but also we want to save RAM content while VM is running.
4157 * The RAM content should appear first in the vmstate. So, we first
4158 * stash the non-RAM part of the vmstate to the temporary buffer,
4159 * then write RAM part of the vmstate to the migration stream
4160 * with vCPUs running and, finally, write stashed non-RAM part of
4161 * the vmstate from the buffer to the migration stream.
4163 s->bioc = qio_channel_buffer_new(512 * 1024);
4164 qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
4165 fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
4166 object_unref(OBJECT(s->bioc));
4168 update_iteration_initial_status(s);
4171 * Prepare for tracking memory writes with UFFD-WP - populate
4172 * RAM pages before protecting.
4174 #ifdef __linux__
4175 ram_write_tracking_prepare();
4176 #endif
4178 qemu_savevm_state_header(s->to_dst_file);
4179 qemu_savevm_state_setup(s->to_dst_file);
4181 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4182 MIGRATION_STATUS_ACTIVE);
4184 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
4186 trace_migration_thread_setup_complete();
4187 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
4189 qemu_mutex_lock_iothread();
4192 * If VM is currently in suspended state, then, to make a valid runstate
4193 * transition in vm_stop_force_state() we need to wakeup it up.
4195 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
4196 s->vm_was_running = runstate_is_running();
4198 if (global_state_store()) {
4199 goto fail;
4201 /* Forcibly stop VM before saving state of vCPUs and devices */
4202 if (vm_stop_force_state(RUN_STATE_PAUSED)) {
4203 goto fail;
4206 * Put vCPUs in sync with shadow context structures, then
4207 * save their state to channel-buffer along with devices.
4209 cpu_synchronize_all_states();
4210 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
4211 goto fail;
4214 * Since we are going to get non-iterable state data directly
4215 * from s->bioc->data, explicit flush is needed here.
4217 qemu_fflush(fb);
4219 /* Now initialize UFFD context and start tracking RAM writes */
4220 if (ram_write_tracking_start()) {
4221 goto fail;
4223 early_fail = false;
4226 * Start VM from BH handler to avoid write-fault lock here.
4227 * UFFD-WP protection for the whole RAM is already enabled so
4228 * calling VM state change notifiers from vm_start() would initiate
4229 * writes to virtio VQs memory which is in write-protected region.
4231 s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
4232 qemu_bh_schedule(s->vm_start_bh);
4234 qemu_mutex_unlock_iothread();
4236 while (migration_is_active(s)) {
4237 MigIterateState iter_state = bg_migration_iteration_run(s);
4238 if (iter_state == MIG_ITERATE_SKIP) {
4239 continue;
4240 } else if (iter_state == MIG_ITERATE_BREAK) {
4241 break;
4245 * Try to detect any kind of failures, and see whether we
4246 * should stop the migration now.
4248 thr_error = migration_detect_error(s);
4249 if (thr_error == MIG_THR_ERR_FATAL) {
4250 /* Stop migration */
4251 break;
4254 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
4257 trace_migration_thread_after_loop();
4259 fail:
4260 if (early_fail) {
4261 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
4262 MIGRATION_STATUS_FAILED);
4263 qemu_mutex_unlock_iothread();
4266 bg_migration_iteration_finish(s);
4268 qemu_fclose(fb);
4269 object_unref(OBJECT(s));
4270 rcu_unregister_thread();
4272 return NULL;
4275 void migrate_fd_connect(MigrationState *s, Error *error_in)
4277 Error *local_err = NULL;
4278 int64_t rate_limit;
4279 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
4282 * If there's a previous error, free it and prepare for another one.
4283 * Meanwhile if migration completes successfully, there won't have an error
4284 * dumped when calling migrate_fd_cleanup().
4286 migrate_error_free(s);
4288 s->expected_downtime = s->parameters.downtime_limit;
4289 if (resume) {
4290 assert(s->cleanup_bh);
4291 } else {
4292 assert(!s->cleanup_bh);
4293 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
4295 if (error_in) {
4296 migrate_fd_error(s, error_in);
4297 if (resume) {
4299 * Don't do cleanup for resume if channel is invalid, but only dump
4300 * the error. We wait for another channel connect from the user.
4301 * The error_report still gives HMP user a hint on what failed.
4302 * It's normally done in migrate_fd_cleanup(), but call it here
4303 * explicitly.
4305 error_report_err(error_copy(s->error));
4306 } else {
4307 migrate_fd_cleanup(s);
4309 return;
4312 if (resume) {
4313 /* This is a resumed migration */
4314 rate_limit = s->parameters.max_postcopy_bandwidth /
4315 XFER_LIMIT_RATIO;
4316 } else {
4317 /* This is a fresh new migration */
4318 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
4320 /* Notify before starting migration thread */
4321 notifier_list_notify(&migration_state_notifiers, s);
4324 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
4325 qemu_file_set_blocking(s->to_dst_file, true);
4328 * Open the return path. For postcopy, it is used exclusively. For
4329 * precopy, only if user specified "return-path" capability would
4330 * QEMU uses the return path.
4332 if (migrate_postcopy_ram() || migrate_use_return_path()) {
4333 if (open_return_path_on_source(s, !resume)) {
4334 error_report("Unable to open return-path for postcopy");
4335 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
4336 migrate_fd_cleanup(s);
4337 return;
4341 /* This needs to be done before resuming a postcopy */
4342 if (postcopy_preempt_setup(s, &local_err)) {
4343 error_report_err(local_err);
4344 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4345 MIGRATION_STATUS_FAILED);
4346 migrate_fd_cleanup(s);
4347 return;
4350 if (resume) {
4351 /* Wakeup the main migration thread to do the recovery */
4352 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
4353 MIGRATION_STATUS_POSTCOPY_RECOVER);
4354 qemu_sem_post(&s->postcopy_pause_sem);
4355 return;
4358 if (multifd_save_setup(&local_err) != 0) {
4359 error_report_err(local_err);
4360 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4361 MIGRATION_STATUS_FAILED);
4362 migrate_fd_cleanup(s);
4363 return;
4366 if (migrate_background_snapshot()) {
4367 qemu_thread_create(&s->thread, "bg_snapshot",
4368 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
4369 } else {
4370 qemu_thread_create(&s->thread, "live_migration",
4371 migration_thread, s, QEMU_THREAD_JOINABLE);
4373 s->migration_thread_running = true;
4376 void migration_global_dump(Monitor *mon)
4378 MigrationState *ms = migrate_get_current();
4380 monitor_printf(mon, "globals:\n");
4381 monitor_printf(mon, "store-global-state: %s\n",
4382 ms->store_global_state ? "on" : "off");
4383 monitor_printf(mon, "only-migratable: %s\n",
4384 only_migratable ? "on" : "off");
4385 monitor_printf(mon, "send-configuration: %s\n",
4386 ms->send_configuration ? "on" : "off");
4387 monitor_printf(mon, "send-section-footer: %s\n",
4388 ms->send_section_footer ? "on" : "off");
4389 monitor_printf(mon, "decompress-error-check: %s\n",
4390 ms->decompress_error_check ? "on" : "off");
4391 monitor_printf(mon, "clear-bitmap-shift: %u\n",
4392 ms->clear_bitmap_shift);
4395 #define DEFINE_PROP_MIG_CAP(name, x) \
4396 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
4398 static Property migration_properties[] = {
4399 DEFINE_PROP_BOOL("store-global-state", MigrationState,
4400 store_global_state, true),
4401 DEFINE_PROP_BOOL("send-configuration", MigrationState,
4402 send_configuration, true),
4403 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
4404 send_section_footer, true),
4405 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
4406 decompress_error_check, true),
4407 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
4408 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
4410 /* Migration parameters */
4411 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
4412 parameters.compress_level,
4413 DEFAULT_MIGRATE_COMPRESS_LEVEL),
4414 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
4415 parameters.compress_threads,
4416 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
4417 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
4418 parameters.compress_wait_thread, true),
4419 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
4420 parameters.decompress_threads,
4421 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
4422 DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
4423 parameters.throttle_trigger_threshold,
4424 DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
4425 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
4426 parameters.cpu_throttle_initial,
4427 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
4428 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
4429 parameters.cpu_throttle_increment,
4430 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
4431 DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState,
4432 parameters.cpu_throttle_tailslow, false),
4433 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
4434 parameters.max_bandwidth, MAX_THROTTLE),
4435 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
4436 parameters.downtime_limit,
4437 DEFAULT_MIGRATE_SET_DOWNTIME),
4438 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
4439 parameters.x_checkpoint_delay,
4440 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
4441 DEFINE_PROP_UINT8("multifd-channels", MigrationState,
4442 parameters.multifd_channels,
4443 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
4444 DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
4445 parameters.multifd_compression,
4446 DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
4447 DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
4448 parameters.multifd_zlib_level,
4449 DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
4450 DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
4451 parameters.multifd_zstd_level,
4452 DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
4453 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
4454 parameters.xbzrle_cache_size,
4455 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
4456 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
4457 parameters.max_postcopy_bandwidth,
4458 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
4459 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
4460 parameters.max_cpu_throttle,
4461 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
4462 DEFINE_PROP_SIZE("announce-initial", MigrationState,
4463 parameters.announce_initial,
4464 DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
4465 DEFINE_PROP_SIZE("announce-max", MigrationState,
4466 parameters.announce_max,
4467 DEFAULT_MIGRATE_ANNOUNCE_MAX),
4468 DEFINE_PROP_SIZE("announce-rounds", MigrationState,
4469 parameters.announce_rounds,
4470 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
4471 DEFINE_PROP_SIZE("announce-step", MigrationState,
4472 parameters.announce_step,
4473 DEFAULT_MIGRATE_ANNOUNCE_STEP),
4474 DEFINE_PROP_STRING("tls-creds", MigrationState, parameters.tls_creds),
4475 DEFINE_PROP_STRING("tls-hostname", MigrationState, parameters.tls_hostname),
4476 DEFINE_PROP_STRING("tls-authz", MigrationState, parameters.tls_authz),
4478 /* Migration capabilities */
4479 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
4480 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
4481 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
4482 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
4483 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
4484 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
4485 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
4486 DEFINE_PROP_MIG_CAP("x-postcopy-preempt",
4487 MIGRATION_CAPABILITY_POSTCOPY_PREEMPT),
4488 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
4489 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
4490 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
4491 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
4492 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
4493 DEFINE_PROP_MIG_CAP("x-background-snapshot",
4494 MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT),
4495 #ifdef CONFIG_LINUX
4496 DEFINE_PROP_MIG_CAP("x-zero-copy-send",
4497 MIGRATION_CAPABILITY_ZERO_COPY_SEND),
4498 #endif
4500 DEFINE_PROP_END_OF_LIST(),
4503 static void migration_class_init(ObjectClass *klass, void *data)
4505 DeviceClass *dc = DEVICE_CLASS(klass);
4507 dc->user_creatable = false;
4508 device_class_set_props(dc, migration_properties);
4511 static void migration_instance_finalize(Object *obj)
4513 MigrationState *ms = MIGRATION_OBJ(obj);
4515 qemu_mutex_destroy(&ms->error_mutex);
4516 qemu_mutex_destroy(&ms->qemu_file_lock);
4517 qemu_sem_destroy(&ms->wait_unplug_sem);
4518 qemu_sem_destroy(&ms->rate_limit_sem);
4519 qemu_sem_destroy(&ms->pause_sem);
4520 qemu_sem_destroy(&ms->postcopy_pause_sem);
4521 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
4522 qemu_sem_destroy(&ms->rp_state.rp_sem);
4523 qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
4524 error_free(ms->error);
4527 static void migration_instance_init(Object *obj)
4529 MigrationState *ms = MIGRATION_OBJ(obj);
4530 MigrationParameters *params = &ms->parameters;
4532 ms->state = MIGRATION_STATUS_NONE;
4533 ms->mbps = -1;
4534 ms->pages_per_second = -1;
4535 qemu_sem_init(&ms->pause_sem, 0);
4536 qemu_mutex_init(&ms->error_mutex);
4538 params->tls_hostname = g_strdup("");
4539 params->tls_creds = g_strdup("");
4541 /* Set has_* up only for parameter checks */
4542 params->has_compress_level = true;
4543 params->has_compress_threads = true;
4544 params->has_compress_wait_thread = true;
4545 params->has_decompress_threads = true;
4546 params->has_throttle_trigger_threshold = true;
4547 params->has_cpu_throttle_initial = true;
4548 params->has_cpu_throttle_increment = true;
4549 params->has_cpu_throttle_tailslow = true;
4550 params->has_max_bandwidth = true;
4551 params->has_downtime_limit = true;
4552 params->has_x_checkpoint_delay = true;
4553 params->has_block_incremental = true;
4554 params->has_multifd_channels = true;
4555 params->has_multifd_compression = true;
4556 params->has_multifd_zlib_level = true;
4557 params->has_multifd_zstd_level = true;
4558 params->has_xbzrle_cache_size = true;
4559 params->has_max_postcopy_bandwidth = true;
4560 params->has_max_cpu_throttle = true;
4561 params->has_announce_initial = true;
4562 params->has_announce_max = true;
4563 params->has_announce_rounds = true;
4564 params->has_announce_step = true;
4566 qemu_sem_init(&ms->postcopy_pause_sem, 0);
4567 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
4568 qemu_sem_init(&ms->rp_state.rp_sem, 0);
4569 qemu_sem_init(&ms->rate_limit_sem, 0);
4570 qemu_sem_init(&ms->wait_unplug_sem, 0);
4571 qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
4572 qemu_mutex_init(&ms->qemu_file_lock);
4576 * Return true if check pass, false otherwise. Error will be put
4577 * inside errp if provided.
4579 static bool migration_object_check(MigrationState *ms, Error **errp)
4581 MigrationCapabilityStatusList *head = NULL;
4582 /* Assuming all off */
4583 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
4584 int i;
4586 if (!migrate_params_check(&ms->parameters, errp)) {
4587 return false;
4590 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
4591 if (ms->enabled_capabilities[i]) {
4592 QAPI_LIST_PREPEND(head, migrate_cap_add(i, true));
4596 ret = migrate_caps_check(cap_list, head, errp);
4598 /* It works with head == NULL */
4599 qapi_free_MigrationCapabilityStatusList(head);
4601 return ret;
4604 static const TypeInfo migration_type = {
4605 .name = TYPE_MIGRATION,
4607 * NOTE: TYPE_MIGRATION is not really a device, as the object is
4608 * not created using qdev_new(), it is not attached to the qdev
4609 * device tree, and it is never realized.
4611 * TODO: Make this TYPE_OBJECT once QOM provides something like
4612 * TYPE_DEVICE's "-global" properties.
4614 .parent = TYPE_DEVICE,
4615 .class_init = migration_class_init,
4616 .class_size = sizeof(MigrationClass),
4617 .instance_size = sizeof(MigrationState),
4618 .instance_init = migration_instance_init,
4619 .instance_finalize = migration_instance_finalize,
4622 static void register_migration_types(void)
4624 type_register_static(&migration_type);
4627 type_init(register_migration_types);