gitlab-ci: Add cross-compiling build tests
[qemu/ar7.git] / migration / migration.c
blob58a5452471f9067b227f4e5f9050ba5464d83af8
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-channel.h"
34 #include "qemu-file.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 "migration/colo.h"
53 #include "hw/boards.h"
54 #include "hw/qdev-properties.h"
55 #include "monitor/monitor.h"
56 #include "net/announce.h"
57 #include "qemu/queue.h"
58 #include "multifd.h"
60 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
62 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
63 * data. */
64 #define BUFFER_DELAY 100
65 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
67 /* Time in milliseconds we are allowed to stop the source,
68 * for sending the last part */
69 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
71 /* Maximum migrate downtime set to 2000 seconds */
72 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
73 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
75 /* Default compression thread count */
76 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
77 /* Default decompression thread count, usually decompression is at
78 * least 4 times as fast as compression.*/
79 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
80 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
81 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
82 /* Define default autoconverge cpu throttle migration parameters */
83 #define DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD 50
84 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
85 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
86 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
88 /* Migration XBZRLE default cache size */
89 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
91 /* The delay time (in ms) between two COLO checkpoints */
92 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
93 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
94 #define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE
95 /* 0: means nocompress, 1: best speed, ... 9: best compress ratio */
96 #define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1
97 /* 0: means nocompress, 1: best speed, ... 20: best compress ratio */
98 #define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1
100 /* Background transfer rate for postcopy, 0 means unlimited, note
101 * that page requests can still exceed this limit.
103 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
106 * Parameters for self_announce_delay giving a stream of RARP/ARP
107 * packets after migration.
109 #define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50
110 #define DEFAULT_MIGRATE_ANNOUNCE_MAX 550
111 #define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5
112 #define DEFAULT_MIGRATE_ANNOUNCE_STEP 100
114 static NotifierList migration_state_notifiers =
115 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
117 static bool deferred_incoming;
119 /* Messages sent on the return path from destination to source */
120 enum mig_rp_message_type {
121 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
122 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
123 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
125 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
126 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
127 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
128 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
130 MIG_RP_MSG_MAX
133 /* When we add fault tolerance, we could have several
134 migrations at once. For now we don't need to add
135 dynamic creation of migration */
137 static MigrationState *current_migration;
138 static MigrationIncomingState *current_incoming;
140 static bool migration_object_check(MigrationState *ms, Error **errp);
141 static int migration_maybe_pause(MigrationState *s,
142 int *current_active_state,
143 int new_state);
144 static void migrate_fd_cancel(MigrationState *s);
146 void migration_object_init(void)
148 MachineState *ms = MACHINE(qdev_get_machine());
149 Error *err = NULL;
151 /* This can only be called once. */
152 assert(!current_migration);
153 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
156 * Init the migrate incoming object as well no matter whether
157 * we'll use it or not.
159 assert(!current_incoming);
160 current_incoming = g_new0(MigrationIncomingState, 1);
161 current_incoming->state = MIGRATION_STATUS_NONE;
162 current_incoming->postcopy_remote_fds =
163 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
164 qemu_mutex_init(&current_incoming->rp_mutex);
165 qemu_event_init(&current_incoming->main_thread_load_event, false);
166 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
167 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
169 if (!migration_object_check(current_migration, &err)) {
170 error_report_err(err);
171 exit(1);
175 * We cannot really do this in migration_instance_init() since at
176 * that time global properties are not yet applied, then this
177 * value will be definitely replaced by something else.
179 if (ms->enforce_config_section) {
180 current_migration->send_configuration = true;
184 void migration_shutdown(void)
187 * Cancel the current migration - that will (eventually)
188 * stop the migration using this structure
190 migrate_fd_cancel(current_migration);
191 object_unref(OBJECT(current_migration));
194 * Cancel outgoing migration of dirty bitmaps. It should
195 * at least unref used block nodes.
197 dirty_bitmap_mig_cancel_outgoing();
200 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
201 * are non-critical data, and their loss never considered as
202 * something serious.
204 dirty_bitmap_mig_cancel_incoming();
207 /* For outgoing */
208 MigrationState *migrate_get_current(void)
210 /* This can only be called after the object created. */
211 assert(current_migration);
212 return current_migration;
215 MigrationIncomingState *migration_incoming_get_current(void)
217 assert(current_incoming);
218 return current_incoming;
221 void migration_incoming_state_destroy(void)
223 struct MigrationIncomingState *mis = migration_incoming_get_current();
225 if (mis->to_src_file) {
226 /* Tell source that we are done */
227 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
228 qemu_fclose(mis->to_src_file);
229 mis->to_src_file = NULL;
232 if (mis->from_src_file) {
233 qemu_fclose(mis->from_src_file);
234 mis->from_src_file = NULL;
236 if (mis->postcopy_remote_fds) {
237 g_array_free(mis->postcopy_remote_fds, TRUE);
238 mis->postcopy_remote_fds = NULL;
241 qemu_event_reset(&mis->main_thread_load_event);
243 if (mis->socket_address_list) {
244 qapi_free_SocketAddressList(mis->socket_address_list);
245 mis->socket_address_list = NULL;
249 static void migrate_generate_event(int new_state)
251 if (migrate_use_events()) {
252 qapi_event_send_migration(new_state);
256 static bool migrate_late_block_activate(void)
258 MigrationState *s;
260 s = migrate_get_current();
262 return s->enabled_capabilities[
263 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
267 * Called on -incoming with a defer: uri.
268 * The migration can be started later after any parameters have been
269 * changed.
271 static void deferred_incoming_migration(Error **errp)
273 if (deferred_incoming) {
274 error_setg(errp, "Incoming migration already deferred");
276 deferred_incoming = true;
280 * Send a message on the return channel back to the source
281 * of the migration.
283 static int migrate_send_rp_message(MigrationIncomingState *mis,
284 enum mig_rp_message_type message_type,
285 uint16_t len, void *data)
287 int ret = 0;
289 trace_migrate_send_rp_message((int)message_type, len);
290 qemu_mutex_lock(&mis->rp_mutex);
293 * It's possible that the file handle got lost due to network
294 * failures.
296 if (!mis->to_src_file) {
297 ret = -EIO;
298 goto error;
301 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
302 qemu_put_be16(mis->to_src_file, len);
303 qemu_put_buffer(mis->to_src_file, data, len);
304 qemu_fflush(mis->to_src_file);
306 /* It's possible that qemu file got error during sending */
307 ret = qemu_file_get_error(mis->to_src_file);
309 error:
310 qemu_mutex_unlock(&mis->rp_mutex);
311 return ret;
314 /* Request a range of pages from the source VM at the given
315 * start address.
316 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
317 * as the last request (a name must have been given previously)
318 * Start: Address offset within the RB
319 * Len: Length in bytes required - must be a multiple of pagesize
321 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
322 ram_addr_t start, size_t len)
324 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
325 size_t msglen = 12; /* start + len */
326 enum mig_rp_message_type msg_type;
328 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
329 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
331 if (rbname) {
332 int rbname_len = strlen(rbname);
333 assert(rbname_len < 256);
335 bufc[msglen++] = rbname_len;
336 memcpy(bufc + msglen, rbname, rbname_len);
337 msglen += rbname_len;
338 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
339 } else {
340 msg_type = MIG_RP_MSG_REQ_PAGES;
343 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
346 static bool migration_colo_enabled;
347 bool migration_incoming_colo_enabled(void)
349 return migration_colo_enabled;
352 void migration_incoming_disable_colo(void)
354 ram_block_discard_disable(false);
355 migration_colo_enabled = false;
358 int migration_incoming_enable_colo(void)
360 if (ram_block_discard_disable(true)) {
361 error_report("COLO: cannot disable RAM discard");
362 return -EBUSY;
364 migration_colo_enabled = true;
365 return 0;
368 void migrate_add_address(SocketAddress *address)
370 MigrationIncomingState *mis = migration_incoming_get_current();
371 SocketAddressList *addrs;
373 addrs = g_new0(SocketAddressList, 1);
374 addrs->next = mis->socket_address_list;
375 mis->socket_address_list = addrs;
376 addrs->value = QAPI_CLONE(SocketAddress, address);
379 void qemu_start_incoming_migration(const char *uri, Error **errp)
381 const char *p = NULL;
383 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
384 if (!strcmp(uri, "defer")) {
385 deferred_incoming_migration(errp);
386 } else if (strstart(uri, "tcp:", &p) ||
387 strstart(uri, "unix:", NULL) ||
388 strstart(uri, "vsock:", NULL)) {
389 socket_start_incoming_migration(p ? p : uri, errp);
390 #ifdef CONFIG_RDMA
391 } else if (strstart(uri, "rdma:", &p)) {
392 rdma_start_incoming_migration(p, errp);
393 #endif
394 } else if (strstart(uri, "exec:", &p)) {
395 exec_start_incoming_migration(p, errp);
396 } else if (strstart(uri, "fd:", &p)) {
397 fd_start_incoming_migration(p, errp);
398 } else {
399 error_setg(errp, "unknown migration protocol: %s", uri);
403 static void process_incoming_migration_bh(void *opaque)
405 Error *local_err = NULL;
406 MigrationIncomingState *mis = opaque;
408 /* If capability late_block_activate is set:
409 * Only fire up the block code now if we're going to restart the
410 * VM, else 'cont' will do it.
411 * This causes file locking to happen; so we don't want it to happen
412 * unless we really are starting the VM.
414 if (!migrate_late_block_activate() ||
415 (autostart && (!global_state_received() ||
416 global_state_get_runstate() == RUN_STATE_RUNNING))) {
417 /* Make sure all file formats flush their mutable metadata.
418 * If we get an error here, just don't restart the VM yet. */
419 bdrv_invalidate_cache_all(&local_err);
420 if (local_err) {
421 error_report_err(local_err);
422 local_err = NULL;
423 autostart = false;
428 * This must happen after all error conditions are dealt with and
429 * we're sure the VM is going to be running on this host.
431 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
433 if (multifd_load_cleanup(&local_err) != 0) {
434 error_report_err(local_err);
435 autostart = false;
437 /* If global state section was not received or we are in running
438 state, we need to obey autostart. Any other state is set with
439 runstate_set. */
441 dirty_bitmap_mig_before_vm_start();
443 if (!global_state_received() ||
444 global_state_get_runstate() == RUN_STATE_RUNNING) {
445 if (autostart) {
446 vm_start();
447 } else {
448 runstate_set(RUN_STATE_PAUSED);
450 } else if (migration_incoming_colo_enabled()) {
451 migration_incoming_disable_colo();
452 vm_start();
453 } else {
454 runstate_set(global_state_get_runstate());
457 * This must happen after any state changes since as soon as an external
458 * observer sees this event they might start to prod at the VM assuming
459 * it's ready to use.
461 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
462 MIGRATION_STATUS_COMPLETED);
463 qemu_bh_delete(mis->bh);
464 migration_incoming_state_destroy();
467 static void process_incoming_migration_co(void *opaque)
469 MigrationIncomingState *mis = migration_incoming_get_current();
470 PostcopyState ps;
471 int ret;
472 Error *local_err = NULL;
474 assert(mis->from_src_file);
475 mis->migration_incoming_co = qemu_coroutine_self();
476 mis->largest_page_size = qemu_ram_pagesize_largest();
477 postcopy_state_set(POSTCOPY_INCOMING_NONE);
478 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
479 MIGRATION_STATUS_ACTIVE);
480 ret = qemu_loadvm_state(mis->from_src_file);
482 ps = postcopy_state_get();
483 trace_process_incoming_migration_co_end(ret, ps);
484 if (ps != POSTCOPY_INCOMING_NONE) {
485 if (ps == POSTCOPY_INCOMING_ADVISE) {
487 * Where a migration had postcopy enabled (and thus went to advise)
488 * but managed to complete within the precopy period, we can use
489 * the normal exit.
491 postcopy_ram_incoming_cleanup(mis);
492 } else if (ret >= 0) {
494 * Postcopy was started, cleanup should happen at the end of the
495 * postcopy thread.
497 trace_process_incoming_migration_co_postcopy_end_main();
498 return;
500 /* Else if something went wrong then just fall out of the normal exit */
503 /* we get COLO info, and know if we are in COLO mode */
504 if (!ret && migration_incoming_colo_enabled()) {
505 /* Make sure all file formats flush their mutable metadata */
506 bdrv_invalidate_cache_all(&local_err);
507 if (local_err) {
508 error_report_err(local_err);
509 goto fail;
512 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
513 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
514 mis->have_colo_incoming_thread = true;
515 qemu_coroutine_yield();
517 /* Wait checkpoint incoming thread exit before free resource */
518 qemu_thread_join(&mis->colo_incoming_thread);
519 /* We hold the global iothread lock, so it is safe here */
520 colo_release_ram_cache();
523 if (ret < 0) {
524 error_report("load of migration failed: %s", strerror(-ret));
525 goto fail;
527 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
528 qemu_bh_schedule(mis->bh);
529 mis->migration_incoming_co = NULL;
530 return;
531 fail:
532 local_err = NULL;
533 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
534 MIGRATION_STATUS_FAILED);
535 qemu_fclose(mis->from_src_file);
536 if (multifd_load_cleanup(&local_err) != 0) {
537 error_report_err(local_err);
539 exit(EXIT_FAILURE);
543 * @migration_incoming_setup: Setup incoming migration
545 * Returns 0 for no error or 1 for error
547 * @f: file for main migration channel
548 * @errp: where to put errors
550 static int migration_incoming_setup(QEMUFile *f, Error **errp)
552 MigrationIncomingState *mis = migration_incoming_get_current();
553 Error *local_err = NULL;
555 if (multifd_load_setup(&local_err) != 0) {
556 /* We haven't been able to create multifd threads
557 nothing better to do */
558 error_report_err(local_err);
559 exit(EXIT_FAILURE);
562 if (!mis->from_src_file) {
563 mis->from_src_file = f;
565 qemu_file_set_blocking(f, false);
566 return 0;
569 void migration_incoming_process(void)
571 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
572 qemu_coroutine_enter(co);
575 /* Returns true if recovered from a paused migration, otherwise false */
576 static bool postcopy_try_recover(QEMUFile *f)
578 MigrationIncomingState *mis = migration_incoming_get_current();
580 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
581 /* Resumed from a paused postcopy migration */
583 mis->from_src_file = f;
584 /* Postcopy has standalone thread to do vm load */
585 qemu_file_set_blocking(f, true);
587 /* Re-configure the return path */
588 mis->to_src_file = qemu_file_get_return_path(f);
590 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
591 MIGRATION_STATUS_POSTCOPY_RECOVER);
594 * Here, we only wake up the main loading thread (while the
595 * fault thread will still be waiting), so that we can receive
596 * commands from source now, and answer it if needed. The
597 * fault thread will be woken up afterwards until we are sure
598 * that source is ready to reply to page requests.
600 qemu_sem_post(&mis->postcopy_pause_sem_dst);
601 return true;
604 return false;
607 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
609 Error *local_err = NULL;
611 if (postcopy_try_recover(f)) {
612 return;
615 if (migration_incoming_setup(f, &local_err)) {
616 if (local_err) {
617 error_propagate(errp, local_err);
619 return;
621 migration_incoming_process();
624 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
626 MigrationIncomingState *mis = migration_incoming_get_current();
627 Error *local_err = NULL;
628 bool start_migration;
630 if (!mis->from_src_file) {
631 /* The first connection (multifd may have multiple) */
632 QEMUFile *f = qemu_fopen_channel_input(ioc);
634 /* If it's a recovery, we're done */
635 if (postcopy_try_recover(f)) {
636 return;
639 if (migration_incoming_setup(f, &local_err)) {
640 if (local_err) {
641 error_propagate(errp, local_err);
643 return;
647 * Common migration only needs one channel, so we can start
648 * right now. Multifd needs more than one channel, we wait.
650 start_migration = !migrate_use_multifd();
651 } else {
652 /* Multiple connections */
653 assert(migrate_use_multifd());
654 start_migration = multifd_recv_new_channel(ioc, &local_err);
655 if (local_err) {
656 error_propagate(errp, local_err);
657 return;
661 if (start_migration) {
662 migration_incoming_process();
667 * @migration_has_all_channels: We have received all channels that we need
669 * Returns true when we have got connections to all the channels that
670 * we need for migration.
672 bool migration_has_all_channels(void)
674 MigrationIncomingState *mis = migration_incoming_get_current();
675 bool all_channels;
677 all_channels = multifd_recv_all_channels_created();
679 return all_channels && mis->from_src_file != NULL;
683 * Send a 'SHUT' message on the return channel with the given value
684 * to indicate that we've finished with the RP. Non-0 value indicates
685 * error.
687 void migrate_send_rp_shut(MigrationIncomingState *mis,
688 uint32_t value)
690 uint32_t buf;
692 buf = cpu_to_be32(value);
693 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
697 * Send a 'PONG' message on the return channel with the given value
698 * (normally in response to a 'PING')
700 void migrate_send_rp_pong(MigrationIncomingState *mis,
701 uint32_t value)
703 uint32_t buf;
705 buf = cpu_to_be32(value);
706 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
709 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
710 char *block_name)
712 char buf[512];
713 int len;
714 int64_t res;
717 * First, we send the header part. It contains only the len of
718 * idstr, and the idstr itself.
720 len = strlen(block_name);
721 buf[0] = len;
722 memcpy(buf + 1, block_name, len);
724 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
725 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
726 __func__);
727 return;
730 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
733 * Next, we dump the received bitmap to the stream.
735 * TODO: currently we are safe since we are the only one that is
736 * using the to_src_file handle (fault thread is still paused),
737 * and it's ok even not taking the mutex. However the best way is
738 * to take the lock before sending the message header, and release
739 * the lock after sending the bitmap.
741 qemu_mutex_lock(&mis->rp_mutex);
742 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
743 qemu_mutex_unlock(&mis->rp_mutex);
745 trace_migrate_send_rp_recv_bitmap(block_name, res);
748 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
750 uint32_t buf;
752 buf = cpu_to_be32(value);
753 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
756 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
758 MigrationCapabilityStatusList *head = NULL;
759 MigrationCapabilityStatusList *caps;
760 MigrationState *s = migrate_get_current();
761 int i;
763 caps = NULL; /* silence compiler warning */
764 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
765 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
766 if (i == MIGRATION_CAPABILITY_BLOCK) {
767 continue;
769 #endif
770 if (head == NULL) {
771 head = g_malloc0(sizeof(*caps));
772 caps = head;
773 } else {
774 caps->next = g_malloc0(sizeof(*caps));
775 caps = caps->next;
777 caps->value =
778 g_malloc(sizeof(*caps->value));
779 caps->value->capability = i;
780 caps->value->state = s->enabled_capabilities[i];
783 return head;
786 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
788 MigrationParameters *params;
789 MigrationState *s = migrate_get_current();
791 /* TODO use QAPI_CLONE() instead of duplicating it inline */
792 params = g_malloc0(sizeof(*params));
793 params->has_compress_level = true;
794 params->compress_level = s->parameters.compress_level;
795 params->has_compress_threads = true;
796 params->compress_threads = s->parameters.compress_threads;
797 params->has_compress_wait_thread = true;
798 params->compress_wait_thread = s->parameters.compress_wait_thread;
799 params->has_decompress_threads = true;
800 params->decompress_threads = s->parameters.decompress_threads;
801 params->has_throttle_trigger_threshold = true;
802 params->throttle_trigger_threshold = s->parameters.throttle_trigger_threshold;
803 params->has_cpu_throttle_initial = true;
804 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
805 params->has_cpu_throttle_increment = true;
806 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
807 params->has_cpu_throttle_tailslow = true;
808 params->cpu_throttle_tailslow = s->parameters.cpu_throttle_tailslow;
809 params->has_tls_creds = true;
810 params->tls_creds = g_strdup(s->parameters.tls_creds);
811 params->has_tls_hostname = true;
812 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
813 params->has_tls_authz = true;
814 params->tls_authz = g_strdup(s->parameters.tls_authz ?
815 s->parameters.tls_authz : "");
816 params->has_max_bandwidth = true;
817 params->max_bandwidth = s->parameters.max_bandwidth;
818 params->has_downtime_limit = true;
819 params->downtime_limit = s->parameters.downtime_limit;
820 params->has_x_checkpoint_delay = true;
821 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
822 params->has_block_incremental = true;
823 params->block_incremental = s->parameters.block_incremental;
824 params->has_multifd_channels = true;
825 params->multifd_channels = s->parameters.multifd_channels;
826 params->has_multifd_compression = true;
827 params->multifd_compression = s->parameters.multifd_compression;
828 params->has_multifd_zlib_level = true;
829 params->multifd_zlib_level = s->parameters.multifd_zlib_level;
830 params->has_multifd_zstd_level = true;
831 params->multifd_zstd_level = s->parameters.multifd_zstd_level;
832 params->has_xbzrle_cache_size = true;
833 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
834 params->has_max_postcopy_bandwidth = true;
835 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
836 params->has_max_cpu_throttle = true;
837 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
838 params->has_announce_initial = true;
839 params->announce_initial = s->parameters.announce_initial;
840 params->has_announce_max = true;
841 params->announce_max = s->parameters.announce_max;
842 params->has_announce_rounds = true;
843 params->announce_rounds = s->parameters.announce_rounds;
844 params->has_announce_step = true;
845 params->announce_step = s->parameters.announce_step;
847 if (s->parameters.has_block_bitmap_mapping) {
848 params->has_block_bitmap_mapping = true;
849 params->block_bitmap_mapping =
850 QAPI_CLONE(BitmapMigrationNodeAliasList,
851 s->parameters.block_bitmap_mapping);
854 return params;
857 AnnounceParameters *migrate_announce_params(void)
859 static AnnounceParameters ap;
861 MigrationState *s = migrate_get_current();
863 ap.initial = s->parameters.announce_initial;
864 ap.max = s->parameters.announce_max;
865 ap.rounds = s->parameters.announce_rounds;
866 ap.step = s->parameters.announce_step;
868 return &ap;
872 * Return true if we're already in the middle of a migration
873 * (i.e. any of the active or setup states)
875 bool migration_is_setup_or_active(int state)
877 switch (state) {
878 case MIGRATION_STATUS_ACTIVE:
879 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
880 case MIGRATION_STATUS_POSTCOPY_PAUSED:
881 case MIGRATION_STATUS_POSTCOPY_RECOVER:
882 case MIGRATION_STATUS_SETUP:
883 case MIGRATION_STATUS_PRE_SWITCHOVER:
884 case MIGRATION_STATUS_DEVICE:
885 case MIGRATION_STATUS_WAIT_UNPLUG:
886 case MIGRATION_STATUS_COLO:
887 return true;
889 default:
890 return false;
895 bool migration_is_running(int state)
897 switch (state) {
898 case MIGRATION_STATUS_ACTIVE:
899 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
900 case MIGRATION_STATUS_POSTCOPY_PAUSED:
901 case MIGRATION_STATUS_POSTCOPY_RECOVER:
902 case MIGRATION_STATUS_SETUP:
903 case MIGRATION_STATUS_PRE_SWITCHOVER:
904 case MIGRATION_STATUS_DEVICE:
905 case MIGRATION_STATUS_WAIT_UNPLUG:
906 case MIGRATION_STATUS_CANCELLING:
907 return true;
909 default:
910 return false;
915 static void populate_time_info(MigrationInfo *info, MigrationState *s)
917 info->has_status = true;
918 info->has_setup_time = true;
919 info->setup_time = s->setup_time;
920 if (s->state == MIGRATION_STATUS_COMPLETED) {
921 info->has_total_time = true;
922 info->total_time = s->total_time;
923 info->has_downtime = true;
924 info->downtime = s->downtime;
925 } else {
926 info->has_total_time = true;
927 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
928 s->start_time;
929 info->has_expected_downtime = true;
930 info->expected_downtime = s->expected_downtime;
934 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
936 info->has_ram = true;
937 info->ram = g_malloc0(sizeof(*info->ram));
938 info->ram->transferred = ram_counters.transferred;
939 info->ram->total = ram_bytes_total();
940 info->ram->duplicate = ram_counters.duplicate;
941 /* legacy value. It is not used anymore */
942 info->ram->skipped = 0;
943 info->ram->normal = ram_counters.normal;
944 info->ram->normal_bytes = ram_counters.normal *
945 qemu_target_page_size();
946 info->ram->mbps = s->mbps;
947 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
948 info->ram->postcopy_requests = ram_counters.postcopy_requests;
949 info->ram->page_size = qemu_target_page_size();
950 info->ram->multifd_bytes = ram_counters.multifd_bytes;
951 info->ram->pages_per_second = s->pages_per_second;
953 if (migrate_use_xbzrle()) {
954 info->has_xbzrle_cache = true;
955 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
956 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
957 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
958 info->xbzrle_cache->pages = xbzrle_counters.pages;
959 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
960 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
961 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
962 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
965 if (migrate_use_compression()) {
966 info->has_compression = true;
967 info->compression = g_malloc0(sizeof(*info->compression));
968 info->compression->pages = compression_counters.pages;
969 info->compression->busy = compression_counters.busy;
970 info->compression->busy_rate = compression_counters.busy_rate;
971 info->compression->compressed_size =
972 compression_counters.compressed_size;
973 info->compression->compression_rate =
974 compression_counters.compression_rate;
977 if (cpu_throttle_active()) {
978 info->has_cpu_throttle_percentage = true;
979 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
982 if (s->state != MIGRATION_STATUS_COMPLETED) {
983 info->ram->remaining = ram_bytes_remaining();
984 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
988 static void populate_disk_info(MigrationInfo *info)
990 if (blk_mig_active()) {
991 info->has_disk = true;
992 info->disk = g_malloc0(sizeof(*info->disk));
993 info->disk->transferred = blk_mig_bytes_transferred();
994 info->disk->remaining = blk_mig_bytes_remaining();
995 info->disk->total = blk_mig_bytes_total();
999 static void fill_source_migration_info(MigrationInfo *info)
1001 MigrationState *s = migrate_get_current();
1003 switch (s->state) {
1004 case MIGRATION_STATUS_NONE:
1005 /* no migration has happened ever */
1006 /* do not overwrite destination migration status */
1007 return;
1008 case MIGRATION_STATUS_SETUP:
1009 info->has_status = true;
1010 info->has_total_time = false;
1011 break;
1012 case MIGRATION_STATUS_ACTIVE:
1013 case MIGRATION_STATUS_CANCELLING:
1014 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1015 case MIGRATION_STATUS_PRE_SWITCHOVER:
1016 case MIGRATION_STATUS_DEVICE:
1017 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1018 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1019 /* TODO add some postcopy stats */
1020 populate_time_info(info, s);
1021 populate_ram_info(info, s);
1022 populate_disk_info(info);
1023 break;
1024 case MIGRATION_STATUS_COLO:
1025 info->has_status = true;
1026 /* TODO: display COLO specific information (checkpoint info etc.) */
1027 break;
1028 case MIGRATION_STATUS_COMPLETED:
1029 populate_time_info(info, s);
1030 populate_ram_info(info, s);
1031 break;
1032 case MIGRATION_STATUS_FAILED:
1033 info->has_status = true;
1034 if (s->error) {
1035 info->has_error_desc = true;
1036 info->error_desc = g_strdup(error_get_pretty(s->error));
1038 break;
1039 case MIGRATION_STATUS_CANCELLED:
1040 info->has_status = true;
1041 break;
1042 case MIGRATION_STATUS_WAIT_UNPLUG:
1043 info->has_status = true;
1044 break;
1046 info->status = s->state;
1050 * @migration_caps_check - check capability validity
1052 * @cap_list: old capability list, array of bool
1053 * @params: new capabilities to be applied soon
1054 * @errp: set *errp if the check failed, with reason
1056 * Returns true if check passed, otherwise false.
1058 static bool migrate_caps_check(bool *cap_list,
1059 MigrationCapabilityStatusList *params,
1060 Error **errp)
1062 MigrationCapabilityStatusList *cap;
1063 bool old_postcopy_cap;
1064 MigrationIncomingState *mis = migration_incoming_get_current();
1066 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1068 for (cap = params; cap; cap = cap->next) {
1069 cap_list[cap->value->capability] = cap->value->state;
1072 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
1073 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
1074 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
1075 "block migration");
1076 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
1077 return false;
1079 #endif
1081 #ifndef CONFIG_REPLICATION
1082 if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
1083 error_setg(errp, "QEMU compiled without replication module"
1084 " can't enable COLO");
1085 error_append_hint(errp, "Please enable replication before COLO.\n");
1086 return false;
1088 #endif
1090 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1091 /* This check is reasonably expensive, so only when it's being
1092 * set the first time, also it's only the destination that needs
1093 * special support.
1095 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
1096 !postcopy_ram_supported_by_host(mis)) {
1097 /* postcopy_ram_supported_by_host will have emitted a more
1098 * detailed message
1100 error_setg(errp, "Postcopy is not supported");
1101 return false;
1104 if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1105 error_setg(errp, "Postcopy is not compatible with ignore-shared");
1106 return false;
1110 return true;
1113 static void fill_destination_migration_info(MigrationInfo *info)
1115 MigrationIncomingState *mis = migration_incoming_get_current();
1117 if (mis->socket_address_list) {
1118 info->has_socket_address = true;
1119 info->socket_address =
1120 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1123 switch (mis->state) {
1124 case MIGRATION_STATUS_NONE:
1125 return;
1126 case MIGRATION_STATUS_SETUP:
1127 case MIGRATION_STATUS_CANCELLING:
1128 case MIGRATION_STATUS_CANCELLED:
1129 case MIGRATION_STATUS_ACTIVE:
1130 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1131 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1132 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1133 case MIGRATION_STATUS_FAILED:
1134 case MIGRATION_STATUS_COLO:
1135 info->has_status = true;
1136 break;
1137 case MIGRATION_STATUS_COMPLETED:
1138 info->has_status = true;
1139 fill_destination_postcopy_migration_info(info);
1140 break;
1142 info->status = mis->state;
1145 MigrationInfo *qmp_query_migrate(Error **errp)
1147 MigrationInfo *info = g_malloc0(sizeof(*info));
1149 fill_destination_migration_info(info);
1150 fill_source_migration_info(info);
1152 return info;
1155 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1156 Error **errp)
1158 MigrationState *s = migrate_get_current();
1159 MigrationCapabilityStatusList *cap;
1160 bool cap_list[MIGRATION_CAPABILITY__MAX];
1162 if (migration_is_running(s->state)) {
1163 error_setg(errp, QERR_MIGRATION_ACTIVE);
1164 return;
1167 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1168 if (!migrate_caps_check(cap_list, params, errp)) {
1169 return;
1172 for (cap = params; cap; cap = cap->next) {
1173 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1178 * Check whether the parameters are valid. Error will be put into errp
1179 * (if provided). Return true if valid, otherwise false.
1181 static bool migrate_params_check(MigrationParameters *params, Error **errp)
1183 if (params->has_compress_level &&
1184 (params->compress_level > 9)) {
1185 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1186 "is invalid, it should be in the range of 0 to 9");
1187 return false;
1190 if (params->has_compress_threads && (params->compress_threads < 1)) {
1191 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1192 "compress_threads",
1193 "is invalid, it should be in the range of 1 to 255");
1194 return false;
1197 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1198 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1199 "decompress_threads",
1200 "is invalid, it should be in the range of 1 to 255");
1201 return false;
1204 if (params->has_throttle_trigger_threshold &&
1205 (params->throttle_trigger_threshold < 1 ||
1206 params->throttle_trigger_threshold > 100)) {
1207 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1208 "throttle_trigger_threshold",
1209 "an integer in the range of 1 to 100");
1210 return false;
1213 if (params->has_cpu_throttle_initial &&
1214 (params->cpu_throttle_initial < 1 ||
1215 params->cpu_throttle_initial > 99)) {
1216 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1217 "cpu_throttle_initial",
1218 "an integer in the range of 1 to 99");
1219 return false;
1222 if (params->has_cpu_throttle_increment &&
1223 (params->cpu_throttle_increment < 1 ||
1224 params->cpu_throttle_increment > 99)) {
1225 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1226 "cpu_throttle_increment",
1227 "an integer in the range of 1 to 99");
1228 return false;
1231 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1232 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1233 "max_bandwidth",
1234 "an integer in the range of 0 to "stringify(SIZE_MAX)
1235 " bytes/second");
1236 return false;
1239 if (params->has_downtime_limit &&
1240 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1241 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1242 "downtime_limit",
1243 "an integer in the range of 0 to "
1244 stringify(MAX_MIGRATE_DOWNTIME)" ms");
1245 return false;
1248 /* x_checkpoint_delay is now always positive */
1250 if (params->has_multifd_channels && (params->multifd_channels < 1)) {
1251 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1252 "multifd_channels",
1253 "is invalid, it should be in the range of 1 to 255");
1254 return false;
1257 if (params->has_multifd_zlib_level &&
1258 (params->multifd_zlib_level > 9)) {
1259 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level",
1260 "is invalid, it should be in the range of 0 to 9");
1261 return false;
1264 if (params->has_multifd_zstd_level &&
1265 (params->multifd_zstd_level > 20)) {
1266 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level",
1267 "is invalid, it should be in the range of 0 to 20");
1268 return false;
1271 if (params->has_xbzrle_cache_size &&
1272 (params->xbzrle_cache_size < qemu_target_page_size() ||
1273 !is_power_of_2(params->xbzrle_cache_size))) {
1274 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1275 "xbzrle_cache_size",
1276 "is invalid, it should be bigger than target page size"
1277 " and a power of 2");
1278 return false;
1281 if (params->has_max_cpu_throttle &&
1282 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1283 params->max_cpu_throttle > 99)) {
1284 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1285 "max_cpu_throttle",
1286 "an integer in the range of cpu_throttle_initial to 99");
1287 return false;
1290 if (params->has_announce_initial &&
1291 params->announce_initial > 100000) {
1292 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1293 "announce_initial",
1294 "is invalid, it must be less than 100000 ms");
1295 return false;
1297 if (params->has_announce_max &&
1298 params->announce_max > 100000) {
1299 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1300 "announce_max",
1301 "is invalid, it must be less than 100000 ms");
1302 return false;
1304 if (params->has_announce_rounds &&
1305 params->announce_rounds > 1000) {
1306 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1307 "announce_rounds",
1308 "is invalid, it must be in the range of 0 to 1000");
1309 return false;
1311 if (params->has_announce_step &&
1312 (params->announce_step < 1 ||
1313 params->announce_step > 10000)) {
1314 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1315 "announce_step",
1316 "is invalid, it must be in the range of 1 to 10000 ms");
1317 return false;
1320 if (params->has_block_bitmap_mapping &&
1321 !check_dirty_bitmap_mig_alias_map(params->block_bitmap_mapping, errp)) {
1322 error_prepend(errp, "Invalid mapping given for block-bitmap-mapping: ");
1323 return false;
1326 return true;
1329 static void migrate_params_test_apply(MigrateSetParameters *params,
1330 MigrationParameters *dest)
1332 *dest = migrate_get_current()->parameters;
1334 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1336 if (params->has_compress_level) {
1337 dest->compress_level = params->compress_level;
1340 if (params->has_compress_threads) {
1341 dest->compress_threads = params->compress_threads;
1344 if (params->has_compress_wait_thread) {
1345 dest->compress_wait_thread = params->compress_wait_thread;
1348 if (params->has_decompress_threads) {
1349 dest->decompress_threads = params->decompress_threads;
1352 if (params->has_throttle_trigger_threshold) {
1353 dest->throttle_trigger_threshold = params->throttle_trigger_threshold;
1356 if (params->has_cpu_throttle_initial) {
1357 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1360 if (params->has_cpu_throttle_increment) {
1361 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1364 if (params->has_cpu_throttle_tailslow) {
1365 dest->cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1368 if (params->has_tls_creds) {
1369 assert(params->tls_creds->type == QTYPE_QSTRING);
1370 dest->tls_creds = params->tls_creds->u.s;
1373 if (params->has_tls_hostname) {
1374 assert(params->tls_hostname->type == QTYPE_QSTRING);
1375 dest->tls_hostname = params->tls_hostname->u.s;
1378 if (params->has_max_bandwidth) {
1379 dest->max_bandwidth = params->max_bandwidth;
1382 if (params->has_downtime_limit) {
1383 dest->downtime_limit = params->downtime_limit;
1386 if (params->has_x_checkpoint_delay) {
1387 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1390 if (params->has_block_incremental) {
1391 dest->block_incremental = params->block_incremental;
1393 if (params->has_multifd_channels) {
1394 dest->multifd_channels = params->multifd_channels;
1396 if (params->has_multifd_compression) {
1397 dest->multifd_compression = params->multifd_compression;
1399 if (params->has_xbzrle_cache_size) {
1400 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1402 if (params->has_max_postcopy_bandwidth) {
1403 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1405 if (params->has_max_cpu_throttle) {
1406 dest->max_cpu_throttle = params->max_cpu_throttle;
1408 if (params->has_announce_initial) {
1409 dest->announce_initial = params->announce_initial;
1411 if (params->has_announce_max) {
1412 dest->announce_max = params->announce_max;
1414 if (params->has_announce_rounds) {
1415 dest->announce_rounds = params->announce_rounds;
1417 if (params->has_announce_step) {
1418 dest->announce_step = params->announce_step;
1421 if (params->has_block_bitmap_mapping) {
1422 dest->has_block_bitmap_mapping = true;
1423 dest->block_bitmap_mapping = params->block_bitmap_mapping;
1427 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1429 MigrationState *s = migrate_get_current();
1431 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1433 if (params->has_compress_level) {
1434 s->parameters.compress_level = params->compress_level;
1437 if (params->has_compress_threads) {
1438 s->parameters.compress_threads = params->compress_threads;
1441 if (params->has_compress_wait_thread) {
1442 s->parameters.compress_wait_thread = params->compress_wait_thread;
1445 if (params->has_decompress_threads) {
1446 s->parameters.decompress_threads = params->decompress_threads;
1449 if (params->has_throttle_trigger_threshold) {
1450 s->parameters.throttle_trigger_threshold = params->throttle_trigger_threshold;
1453 if (params->has_cpu_throttle_initial) {
1454 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1457 if (params->has_cpu_throttle_increment) {
1458 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1461 if (params->has_cpu_throttle_tailslow) {
1462 s->parameters.cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1465 if (params->has_tls_creds) {
1466 g_free(s->parameters.tls_creds);
1467 assert(params->tls_creds->type == QTYPE_QSTRING);
1468 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1471 if (params->has_tls_hostname) {
1472 g_free(s->parameters.tls_hostname);
1473 assert(params->tls_hostname->type == QTYPE_QSTRING);
1474 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1477 if (params->has_tls_authz) {
1478 g_free(s->parameters.tls_authz);
1479 assert(params->tls_authz->type == QTYPE_QSTRING);
1480 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1483 if (params->has_max_bandwidth) {
1484 s->parameters.max_bandwidth = params->max_bandwidth;
1485 if (s->to_dst_file && !migration_in_postcopy()) {
1486 qemu_file_set_rate_limit(s->to_dst_file,
1487 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1491 if (params->has_downtime_limit) {
1492 s->parameters.downtime_limit = params->downtime_limit;
1495 if (params->has_x_checkpoint_delay) {
1496 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1497 if (migration_in_colo_state()) {
1498 colo_checkpoint_notify(s);
1502 if (params->has_block_incremental) {
1503 s->parameters.block_incremental = params->block_incremental;
1505 if (params->has_multifd_channels) {
1506 s->parameters.multifd_channels = params->multifd_channels;
1508 if (params->has_multifd_compression) {
1509 s->parameters.multifd_compression = params->multifd_compression;
1511 if (params->has_xbzrle_cache_size) {
1512 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1513 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1515 if (params->has_max_postcopy_bandwidth) {
1516 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1517 if (s->to_dst_file && migration_in_postcopy()) {
1518 qemu_file_set_rate_limit(s->to_dst_file,
1519 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1522 if (params->has_max_cpu_throttle) {
1523 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1525 if (params->has_announce_initial) {
1526 s->parameters.announce_initial = params->announce_initial;
1528 if (params->has_announce_max) {
1529 s->parameters.announce_max = params->announce_max;
1531 if (params->has_announce_rounds) {
1532 s->parameters.announce_rounds = params->announce_rounds;
1534 if (params->has_announce_step) {
1535 s->parameters.announce_step = params->announce_step;
1538 if (params->has_block_bitmap_mapping) {
1539 qapi_free_BitmapMigrationNodeAliasList(
1540 s->parameters.block_bitmap_mapping);
1542 s->parameters.has_block_bitmap_mapping = true;
1543 s->parameters.block_bitmap_mapping =
1544 QAPI_CLONE(BitmapMigrationNodeAliasList,
1545 params->block_bitmap_mapping);
1549 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1551 MigrationParameters tmp;
1553 /* TODO Rewrite "" to null instead */
1554 if (params->has_tls_creds
1555 && params->tls_creds->type == QTYPE_QNULL) {
1556 qobject_unref(params->tls_creds->u.n);
1557 params->tls_creds->type = QTYPE_QSTRING;
1558 params->tls_creds->u.s = strdup("");
1560 /* TODO Rewrite "" to null instead */
1561 if (params->has_tls_hostname
1562 && params->tls_hostname->type == QTYPE_QNULL) {
1563 qobject_unref(params->tls_hostname->u.n);
1564 params->tls_hostname->type = QTYPE_QSTRING;
1565 params->tls_hostname->u.s = strdup("");
1568 migrate_params_test_apply(params, &tmp);
1570 if (!migrate_params_check(&tmp, errp)) {
1571 /* Invalid parameter */
1572 return;
1575 migrate_params_apply(params, errp);
1579 void qmp_migrate_start_postcopy(Error **errp)
1581 MigrationState *s = migrate_get_current();
1583 if (!migrate_postcopy()) {
1584 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1585 " the start of migration");
1586 return;
1589 if (s->state == MIGRATION_STATUS_NONE) {
1590 error_setg(errp, "Postcopy must be started after migration has been"
1591 " started");
1592 return;
1595 * we don't error if migration has finished since that would be racy
1596 * with issuing this command.
1598 atomic_set(&s->start_postcopy, true);
1601 /* shared migration helpers */
1603 void migrate_set_state(int *state, int old_state, int new_state)
1605 assert(new_state < MIGRATION_STATUS__MAX);
1606 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1607 trace_migrate_set_state(MigrationStatus_str(new_state));
1608 migrate_generate_event(new_state);
1612 static MigrationCapabilityStatusList *migrate_cap_add(
1613 MigrationCapabilityStatusList *list,
1614 MigrationCapability index,
1615 bool state)
1617 MigrationCapabilityStatusList *cap;
1619 cap = g_new0(MigrationCapabilityStatusList, 1);
1620 cap->value = g_new0(MigrationCapabilityStatus, 1);
1621 cap->value->capability = index;
1622 cap->value->state = state;
1623 cap->next = list;
1625 return cap;
1628 void migrate_set_block_enabled(bool value, Error **errp)
1630 MigrationCapabilityStatusList *cap;
1632 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1633 qmp_migrate_set_capabilities(cap, errp);
1634 qapi_free_MigrationCapabilityStatusList(cap);
1637 static void migrate_set_block_incremental(MigrationState *s, bool value)
1639 s->parameters.block_incremental = value;
1642 static void block_cleanup_parameters(MigrationState *s)
1644 if (s->must_remove_block_options) {
1645 /* setting to false can never fail */
1646 migrate_set_block_enabled(false, &error_abort);
1647 migrate_set_block_incremental(s, false);
1648 s->must_remove_block_options = false;
1652 static void migrate_fd_cleanup(MigrationState *s)
1654 qemu_bh_delete(s->cleanup_bh);
1655 s->cleanup_bh = NULL;
1657 qemu_savevm_state_cleanup();
1659 if (s->to_dst_file) {
1660 QEMUFile *tmp;
1662 trace_migrate_fd_cleanup();
1663 qemu_mutex_unlock_iothread();
1664 if (s->migration_thread_running) {
1665 qemu_thread_join(&s->thread);
1666 s->migration_thread_running = false;
1668 qemu_mutex_lock_iothread();
1670 multifd_save_cleanup();
1671 qemu_mutex_lock(&s->qemu_file_lock);
1672 tmp = s->to_dst_file;
1673 s->to_dst_file = NULL;
1674 qemu_mutex_unlock(&s->qemu_file_lock);
1676 * Close the file handle without the lock to make sure the
1677 * critical section won't block for long.
1679 qemu_fclose(tmp);
1682 assert(!migration_is_active(s));
1684 if (s->state == MIGRATION_STATUS_CANCELLING) {
1685 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1686 MIGRATION_STATUS_CANCELLED);
1689 if (s->error) {
1690 /* It is used on info migrate. We can't free it */
1691 error_report_err(error_copy(s->error));
1693 notifier_list_notify(&migration_state_notifiers, s);
1694 block_cleanup_parameters(s);
1697 static void migrate_fd_cleanup_schedule(MigrationState *s)
1700 * Ref the state for bh, because it may be called when
1701 * there're already no other refs
1703 object_ref(OBJECT(s));
1704 qemu_bh_schedule(s->cleanup_bh);
1707 static void migrate_fd_cleanup_bh(void *opaque)
1709 MigrationState *s = opaque;
1710 migrate_fd_cleanup(s);
1711 object_unref(OBJECT(s));
1714 void migrate_set_error(MigrationState *s, const Error *error)
1716 QEMU_LOCK_GUARD(&s->error_mutex);
1717 if (!s->error) {
1718 s->error = error_copy(error);
1722 void migrate_fd_error(MigrationState *s, const Error *error)
1724 trace_migrate_fd_error(error_get_pretty(error));
1725 assert(s->to_dst_file == NULL);
1726 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1727 MIGRATION_STATUS_FAILED);
1728 migrate_set_error(s, error);
1731 static void migrate_fd_cancel(MigrationState *s)
1733 int old_state ;
1734 QEMUFile *f = migrate_get_current()->to_dst_file;
1735 trace_migrate_fd_cancel();
1737 if (s->rp_state.from_dst_file) {
1738 /* shutdown the rp socket, so causing the rp thread to shutdown */
1739 qemu_file_shutdown(s->rp_state.from_dst_file);
1742 do {
1743 old_state = s->state;
1744 if (!migration_is_running(old_state)) {
1745 break;
1747 /* If the migration is paused, kick it out of the pause */
1748 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1749 qemu_sem_post(&s->pause_sem);
1751 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1752 } while (s->state != MIGRATION_STATUS_CANCELLING);
1755 * If we're unlucky the migration code might be stuck somewhere in a
1756 * send/write while the network has failed and is waiting to timeout;
1757 * if we've got shutdown(2) available then we can force it to quit.
1758 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1759 * called in a bh, so there is no race against this cancel.
1761 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1762 qemu_file_shutdown(f);
1764 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1765 Error *local_err = NULL;
1767 bdrv_invalidate_cache_all(&local_err);
1768 if (local_err) {
1769 error_report_err(local_err);
1770 } else {
1771 s->block_inactive = false;
1776 void add_migration_state_change_notifier(Notifier *notify)
1778 notifier_list_add(&migration_state_notifiers, notify);
1781 void remove_migration_state_change_notifier(Notifier *notify)
1783 notifier_remove(notify);
1786 bool migration_in_setup(MigrationState *s)
1788 return s->state == MIGRATION_STATUS_SETUP;
1791 bool migration_has_finished(MigrationState *s)
1793 return s->state == MIGRATION_STATUS_COMPLETED;
1796 bool migration_has_failed(MigrationState *s)
1798 return (s->state == MIGRATION_STATUS_CANCELLED ||
1799 s->state == MIGRATION_STATUS_FAILED);
1802 bool migration_in_postcopy(void)
1804 MigrationState *s = migrate_get_current();
1806 switch (s->state) {
1807 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1808 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1809 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1810 return true;
1811 default:
1812 return false;
1816 bool migration_in_postcopy_after_devices(MigrationState *s)
1818 return migration_in_postcopy() && s->postcopy_after_devices;
1821 bool migration_in_incoming_postcopy(void)
1823 PostcopyState ps = postcopy_state_get();
1825 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
1828 bool migration_is_idle(void)
1830 MigrationState *s = current_migration;
1832 if (!s) {
1833 return true;
1836 switch (s->state) {
1837 case MIGRATION_STATUS_NONE:
1838 case MIGRATION_STATUS_CANCELLED:
1839 case MIGRATION_STATUS_COMPLETED:
1840 case MIGRATION_STATUS_FAILED:
1841 return true;
1842 case MIGRATION_STATUS_SETUP:
1843 case MIGRATION_STATUS_CANCELLING:
1844 case MIGRATION_STATUS_ACTIVE:
1845 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1846 case MIGRATION_STATUS_COLO:
1847 case MIGRATION_STATUS_PRE_SWITCHOVER:
1848 case MIGRATION_STATUS_DEVICE:
1849 case MIGRATION_STATUS_WAIT_UNPLUG:
1850 return false;
1851 case MIGRATION_STATUS__MAX:
1852 g_assert_not_reached();
1855 return false;
1858 bool migration_is_active(MigrationState *s)
1860 return (s->state == MIGRATION_STATUS_ACTIVE ||
1861 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1864 void migrate_init(MigrationState *s)
1867 * Reinitialise all migration state, except
1868 * parameters/capabilities that the user set, and
1869 * locks.
1871 s->cleanup_bh = 0;
1872 s->to_dst_file = NULL;
1873 s->state = MIGRATION_STATUS_NONE;
1874 s->rp_state.from_dst_file = NULL;
1875 s->rp_state.error = false;
1876 s->mbps = 0.0;
1877 s->pages_per_second = 0.0;
1878 s->downtime = 0;
1879 s->expected_downtime = 0;
1880 s->setup_time = 0;
1881 s->start_postcopy = false;
1882 s->postcopy_after_devices = false;
1883 s->migration_thread_running = false;
1884 error_free(s->error);
1885 s->error = NULL;
1887 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1889 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1890 s->total_time = 0;
1891 s->vm_was_running = false;
1892 s->iteration_initial_bytes = 0;
1893 s->threshold_size = 0;
1896 static GSList *migration_blockers;
1898 int migrate_add_blocker(Error *reason, Error **errp)
1900 if (only_migratable) {
1901 error_propagate_prepend(errp, error_copy(reason),
1902 "disallowing migration blocker "
1903 "(--only-migratable) for: ");
1904 return -EACCES;
1907 if (migration_is_idle()) {
1908 migration_blockers = g_slist_prepend(migration_blockers, reason);
1909 return 0;
1912 error_propagate_prepend(errp, error_copy(reason),
1913 "disallowing migration blocker "
1914 "(migration in progress) for: ");
1915 return -EBUSY;
1918 void migrate_del_blocker(Error *reason)
1920 migration_blockers = g_slist_remove(migration_blockers, reason);
1923 void qmp_migrate_incoming(const char *uri, Error **errp)
1925 Error *local_err = NULL;
1926 static bool once = true;
1928 if (!deferred_incoming) {
1929 error_setg(errp, "For use with '-incoming defer'");
1930 return;
1932 if (!once) {
1933 error_setg(errp, "The incoming migration has already been started");
1934 return;
1937 qemu_start_incoming_migration(uri, &local_err);
1939 if (local_err) {
1940 error_propagate(errp, local_err);
1941 return;
1944 once = false;
1947 void qmp_migrate_recover(const char *uri, Error **errp)
1949 MigrationIncomingState *mis = migration_incoming_get_current();
1951 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1952 error_setg(errp, "Migrate recover can only be run "
1953 "when postcopy is paused.");
1954 return;
1957 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1958 false, true) == true) {
1959 error_setg(errp, "Migrate recovery is triggered already");
1960 return;
1964 * Note that this call will never start a real migration; it will
1965 * only re-setup the migration stream and poke existing migration
1966 * to continue using that newly established channel.
1968 qemu_start_incoming_migration(uri, errp);
1971 void qmp_migrate_pause(Error **errp)
1973 MigrationState *ms = migrate_get_current();
1974 MigrationIncomingState *mis = migration_incoming_get_current();
1975 int ret;
1977 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1978 /* Source side, during postcopy */
1979 qemu_mutex_lock(&ms->qemu_file_lock);
1980 ret = qemu_file_shutdown(ms->to_dst_file);
1981 qemu_mutex_unlock(&ms->qemu_file_lock);
1982 if (ret) {
1983 error_setg(errp, "Failed to pause source migration");
1985 return;
1988 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1989 ret = qemu_file_shutdown(mis->from_src_file);
1990 if (ret) {
1991 error_setg(errp, "Failed to pause destination migration");
1993 return;
1996 error_setg(errp, "migrate-pause is currently only supported "
1997 "during postcopy-active state");
2000 bool migration_is_blocked(Error **errp)
2002 if (qemu_savevm_state_blocked(errp)) {
2003 return true;
2006 if (migration_blockers) {
2007 error_propagate(errp, error_copy(migration_blockers->data));
2008 return true;
2011 return false;
2014 /* Returns true if continue to migrate, or false if error detected */
2015 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
2016 bool resume, Error **errp)
2018 Error *local_err = NULL;
2020 if (resume) {
2021 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2022 error_setg(errp, "Cannot resume if there is no "
2023 "paused migration");
2024 return false;
2028 * Postcopy recovery won't work well with release-ram
2029 * capability since release-ram will drop the page buffer as
2030 * long as the page is put into the send buffer. So if there
2031 * is a network failure happened, any page buffers that have
2032 * not yet reached the destination VM but have already been
2033 * sent from the source VM will be lost forever. Let's refuse
2034 * the client from resuming such a postcopy migration.
2035 * Luckily release-ram was designed to only be used when src
2036 * and destination VMs are on the same host, so it should be
2037 * fine.
2039 if (migrate_release_ram()) {
2040 error_setg(errp, "Postcopy recovery cannot work "
2041 "when release-ram capability is set");
2042 return false;
2045 /* This is a resume, skip init status */
2046 return true;
2049 if (migration_is_running(s->state)) {
2050 error_setg(errp, QERR_MIGRATION_ACTIVE);
2051 return false;
2054 if (runstate_check(RUN_STATE_INMIGRATE)) {
2055 error_setg(errp, "Guest is waiting for an incoming migration");
2056 return false;
2059 if (migration_is_blocked(errp)) {
2060 return false;
2063 if (blk || blk_inc) {
2064 if (migrate_use_block() || migrate_use_block_incremental()) {
2065 error_setg(errp, "Command options are incompatible with "
2066 "current migration capabilities");
2067 return false;
2069 migrate_set_block_enabled(true, &local_err);
2070 if (local_err) {
2071 error_propagate(errp, local_err);
2072 return false;
2074 s->must_remove_block_options = true;
2077 if (blk_inc) {
2078 migrate_set_block_incremental(s, true);
2081 migrate_init(s);
2083 * set ram_counters memory to zero for a
2084 * new migration
2086 memset(&ram_counters, 0, sizeof(ram_counters));
2088 return true;
2091 void qmp_migrate(const char *uri, bool has_blk, bool blk,
2092 bool has_inc, bool inc, bool has_detach, bool detach,
2093 bool has_resume, bool resume, Error **errp)
2095 Error *local_err = NULL;
2096 MigrationState *s = migrate_get_current();
2097 const char *p = NULL;
2099 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2100 has_resume && resume, errp)) {
2101 /* Error detected, put into errp */
2102 return;
2105 if (strstart(uri, "tcp:", &p) ||
2106 strstart(uri, "unix:", NULL) ||
2107 strstart(uri, "vsock:", NULL)) {
2108 socket_start_outgoing_migration(s, p ? p : uri, &local_err);
2109 #ifdef CONFIG_RDMA
2110 } else if (strstart(uri, "rdma:", &p)) {
2111 rdma_start_outgoing_migration(s, p, &local_err);
2112 #endif
2113 } else if (strstart(uri, "exec:", &p)) {
2114 exec_start_outgoing_migration(s, p, &local_err);
2115 } else if (strstart(uri, "fd:", &p)) {
2116 fd_start_outgoing_migration(s, p, &local_err);
2117 } else {
2118 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2119 "a valid migration protocol");
2120 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2121 MIGRATION_STATUS_FAILED);
2122 block_cleanup_parameters(s);
2123 return;
2126 if (local_err) {
2127 migrate_fd_error(s, local_err);
2128 error_propagate(errp, local_err);
2129 return;
2133 void qmp_migrate_cancel(Error **errp)
2135 migrate_fd_cancel(migrate_get_current());
2138 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2140 MigrationState *s = migrate_get_current();
2141 if (s->state != state) {
2142 error_setg(errp, "Migration not in expected state: %s",
2143 MigrationStatus_str(s->state));
2144 return;
2146 qemu_sem_post(&s->pause_sem);
2149 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
2151 MigrateSetParameters p = {
2152 .has_xbzrle_cache_size = true,
2153 .xbzrle_cache_size = value,
2156 qmp_migrate_set_parameters(&p, errp);
2159 int64_t qmp_query_migrate_cache_size(Error **errp)
2161 return migrate_xbzrle_cache_size();
2164 void qmp_migrate_set_speed(int64_t value, Error **errp)
2166 MigrateSetParameters p = {
2167 .has_max_bandwidth = true,
2168 .max_bandwidth = value,
2171 qmp_migrate_set_parameters(&p, errp);
2174 void qmp_migrate_set_downtime(double value, Error **errp)
2176 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
2177 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
2178 "downtime_limit",
2179 "an integer in the range of 0 to "
2180 stringify(MAX_MIGRATE_DOWNTIME_SECONDS)" seconds");
2181 return;
2184 value *= 1000; /* Convert to milliseconds */
2186 MigrateSetParameters p = {
2187 .has_downtime_limit = true,
2188 .downtime_limit = (int64_t)value,
2191 qmp_migrate_set_parameters(&p, errp);
2194 bool migrate_release_ram(void)
2196 MigrationState *s;
2198 s = migrate_get_current();
2200 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2203 bool migrate_postcopy_ram(void)
2205 MigrationState *s;
2207 s = migrate_get_current();
2209 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
2212 bool migrate_postcopy(void)
2214 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
2217 bool migrate_auto_converge(void)
2219 MigrationState *s;
2221 s = migrate_get_current();
2223 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2226 bool migrate_zero_blocks(void)
2228 MigrationState *s;
2230 s = migrate_get_current();
2232 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2235 bool migrate_postcopy_blocktime(void)
2237 MigrationState *s;
2239 s = migrate_get_current();
2241 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2244 bool migrate_use_compression(void)
2246 MigrationState *s;
2248 s = migrate_get_current();
2250 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
2253 int migrate_compress_level(void)
2255 MigrationState *s;
2257 s = migrate_get_current();
2259 return s->parameters.compress_level;
2262 int migrate_compress_threads(void)
2264 MigrationState *s;
2266 s = migrate_get_current();
2268 return s->parameters.compress_threads;
2271 int migrate_compress_wait_thread(void)
2273 MigrationState *s;
2275 s = migrate_get_current();
2277 return s->parameters.compress_wait_thread;
2280 int migrate_decompress_threads(void)
2282 MigrationState *s;
2284 s = migrate_get_current();
2286 return s->parameters.decompress_threads;
2289 bool migrate_dirty_bitmaps(void)
2291 MigrationState *s;
2293 s = migrate_get_current();
2295 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2298 bool migrate_ignore_shared(void)
2300 MigrationState *s;
2302 s = migrate_get_current();
2304 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2307 bool migrate_validate_uuid(void)
2309 MigrationState *s;
2311 s = migrate_get_current();
2313 return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2316 bool migrate_use_events(void)
2318 MigrationState *s;
2320 s = migrate_get_current();
2322 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2325 bool migrate_use_multifd(void)
2327 MigrationState *s;
2329 s = migrate_get_current();
2331 return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
2334 bool migrate_pause_before_switchover(void)
2336 MigrationState *s;
2338 s = migrate_get_current();
2340 return s->enabled_capabilities[
2341 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2344 int migrate_multifd_channels(void)
2346 MigrationState *s;
2348 s = migrate_get_current();
2350 return s->parameters.multifd_channels;
2353 MultiFDCompression migrate_multifd_compression(void)
2355 MigrationState *s;
2357 s = migrate_get_current();
2359 return s->parameters.multifd_compression;
2362 int migrate_multifd_zlib_level(void)
2364 MigrationState *s;
2366 s = migrate_get_current();
2368 return s->parameters.multifd_zlib_level;
2371 int migrate_multifd_zstd_level(void)
2373 MigrationState *s;
2375 s = migrate_get_current();
2377 return s->parameters.multifd_zstd_level;
2380 int migrate_use_xbzrle(void)
2382 MigrationState *s;
2384 s = migrate_get_current();
2386 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2389 int64_t migrate_xbzrle_cache_size(void)
2391 MigrationState *s;
2393 s = migrate_get_current();
2395 return s->parameters.xbzrle_cache_size;
2398 static int64_t migrate_max_postcopy_bandwidth(void)
2400 MigrationState *s;
2402 s = migrate_get_current();
2404 return s->parameters.max_postcopy_bandwidth;
2407 bool migrate_use_block(void)
2409 MigrationState *s;
2411 s = migrate_get_current();
2413 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2416 bool migrate_use_return_path(void)
2418 MigrationState *s;
2420 s = migrate_get_current();
2422 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2425 bool migrate_use_block_incremental(void)
2427 MigrationState *s;
2429 s = migrate_get_current();
2431 return s->parameters.block_incremental;
2434 /* migration thread support */
2436 * Something bad happened to the RP stream, mark an error
2437 * The caller shall print or trace something to indicate why
2439 static void mark_source_rp_bad(MigrationState *s)
2441 s->rp_state.error = true;
2444 static struct rp_cmd_args {
2445 ssize_t len; /* -1 = variable */
2446 const char *name;
2447 } rp_cmd_args[] = {
2448 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2449 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2450 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2451 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2452 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2453 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2454 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2455 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2459 * Process a request for pages received on the return path,
2460 * We're allowed to send more than requested (e.g. to round to our page size)
2461 * and we don't need to send pages that have already been sent.
2463 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2464 ram_addr_t start, size_t len)
2466 long our_host_ps = qemu_real_host_page_size;
2468 trace_migrate_handle_rp_req_pages(rbname, start, len);
2471 * Since we currently insist on matching page sizes, just sanity check
2472 * we're being asked for whole host pages.
2474 if (start & (our_host_ps-1) ||
2475 (len & (our_host_ps-1))) {
2476 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2477 " len: %zd", __func__, start, len);
2478 mark_source_rp_bad(ms);
2479 return;
2482 if (ram_save_queue_pages(rbname, start, len)) {
2483 mark_source_rp_bad(ms);
2487 /* Return true to retry, false to quit */
2488 static bool postcopy_pause_return_path_thread(MigrationState *s)
2490 trace_postcopy_pause_return_path();
2492 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2494 trace_postcopy_pause_return_path_continued();
2496 return true;
2499 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2501 RAMBlock *block = qemu_ram_block_by_name(block_name);
2503 if (!block) {
2504 error_report("%s: invalid block name '%s'", __func__, block_name);
2505 return -EINVAL;
2508 /* Fetch the received bitmap and refresh the dirty bitmap */
2509 return ram_dirty_bitmap_reload(s, block);
2512 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2514 trace_source_return_path_thread_resume_ack(value);
2516 if (value != MIGRATION_RESUME_ACK_VALUE) {
2517 error_report("%s: illegal resume_ack value %"PRIu32,
2518 __func__, value);
2519 return -1;
2522 /* Now both sides are active. */
2523 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2524 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2526 /* Notify send thread that time to continue send pages */
2527 qemu_sem_post(&s->rp_state.rp_sem);
2529 return 0;
2533 * Handles messages sent on the return path towards the source VM
2536 static void *source_return_path_thread(void *opaque)
2538 MigrationState *ms = opaque;
2539 QEMUFile *rp = ms->rp_state.from_dst_file;
2540 uint16_t header_len, header_type;
2541 uint8_t buf[512];
2542 uint32_t tmp32, sibling_error;
2543 ram_addr_t start = 0; /* =0 to silence warning */
2544 size_t len = 0, expected_len;
2545 int res;
2547 trace_source_return_path_thread_entry();
2548 rcu_register_thread();
2550 retry:
2551 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2552 migration_is_setup_or_active(ms->state)) {
2553 trace_source_return_path_thread_loop_top();
2554 header_type = qemu_get_be16(rp);
2555 header_len = qemu_get_be16(rp);
2557 if (qemu_file_get_error(rp)) {
2558 mark_source_rp_bad(ms);
2559 goto out;
2562 if (header_type >= MIG_RP_MSG_MAX ||
2563 header_type == MIG_RP_MSG_INVALID) {
2564 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2565 header_type, header_len);
2566 mark_source_rp_bad(ms);
2567 goto out;
2570 if ((rp_cmd_args[header_type].len != -1 &&
2571 header_len != rp_cmd_args[header_type].len) ||
2572 header_len > sizeof(buf)) {
2573 error_report("RP: Received '%s' message (0x%04x) with"
2574 "incorrect length %d expecting %zu",
2575 rp_cmd_args[header_type].name, header_type, header_len,
2576 (size_t)rp_cmd_args[header_type].len);
2577 mark_source_rp_bad(ms);
2578 goto out;
2581 /* We know we've got a valid header by this point */
2582 res = qemu_get_buffer(rp, buf, header_len);
2583 if (res != header_len) {
2584 error_report("RP: Failed reading data for message 0x%04x"
2585 " read %d expected %d",
2586 header_type, res, header_len);
2587 mark_source_rp_bad(ms);
2588 goto out;
2591 /* OK, we have the message and the data */
2592 switch (header_type) {
2593 case MIG_RP_MSG_SHUT:
2594 sibling_error = ldl_be_p(buf);
2595 trace_source_return_path_thread_shut(sibling_error);
2596 if (sibling_error) {
2597 error_report("RP: Sibling indicated error %d", sibling_error);
2598 mark_source_rp_bad(ms);
2601 * We'll let the main thread deal with closing the RP
2602 * we could do a shutdown(2) on it, but we're the only user
2603 * anyway, so there's nothing gained.
2605 goto out;
2607 case MIG_RP_MSG_PONG:
2608 tmp32 = ldl_be_p(buf);
2609 trace_source_return_path_thread_pong(tmp32);
2610 break;
2612 case MIG_RP_MSG_REQ_PAGES:
2613 start = ldq_be_p(buf);
2614 len = ldl_be_p(buf + 8);
2615 migrate_handle_rp_req_pages(ms, NULL, start, len);
2616 break;
2618 case MIG_RP_MSG_REQ_PAGES_ID:
2619 expected_len = 12 + 1; /* header + termination */
2621 if (header_len >= expected_len) {
2622 start = ldq_be_p(buf);
2623 len = ldl_be_p(buf + 8);
2624 /* Now we expect an idstr */
2625 tmp32 = buf[12]; /* Length of the following idstr */
2626 buf[13 + tmp32] = '\0';
2627 expected_len += tmp32;
2629 if (header_len != expected_len) {
2630 error_report("RP: Req_Page_id with length %d expecting %zd",
2631 header_len, expected_len);
2632 mark_source_rp_bad(ms);
2633 goto out;
2635 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2636 break;
2638 case MIG_RP_MSG_RECV_BITMAP:
2639 if (header_len < 1) {
2640 error_report("%s: missing block name", __func__);
2641 mark_source_rp_bad(ms);
2642 goto out;
2644 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2645 buf[buf[0] + 1] = '\0';
2646 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2647 mark_source_rp_bad(ms);
2648 goto out;
2650 break;
2652 case MIG_RP_MSG_RESUME_ACK:
2653 tmp32 = ldl_be_p(buf);
2654 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2655 mark_source_rp_bad(ms);
2656 goto out;
2658 break;
2660 default:
2661 break;
2665 out:
2666 res = qemu_file_get_error(rp);
2667 if (res) {
2668 if (res == -EIO && migration_in_postcopy()) {
2670 * Maybe there is something we can do: it looks like a
2671 * network down issue, and we pause for a recovery.
2673 if (postcopy_pause_return_path_thread(ms)) {
2674 /* Reload rp, reset the rest */
2675 if (rp != ms->rp_state.from_dst_file) {
2676 qemu_fclose(rp);
2677 rp = ms->rp_state.from_dst_file;
2679 ms->rp_state.error = false;
2680 goto retry;
2684 trace_source_return_path_thread_bad_end();
2685 mark_source_rp_bad(ms);
2688 trace_source_return_path_thread_end();
2689 ms->rp_state.from_dst_file = NULL;
2690 qemu_fclose(rp);
2691 rcu_unregister_thread();
2692 return NULL;
2695 static int open_return_path_on_source(MigrationState *ms,
2696 bool create_thread)
2699 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2700 if (!ms->rp_state.from_dst_file) {
2701 return -1;
2704 trace_open_return_path_on_source();
2706 if (!create_thread) {
2707 /* We're done */
2708 return 0;
2711 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2712 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2714 trace_open_return_path_on_source_continue();
2716 return 0;
2719 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2720 static int await_return_path_close_on_source(MigrationState *ms)
2723 * If this is a normal exit then the destination will send a SHUT and the
2724 * rp_thread will exit, however if there's an error we need to cause
2725 * it to exit.
2727 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2729 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2730 * waiting for the destination.
2732 qemu_file_shutdown(ms->rp_state.from_dst_file);
2733 mark_source_rp_bad(ms);
2735 trace_await_return_path_close_on_source_joining();
2736 qemu_thread_join(&ms->rp_state.rp_thread);
2737 trace_await_return_path_close_on_source_close();
2738 return ms->rp_state.error;
2742 * Switch from normal iteration to postcopy
2743 * Returns non-0 on error
2745 static int postcopy_start(MigrationState *ms)
2747 int ret;
2748 QIOChannelBuffer *bioc;
2749 QEMUFile *fb;
2750 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2751 int64_t bandwidth = migrate_max_postcopy_bandwidth();
2752 bool restart_block = false;
2753 int cur_state = MIGRATION_STATUS_ACTIVE;
2754 if (!migrate_pause_before_switchover()) {
2755 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2756 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2759 trace_postcopy_start();
2760 qemu_mutex_lock_iothread();
2761 trace_postcopy_start_set_run();
2763 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2764 global_state_store();
2765 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2766 if (ret < 0) {
2767 goto fail;
2770 ret = migration_maybe_pause(ms, &cur_state,
2771 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2772 if (ret < 0) {
2773 goto fail;
2776 ret = bdrv_inactivate_all();
2777 if (ret < 0) {
2778 goto fail;
2780 restart_block = true;
2783 * Cause any non-postcopiable, but iterative devices to
2784 * send out their final data.
2786 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2789 * in Finish migrate and with the io-lock held everything should
2790 * be quiet, but we've potentially still got dirty pages and we
2791 * need to tell the destination to throw any pages it's already received
2792 * that are dirty
2794 if (migrate_postcopy_ram()) {
2795 if (ram_postcopy_send_discard_bitmap(ms)) {
2796 error_report("postcopy send discard bitmap failed");
2797 goto fail;
2802 * send rest of state - note things that are doing postcopy
2803 * will notice we're in POSTCOPY_ACTIVE and not actually
2804 * wrap their state up here
2806 /* 0 max-postcopy-bandwidth means unlimited */
2807 if (!bandwidth) {
2808 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2809 } else {
2810 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2812 if (migrate_postcopy_ram()) {
2813 /* Ping just for debugging, helps line traces up */
2814 qemu_savevm_send_ping(ms->to_dst_file, 2);
2818 * While loading the device state we may trigger page transfer
2819 * requests and the fd must be free to process those, and thus
2820 * the destination must read the whole device state off the fd before
2821 * it starts processing it. Unfortunately the ad-hoc migration format
2822 * doesn't allow the destination to know the size to read without fully
2823 * parsing it through each devices load-state code (especially the open
2824 * coded devices that use get/put).
2825 * So we wrap the device state up in a package with a length at the start;
2826 * to do this we use a qemu_buf to hold the whole of the device state.
2828 bioc = qio_channel_buffer_new(4096);
2829 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2830 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2831 object_unref(OBJECT(bioc));
2834 * Make sure the receiver can get incoming pages before we send the rest
2835 * of the state
2837 qemu_savevm_send_postcopy_listen(fb);
2839 qemu_savevm_state_complete_precopy(fb, false, false);
2840 if (migrate_postcopy_ram()) {
2841 qemu_savevm_send_ping(fb, 3);
2844 qemu_savevm_send_postcopy_run(fb);
2846 /* <><> end of stuff going into the package */
2848 /* Last point of recovery; as soon as we send the package the destination
2849 * can open devices and potentially start running.
2850 * Lets just check again we've not got any errors.
2852 ret = qemu_file_get_error(ms->to_dst_file);
2853 if (ret) {
2854 error_report("postcopy_start: Migration stream errored (pre package)");
2855 goto fail_closefb;
2858 restart_block = false;
2860 /* Now send that blob */
2861 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2862 goto fail_closefb;
2864 qemu_fclose(fb);
2866 /* Send a notify to give a chance for anything that needs to happen
2867 * at the transition to postcopy and after the device state; in particular
2868 * spice needs to trigger a transition now
2870 ms->postcopy_after_devices = true;
2871 notifier_list_notify(&migration_state_notifiers, ms);
2873 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2875 qemu_mutex_unlock_iothread();
2877 if (migrate_postcopy_ram()) {
2879 * Although this ping is just for debug, it could potentially be
2880 * used for getting a better measurement of downtime at the source.
2882 qemu_savevm_send_ping(ms->to_dst_file, 4);
2885 if (migrate_release_ram()) {
2886 ram_postcopy_migrated_memory_release(ms);
2889 ret = qemu_file_get_error(ms->to_dst_file);
2890 if (ret) {
2891 error_report("postcopy_start: Migration stream errored");
2892 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2893 MIGRATION_STATUS_FAILED);
2896 return ret;
2898 fail_closefb:
2899 qemu_fclose(fb);
2900 fail:
2901 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2902 MIGRATION_STATUS_FAILED);
2903 if (restart_block) {
2904 /* A failure happened early enough that we know the destination hasn't
2905 * accessed block devices, so we're safe to recover.
2907 Error *local_err = NULL;
2909 bdrv_invalidate_cache_all(&local_err);
2910 if (local_err) {
2911 error_report_err(local_err);
2914 qemu_mutex_unlock_iothread();
2915 return -1;
2919 * migration_maybe_pause: Pause if required to by
2920 * migrate_pause_before_switchover called with the iothread locked
2921 * Returns: 0 on success
2923 static int migration_maybe_pause(MigrationState *s,
2924 int *current_active_state,
2925 int new_state)
2927 if (!migrate_pause_before_switchover()) {
2928 return 0;
2931 /* Since leaving this state is not atomic with posting the semaphore
2932 * it's possible that someone could have issued multiple migrate_continue
2933 * and the semaphore is incorrectly positive at this point;
2934 * the docs say it's undefined to reinit a semaphore that's already
2935 * init'd, so use timedwait to eat up any existing posts.
2937 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2938 /* This block intentionally left blank */
2942 * If the migration is cancelled when it is in the completion phase,
2943 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2944 * So we don't need to wait a semaphore, otherwise we would always
2945 * wait for the 'pause_sem' semaphore.
2947 if (s->state != MIGRATION_STATUS_CANCELLING) {
2948 qemu_mutex_unlock_iothread();
2949 migrate_set_state(&s->state, *current_active_state,
2950 MIGRATION_STATUS_PRE_SWITCHOVER);
2951 qemu_sem_wait(&s->pause_sem);
2952 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2953 new_state);
2954 *current_active_state = new_state;
2955 qemu_mutex_lock_iothread();
2958 return s->state == new_state ? 0 : -EINVAL;
2962 * migration_completion: Used by migration_thread when there's not much left.
2963 * The caller 'breaks' the loop when this returns.
2965 * @s: Current migration state
2967 static void migration_completion(MigrationState *s)
2969 int ret;
2970 int current_active_state = s->state;
2972 if (s->state == MIGRATION_STATUS_ACTIVE) {
2973 qemu_mutex_lock_iothread();
2974 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2975 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2976 s->vm_was_running = runstate_is_running();
2977 ret = global_state_store();
2979 if (!ret) {
2980 bool inactivate = !migrate_colo_enabled();
2981 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2982 if (ret >= 0) {
2983 ret = migration_maybe_pause(s, &current_active_state,
2984 MIGRATION_STATUS_DEVICE);
2986 if (ret >= 0) {
2987 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2988 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2989 inactivate);
2991 if (inactivate && ret >= 0) {
2992 s->block_inactive = true;
2995 qemu_mutex_unlock_iothread();
2997 if (ret < 0) {
2998 goto fail;
3000 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3001 trace_migration_completion_postcopy_end();
3003 qemu_savevm_state_complete_postcopy(s->to_dst_file);
3004 trace_migration_completion_postcopy_end_after_complete();
3008 * If rp was opened we must clean up the thread before
3009 * cleaning everything else up (since if there are no failures
3010 * it will wait for the destination to send it's status in
3011 * a SHUT command).
3013 if (s->rp_state.from_dst_file) {
3014 int rp_error;
3015 trace_migration_return_path_end_before();
3016 rp_error = await_return_path_close_on_source(s);
3017 trace_migration_return_path_end_after(rp_error);
3018 if (rp_error) {
3019 goto fail_invalidate;
3023 if (qemu_file_get_error(s->to_dst_file)) {
3024 trace_migration_completion_file_err();
3025 goto fail_invalidate;
3028 if (!migrate_colo_enabled()) {
3029 migrate_set_state(&s->state, current_active_state,
3030 MIGRATION_STATUS_COMPLETED);
3033 return;
3035 fail_invalidate:
3036 /* If not doing postcopy, vm_start() will be called: let's regain
3037 * control on images.
3039 if (s->state == MIGRATION_STATUS_ACTIVE ||
3040 s->state == MIGRATION_STATUS_DEVICE) {
3041 Error *local_err = NULL;
3043 qemu_mutex_lock_iothread();
3044 bdrv_invalidate_cache_all(&local_err);
3045 if (local_err) {
3046 error_report_err(local_err);
3047 } else {
3048 s->block_inactive = false;
3050 qemu_mutex_unlock_iothread();
3053 fail:
3054 migrate_set_state(&s->state, current_active_state,
3055 MIGRATION_STATUS_FAILED);
3058 bool migrate_colo_enabled(void)
3060 MigrationState *s = migrate_get_current();
3061 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
3064 typedef enum MigThrError {
3065 /* No error detected */
3066 MIG_THR_ERR_NONE = 0,
3067 /* Detected error, but resumed successfully */
3068 MIG_THR_ERR_RECOVERED = 1,
3069 /* Detected fatal error, need to exit */
3070 MIG_THR_ERR_FATAL = 2,
3071 } MigThrError;
3073 static int postcopy_resume_handshake(MigrationState *s)
3075 qemu_savevm_send_postcopy_resume(s->to_dst_file);
3077 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3078 qemu_sem_wait(&s->rp_state.rp_sem);
3081 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3082 return 0;
3085 return -1;
3088 /* Return zero if success, or <0 for error */
3089 static int postcopy_do_resume(MigrationState *s)
3091 int ret;
3094 * Call all the resume_prepare() hooks, so that modules can be
3095 * ready for the migration resume.
3097 ret = qemu_savevm_state_resume_prepare(s);
3098 if (ret) {
3099 error_report("%s: resume_prepare() failure detected: %d",
3100 __func__, ret);
3101 return ret;
3105 * Last handshake with destination on the resume (destination will
3106 * switch to postcopy-active afterwards)
3108 ret = postcopy_resume_handshake(s);
3109 if (ret) {
3110 error_report("%s: handshake failed: %d", __func__, ret);
3111 return ret;
3114 return 0;
3118 * We don't return until we are in a safe state to continue current
3119 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
3120 * MIG_THR_ERR_FATAL if unrecovery failure happened.
3122 static MigThrError postcopy_pause(MigrationState *s)
3124 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3126 while (true) {
3127 QEMUFile *file;
3129 migrate_set_state(&s->state, s->state,
3130 MIGRATION_STATUS_POSTCOPY_PAUSED);
3132 /* Current channel is possibly broken. Release it. */
3133 assert(s->to_dst_file);
3134 qemu_mutex_lock(&s->qemu_file_lock);
3135 file = s->to_dst_file;
3136 s->to_dst_file = NULL;
3137 qemu_mutex_unlock(&s->qemu_file_lock);
3139 qemu_file_shutdown(file);
3140 qemu_fclose(file);
3142 error_report("Detected IO failure for postcopy. "
3143 "Migration paused.");
3146 * We wait until things fixed up. Then someone will setup the
3147 * status back for us.
3149 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3150 qemu_sem_wait(&s->postcopy_pause_sem);
3153 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3154 /* Woken up by a recover procedure. Give it a shot */
3157 * Firstly, let's wake up the return path now, with a new
3158 * return path channel.
3160 qemu_sem_post(&s->postcopy_pause_rp_sem);
3162 /* Do the resume logic */
3163 if (postcopy_do_resume(s) == 0) {
3164 /* Let's continue! */
3165 trace_postcopy_pause_continued();
3166 return MIG_THR_ERR_RECOVERED;
3167 } else {
3169 * Something wrong happened during the recovery, let's
3170 * pause again. Pause is always better than throwing
3171 * data away.
3173 continue;
3175 } else {
3176 /* This is not right... Time to quit. */
3177 return MIG_THR_ERR_FATAL;
3182 static MigThrError migration_detect_error(MigrationState *s)
3184 int ret;
3185 int state = s->state;
3186 Error *local_error = NULL;
3188 if (state == MIGRATION_STATUS_CANCELLING ||
3189 state == MIGRATION_STATUS_CANCELLED) {
3190 /* End the migration, but don't set the state to failed */
3191 return MIG_THR_ERR_FATAL;
3194 /* Try to detect any file errors */
3195 ret = qemu_file_get_error_obj(s->to_dst_file, &local_error);
3196 if (!ret) {
3197 /* Everything is fine */
3198 assert(!local_error);
3199 return MIG_THR_ERR_NONE;
3202 if (local_error) {
3203 migrate_set_error(s, local_error);
3204 error_free(local_error);
3207 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
3209 * For postcopy, we allow the network to be down for a
3210 * while. After that, it can be continued by a
3211 * recovery phase.
3213 return postcopy_pause(s);
3214 } else {
3216 * For precopy (or postcopy with error outside IO), we fail
3217 * with no time.
3219 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3220 trace_migration_thread_file_err();
3222 /* Time to stop the migration, now. */
3223 return MIG_THR_ERR_FATAL;
3227 /* How many bytes have we transferred since the beginning of the migration */
3228 static uint64_t migration_total_bytes(MigrationState *s)
3230 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
3233 static void migration_calculate_complete(MigrationState *s)
3235 uint64_t bytes = migration_total_bytes(s);
3236 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3237 int64_t transfer_time;
3239 s->total_time = end_time - s->start_time;
3240 if (!s->downtime) {
3242 * It's still not set, so we are precopy migration. For
3243 * postcopy, downtime is calculated during postcopy_start().
3245 s->downtime = end_time - s->downtime_start;
3248 transfer_time = s->total_time - s->setup_time;
3249 if (transfer_time) {
3250 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3254 static void update_iteration_initial_status(MigrationState *s)
3257 * Update these three fields at the same time to avoid mismatch info lead
3258 * wrong speed calculation.
3260 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3261 s->iteration_initial_bytes = migration_total_bytes(s);
3262 s->iteration_initial_pages = ram_get_total_transferred_pages();
3265 static void migration_update_counters(MigrationState *s,
3266 int64_t current_time)
3268 uint64_t transferred, transferred_pages, time_spent;
3269 uint64_t current_bytes; /* bytes transferred since the beginning */
3270 double bandwidth;
3272 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3273 return;
3276 current_bytes = migration_total_bytes(s);
3277 transferred = current_bytes - s->iteration_initial_bytes;
3278 time_spent = current_time - s->iteration_start_time;
3279 bandwidth = (double)transferred / time_spent;
3280 s->threshold_size = bandwidth * s->parameters.downtime_limit;
3282 s->mbps = (((double) transferred * 8.0) /
3283 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3285 transferred_pages = ram_get_total_transferred_pages() -
3286 s->iteration_initial_pages;
3287 s->pages_per_second = (double) transferred_pages /
3288 (((double) time_spent / 1000.0));
3291 * if we haven't sent anything, we don't want to
3292 * recalculate. 10000 is a small enough number for our purposes
3294 if (ram_counters.dirty_pages_rate && transferred > 10000) {
3295 s->expected_downtime = ram_counters.remaining / bandwidth;
3298 qemu_file_reset_rate_limit(s->to_dst_file);
3300 update_iteration_initial_status(s);
3302 trace_migrate_transferred(transferred, time_spent,
3303 bandwidth, s->threshold_size);
3306 /* Migration thread iteration status */
3307 typedef enum {
3308 MIG_ITERATE_RESUME, /* Resume current iteration */
3309 MIG_ITERATE_SKIP, /* Skip current iteration */
3310 MIG_ITERATE_BREAK, /* Break the loop */
3311 } MigIterateState;
3314 * Return true if continue to the next iteration directly, false
3315 * otherwise.
3317 static MigIterateState migration_iteration_run(MigrationState *s)
3319 uint64_t pending_size, pend_pre, pend_compat, pend_post;
3320 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3322 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
3323 &pend_compat, &pend_post);
3324 pending_size = pend_pre + pend_compat + pend_post;
3326 trace_migrate_pending(pending_size, s->threshold_size,
3327 pend_pre, pend_compat, pend_post);
3329 if (pending_size && pending_size >= s->threshold_size) {
3330 /* Still a significant amount to transfer */
3331 if (!in_postcopy && pend_pre <= s->threshold_size &&
3332 atomic_read(&s->start_postcopy)) {
3333 if (postcopy_start(s)) {
3334 error_report("%s: postcopy failed to start", __func__);
3336 return MIG_ITERATE_SKIP;
3338 /* Just another iteration step */
3339 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3340 } else {
3341 trace_migration_thread_low_pending(pending_size);
3342 migration_completion(s);
3343 return MIG_ITERATE_BREAK;
3346 return MIG_ITERATE_RESUME;
3349 static void migration_iteration_finish(MigrationState *s)
3351 /* If we enabled cpu throttling for auto-converge, turn it off. */
3352 cpu_throttle_stop();
3354 qemu_mutex_lock_iothread();
3355 switch (s->state) {
3356 case MIGRATION_STATUS_COMPLETED:
3357 migration_calculate_complete(s);
3358 runstate_set(RUN_STATE_POSTMIGRATE);
3359 break;
3361 case MIGRATION_STATUS_ACTIVE:
3363 * We should really assert here, but since it's during
3364 * migration, let's try to reduce the usage of assertions.
3366 if (!migrate_colo_enabled()) {
3367 error_report("%s: critical error: calling COLO code without "
3368 "COLO enabled", __func__);
3370 migrate_start_colo_process(s);
3372 * Fixme: we will run VM in COLO no matter its old running state.
3373 * After exited COLO, we will keep running.
3375 s->vm_was_running = true;
3376 /* Fallthrough */
3377 case MIGRATION_STATUS_FAILED:
3378 case MIGRATION_STATUS_CANCELLED:
3379 case MIGRATION_STATUS_CANCELLING:
3380 if (s->vm_was_running) {
3381 vm_start();
3382 } else {
3383 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3384 runstate_set(RUN_STATE_POSTMIGRATE);
3387 break;
3389 default:
3390 /* Should not reach here, but if so, forgive the VM. */
3391 error_report("%s: Unknown ending state %d", __func__, s->state);
3392 break;
3394 migrate_fd_cleanup_schedule(s);
3395 qemu_mutex_unlock_iothread();
3398 void migration_make_urgent_request(void)
3400 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3403 void migration_consume_urgent_request(void)
3405 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3408 /* Returns true if the rate limiting was broken by an urgent request */
3409 bool migration_rate_limit(void)
3411 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3412 MigrationState *s = migrate_get_current();
3414 bool urgent = false;
3415 migration_update_counters(s, now);
3416 if (qemu_file_rate_limit(s->to_dst_file)) {
3418 if (qemu_file_get_error(s->to_dst_file)) {
3419 return false;
3422 * Wait for a delay to do rate limiting OR
3423 * something urgent to post the semaphore.
3425 int ms = s->iteration_start_time + BUFFER_DELAY - now;
3426 trace_migration_rate_limit_pre(ms);
3427 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3429 * We were woken by one or more urgent things but
3430 * the timedwait will have consumed one of them.
3431 * The service routine for the urgent wake will dec
3432 * the semaphore itself for each item it consumes,
3433 * so add this one we just eat back.
3435 qemu_sem_post(&s->rate_limit_sem);
3436 urgent = true;
3438 trace_migration_rate_limit_post(urgent);
3440 return urgent;
3444 * Master migration thread on the source VM.
3445 * It drives the migration and pumps the data down the outgoing channel.
3447 static void *migration_thread(void *opaque)
3449 MigrationState *s = opaque;
3450 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3451 MigThrError thr_error;
3452 bool urgent = false;
3454 rcu_register_thread();
3456 object_ref(OBJECT(s));
3457 update_iteration_initial_status(s);
3459 qemu_savevm_state_header(s->to_dst_file);
3462 * If we opened the return path, we need to make sure dst has it
3463 * opened as well.
3465 if (s->rp_state.from_dst_file) {
3466 /* Now tell the dest that it should open its end so it can reply */
3467 qemu_savevm_send_open_return_path(s->to_dst_file);
3469 /* And do a ping that will make stuff easier to debug */
3470 qemu_savevm_send_ping(s->to_dst_file, 1);
3473 if (migrate_postcopy()) {
3475 * Tell the destination that we *might* want to do postcopy later;
3476 * if the other end can't do postcopy it should fail now, nice and
3477 * early.
3479 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3482 if (migrate_colo_enabled()) {
3483 /* Notify migration destination that we enable COLO */
3484 qemu_savevm_send_colo_enable(s->to_dst_file);
3487 qemu_savevm_state_setup(s->to_dst_file);
3489 if (qemu_savevm_state_guest_unplug_pending()) {
3490 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3491 MIGRATION_STATUS_WAIT_UNPLUG);
3493 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3494 qemu_savevm_state_guest_unplug_pending()) {
3495 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3498 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG,
3499 MIGRATION_STATUS_ACTIVE);
3502 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3503 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3504 MIGRATION_STATUS_ACTIVE);
3506 trace_migration_thread_setup_complete();
3508 while (migration_is_active(s)) {
3509 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3510 MigIterateState iter_state = migration_iteration_run(s);
3511 if (iter_state == MIG_ITERATE_SKIP) {
3512 continue;
3513 } else if (iter_state == MIG_ITERATE_BREAK) {
3514 break;
3519 * Try to detect any kind of failures, and see whether we
3520 * should stop the migration now.
3522 thr_error = migration_detect_error(s);
3523 if (thr_error == MIG_THR_ERR_FATAL) {
3524 /* Stop migration */
3525 break;
3526 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3528 * Just recovered from a e.g. network failure, reset all
3529 * the local variables. This is important to avoid
3530 * breaking transferred_bytes and bandwidth calculation
3532 update_iteration_initial_status(s);
3535 urgent = migration_rate_limit();
3538 trace_migration_thread_after_loop();
3539 migration_iteration_finish(s);
3540 object_unref(OBJECT(s));
3541 rcu_unregister_thread();
3542 return NULL;
3545 void migrate_fd_connect(MigrationState *s, Error *error_in)
3547 Error *local_err = NULL;
3548 int64_t rate_limit;
3549 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3551 s->expected_downtime = s->parameters.downtime_limit;
3552 if (resume) {
3553 assert(s->cleanup_bh);
3554 } else {
3555 assert(!s->cleanup_bh);
3556 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
3558 if (error_in) {
3559 migrate_fd_error(s, error_in);
3560 migrate_fd_cleanup(s);
3561 return;
3564 if (resume) {
3565 /* This is a resumed migration */
3566 rate_limit = s->parameters.max_postcopy_bandwidth /
3567 XFER_LIMIT_RATIO;
3568 } else {
3569 /* This is a fresh new migration */
3570 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3572 /* Notify before starting migration thread */
3573 notifier_list_notify(&migration_state_notifiers, s);
3576 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3577 qemu_file_set_blocking(s->to_dst_file, true);
3580 * Open the return path. For postcopy, it is used exclusively. For
3581 * precopy, only if user specified "return-path" capability would
3582 * QEMU uses the return path.
3584 if (migrate_postcopy_ram() || migrate_use_return_path()) {
3585 if (open_return_path_on_source(s, !resume)) {
3586 error_report("Unable to open return-path for postcopy");
3587 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3588 migrate_fd_cleanup(s);
3589 return;
3593 if (resume) {
3594 /* Wakeup the main migration thread to do the recovery */
3595 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3596 MIGRATION_STATUS_POSTCOPY_RECOVER);
3597 qemu_sem_post(&s->postcopy_pause_sem);
3598 return;
3601 if (multifd_save_setup(&local_err) != 0) {
3602 error_report_err(local_err);
3603 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3604 MIGRATION_STATUS_FAILED);
3605 migrate_fd_cleanup(s);
3606 return;
3608 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3609 QEMU_THREAD_JOINABLE);
3610 s->migration_thread_running = true;
3613 void migration_global_dump(Monitor *mon)
3615 MigrationState *ms = migrate_get_current();
3617 monitor_printf(mon, "globals:\n");
3618 monitor_printf(mon, "store-global-state: %s\n",
3619 ms->store_global_state ? "on" : "off");
3620 monitor_printf(mon, "only-migratable: %s\n",
3621 only_migratable ? "on" : "off");
3622 monitor_printf(mon, "send-configuration: %s\n",
3623 ms->send_configuration ? "on" : "off");
3624 monitor_printf(mon, "send-section-footer: %s\n",
3625 ms->send_section_footer ? "on" : "off");
3626 monitor_printf(mon, "decompress-error-check: %s\n",
3627 ms->decompress_error_check ? "on" : "off");
3628 monitor_printf(mon, "clear-bitmap-shift: %u\n",
3629 ms->clear_bitmap_shift);
3632 #define DEFINE_PROP_MIG_CAP(name, x) \
3633 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3635 static Property migration_properties[] = {
3636 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3637 store_global_state, true),
3638 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3639 send_configuration, true),
3640 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3641 send_section_footer, true),
3642 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3643 decompress_error_check, true),
3644 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
3645 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
3647 /* Migration parameters */
3648 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3649 parameters.compress_level,
3650 DEFAULT_MIGRATE_COMPRESS_LEVEL),
3651 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3652 parameters.compress_threads,
3653 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3654 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3655 parameters.compress_wait_thread, true),
3656 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3657 parameters.decompress_threads,
3658 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3659 DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
3660 parameters.throttle_trigger_threshold,
3661 DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
3662 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3663 parameters.cpu_throttle_initial,
3664 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3665 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3666 parameters.cpu_throttle_increment,
3667 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3668 DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState,
3669 parameters.cpu_throttle_tailslow, false),
3670 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3671 parameters.max_bandwidth, MAX_THROTTLE),
3672 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3673 parameters.downtime_limit,
3674 DEFAULT_MIGRATE_SET_DOWNTIME),
3675 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3676 parameters.x_checkpoint_delay,
3677 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3678 DEFINE_PROP_UINT8("multifd-channels", MigrationState,
3679 parameters.multifd_channels,
3680 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3681 DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
3682 parameters.multifd_compression,
3683 DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
3684 DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
3685 parameters.multifd_zlib_level,
3686 DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
3687 DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
3688 parameters.multifd_zstd_level,
3689 DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
3690 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3691 parameters.xbzrle_cache_size,
3692 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3693 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3694 parameters.max_postcopy_bandwidth,
3695 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3696 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3697 parameters.max_cpu_throttle,
3698 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3699 DEFINE_PROP_SIZE("announce-initial", MigrationState,
3700 parameters.announce_initial,
3701 DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
3702 DEFINE_PROP_SIZE("announce-max", MigrationState,
3703 parameters.announce_max,
3704 DEFAULT_MIGRATE_ANNOUNCE_MAX),
3705 DEFINE_PROP_SIZE("announce-rounds", MigrationState,
3706 parameters.announce_rounds,
3707 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
3708 DEFINE_PROP_SIZE("announce-step", MigrationState,
3709 parameters.announce_step,
3710 DEFAULT_MIGRATE_ANNOUNCE_STEP),
3712 /* Migration capabilities */
3713 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3714 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3715 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3716 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3717 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3718 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3719 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3720 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3721 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3722 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3723 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3724 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
3726 DEFINE_PROP_END_OF_LIST(),
3729 static void migration_class_init(ObjectClass *klass, void *data)
3731 DeviceClass *dc = DEVICE_CLASS(klass);
3733 dc->user_creatable = false;
3734 device_class_set_props(dc, migration_properties);
3737 static void migration_instance_finalize(Object *obj)
3739 MigrationState *ms = MIGRATION_OBJ(obj);
3740 MigrationParameters *params = &ms->parameters;
3742 qemu_mutex_destroy(&ms->error_mutex);
3743 qemu_mutex_destroy(&ms->qemu_file_lock);
3744 g_free(params->tls_hostname);
3745 g_free(params->tls_creds);
3746 qemu_sem_destroy(&ms->wait_unplug_sem);
3747 qemu_sem_destroy(&ms->rate_limit_sem);
3748 qemu_sem_destroy(&ms->pause_sem);
3749 qemu_sem_destroy(&ms->postcopy_pause_sem);
3750 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3751 qemu_sem_destroy(&ms->rp_state.rp_sem);
3752 error_free(ms->error);
3755 static void migration_instance_init(Object *obj)
3757 MigrationState *ms = MIGRATION_OBJ(obj);
3758 MigrationParameters *params = &ms->parameters;
3760 ms->state = MIGRATION_STATUS_NONE;
3761 ms->mbps = -1;
3762 ms->pages_per_second = -1;
3763 qemu_sem_init(&ms->pause_sem, 0);
3764 qemu_mutex_init(&ms->error_mutex);
3766 params->tls_hostname = g_strdup("");
3767 params->tls_creds = g_strdup("");
3769 /* Set has_* up only for parameter checks */
3770 params->has_compress_level = true;
3771 params->has_compress_threads = true;
3772 params->has_decompress_threads = true;
3773 params->has_throttle_trigger_threshold = true;
3774 params->has_cpu_throttle_initial = true;
3775 params->has_cpu_throttle_increment = true;
3776 params->has_cpu_throttle_tailslow = true;
3777 params->has_max_bandwidth = true;
3778 params->has_downtime_limit = true;
3779 params->has_x_checkpoint_delay = true;
3780 params->has_block_incremental = true;
3781 params->has_multifd_channels = true;
3782 params->has_multifd_compression = true;
3783 params->has_multifd_zlib_level = true;
3784 params->has_multifd_zstd_level = true;
3785 params->has_xbzrle_cache_size = true;
3786 params->has_max_postcopy_bandwidth = true;
3787 params->has_max_cpu_throttle = true;
3788 params->has_announce_initial = true;
3789 params->has_announce_max = true;
3790 params->has_announce_rounds = true;
3791 params->has_announce_step = true;
3793 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3794 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3795 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3796 qemu_sem_init(&ms->rate_limit_sem, 0);
3797 qemu_sem_init(&ms->wait_unplug_sem, 0);
3798 qemu_mutex_init(&ms->qemu_file_lock);
3802 * Return true if check pass, false otherwise. Error will be put
3803 * inside errp if provided.
3805 static bool migration_object_check(MigrationState *ms, Error **errp)
3807 MigrationCapabilityStatusList *head = NULL;
3808 /* Assuming all off */
3809 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3810 int i;
3812 if (!migrate_params_check(&ms->parameters, errp)) {
3813 return false;
3816 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3817 if (ms->enabled_capabilities[i]) {
3818 head = migrate_cap_add(head, i, true);
3822 ret = migrate_caps_check(cap_list, head, errp);
3824 /* It works with head == NULL */
3825 qapi_free_MigrationCapabilityStatusList(head);
3827 return ret;
3830 static const TypeInfo migration_type = {
3831 .name = TYPE_MIGRATION,
3833 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3834 * not created using qdev_new(), it is not attached to the qdev
3835 * device tree, and it is never realized.
3837 * TODO: Make this TYPE_OBJECT once QOM provides something like
3838 * TYPE_DEVICE's "-global" properties.
3840 .parent = TYPE_DEVICE,
3841 .class_init = migration_class_init,
3842 .class_size = sizeof(MigrationClass),
3843 .instance_size = sizeof(MigrationState),
3844 .instance_init = migration_instance_init,
3845 .instance_finalize = migration_instance_finalize,
3848 static void register_migration_types(void)
3850 type_register_static(&migration_type);
3853 type_init(register_migration_types);