COLO: Remove colo_state migration struct
[qemu/kevin.git] / migration / migration.c
blob215e81a190b3610dcab1b926f6a84b2b787d06f6
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 "migration/blocker.h"
20 #include "exec.h"
21 #include "fd.h"
22 #include "socket.h"
23 #include "rdma.h"
24 #include "ram.h"
25 #include "migration/global_state.h"
26 #include "migration/misc.h"
27 #include "migration.h"
28 #include "savevm.h"
29 #include "qemu-file-channel.h"
30 #include "qemu-file.h"
31 #include "migration/vmstate.h"
32 #include "block/block.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-commands-migration.h"
35 #include "qapi/qapi-events-migration.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qapi/qmp/qnull.h"
38 #include "qemu/rcu.h"
39 #include "block.h"
40 #include "postcopy-ram.h"
41 #include "qemu/thread.h"
42 #include "trace.h"
43 #include "exec/target_page.h"
44 #include "io/channel-buffer.h"
45 #include "migration/colo.h"
46 #include "hw/boards.h"
47 #include "monitor/monitor.h"
49 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
51 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
52 * data. */
53 #define BUFFER_DELAY 100
54 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
56 /* Time in milliseconds we are allowed to stop the source,
57 * for sending the last part */
58 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
60 /* Maximum migrate downtime set to 2000 seconds */
61 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
62 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
64 /* Default compression thread count */
65 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
66 /* Default decompression thread count, usually decompression is at
67 * least 4 times as fast as compression.*/
68 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
69 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
70 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
71 /* Define default autoconverge cpu throttle migration parameters */
72 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
73 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
74 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
76 /* Migration XBZRLE default cache size */
77 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
79 /* The delay time (in ms) between two COLO checkpoints */
80 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
81 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
82 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
84 /* Background transfer rate for postcopy, 0 means unlimited, note
85 * that page requests can still exceed this limit.
87 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
89 static NotifierList migration_state_notifiers =
90 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
92 static bool deferred_incoming;
94 /* Messages sent on the return path from destination to source */
95 enum mig_rp_message_type {
96 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
97 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
98 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
100 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
101 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
102 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
103 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
105 MIG_RP_MSG_MAX
108 /* When we add fault tolerance, we could have several
109 migrations at once. For now we don't need to add
110 dynamic creation of migration */
112 static MigrationState *current_migration;
113 static MigrationIncomingState *current_incoming;
115 static bool migration_object_check(MigrationState *ms, Error **errp);
116 static int migration_maybe_pause(MigrationState *s,
117 int *current_active_state,
118 int new_state);
120 void migration_object_init(void)
122 MachineState *ms = MACHINE(qdev_get_machine());
123 Error *err = NULL;
125 /* This can only be called once. */
126 assert(!current_migration);
127 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
130 * Init the migrate incoming object as well no matter whether
131 * we'll use it or not.
133 assert(!current_incoming);
134 current_incoming = g_new0(MigrationIncomingState, 1);
135 current_incoming->state = MIGRATION_STATUS_NONE;
136 current_incoming->postcopy_remote_fds =
137 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
138 qemu_mutex_init(&current_incoming->rp_mutex);
139 qemu_event_init(&current_incoming->main_thread_load_event, false);
140 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
141 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
143 init_dirty_bitmap_incoming_migration();
145 if (!migration_object_check(current_migration, &err)) {
146 error_report_err(err);
147 exit(1);
151 * We cannot really do this in migration_instance_init() since at
152 * that time global properties are not yet applied, then this
153 * value will be definitely replaced by something else.
155 if (ms->enforce_config_section) {
156 current_migration->send_configuration = true;
160 void migration_object_finalize(void)
162 object_unref(OBJECT(current_migration));
165 /* For outgoing */
166 MigrationState *migrate_get_current(void)
168 /* This can only be called after the object created. */
169 assert(current_migration);
170 return current_migration;
173 MigrationIncomingState *migration_incoming_get_current(void)
175 assert(current_incoming);
176 return current_incoming;
179 void migration_incoming_state_destroy(void)
181 struct MigrationIncomingState *mis = migration_incoming_get_current();
183 if (mis->to_src_file) {
184 /* Tell source that we are done */
185 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
186 qemu_fclose(mis->to_src_file);
187 mis->to_src_file = NULL;
190 if (mis->from_src_file) {
191 qemu_fclose(mis->from_src_file);
192 mis->from_src_file = NULL;
194 if (mis->postcopy_remote_fds) {
195 g_array_free(mis->postcopy_remote_fds, TRUE);
196 mis->postcopy_remote_fds = NULL;
199 qemu_event_reset(&mis->main_thread_load_event);
202 static void migrate_generate_event(int new_state)
204 if (migrate_use_events()) {
205 qapi_event_send_migration(new_state);
209 static bool migrate_late_block_activate(void)
211 MigrationState *s;
213 s = migrate_get_current();
215 return s->enabled_capabilities[
216 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
220 * Called on -incoming with a defer: uri.
221 * The migration can be started later after any parameters have been
222 * changed.
224 static void deferred_incoming_migration(Error **errp)
226 if (deferred_incoming) {
227 error_setg(errp, "Incoming migration already deferred");
229 deferred_incoming = true;
233 * Send a message on the return channel back to the source
234 * of the migration.
236 static int migrate_send_rp_message(MigrationIncomingState *mis,
237 enum mig_rp_message_type message_type,
238 uint16_t len, void *data)
240 int ret = 0;
242 trace_migrate_send_rp_message((int)message_type, len);
243 qemu_mutex_lock(&mis->rp_mutex);
246 * It's possible that the file handle got lost due to network
247 * failures.
249 if (!mis->to_src_file) {
250 ret = -EIO;
251 goto error;
254 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
255 qemu_put_be16(mis->to_src_file, len);
256 qemu_put_buffer(mis->to_src_file, data, len);
257 qemu_fflush(mis->to_src_file);
259 /* It's possible that qemu file got error during sending */
260 ret = qemu_file_get_error(mis->to_src_file);
262 error:
263 qemu_mutex_unlock(&mis->rp_mutex);
264 return ret;
267 /* Request a range of pages from the source VM at the given
268 * start address.
269 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
270 * as the last request (a name must have been given previously)
271 * Start: Address offset within the RB
272 * Len: Length in bytes required - must be a multiple of pagesize
274 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
275 ram_addr_t start, size_t len)
277 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
278 size_t msglen = 12; /* start + len */
279 enum mig_rp_message_type msg_type;
281 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
282 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
284 if (rbname) {
285 int rbname_len = strlen(rbname);
286 assert(rbname_len < 256);
288 bufc[msglen++] = rbname_len;
289 memcpy(bufc + msglen, rbname, rbname_len);
290 msglen += rbname_len;
291 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
292 } else {
293 msg_type = MIG_RP_MSG_REQ_PAGES;
296 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
299 static bool migration_colo_enabled;
300 bool migration_incoming_colo_enabled(void)
302 return migration_colo_enabled;
305 void migration_incoming_disable_colo(void)
307 migration_colo_enabled = false;
310 void migration_incoming_enable_colo(void)
312 migration_colo_enabled = true;
315 void qemu_start_incoming_migration(const char *uri, Error **errp)
317 const char *p;
319 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
320 if (!strcmp(uri, "defer")) {
321 deferred_incoming_migration(errp);
322 } else if (strstart(uri, "tcp:", &p)) {
323 tcp_start_incoming_migration(p, errp);
324 #ifdef CONFIG_RDMA
325 } else if (strstart(uri, "rdma:", &p)) {
326 rdma_start_incoming_migration(p, errp);
327 #endif
328 } else if (strstart(uri, "exec:", &p)) {
329 exec_start_incoming_migration(p, errp);
330 } else if (strstart(uri, "unix:", &p)) {
331 unix_start_incoming_migration(p, errp);
332 } else if (strstart(uri, "fd:", &p)) {
333 fd_start_incoming_migration(p, errp);
334 } else {
335 error_setg(errp, "unknown migration protocol: %s", uri);
339 static void process_incoming_migration_bh(void *opaque)
341 Error *local_err = NULL;
342 MigrationIncomingState *mis = opaque;
344 /* If capability late_block_activate is set:
345 * Only fire up the block code now if we're going to restart the
346 * VM, else 'cont' will do it.
347 * This causes file locking to happen; so we don't want it to happen
348 * unless we really are starting the VM.
350 if (!migrate_late_block_activate() ||
351 (autostart && (!global_state_received() ||
352 global_state_get_runstate() == RUN_STATE_RUNNING))) {
353 /* Make sure all file formats flush their mutable metadata.
354 * If we get an error here, just don't restart the VM yet. */
355 bdrv_invalidate_cache_all(&local_err);
356 if (local_err) {
357 error_report_err(local_err);
358 local_err = NULL;
359 autostart = false;
364 * This must happen after all error conditions are dealt with and
365 * we're sure the VM is going to be running on this host.
367 qemu_announce_self();
369 if (multifd_load_cleanup(&local_err) != 0) {
370 error_report_err(local_err);
371 autostart = false;
373 /* If global state section was not received or we are in running
374 state, we need to obey autostart. Any other state is set with
375 runstate_set. */
377 dirty_bitmap_mig_before_vm_start();
379 if (!global_state_received() ||
380 global_state_get_runstate() == RUN_STATE_RUNNING) {
381 if (autostart) {
382 vm_start();
383 } else {
384 runstate_set(RUN_STATE_PAUSED);
386 } else {
387 runstate_set(global_state_get_runstate());
390 * This must happen after any state changes since as soon as an external
391 * observer sees this event they might start to prod at the VM assuming
392 * it's ready to use.
394 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
395 MIGRATION_STATUS_COMPLETED);
396 qemu_bh_delete(mis->bh);
397 migration_incoming_state_destroy();
400 static void process_incoming_migration_co(void *opaque)
402 MigrationIncomingState *mis = migration_incoming_get_current();
403 PostcopyState ps;
404 int ret;
405 Error *local_err = NULL;
407 assert(mis->from_src_file);
408 mis->migration_incoming_co = qemu_coroutine_self();
409 mis->largest_page_size = qemu_ram_pagesize_largest();
410 postcopy_state_set(POSTCOPY_INCOMING_NONE);
411 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
412 MIGRATION_STATUS_ACTIVE);
413 ret = qemu_loadvm_state(mis->from_src_file);
415 ps = postcopy_state_get();
416 trace_process_incoming_migration_co_end(ret, ps);
417 if (ps != POSTCOPY_INCOMING_NONE) {
418 if (ps == POSTCOPY_INCOMING_ADVISE) {
420 * Where a migration had postcopy enabled (and thus went to advise)
421 * but managed to complete within the precopy period, we can use
422 * the normal exit.
424 postcopy_ram_incoming_cleanup(mis);
425 } else if (ret >= 0) {
427 * Postcopy was started, cleanup should happen at the end of the
428 * postcopy thread.
430 trace_process_incoming_migration_co_postcopy_end_main();
431 return;
433 /* Else if something went wrong then just fall out of the normal exit */
436 /* we get COLO info, and know if we are in COLO mode */
437 if (!ret && migration_incoming_colo_enabled()) {
438 /* Make sure all file formats flush their mutable metadata */
439 bdrv_invalidate_cache_all(&local_err);
440 if (local_err) {
441 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
442 MIGRATION_STATUS_FAILED);
443 error_report_err(local_err);
444 exit(EXIT_FAILURE);
447 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
448 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
449 mis->have_colo_incoming_thread = true;
450 qemu_coroutine_yield();
452 /* Wait checkpoint incoming thread exit before free resource */
453 qemu_thread_join(&mis->colo_incoming_thread);
456 if (ret < 0) {
457 Error *local_err = NULL;
459 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
460 MIGRATION_STATUS_FAILED);
461 error_report("load of migration failed: %s", strerror(-ret));
462 qemu_fclose(mis->from_src_file);
463 if (multifd_load_cleanup(&local_err) != 0) {
464 error_report_err(local_err);
466 exit(EXIT_FAILURE);
468 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
469 qemu_bh_schedule(mis->bh);
470 mis->migration_incoming_co = NULL;
473 static void migration_incoming_setup(QEMUFile *f)
475 MigrationIncomingState *mis = migration_incoming_get_current();
477 if (multifd_load_setup() != 0) {
478 /* We haven't been able to create multifd threads
479 nothing better to do */
480 exit(EXIT_FAILURE);
483 if (!mis->from_src_file) {
484 mis->from_src_file = f;
486 qemu_file_set_blocking(f, false);
489 void migration_incoming_process(void)
491 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
492 qemu_coroutine_enter(co);
495 /* Returns true if recovered from a paused migration, otherwise false */
496 static bool postcopy_try_recover(QEMUFile *f)
498 MigrationIncomingState *mis = migration_incoming_get_current();
500 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
501 /* Resumed from a paused postcopy migration */
503 mis->from_src_file = f;
504 /* Postcopy has standalone thread to do vm load */
505 qemu_file_set_blocking(f, true);
507 /* Re-configure the return path */
508 mis->to_src_file = qemu_file_get_return_path(f);
510 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
511 MIGRATION_STATUS_POSTCOPY_RECOVER);
514 * Here, we only wake up the main loading thread (while the
515 * fault thread will still be waiting), so that we can receive
516 * commands from source now, and answer it if needed. The
517 * fault thread will be woken up afterwards until we are sure
518 * that source is ready to reply to page requests.
520 qemu_sem_post(&mis->postcopy_pause_sem_dst);
521 return true;
524 return false;
527 void migration_fd_process_incoming(QEMUFile *f)
529 if (postcopy_try_recover(f)) {
530 return;
533 migration_incoming_setup(f);
534 migration_incoming_process();
537 void migration_ioc_process_incoming(QIOChannel *ioc)
539 MigrationIncomingState *mis = migration_incoming_get_current();
540 bool start_migration;
542 if (!mis->from_src_file) {
543 /* The first connection (multifd may have multiple) */
544 QEMUFile *f = qemu_fopen_channel_input(ioc);
546 /* If it's a recovery, we're done */
547 if (postcopy_try_recover(f)) {
548 return;
551 migration_incoming_setup(f);
554 * Common migration only needs one channel, so we can start
555 * right now. Multifd needs more than one channel, we wait.
557 start_migration = !migrate_use_multifd();
558 } else {
559 /* Multiple connections */
560 assert(migrate_use_multifd());
561 start_migration = multifd_recv_new_channel(ioc);
564 if (start_migration) {
565 migration_incoming_process();
570 * @migration_has_all_channels: We have received all channels that we need
572 * Returns true when we have got connections to all the channels that
573 * we need for migration.
575 bool migration_has_all_channels(void)
577 MigrationIncomingState *mis = migration_incoming_get_current();
578 bool all_channels;
580 all_channels = multifd_recv_all_channels_created();
582 return all_channels && mis->from_src_file != NULL;
586 * Send a 'SHUT' message on the return channel with the given value
587 * to indicate that we've finished with the RP. Non-0 value indicates
588 * error.
590 void migrate_send_rp_shut(MigrationIncomingState *mis,
591 uint32_t value)
593 uint32_t buf;
595 buf = cpu_to_be32(value);
596 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
600 * Send a 'PONG' message on the return channel with the given value
601 * (normally in response to a 'PING')
603 void migrate_send_rp_pong(MigrationIncomingState *mis,
604 uint32_t value)
606 uint32_t buf;
608 buf = cpu_to_be32(value);
609 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
612 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
613 char *block_name)
615 char buf[512];
616 int len;
617 int64_t res;
620 * First, we send the header part. It contains only the len of
621 * idstr, and the idstr itself.
623 len = strlen(block_name);
624 buf[0] = len;
625 memcpy(buf + 1, block_name, len);
627 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
628 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
629 __func__);
630 return;
633 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
636 * Next, we dump the received bitmap to the stream.
638 * TODO: currently we are safe since we are the only one that is
639 * using the to_src_file handle (fault thread is still paused),
640 * and it's ok even not taking the mutex. However the best way is
641 * to take the lock before sending the message header, and release
642 * the lock after sending the bitmap.
644 qemu_mutex_lock(&mis->rp_mutex);
645 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
646 qemu_mutex_unlock(&mis->rp_mutex);
648 trace_migrate_send_rp_recv_bitmap(block_name, res);
651 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
653 uint32_t buf;
655 buf = cpu_to_be32(value);
656 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
659 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
661 MigrationCapabilityStatusList *head = NULL;
662 MigrationCapabilityStatusList *caps;
663 MigrationState *s = migrate_get_current();
664 int i;
666 caps = NULL; /* silence compiler warning */
667 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
668 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
669 if (i == MIGRATION_CAPABILITY_BLOCK) {
670 continue;
672 #endif
673 if (head == NULL) {
674 head = g_malloc0(sizeof(*caps));
675 caps = head;
676 } else {
677 caps->next = g_malloc0(sizeof(*caps));
678 caps = caps->next;
680 caps->value =
681 g_malloc(sizeof(*caps->value));
682 caps->value->capability = i;
683 caps->value->state = s->enabled_capabilities[i];
686 return head;
689 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
691 MigrationParameters *params;
692 MigrationState *s = migrate_get_current();
694 /* TODO use QAPI_CLONE() instead of duplicating it inline */
695 params = g_malloc0(sizeof(*params));
696 params->has_compress_level = true;
697 params->compress_level = s->parameters.compress_level;
698 params->has_compress_threads = true;
699 params->compress_threads = s->parameters.compress_threads;
700 params->has_compress_wait_thread = true;
701 params->compress_wait_thread = s->parameters.compress_wait_thread;
702 params->has_decompress_threads = true;
703 params->decompress_threads = s->parameters.decompress_threads;
704 params->has_cpu_throttle_initial = true;
705 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
706 params->has_cpu_throttle_increment = true;
707 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
708 params->has_tls_creds = true;
709 params->tls_creds = g_strdup(s->parameters.tls_creds);
710 params->has_tls_hostname = true;
711 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
712 params->has_max_bandwidth = true;
713 params->max_bandwidth = s->parameters.max_bandwidth;
714 params->has_downtime_limit = true;
715 params->downtime_limit = s->parameters.downtime_limit;
716 params->has_x_checkpoint_delay = true;
717 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
718 params->has_block_incremental = true;
719 params->block_incremental = s->parameters.block_incremental;
720 params->has_x_multifd_channels = true;
721 params->x_multifd_channels = s->parameters.x_multifd_channels;
722 params->has_x_multifd_page_count = true;
723 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
724 params->has_xbzrle_cache_size = true;
725 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
726 params->has_max_postcopy_bandwidth = true;
727 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
728 params->has_max_cpu_throttle = true;
729 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
731 return params;
735 * Return true if we're already in the middle of a migration
736 * (i.e. any of the active or setup states)
738 static bool migration_is_setup_or_active(int state)
740 switch (state) {
741 case MIGRATION_STATUS_ACTIVE:
742 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
743 case MIGRATION_STATUS_POSTCOPY_PAUSED:
744 case MIGRATION_STATUS_POSTCOPY_RECOVER:
745 case MIGRATION_STATUS_SETUP:
746 case MIGRATION_STATUS_PRE_SWITCHOVER:
747 case MIGRATION_STATUS_DEVICE:
748 return true;
750 default:
751 return false;
756 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
758 info->has_ram = true;
759 info->ram = g_malloc0(sizeof(*info->ram));
760 info->ram->transferred = ram_counters.transferred;
761 info->ram->total = ram_bytes_total();
762 info->ram->duplicate = ram_counters.duplicate;
763 /* legacy value. It is not used anymore */
764 info->ram->skipped = 0;
765 info->ram->normal = ram_counters.normal;
766 info->ram->normal_bytes = ram_counters.normal *
767 qemu_target_page_size();
768 info->ram->mbps = s->mbps;
769 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
770 info->ram->postcopy_requests = ram_counters.postcopy_requests;
771 info->ram->page_size = qemu_target_page_size();
772 info->ram->multifd_bytes = ram_counters.multifd_bytes;
774 if (migrate_use_xbzrle()) {
775 info->has_xbzrle_cache = true;
776 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
777 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
778 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
779 info->xbzrle_cache->pages = xbzrle_counters.pages;
780 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
781 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
782 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
785 if (migrate_use_compression()) {
786 info->has_compression = true;
787 info->compression = g_malloc0(sizeof(*info->compression));
788 info->compression->pages = compression_counters.pages;
789 info->compression->busy = compression_counters.busy;
790 info->compression->busy_rate = compression_counters.busy_rate;
791 info->compression->compressed_size =
792 compression_counters.compressed_size;
793 info->compression->compression_rate =
794 compression_counters.compression_rate;
797 if (cpu_throttle_active()) {
798 info->has_cpu_throttle_percentage = true;
799 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
802 if (s->state != MIGRATION_STATUS_COMPLETED) {
803 info->ram->remaining = ram_bytes_remaining();
804 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
808 static void populate_disk_info(MigrationInfo *info)
810 if (blk_mig_active()) {
811 info->has_disk = true;
812 info->disk = g_malloc0(sizeof(*info->disk));
813 info->disk->transferred = blk_mig_bytes_transferred();
814 info->disk->remaining = blk_mig_bytes_remaining();
815 info->disk->total = blk_mig_bytes_total();
819 static void fill_source_migration_info(MigrationInfo *info)
821 MigrationState *s = migrate_get_current();
823 switch (s->state) {
824 case MIGRATION_STATUS_NONE:
825 /* no migration has happened ever */
826 /* do not overwrite destination migration status */
827 return;
828 break;
829 case MIGRATION_STATUS_SETUP:
830 info->has_status = true;
831 info->has_total_time = false;
832 break;
833 case MIGRATION_STATUS_ACTIVE:
834 case MIGRATION_STATUS_CANCELLING:
835 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
836 case MIGRATION_STATUS_PRE_SWITCHOVER:
837 case MIGRATION_STATUS_DEVICE:
838 case MIGRATION_STATUS_POSTCOPY_PAUSED:
839 case MIGRATION_STATUS_POSTCOPY_RECOVER:
840 /* TODO add some postcopy stats */
841 info->has_status = true;
842 info->has_total_time = true;
843 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
844 - s->start_time;
845 info->has_expected_downtime = true;
846 info->expected_downtime = s->expected_downtime;
847 info->has_setup_time = true;
848 info->setup_time = s->setup_time;
850 populate_ram_info(info, s);
851 populate_disk_info(info);
852 break;
853 case MIGRATION_STATUS_COLO:
854 info->has_status = true;
855 /* TODO: display COLO specific information (checkpoint info etc.) */
856 break;
857 case MIGRATION_STATUS_COMPLETED:
858 info->has_status = true;
859 info->has_total_time = true;
860 info->total_time = s->total_time;
861 info->has_downtime = true;
862 info->downtime = s->downtime;
863 info->has_setup_time = true;
864 info->setup_time = s->setup_time;
866 populate_ram_info(info, s);
867 break;
868 case MIGRATION_STATUS_FAILED:
869 info->has_status = true;
870 if (s->error) {
871 info->has_error_desc = true;
872 info->error_desc = g_strdup(error_get_pretty(s->error));
874 break;
875 case MIGRATION_STATUS_CANCELLED:
876 info->has_status = true;
877 break;
879 info->status = s->state;
883 * @migration_caps_check - check capability validity
885 * @cap_list: old capability list, array of bool
886 * @params: new capabilities to be applied soon
887 * @errp: set *errp if the check failed, with reason
889 * Returns true if check passed, otherwise false.
891 static bool migrate_caps_check(bool *cap_list,
892 MigrationCapabilityStatusList *params,
893 Error **errp)
895 MigrationCapabilityStatusList *cap;
896 bool old_postcopy_cap;
897 MigrationIncomingState *mis = migration_incoming_get_current();
899 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
901 for (cap = params; cap; cap = cap->next) {
902 cap_list[cap->value->capability] = cap->value->state;
905 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
906 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
907 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
908 "block migration");
909 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
910 return false;
912 #endif
914 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
915 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
916 /* The decompression threads asynchronously write into RAM
917 * rather than use the atomic copies needed to avoid
918 * userfaulting. It should be possible to fix the decompression
919 * threads for compatibility in future.
921 error_setg(errp, "Postcopy is not currently compatible "
922 "with compression");
923 return false;
926 /* This check is reasonably expensive, so only when it's being
927 * set the first time, also it's only the destination that needs
928 * special support.
930 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
931 !postcopy_ram_supported_by_host(mis)) {
932 /* postcopy_ram_supported_by_host will have emitted a more
933 * detailed message
935 error_setg(errp, "Postcopy is not supported");
936 return false;
940 return true;
943 static void fill_destination_migration_info(MigrationInfo *info)
945 MigrationIncomingState *mis = migration_incoming_get_current();
947 switch (mis->state) {
948 case MIGRATION_STATUS_NONE:
949 return;
950 break;
951 case MIGRATION_STATUS_SETUP:
952 case MIGRATION_STATUS_CANCELLING:
953 case MIGRATION_STATUS_CANCELLED:
954 case MIGRATION_STATUS_ACTIVE:
955 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
956 case MIGRATION_STATUS_POSTCOPY_PAUSED:
957 case MIGRATION_STATUS_POSTCOPY_RECOVER:
958 case MIGRATION_STATUS_FAILED:
959 case MIGRATION_STATUS_COLO:
960 info->has_status = true;
961 break;
962 case MIGRATION_STATUS_COMPLETED:
963 info->has_status = true;
964 fill_destination_postcopy_migration_info(info);
965 break;
967 info->status = mis->state;
970 MigrationInfo *qmp_query_migrate(Error **errp)
972 MigrationInfo *info = g_malloc0(sizeof(*info));
974 fill_destination_migration_info(info);
975 fill_source_migration_info(info);
977 return info;
980 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
981 Error **errp)
983 MigrationState *s = migrate_get_current();
984 MigrationCapabilityStatusList *cap;
985 bool cap_list[MIGRATION_CAPABILITY__MAX];
987 if (migration_is_setup_or_active(s->state)) {
988 error_setg(errp, QERR_MIGRATION_ACTIVE);
989 return;
992 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
993 if (!migrate_caps_check(cap_list, params, errp)) {
994 return;
997 for (cap = params; cap; cap = cap->next) {
998 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1003 * Check whether the parameters are valid. Error will be put into errp
1004 * (if provided). Return true if valid, otherwise false.
1006 static bool migrate_params_check(MigrationParameters *params, Error **errp)
1008 if (params->has_compress_level &&
1009 (params->compress_level > 9)) {
1010 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1011 "is invalid, it should be in the range of 0 to 9");
1012 return false;
1015 if (params->has_compress_threads && (params->compress_threads < 1)) {
1016 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1017 "compress_threads",
1018 "is invalid, it should be in the range of 1 to 255");
1019 return false;
1022 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1023 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1024 "decompress_threads",
1025 "is invalid, it should be in the range of 1 to 255");
1026 return false;
1029 if (params->has_cpu_throttle_initial &&
1030 (params->cpu_throttle_initial < 1 ||
1031 params->cpu_throttle_initial > 99)) {
1032 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1033 "cpu_throttle_initial",
1034 "an integer in the range of 1 to 99");
1035 return false;
1038 if (params->has_cpu_throttle_increment &&
1039 (params->cpu_throttle_increment < 1 ||
1040 params->cpu_throttle_increment > 99)) {
1041 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1042 "cpu_throttle_increment",
1043 "an integer in the range of 1 to 99");
1044 return false;
1047 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1048 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
1049 " range of 0 to %zu bytes/second", SIZE_MAX);
1050 return false;
1053 if (params->has_downtime_limit &&
1054 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1055 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1056 "the range of 0 to %d milliseconds",
1057 MAX_MIGRATE_DOWNTIME);
1058 return false;
1061 /* x_checkpoint_delay is now always positive */
1063 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
1064 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1065 "multifd_channels",
1066 "is invalid, it should be in the range of 1 to 255");
1067 return false;
1069 if (params->has_x_multifd_page_count &&
1070 (params->x_multifd_page_count < 1 ||
1071 params->x_multifd_page_count > 10000)) {
1072 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1073 "multifd_page_count",
1074 "is invalid, it should be in the range of 1 to 10000");
1075 return false;
1078 if (params->has_xbzrle_cache_size &&
1079 (params->xbzrle_cache_size < qemu_target_page_size() ||
1080 !is_power_of_2(params->xbzrle_cache_size))) {
1081 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1082 "xbzrle_cache_size",
1083 "is invalid, it should be bigger than target page size"
1084 " and a power of two");
1085 return false;
1088 if (params->has_max_cpu_throttle &&
1089 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1090 params->max_cpu_throttle > 99)) {
1091 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1092 "max_cpu_throttle",
1093 "an integer in the range of cpu_throttle_initial to 99");
1094 return false;
1097 return true;
1100 static void migrate_params_test_apply(MigrateSetParameters *params,
1101 MigrationParameters *dest)
1103 *dest = migrate_get_current()->parameters;
1105 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1107 if (params->has_compress_level) {
1108 dest->compress_level = params->compress_level;
1111 if (params->has_compress_threads) {
1112 dest->compress_threads = params->compress_threads;
1115 if (params->has_compress_wait_thread) {
1116 dest->compress_wait_thread = params->compress_wait_thread;
1119 if (params->has_decompress_threads) {
1120 dest->decompress_threads = params->decompress_threads;
1123 if (params->has_cpu_throttle_initial) {
1124 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1127 if (params->has_cpu_throttle_increment) {
1128 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1131 if (params->has_tls_creds) {
1132 assert(params->tls_creds->type == QTYPE_QSTRING);
1133 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1136 if (params->has_tls_hostname) {
1137 assert(params->tls_hostname->type == QTYPE_QSTRING);
1138 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1141 if (params->has_max_bandwidth) {
1142 dest->max_bandwidth = params->max_bandwidth;
1145 if (params->has_downtime_limit) {
1146 dest->downtime_limit = params->downtime_limit;
1149 if (params->has_x_checkpoint_delay) {
1150 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1153 if (params->has_block_incremental) {
1154 dest->block_incremental = params->block_incremental;
1156 if (params->has_x_multifd_channels) {
1157 dest->x_multifd_channels = params->x_multifd_channels;
1159 if (params->has_x_multifd_page_count) {
1160 dest->x_multifd_page_count = params->x_multifd_page_count;
1162 if (params->has_xbzrle_cache_size) {
1163 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1165 if (params->has_max_postcopy_bandwidth) {
1166 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1168 if (params->has_max_cpu_throttle) {
1169 dest->max_cpu_throttle = params->max_cpu_throttle;
1173 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1175 MigrationState *s = migrate_get_current();
1177 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1179 if (params->has_compress_level) {
1180 s->parameters.compress_level = params->compress_level;
1183 if (params->has_compress_threads) {
1184 s->parameters.compress_threads = params->compress_threads;
1187 if (params->has_compress_wait_thread) {
1188 s->parameters.compress_wait_thread = params->compress_wait_thread;
1191 if (params->has_decompress_threads) {
1192 s->parameters.decompress_threads = params->decompress_threads;
1195 if (params->has_cpu_throttle_initial) {
1196 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1199 if (params->has_cpu_throttle_increment) {
1200 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1203 if (params->has_tls_creds) {
1204 g_free(s->parameters.tls_creds);
1205 assert(params->tls_creds->type == QTYPE_QSTRING);
1206 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1209 if (params->has_tls_hostname) {
1210 g_free(s->parameters.tls_hostname);
1211 assert(params->tls_hostname->type == QTYPE_QSTRING);
1212 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1215 if (params->has_max_bandwidth) {
1216 s->parameters.max_bandwidth = params->max_bandwidth;
1217 if (s->to_dst_file) {
1218 qemu_file_set_rate_limit(s->to_dst_file,
1219 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1223 if (params->has_downtime_limit) {
1224 s->parameters.downtime_limit = params->downtime_limit;
1227 if (params->has_x_checkpoint_delay) {
1228 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1229 if (migration_in_colo_state()) {
1230 colo_checkpoint_notify(s);
1234 if (params->has_block_incremental) {
1235 s->parameters.block_incremental = params->block_incremental;
1237 if (params->has_x_multifd_channels) {
1238 s->parameters.x_multifd_channels = params->x_multifd_channels;
1240 if (params->has_x_multifd_page_count) {
1241 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
1243 if (params->has_xbzrle_cache_size) {
1244 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1245 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1247 if (params->has_max_postcopy_bandwidth) {
1248 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1250 if (params->has_max_cpu_throttle) {
1251 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1255 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1257 MigrationParameters tmp;
1259 /* TODO Rewrite "" to null instead */
1260 if (params->has_tls_creds
1261 && params->tls_creds->type == QTYPE_QNULL) {
1262 qobject_unref(params->tls_creds->u.n);
1263 params->tls_creds->type = QTYPE_QSTRING;
1264 params->tls_creds->u.s = strdup("");
1266 /* TODO Rewrite "" to null instead */
1267 if (params->has_tls_hostname
1268 && params->tls_hostname->type == QTYPE_QNULL) {
1269 qobject_unref(params->tls_hostname->u.n);
1270 params->tls_hostname->type = QTYPE_QSTRING;
1271 params->tls_hostname->u.s = strdup("");
1274 migrate_params_test_apply(params, &tmp);
1276 if (!migrate_params_check(&tmp, errp)) {
1277 /* Invalid parameter */
1278 return;
1281 migrate_params_apply(params, errp);
1285 void qmp_migrate_start_postcopy(Error **errp)
1287 MigrationState *s = migrate_get_current();
1289 if (!migrate_postcopy()) {
1290 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1291 " the start of migration");
1292 return;
1295 if (s->state == MIGRATION_STATUS_NONE) {
1296 error_setg(errp, "Postcopy must be started after migration has been"
1297 " started");
1298 return;
1301 * we don't error if migration has finished since that would be racy
1302 * with issuing this command.
1304 atomic_set(&s->start_postcopy, true);
1307 /* shared migration helpers */
1309 void migrate_set_state(int *state, int old_state, int new_state)
1311 assert(new_state < MIGRATION_STATUS__MAX);
1312 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1313 trace_migrate_set_state(MigrationStatus_str(new_state));
1314 migrate_generate_event(new_state);
1318 static MigrationCapabilityStatusList *migrate_cap_add(
1319 MigrationCapabilityStatusList *list,
1320 MigrationCapability index,
1321 bool state)
1323 MigrationCapabilityStatusList *cap;
1325 cap = g_new0(MigrationCapabilityStatusList, 1);
1326 cap->value = g_new0(MigrationCapabilityStatus, 1);
1327 cap->value->capability = index;
1328 cap->value->state = state;
1329 cap->next = list;
1331 return cap;
1334 void migrate_set_block_enabled(bool value, Error **errp)
1336 MigrationCapabilityStatusList *cap;
1338 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1339 qmp_migrate_set_capabilities(cap, errp);
1340 qapi_free_MigrationCapabilityStatusList(cap);
1343 static void migrate_set_block_incremental(MigrationState *s, bool value)
1345 s->parameters.block_incremental = value;
1348 static void block_cleanup_parameters(MigrationState *s)
1350 if (s->must_remove_block_options) {
1351 /* setting to false can never fail */
1352 migrate_set_block_enabled(false, &error_abort);
1353 migrate_set_block_incremental(s, false);
1354 s->must_remove_block_options = false;
1358 static void migrate_fd_cleanup(void *opaque)
1360 MigrationState *s = opaque;
1362 qemu_bh_delete(s->cleanup_bh);
1363 s->cleanup_bh = NULL;
1365 qemu_savevm_state_cleanup();
1367 if (s->to_dst_file) {
1368 Error *local_err = NULL;
1369 QEMUFile *tmp;
1371 trace_migrate_fd_cleanup();
1372 qemu_mutex_unlock_iothread();
1373 if (s->migration_thread_running) {
1374 qemu_thread_join(&s->thread);
1375 s->migration_thread_running = false;
1377 qemu_mutex_lock_iothread();
1379 if (multifd_save_cleanup(&local_err) != 0) {
1380 error_report_err(local_err);
1382 qemu_mutex_lock(&s->qemu_file_lock);
1383 tmp = s->to_dst_file;
1384 s->to_dst_file = NULL;
1385 qemu_mutex_unlock(&s->qemu_file_lock);
1387 * Close the file handle without the lock to make sure the
1388 * critical section won't block for long.
1390 qemu_fclose(tmp);
1393 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1394 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1396 if (s->state == MIGRATION_STATUS_CANCELLING) {
1397 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1398 MIGRATION_STATUS_CANCELLED);
1401 if (s->error) {
1402 /* It is used on info migrate. We can't free it */
1403 error_report_err(error_copy(s->error));
1405 notifier_list_notify(&migration_state_notifiers, s);
1406 block_cleanup_parameters(s);
1409 void migrate_set_error(MigrationState *s, const Error *error)
1411 qemu_mutex_lock(&s->error_mutex);
1412 if (!s->error) {
1413 s->error = error_copy(error);
1415 qemu_mutex_unlock(&s->error_mutex);
1418 void migrate_fd_error(MigrationState *s, const Error *error)
1420 trace_migrate_fd_error(error_get_pretty(error));
1421 assert(s->to_dst_file == NULL);
1422 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1423 MIGRATION_STATUS_FAILED);
1424 migrate_set_error(s, error);
1427 static void migrate_fd_cancel(MigrationState *s)
1429 int old_state ;
1430 QEMUFile *f = migrate_get_current()->to_dst_file;
1431 trace_migrate_fd_cancel();
1433 if (s->rp_state.from_dst_file) {
1434 /* shutdown the rp socket, so causing the rp thread to shutdown */
1435 qemu_file_shutdown(s->rp_state.from_dst_file);
1438 do {
1439 old_state = s->state;
1440 if (!migration_is_setup_or_active(old_state)) {
1441 break;
1443 /* If the migration is paused, kick it out of the pause */
1444 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1445 qemu_sem_post(&s->pause_sem);
1447 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1448 } while (s->state != MIGRATION_STATUS_CANCELLING);
1451 * If we're unlucky the migration code might be stuck somewhere in a
1452 * send/write while the network has failed and is waiting to timeout;
1453 * if we've got shutdown(2) available then we can force it to quit.
1454 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1455 * called in a bh, so there is no race against this cancel.
1457 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1458 qemu_file_shutdown(f);
1460 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1461 Error *local_err = NULL;
1463 bdrv_invalidate_cache_all(&local_err);
1464 if (local_err) {
1465 error_report_err(local_err);
1466 } else {
1467 s->block_inactive = false;
1472 void add_migration_state_change_notifier(Notifier *notify)
1474 notifier_list_add(&migration_state_notifiers, notify);
1477 void remove_migration_state_change_notifier(Notifier *notify)
1479 notifier_remove(notify);
1482 bool migration_in_setup(MigrationState *s)
1484 return s->state == MIGRATION_STATUS_SETUP;
1487 bool migration_has_finished(MigrationState *s)
1489 return s->state == MIGRATION_STATUS_COMPLETED;
1492 bool migration_has_failed(MigrationState *s)
1494 return (s->state == MIGRATION_STATUS_CANCELLED ||
1495 s->state == MIGRATION_STATUS_FAILED);
1498 bool migration_in_postcopy(void)
1500 MigrationState *s = migrate_get_current();
1502 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1505 bool migration_in_postcopy_after_devices(MigrationState *s)
1507 return migration_in_postcopy() && s->postcopy_after_devices;
1510 bool migration_is_idle(void)
1512 MigrationState *s = migrate_get_current();
1514 switch (s->state) {
1515 case MIGRATION_STATUS_NONE:
1516 case MIGRATION_STATUS_CANCELLED:
1517 case MIGRATION_STATUS_COMPLETED:
1518 case MIGRATION_STATUS_FAILED:
1519 return true;
1520 case MIGRATION_STATUS_SETUP:
1521 case MIGRATION_STATUS_CANCELLING:
1522 case MIGRATION_STATUS_ACTIVE:
1523 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1524 case MIGRATION_STATUS_COLO:
1525 case MIGRATION_STATUS_PRE_SWITCHOVER:
1526 case MIGRATION_STATUS_DEVICE:
1527 return false;
1528 case MIGRATION_STATUS__MAX:
1529 g_assert_not_reached();
1532 return false;
1535 void migrate_init(MigrationState *s)
1538 * Reinitialise all migration state, except
1539 * parameters/capabilities that the user set, and
1540 * locks.
1542 s->bytes_xfer = 0;
1543 s->xfer_limit = 0;
1544 s->cleanup_bh = 0;
1545 s->to_dst_file = NULL;
1546 s->state = MIGRATION_STATUS_NONE;
1547 s->rp_state.from_dst_file = NULL;
1548 s->rp_state.error = false;
1549 s->mbps = 0.0;
1550 s->downtime = 0;
1551 s->expected_downtime = 0;
1552 s->setup_time = 0;
1553 s->start_postcopy = false;
1554 s->postcopy_after_devices = false;
1555 s->migration_thread_running = false;
1556 error_free(s->error);
1557 s->error = NULL;
1559 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1561 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1562 s->total_time = 0;
1563 s->vm_was_running = false;
1564 s->iteration_initial_bytes = 0;
1565 s->threshold_size = 0;
1568 static GSList *migration_blockers;
1570 int migrate_add_blocker(Error *reason, Error **errp)
1572 if (migrate_get_current()->only_migratable) {
1573 error_propagate(errp, error_copy(reason));
1574 error_prepend(errp, "disallowing migration blocker "
1575 "(--only_migratable) for: ");
1576 return -EACCES;
1579 if (migration_is_idle()) {
1580 migration_blockers = g_slist_prepend(migration_blockers, reason);
1581 return 0;
1584 error_propagate(errp, error_copy(reason));
1585 error_prepend(errp, "disallowing migration blocker (migration in "
1586 "progress) for: ");
1587 return -EBUSY;
1590 void migrate_del_blocker(Error *reason)
1592 migration_blockers = g_slist_remove(migration_blockers, reason);
1595 void qmp_migrate_incoming(const char *uri, Error **errp)
1597 Error *local_err = NULL;
1598 static bool once = true;
1600 if (!deferred_incoming) {
1601 error_setg(errp, "For use with '-incoming defer'");
1602 return;
1604 if (!once) {
1605 error_setg(errp, "The incoming migration has already been started");
1608 qemu_start_incoming_migration(uri, &local_err);
1610 if (local_err) {
1611 error_propagate(errp, local_err);
1612 return;
1615 once = false;
1618 void qmp_migrate_recover(const char *uri, Error **errp)
1620 MigrationIncomingState *mis = migration_incoming_get_current();
1622 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1623 error_setg(errp, "Migrate recover can only be run "
1624 "when postcopy is paused.");
1625 return;
1628 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1629 false, true) == true) {
1630 error_setg(errp, "Migrate recovery is triggered already");
1631 return;
1635 * Note that this call will never start a real migration; it will
1636 * only re-setup the migration stream and poke existing migration
1637 * to continue using that newly established channel.
1639 qemu_start_incoming_migration(uri, errp);
1642 void qmp_migrate_pause(Error **errp)
1644 MigrationState *ms = migrate_get_current();
1645 MigrationIncomingState *mis = migration_incoming_get_current();
1646 int ret;
1648 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1649 /* Source side, during postcopy */
1650 qemu_mutex_lock(&ms->qemu_file_lock);
1651 ret = qemu_file_shutdown(ms->to_dst_file);
1652 qemu_mutex_unlock(&ms->qemu_file_lock);
1653 if (ret) {
1654 error_setg(errp, "Failed to pause source migration");
1656 return;
1659 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1660 ret = qemu_file_shutdown(mis->from_src_file);
1661 if (ret) {
1662 error_setg(errp, "Failed to pause destination migration");
1664 return;
1667 error_setg(errp, "migrate-pause is currently only supported "
1668 "during postcopy-active state");
1671 bool migration_is_blocked(Error **errp)
1673 if (qemu_savevm_state_blocked(errp)) {
1674 return true;
1677 if (migration_blockers) {
1678 error_propagate(errp, error_copy(migration_blockers->data));
1679 return true;
1682 return false;
1685 /* Returns true if continue to migrate, or false if error detected */
1686 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1687 bool resume, Error **errp)
1689 Error *local_err = NULL;
1691 if (resume) {
1692 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1693 error_setg(errp, "Cannot resume if there is no "
1694 "paused migration");
1695 return false;
1699 * Postcopy recovery won't work well with release-ram
1700 * capability since release-ram will drop the page buffer as
1701 * long as the page is put into the send buffer. So if there
1702 * is a network failure happened, any page buffers that have
1703 * not yet reached the destination VM but have already been
1704 * sent from the source VM will be lost forever. Let's refuse
1705 * the client from resuming such a postcopy migration.
1706 * Luckily release-ram was designed to only be used when src
1707 * and destination VMs are on the same host, so it should be
1708 * fine.
1710 if (migrate_release_ram()) {
1711 error_setg(errp, "Postcopy recovery cannot work "
1712 "when release-ram capability is set");
1713 return false;
1716 /* This is a resume, skip init status */
1717 return true;
1720 if (migration_is_setup_or_active(s->state) ||
1721 s->state == MIGRATION_STATUS_CANCELLING ||
1722 s->state == MIGRATION_STATUS_COLO) {
1723 error_setg(errp, QERR_MIGRATION_ACTIVE);
1724 return false;
1727 if (runstate_check(RUN_STATE_INMIGRATE)) {
1728 error_setg(errp, "Guest is waiting for an incoming migration");
1729 return false;
1732 if (migration_is_blocked(errp)) {
1733 return false;
1736 if (blk || blk_inc) {
1737 if (migrate_use_block() || migrate_use_block_incremental()) {
1738 error_setg(errp, "Command options are incompatible with "
1739 "current migration capabilities");
1740 return false;
1742 migrate_set_block_enabled(true, &local_err);
1743 if (local_err) {
1744 error_propagate(errp, local_err);
1745 return false;
1747 s->must_remove_block_options = true;
1750 if (blk_inc) {
1751 migrate_set_block_incremental(s, true);
1754 migrate_init(s);
1756 return true;
1759 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1760 bool has_inc, bool inc, bool has_detach, bool detach,
1761 bool has_resume, bool resume, Error **errp)
1763 Error *local_err = NULL;
1764 MigrationState *s = migrate_get_current();
1765 const char *p;
1767 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1768 has_resume && resume, errp)) {
1769 /* Error detected, put into errp */
1770 return;
1773 if (strstart(uri, "tcp:", &p)) {
1774 tcp_start_outgoing_migration(s, p, &local_err);
1775 #ifdef CONFIG_RDMA
1776 } else if (strstart(uri, "rdma:", &p)) {
1777 rdma_start_outgoing_migration(s, p, &local_err);
1778 #endif
1779 } else if (strstart(uri, "exec:", &p)) {
1780 exec_start_outgoing_migration(s, p, &local_err);
1781 } else if (strstart(uri, "unix:", &p)) {
1782 unix_start_outgoing_migration(s, p, &local_err);
1783 } else if (strstart(uri, "fd:", &p)) {
1784 fd_start_outgoing_migration(s, p, &local_err);
1785 } else {
1786 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1787 "a valid migration protocol");
1788 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1789 MIGRATION_STATUS_FAILED);
1790 block_cleanup_parameters(s);
1791 return;
1794 if (local_err) {
1795 migrate_fd_error(s, local_err);
1796 error_propagate(errp, local_err);
1797 return;
1801 void qmp_migrate_cancel(Error **errp)
1803 migrate_fd_cancel(migrate_get_current());
1806 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1808 MigrationState *s = migrate_get_current();
1809 if (s->state != state) {
1810 error_setg(errp, "Migration not in expected state: %s",
1811 MigrationStatus_str(s->state));
1812 return;
1814 qemu_sem_post(&s->pause_sem);
1817 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1819 MigrateSetParameters p = {
1820 .has_xbzrle_cache_size = true,
1821 .xbzrle_cache_size = value,
1824 qmp_migrate_set_parameters(&p, errp);
1827 int64_t qmp_query_migrate_cache_size(Error **errp)
1829 return migrate_xbzrle_cache_size();
1832 void qmp_migrate_set_speed(int64_t value, Error **errp)
1834 MigrateSetParameters p = {
1835 .has_max_bandwidth = true,
1836 .max_bandwidth = value,
1839 qmp_migrate_set_parameters(&p, errp);
1842 void qmp_migrate_set_downtime(double value, Error **errp)
1844 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1845 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1846 "the range of 0 to %d seconds",
1847 MAX_MIGRATE_DOWNTIME_SECONDS);
1848 return;
1851 value *= 1000; /* Convert to milliseconds */
1852 value = MAX(0, MIN(INT64_MAX, value));
1854 MigrateSetParameters p = {
1855 .has_downtime_limit = true,
1856 .downtime_limit = value,
1859 qmp_migrate_set_parameters(&p, errp);
1862 bool migrate_release_ram(void)
1864 MigrationState *s;
1866 s = migrate_get_current();
1868 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1871 bool migrate_postcopy_ram(void)
1873 MigrationState *s;
1875 s = migrate_get_current();
1877 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1880 bool migrate_postcopy(void)
1882 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1885 bool migrate_auto_converge(void)
1887 MigrationState *s;
1889 s = migrate_get_current();
1891 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1894 bool migrate_zero_blocks(void)
1896 MigrationState *s;
1898 s = migrate_get_current();
1900 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1903 bool migrate_postcopy_blocktime(void)
1905 MigrationState *s;
1907 s = migrate_get_current();
1909 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
1912 bool migrate_use_compression(void)
1914 MigrationState *s;
1916 s = migrate_get_current();
1918 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1921 int migrate_compress_level(void)
1923 MigrationState *s;
1925 s = migrate_get_current();
1927 return s->parameters.compress_level;
1930 int migrate_compress_threads(void)
1932 MigrationState *s;
1934 s = migrate_get_current();
1936 return s->parameters.compress_threads;
1939 int migrate_compress_wait_thread(void)
1941 MigrationState *s;
1943 s = migrate_get_current();
1945 return s->parameters.compress_wait_thread;
1948 int migrate_decompress_threads(void)
1950 MigrationState *s;
1952 s = migrate_get_current();
1954 return s->parameters.decompress_threads;
1957 bool migrate_dirty_bitmaps(void)
1959 MigrationState *s;
1961 s = migrate_get_current();
1963 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1966 bool migrate_use_events(void)
1968 MigrationState *s;
1970 s = migrate_get_current();
1972 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1975 bool migrate_use_multifd(void)
1977 MigrationState *s;
1979 s = migrate_get_current();
1981 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1984 bool migrate_pause_before_switchover(void)
1986 MigrationState *s;
1988 s = migrate_get_current();
1990 return s->enabled_capabilities[
1991 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1994 int migrate_multifd_channels(void)
1996 MigrationState *s;
1998 s = migrate_get_current();
2000 return s->parameters.x_multifd_channels;
2003 int migrate_multifd_page_count(void)
2005 MigrationState *s;
2007 s = migrate_get_current();
2009 return s->parameters.x_multifd_page_count;
2012 int migrate_use_xbzrle(void)
2014 MigrationState *s;
2016 s = migrate_get_current();
2018 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2021 int64_t migrate_xbzrle_cache_size(void)
2023 MigrationState *s;
2025 s = migrate_get_current();
2027 return s->parameters.xbzrle_cache_size;
2030 static int64_t migrate_max_postcopy_bandwidth(void)
2032 MigrationState *s;
2034 s = migrate_get_current();
2036 return s->parameters.max_postcopy_bandwidth;
2039 bool migrate_use_block(void)
2041 MigrationState *s;
2043 s = migrate_get_current();
2045 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2048 bool migrate_use_return_path(void)
2050 MigrationState *s;
2052 s = migrate_get_current();
2054 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2057 bool migrate_use_block_incremental(void)
2059 MigrationState *s;
2061 s = migrate_get_current();
2063 return s->parameters.block_incremental;
2066 /* migration thread support */
2068 * Something bad happened to the RP stream, mark an error
2069 * The caller shall print or trace something to indicate why
2071 static void mark_source_rp_bad(MigrationState *s)
2073 s->rp_state.error = true;
2076 static struct rp_cmd_args {
2077 ssize_t len; /* -1 = variable */
2078 const char *name;
2079 } rp_cmd_args[] = {
2080 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2081 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2082 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2083 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2084 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2085 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2086 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2087 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2091 * Process a request for pages received on the return path,
2092 * We're allowed to send more than requested (e.g. to round to our page size)
2093 * and we don't need to send pages that have already been sent.
2095 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2096 ram_addr_t start, size_t len)
2098 long our_host_ps = getpagesize();
2100 trace_migrate_handle_rp_req_pages(rbname, start, len);
2103 * Since we currently insist on matching page sizes, just sanity check
2104 * we're being asked for whole host pages.
2106 if (start & (our_host_ps-1) ||
2107 (len & (our_host_ps-1))) {
2108 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2109 " len: %zd", __func__, start, len);
2110 mark_source_rp_bad(ms);
2111 return;
2114 if (ram_save_queue_pages(rbname, start, len)) {
2115 mark_source_rp_bad(ms);
2119 /* Return true to retry, false to quit */
2120 static bool postcopy_pause_return_path_thread(MigrationState *s)
2122 trace_postcopy_pause_return_path();
2124 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2126 trace_postcopy_pause_return_path_continued();
2128 return true;
2131 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2133 RAMBlock *block = qemu_ram_block_by_name(block_name);
2135 if (!block) {
2136 error_report("%s: invalid block name '%s'", __func__, block_name);
2137 return -EINVAL;
2140 /* Fetch the received bitmap and refresh the dirty bitmap */
2141 return ram_dirty_bitmap_reload(s, block);
2144 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2146 trace_source_return_path_thread_resume_ack(value);
2148 if (value != MIGRATION_RESUME_ACK_VALUE) {
2149 error_report("%s: illegal resume_ack value %"PRIu32,
2150 __func__, value);
2151 return -1;
2154 /* Now both sides are active. */
2155 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2156 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2158 /* Notify send thread that time to continue send pages */
2159 qemu_sem_post(&s->rp_state.rp_sem);
2161 return 0;
2165 * Handles messages sent on the return path towards the source VM
2168 static void *source_return_path_thread(void *opaque)
2170 MigrationState *ms = opaque;
2171 QEMUFile *rp = ms->rp_state.from_dst_file;
2172 uint16_t header_len, header_type;
2173 uint8_t buf[512];
2174 uint32_t tmp32, sibling_error;
2175 ram_addr_t start = 0; /* =0 to silence warning */
2176 size_t len = 0, expected_len;
2177 int res;
2179 trace_source_return_path_thread_entry();
2180 rcu_register_thread();
2182 retry:
2183 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2184 migration_is_setup_or_active(ms->state)) {
2185 trace_source_return_path_thread_loop_top();
2186 header_type = qemu_get_be16(rp);
2187 header_len = qemu_get_be16(rp);
2189 if (qemu_file_get_error(rp)) {
2190 mark_source_rp_bad(ms);
2191 goto out;
2194 if (header_type >= MIG_RP_MSG_MAX ||
2195 header_type == MIG_RP_MSG_INVALID) {
2196 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2197 header_type, header_len);
2198 mark_source_rp_bad(ms);
2199 goto out;
2202 if ((rp_cmd_args[header_type].len != -1 &&
2203 header_len != rp_cmd_args[header_type].len) ||
2204 header_len > sizeof(buf)) {
2205 error_report("RP: Received '%s' message (0x%04x) with"
2206 "incorrect length %d expecting %zu",
2207 rp_cmd_args[header_type].name, header_type, header_len,
2208 (size_t)rp_cmd_args[header_type].len);
2209 mark_source_rp_bad(ms);
2210 goto out;
2213 /* We know we've got a valid header by this point */
2214 res = qemu_get_buffer(rp, buf, header_len);
2215 if (res != header_len) {
2216 error_report("RP: Failed reading data for message 0x%04x"
2217 " read %d expected %d",
2218 header_type, res, header_len);
2219 mark_source_rp_bad(ms);
2220 goto out;
2223 /* OK, we have the message and the data */
2224 switch (header_type) {
2225 case MIG_RP_MSG_SHUT:
2226 sibling_error = ldl_be_p(buf);
2227 trace_source_return_path_thread_shut(sibling_error);
2228 if (sibling_error) {
2229 error_report("RP: Sibling indicated error %d", sibling_error);
2230 mark_source_rp_bad(ms);
2233 * We'll let the main thread deal with closing the RP
2234 * we could do a shutdown(2) on it, but we're the only user
2235 * anyway, so there's nothing gained.
2237 goto out;
2239 case MIG_RP_MSG_PONG:
2240 tmp32 = ldl_be_p(buf);
2241 trace_source_return_path_thread_pong(tmp32);
2242 break;
2244 case MIG_RP_MSG_REQ_PAGES:
2245 start = ldq_be_p(buf);
2246 len = ldl_be_p(buf + 8);
2247 migrate_handle_rp_req_pages(ms, NULL, start, len);
2248 break;
2250 case MIG_RP_MSG_REQ_PAGES_ID:
2251 expected_len = 12 + 1; /* header + termination */
2253 if (header_len >= expected_len) {
2254 start = ldq_be_p(buf);
2255 len = ldl_be_p(buf + 8);
2256 /* Now we expect an idstr */
2257 tmp32 = buf[12]; /* Length of the following idstr */
2258 buf[13 + tmp32] = '\0';
2259 expected_len += tmp32;
2261 if (header_len != expected_len) {
2262 error_report("RP: Req_Page_id with length %d expecting %zd",
2263 header_len, expected_len);
2264 mark_source_rp_bad(ms);
2265 goto out;
2267 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2268 break;
2270 case MIG_RP_MSG_RECV_BITMAP:
2271 if (header_len < 1) {
2272 error_report("%s: missing block name", __func__);
2273 mark_source_rp_bad(ms);
2274 goto out;
2276 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2277 buf[buf[0] + 1] = '\0';
2278 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2279 mark_source_rp_bad(ms);
2280 goto out;
2282 break;
2284 case MIG_RP_MSG_RESUME_ACK:
2285 tmp32 = ldl_be_p(buf);
2286 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2287 mark_source_rp_bad(ms);
2288 goto out;
2290 break;
2292 default:
2293 break;
2297 out:
2298 res = qemu_file_get_error(rp);
2299 if (res) {
2300 if (res == -EIO) {
2302 * Maybe there is something we can do: it looks like a
2303 * network down issue, and we pause for a recovery.
2305 if (postcopy_pause_return_path_thread(ms)) {
2306 /* Reload rp, reset the rest */
2307 if (rp != ms->rp_state.from_dst_file) {
2308 qemu_fclose(rp);
2309 rp = ms->rp_state.from_dst_file;
2311 ms->rp_state.error = false;
2312 goto retry;
2316 trace_source_return_path_thread_bad_end();
2317 mark_source_rp_bad(ms);
2320 trace_source_return_path_thread_end();
2321 ms->rp_state.from_dst_file = NULL;
2322 qemu_fclose(rp);
2323 rcu_unregister_thread();
2324 return NULL;
2327 static int open_return_path_on_source(MigrationState *ms,
2328 bool create_thread)
2331 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2332 if (!ms->rp_state.from_dst_file) {
2333 return -1;
2336 trace_open_return_path_on_source();
2338 if (!create_thread) {
2339 /* We're done */
2340 return 0;
2343 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2344 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2346 trace_open_return_path_on_source_continue();
2348 return 0;
2351 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2352 static int await_return_path_close_on_source(MigrationState *ms)
2355 * If this is a normal exit then the destination will send a SHUT and the
2356 * rp_thread will exit, however if there's an error we need to cause
2357 * it to exit.
2359 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2361 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2362 * waiting for the destination.
2364 qemu_file_shutdown(ms->rp_state.from_dst_file);
2365 mark_source_rp_bad(ms);
2367 trace_await_return_path_close_on_source_joining();
2368 qemu_thread_join(&ms->rp_state.rp_thread);
2369 trace_await_return_path_close_on_source_close();
2370 return ms->rp_state.error;
2374 * Switch from normal iteration to postcopy
2375 * Returns non-0 on error
2377 static int postcopy_start(MigrationState *ms)
2379 int ret;
2380 QIOChannelBuffer *bioc;
2381 QEMUFile *fb;
2382 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2383 int64_t bandwidth = migrate_max_postcopy_bandwidth();
2384 bool restart_block = false;
2385 int cur_state = MIGRATION_STATUS_ACTIVE;
2386 if (!migrate_pause_before_switchover()) {
2387 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2388 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2391 trace_postcopy_start();
2392 qemu_mutex_lock_iothread();
2393 trace_postcopy_start_set_run();
2395 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2396 global_state_store();
2397 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2398 if (ret < 0) {
2399 goto fail;
2402 ret = migration_maybe_pause(ms, &cur_state,
2403 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2404 if (ret < 0) {
2405 goto fail;
2408 ret = bdrv_inactivate_all();
2409 if (ret < 0) {
2410 goto fail;
2412 restart_block = true;
2415 * Cause any non-postcopiable, but iterative devices to
2416 * send out their final data.
2418 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2421 * in Finish migrate and with the io-lock held everything should
2422 * be quiet, but we've potentially still got dirty pages and we
2423 * need to tell the destination to throw any pages it's already received
2424 * that are dirty
2426 if (migrate_postcopy_ram()) {
2427 if (ram_postcopy_send_discard_bitmap(ms)) {
2428 error_report("postcopy send discard bitmap failed");
2429 goto fail;
2434 * send rest of state - note things that are doing postcopy
2435 * will notice we're in POSTCOPY_ACTIVE and not actually
2436 * wrap their state up here
2438 /* 0 max-postcopy-bandwidth means unlimited */
2439 if (!bandwidth) {
2440 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2441 } else {
2442 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2444 if (migrate_postcopy_ram()) {
2445 /* Ping just for debugging, helps line traces up */
2446 qemu_savevm_send_ping(ms->to_dst_file, 2);
2450 * While loading the device state we may trigger page transfer
2451 * requests and the fd must be free to process those, and thus
2452 * the destination must read the whole device state off the fd before
2453 * it starts processing it. Unfortunately the ad-hoc migration format
2454 * doesn't allow the destination to know the size to read without fully
2455 * parsing it through each devices load-state code (especially the open
2456 * coded devices that use get/put).
2457 * So we wrap the device state up in a package with a length at the start;
2458 * to do this we use a qemu_buf to hold the whole of the device state.
2460 bioc = qio_channel_buffer_new(4096);
2461 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2462 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2463 object_unref(OBJECT(bioc));
2466 * Make sure the receiver can get incoming pages before we send the rest
2467 * of the state
2469 qemu_savevm_send_postcopy_listen(fb);
2471 qemu_savevm_state_complete_precopy(fb, false, false);
2472 if (migrate_postcopy_ram()) {
2473 qemu_savevm_send_ping(fb, 3);
2476 qemu_savevm_send_postcopy_run(fb);
2478 /* <><> end of stuff going into the package */
2480 /* Last point of recovery; as soon as we send the package the destination
2481 * can open devices and potentially start running.
2482 * Lets just check again we've not got any errors.
2484 ret = qemu_file_get_error(ms->to_dst_file);
2485 if (ret) {
2486 error_report("postcopy_start: Migration stream errored (pre package)");
2487 goto fail_closefb;
2490 restart_block = false;
2492 /* Now send that blob */
2493 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2494 goto fail_closefb;
2496 qemu_fclose(fb);
2498 /* Send a notify to give a chance for anything that needs to happen
2499 * at the transition to postcopy and after the device state; in particular
2500 * spice needs to trigger a transition now
2502 ms->postcopy_after_devices = true;
2503 notifier_list_notify(&migration_state_notifiers, ms);
2505 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2507 qemu_mutex_unlock_iothread();
2509 if (migrate_postcopy_ram()) {
2511 * Although this ping is just for debug, it could potentially be
2512 * used for getting a better measurement of downtime at the source.
2514 qemu_savevm_send_ping(ms->to_dst_file, 4);
2517 if (migrate_release_ram()) {
2518 ram_postcopy_migrated_memory_release(ms);
2521 ret = qemu_file_get_error(ms->to_dst_file);
2522 if (ret) {
2523 error_report("postcopy_start: Migration stream errored");
2524 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2525 MIGRATION_STATUS_FAILED);
2528 return ret;
2530 fail_closefb:
2531 qemu_fclose(fb);
2532 fail:
2533 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2534 MIGRATION_STATUS_FAILED);
2535 if (restart_block) {
2536 /* A failure happened early enough that we know the destination hasn't
2537 * accessed block devices, so we're safe to recover.
2539 Error *local_err = NULL;
2541 bdrv_invalidate_cache_all(&local_err);
2542 if (local_err) {
2543 error_report_err(local_err);
2546 qemu_mutex_unlock_iothread();
2547 return -1;
2551 * migration_maybe_pause: Pause if required to by
2552 * migrate_pause_before_switchover called with the iothread locked
2553 * Returns: 0 on success
2555 static int migration_maybe_pause(MigrationState *s,
2556 int *current_active_state,
2557 int new_state)
2559 if (!migrate_pause_before_switchover()) {
2560 return 0;
2563 /* Since leaving this state is not atomic with posting the semaphore
2564 * it's possible that someone could have issued multiple migrate_continue
2565 * and the semaphore is incorrectly positive at this point;
2566 * the docs say it's undefined to reinit a semaphore that's already
2567 * init'd, so use timedwait to eat up any existing posts.
2569 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2570 /* This block intentionally left blank */
2573 qemu_mutex_unlock_iothread();
2574 migrate_set_state(&s->state, *current_active_state,
2575 MIGRATION_STATUS_PRE_SWITCHOVER);
2576 qemu_sem_wait(&s->pause_sem);
2577 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2578 new_state);
2579 *current_active_state = new_state;
2580 qemu_mutex_lock_iothread();
2582 return s->state == new_state ? 0 : -EINVAL;
2586 * migration_completion: Used by migration_thread when there's not much left.
2587 * The caller 'breaks' the loop when this returns.
2589 * @s: Current migration state
2591 static void migration_completion(MigrationState *s)
2593 int ret;
2594 int current_active_state = s->state;
2596 if (s->state == MIGRATION_STATUS_ACTIVE) {
2597 qemu_mutex_lock_iothread();
2598 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2599 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2600 s->vm_was_running = runstate_is_running();
2601 ret = global_state_store();
2603 if (!ret) {
2604 bool inactivate = !migrate_colo_enabled();
2605 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2606 if (ret >= 0) {
2607 ret = migration_maybe_pause(s, &current_active_state,
2608 MIGRATION_STATUS_DEVICE);
2610 if (ret >= 0) {
2611 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2612 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2613 inactivate);
2615 if (inactivate && ret >= 0) {
2616 s->block_inactive = true;
2619 qemu_mutex_unlock_iothread();
2621 if (ret < 0) {
2622 goto fail;
2624 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2625 trace_migration_completion_postcopy_end();
2627 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2628 trace_migration_completion_postcopy_end_after_complete();
2632 * If rp was opened we must clean up the thread before
2633 * cleaning everything else up (since if there are no failures
2634 * it will wait for the destination to send it's status in
2635 * a SHUT command).
2637 if (s->rp_state.from_dst_file) {
2638 int rp_error;
2639 trace_migration_return_path_end_before();
2640 rp_error = await_return_path_close_on_source(s);
2641 trace_migration_return_path_end_after(rp_error);
2642 if (rp_error) {
2643 goto fail_invalidate;
2647 if (qemu_file_get_error(s->to_dst_file)) {
2648 trace_migration_completion_file_err();
2649 goto fail_invalidate;
2652 if (!migrate_colo_enabled()) {
2653 migrate_set_state(&s->state, current_active_state,
2654 MIGRATION_STATUS_COMPLETED);
2657 return;
2659 fail_invalidate:
2660 /* If not doing postcopy, vm_start() will be called: let's regain
2661 * control on images.
2663 if (s->state == MIGRATION_STATUS_ACTIVE ||
2664 s->state == MIGRATION_STATUS_DEVICE) {
2665 Error *local_err = NULL;
2667 qemu_mutex_lock_iothread();
2668 bdrv_invalidate_cache_all(&local_err);
2669 if (local_err) {
2670 error_report_err(local_err);
2671 } else {
2672 s->block_inactive = false;
2674 qemu_mutex_unlock_iothread();
2677 fail:
2678 migrate_set_state(&s->state, current_active_state,
2679 MIGRATION_STATUS_FAILED);
2682 bool migrate_colo_enabled(void)
2684 MigrationState *s = migrate_get_current();
2685 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2688 typedef enum MigThrError {
2689 /* No error detected */
2690 MIG_THR_ERR_NONE = 0,
2691 /* Detected error, but resumed successfully */
2692 MIG_THR_ERR_RECOVERED = 1,
2693 /* Detected fatal error, need to exit */
2694 MIG_THR_ERR_FATAL = 2,
2695 } MigThrError;
2697 static int postcopy_resume_handshake(MigrationState *s)
2699 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2701 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2702 qemu_sem_wait(&s->rp_state.rp_sem);
2705 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2706 return 0;
2709 return -1;
2712 /* Return zero if success, or <0 for error */
2713 static int postcopy_do_resume(MigrationState *s)
2715 int ret;
2718 * Call all the resume_prepare() hooks, so that modules can be
2719 * ready for the migration resume.
2721 ret = qemu_savevm_state_resume_prepare(s);
2722 if (ret) {
2723 error_report("%s: resume_prepare() failure detected: %d",
2724 __func__, ret);
2725 return ret;
2729 * Last handshake with destination on the resume (destination will
2730 * switch to postcopy-active afterwards)
2732 ret = postcopy_resume_handshake(s);
2733 if (ret) {
2734 error_report("%s: handshake failed: %d", __func__, ret);
2735 return ret;
2738 return 0;
2742 * We don't return until we are in a safe state to continue current
2743 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2744 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2746 static MigThrError postcopy_pause(MigrationState *s)
2748 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2750 while (true) {
2751 QEMUFile *file;
2753 migrate_set_state(&s->state, s->state,
2754 MIGRATION_STATUS_POSTCOPY_PAUSED);
2756 /* Current channel is possibly broken. Release it. */
2757 assert(s->to_dst_file);
2758 qemu_mutex_lock(&s->qemu_file_lock);
2759 file = s->to_dst_file;
2760 s->to_dst_file = NULL;
2761 qemu_mutex_unlock(&s->qemu_file_lock);
2763 qemu_file_shutdown(file);
2764 qemu_fclose(file);
2766 error_report("Detected IO failure for postcopy. "
2767 "Migration paused.");
2770 * We wait until things fixed up. Then someone will setup the
2771 * status back for us.
2773 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2774 qemu_sem_wait(&s->postcopy_pause_sem);
2777 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2778 /* Woken up by a recover procedure. Give it a shot */
2781 * Firstly, let's wake up the return path now, with a new
2782 * return path channel.
2784 qemu_sem_post(&s->postcopy_pause_rp_sem);
2786 /* Do the resume logic */
2787 if (postcopy_do_resume(s) == 0) {
2788 /* Let's continue! */
2789 trace_postcopy_pause_continued();
2790 return MIG_THR_ERR_RECOVERED;
2791 } else {
2793 * Something wrong happened during the recovery, let's
2794 * pause again. Pause is always better than throwing
2795 * data away.
2797 continue;
2799 } else {
2800 /* This is not right... Time to quit. */
2801 return MIG_THR_ERR_FATAL;
2806 static MigThrError migration_detect_error(MigrationState *s)
2808 int ret;
2810 /* Try to detect any file errors */
2811 ret = qemu_file_get_error(s->to_dst_file);
2813 if (!ret) {
2814 /* Everything is fine */
2815 return MIG_THR_ERR_NONE;
2818 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
2820 * For postcopy, we allow the network to be down for a
2821 * while. After that, it can be continued by a
2822 * recovery phase.
2824 return postcopy_pause(s);
2825 } else {
2827 * For precopy (or postcopy with error outside IO), we fail
2828 * with no time.
2830 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
2831 trace_migration_thread_file_err();
2833 /* Time to stop the migration, now. */
2834 return MIG_THR_ERR_FATAL;
2838 /* How many bytes have we transferred since the beggining of the migration */
2839 static uint64_t migration_total_bytes(MigrationState *s)
2841 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
2844 static void migration_calculate_complete(MigrationState *s)
2846 uint64_t bytes = migration_total_bytes(s);
2847 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2848 int64_t transfer_time;
2850 s->total_time = end_time - s->start_time;
2851 if (!s->downtime) {
2853 * It's still not set, so we are precopy migration. For
2854 * postcopy, downtime is calculated during postcopy_start().
2856 s->downtime = end_time - s->downtime_start;
2859 transfer_time = s->total_time - s->setup_time;
2860 if (transfer_time) {
2861 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
2865 static void migration_update_counters(MigrationState *s,
2866 int64_t current_time)
2868 uint64_t transferred, time_spent;
2869 uint64_t current_bytes; /* bytes transferred since the beginning */
2870 double bandwidth;
2872 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2873 return;
2876 current_bytes = migration_total_bytes(s);
2877 transferred = current_bytes - s->iteration_initial_bytes;
2878 time_spent = current_time - s->iteration_start_time;
2879 bandwidth = (double)transferred / time_spent;
2880 s->threshold_size = bandwidth * s->parameters.downtime_limit;
2882 s->mbps = (((double) transferred * 8.0) /
2883 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2886 * if we haven't sent anything, we don't want to
2887 * recalculate. 10000 is a small enough number for our purposes
2889 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2890 s->expected_downtime = ram_counters.remaining / bandwidth;
2893 qemu_file_reset_rate_limit(s->to_dst_file);
2895 s->iteration_start_time = current_time;
2896 s->iteration_initial_bytes = current_bytes;
2898 trace_migrate_transferred(transferred, time_spent,
2899 bandwidth, s->threshold_size);
2902 /* Migration thread iteration status */
2903 typedef enum {
2904 MIG_ITERATE_RESUME, /* Resume current iteration */
2905 MIG_ITERATE_SKIP, /* Skip current iteration */
2906 MIG_ITERATE_BREAK, /* Break the loop */
2907 } MigIterateState;
2910 * Return true if continue to the next iteration directly, false
2911 * otherwise.
2913 static MigIterateState migration_iteration_run(MigrationState *s)
2915 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2916 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2918 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2919 &pend_compat, &pend_post);
2920 pending_size = pend_pre + pend_compat + pend_post;
2922 trace_migrate_pending(pending_size, s->threshold_size,
2923 pend_pre, pend_compat, pend_post);
2925 if (pending_size && pending_size >= s->threshold_size) {
2926 /* Still a significant amount to transfer */
2927 if (migrate_postcopy() && !in_postcopy &&
2928 pend_pre <= s->threshold_size &&
2929 atomic_read(&s->start_postcopy)) {
2930 if (postcopy_start(s)) {
2931 error_report("%s: postcopy failed to start", __func__);
2933 return MIG_ITERATE_SKIP;
2935 /* Just another iteration step */
2936 qemu_savevm_state_iterate(s->to_dst_file,
2937 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2938 } else {
2939 trace_migration_thread_low_pending(pending_size);
2940 migration_completion(s);
2941 return MIG_ITERATE_BREAK;
2944 return MIG_ITERATE_RESUME;
2947 static void migration_iteration_finish(MigrationState *s)
2949 /* If we enabled cpu throttling for auto-converge, turn it off. */
2950 cpu_throttle_stop();
2952 qemu_mutex_lock_iothread();
2953 switch (s->state) {
2954 case MIGRATION_STATUS_COMPLETED:
2955 migration_calculate_complete(s);
2956 runstate_set(RUN_STATE_POSTMIGRATE);
2957 break;
2959 case MIGRATION_STATUS_ACTIVE:
2961 * We should really assert here, but since it's during
2962 * migration, let's try to reduce the usage of assertions.
2964 if (!migrate_colo_enabled()) {
2965 error_report("%s: critical error: calling COLO code without "
2966 "COLO enabled", __func__);
2968 migrate_start_colo_process(s);
2970 * Fixme: we will run VM in COLO no matter its old running state.
2971 * After exited COLO, we will keep running.
2973 s->vm_was_running = true;
2974 /* Fallthrough */
2975 case MIGRATION_STATUS_FAILED:
2976 case MIGRATION_STATUS_CANCELLED:
2977 case MIGRATION_STATUS_CANCELLING:
2978 if (s->vm_was_running) {
2979 vm_start();
2980 } else {
2981 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2982 runstate_set(RUN_STATE_POSTMIGRATE);
2985 break;
2987 default:
2988 /* Should not reach here, but if so, forgive the VM. */
2989 error_report("%s: Unknown ending state %d", __func__, s->state);
2990 break;
2992 qemu_bh_schedule(s->cleanup_bh);
2993 qemu_mutex_unlock_iothread();
2996 void migration_make_urgent_request(void)
2998 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3001 void migration_consume_urgent_request(void)
3003 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3007 * Master migration thread on the source VM.
3008 * It drives the migration and pumps the data down the outgoing channel.
3010 static void *migration_thread(void *opaque)
3012 MigrationState *s = opaque;
3013 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3014 MigThrError thr_error;
3015 bool urgent = false;
3017 rcu_register_thread();
3019 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3021 qemu_savevm_state_header(s->to_dst_file);
3024 * If we opened the return path, we need to make sure dst has it
3025 * opened as well.
3027 if (s->rp_state.from_dst_file) {
3028 /* Now tell the dest that it should open its end so it can reply */
3029 qemu_savevm_send_open_return_path(s->to_dst_file);
3031 /* And do a ping that will make stuff easier to debug */
3032 qemu_savevm_send_ping(s->to_dst_file, 1);
3035 if (migrate_postcopy()) {
3037 * Tell the destination that we *might* want to do postcopy later;
3038 * if the other end can't do postcopy it should fail now, nice and
3039 * early.
3041 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3044 if (migrate_colo_enabled()) {
3045 /* Notify migration destination that we enable COLO */
3046 qemu_savevm_send_colo_enable(s->to_dst_file);
3049 qemu_savevm_state_setup(s->to_dst_file);
3051 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3052 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3053 MIGRATION_STATUS_ACTIVE);
3055 trace_migration_thread_setup_complete();
3057 while (s->state == MIGRATION_STATUS_ACTIVE ||
3058 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3059 int64_t current_time;
3061 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3062 MigIterateState iter_state = migration_iteration_run(s);
3063 if (iter_state == MIG_ITERATE_SKIP) {
3064 continue;
3065 } else if (iter_state == MIG_ITERATE_BREAK) {
3066 break;
3071 * Try to detect any kind of failures, and see whether we
3072 * should stop the migration now.
3074 thr_error = migration_detect_error(s);
3075 if (thr_error == MIG_THR_ERR_FATAL) {
3076 /* Stop migration */
3077 break;
3078 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3080 * Just recovered from a e.g. network failure, reset all
3081 * the local variables. This is important to avoid
3082 * breaking transferred_bytes and bandwidth calculation
3084 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3085 s->iteration_initial_bytes = 0;
3088 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3090 migration_update_counters(s, current_time);
3092 urgent = false;
3093 if (qemu_file_rate_limit(s->to_dst_file)) {
3094 /* Wait for a delay to do rate limiting OR
3095 * something urgent to post the semaphore.
3097 int ms = s->iteration_start_time + BUFFER_DELAY - current_time;
3098 trace_migration_thread_ratelimit_pre(ms);
3099 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3100 /* We were worken by one or more urgent things but
3101 * the timedwait will have consumed one of them.
3102 * The service routine for the urgent wake will dec
3103 * the semaphore itself for each item it consumes,
3104 * so add this one we just eat back.
3106 qemu_sem_post(&s->rate_limit_sem);
3107 urgent = true;
3109 trace_migration_thread_ratelimit_post(urgent);
3113 trace_migration_thread_after_loop();
3114 migration_iteration_finish(s);
3115 rcu_unregister_thread();
3116 return NULL;
3119 void migrate_fd_connect(MigrationState *s, Error *error_in)
3121 int64_t rate_limit;
3122 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3124 s->expected_downtime = s->parameters.downtime_limit;
3125 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
3126 if (error_in) {
3127 migrate_fd_error(s, error_in);
3128 migrate_fd_cleanup(s);
3129 return;
3132 if (resume) {
3133 /* This is a resumed migration */
3134 rate_limit = INT64_MAX;
3135 } else {
3136 /* This is a fresh new migration */
3137 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3139 /* Notify before starting migration thread */
3140 notifier_list_notify(&migration_state_notifiers, s);
3143 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3144 qemu_file_set_blocking(s->to_dst_file, true);
3147 * Open the return path. For postcopy, it is used exclusively. For
3148 * precopy, only if user specified "return-path" capability would
3149 * QEMU uses the return path.
3151 if (migrate_postcopy_ram() || migrate_use_return_path()) {
3152 if (open_return_path_on_source(s, !resume)) {
3153 error_report("Unable to open return-path for postcopy");
3154 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3155 migrate_fd_cleanup(s);
3156 return;
3160 if (resume) {
3161 /* Wakeup the main migration thread to do the recovery */
3162 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3163 MIGRATION_STATUS_POSTCOPY_RECOVER);
3164 qemu_sem_post(&s->postcopy_pause_sem);
3165 return;
3168 if (multifd_save_setup() != 0) {
3169 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3170 MIGRATION_STATUS_FAILED);
3171 migrate_fd_cleanup(s);
3172 return;
3174 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3175 QEMU_THREAD_JOINABLE);
3176 s->migration_thread_running = true;
3179 void migration_global_dump(Monitor *mon)
3181 MigrationState *ms = migrate_get_current();
3183 monitor_printf(mon, "globals:\n");
3184 monitor_printf(mon, "store-global-state: %s\n",
3185 ms->store_global_state ? "on" : "off");
3186 monitor_printf(mon, "only-migratable: %s\n",
3187 ms->only_migratable ? "on" : "off");
3188 monitor_printf(mon, "send-configuration: %s\n",
3189 ms->send_configuration ? "on" : "off");
3190 monitor_printf(mon, "send-section-footer: %s\n",
3191 ms->send_section_footer ? "on" : "off");
3192 monitor_printf(mon, "decompress-error-check: %s\n",
3193 ms->decompress_error_check ? "on" : "off");
3196 #define DEFINE_PROP_MIG_CAP(name, x) \
3197 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3199 static Property migration_properties[] = {
3200 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3201 store_global_state, true),
3202 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
3203 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3204 send_configuration, true),
3205 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3206 send_section_footer, true),
3207 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3208 decompress_error_check, true),
3210 /* Migration parameters */
3211 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3212 parameters.compress_level,
3213 DEFAULT_MIGRATE_COMPRESS_LEVEL),
3214 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3215 parameters.compress_threads,
3216 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3217 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3218 parameters.compress_wait_thread, true),
3219 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3220 parameters.decompress_threads,
3221 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3222 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3223 parameters.cpu_throttle_initial,
3224 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3225 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3226 parameters.cpu_throttle_increment,
3227 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3228 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3229 parameters.max_bandwidth, MAX_THROTTLE),
3230 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3231 parameters.downtime_limit,
3232 DEFAULT_MIGRATE_SET_DOWNTIME),
3233 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3234 parameters.x_checkpoint_delay,
3235 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3236 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
3237 parameters.x_multifd_channels,
3238 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3239 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
3240 parameters.x_multifd_page_count,
3241 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
3242 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3243 parameters.xbzrle_cache_size,
3244 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3245 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3246 parameters.max_postcopy_bandwidth,
3247 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3248 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3249 parameters.max_cpu_throttle,
3250 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3252 /* Migration capabilities */
3253 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3254 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3255 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3256 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3257 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3258 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3259 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3260 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3261 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3262 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3263 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3264 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
3266 DEFINE_PROP_END_OF_LIST(),
3269 static void migration_class_init(ObjectClass *klass, void *data)
3271 DeviceClass *dc = DEVICE_CLASS(klass);
3273 dc->user_creatable = false;
3274 dc->props = migration_properties;
3277 static void migration_instance_finalize(Object *obj)
3279 MigrationState *ms = MIGRATION_OBJ(obj);
3280 MigrationParameters *params = &ms->parameters;
3282 qemu_mutex_destroy(&ms->error_mutex);
3283 qemu_mutex_destroy(&ms->qemu_file_lock);
3284 g_free(params->tls_hostname);
3285 g_free(params->tls_creds);
3286 qemu_sem_destroy(&ms->rate_limit_sem);
3287 qemu_sem_destroy(&ms->pause_sem);
3288 qemu_sem_destroy(&ms->postcopy_pause_sem);
3289 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3290 qemu_sem_destroy(&ms->rp_state.rp_sem);
3291 error_free(ms->error);
3294 static void migration_instance_init(Object *obj)
3296 MigrationState *ms = MIGRATION_OBJ(obj);
3297 MigrationParameters *params = &ms->parameters;
3299 ms->state = MIGRATION_STATUS_NONE;
3300 ms->mbps = -1;
3301 qemu_sem_init(&ms->pause_sem, 0);
3302 qemu_mutex_init(&ms->error_mutex);
3304 params->tls_hostname = g_strdup("");
3305 params->tls_creds = g_strdup("");
3307 /* Set has_* up only for parameter checks */
3308 params->has_compress_level = true;
3309 params->has_compress_threads = true;
3310 params->has_decompress_threads = true;
3311 params->has_cpu_throttle_initial = true;
3312 params->has_cpu_throttle_increment = true;
3313 params->has_max_bandwidth = true;
3314 params->has_downtime_limit = true;
3315 params->has_x_checkpoint_delay = true;
3316 params->has_block_incremental = true;
3317 params->has_x_multifd_channels = true;
3318 params->has_x_multifd_page_count = true;
3319 params->has_xbzrle_cache_size = true;
3320 params->has_max_postcopy_bandwidth = true;
3321 params->has_max_cpu_throttle = true;
3323 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3324 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3325 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3326 qemu_sem_init(&ms->rate_limit_sem, 0);
3327 qemu_mutex_init(&ms->qemu_file_lock);
3331 * Return true if check pass, false otherwise. Error will be put
3332 * inside errp if provided.
3334 static bool migration_object_check(MigrationState *ms, Error **errp)
3336 MigrationCapabilityStatusList *head = NULL;
3337 /* Assuming all off */
3338 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3339 int i;
3341 if (!migrate_params_check(&ms->parameters, errp)) {
3342 return false;
3345 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3346 if (ms->enabled_capabilities[i]) {
3347 head = migrate_cap_add(head, i, true);
3351 ret = migrate_caps_check(cap_list, head, errp);
3353 /* It works with head == NULL */
3354 qapi_free_MigrationCapabilityStatusList(head);
3356 return ret;
3359 static const TypeInfo migration_type = {
3360 .name = TYPE_MIGRATION,
3362 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3363 * not created using qdev_create(), it is not attached to the qdev
3364 * device tree, and it is never realized.
3366 * TODO: Make this TYPE_OBJECT once QOM provides something like
3367 * TYPE_DEVICE's "-global" properties.
3369 .parent = TYPE_DEVICE,
3370 .class_init = migration_class_init,
3371 .class_size = sizeof(MigrationClass),
3372 .instance_size = sizeof(MigrationState),
3373 .instance_init = migration_instance_init,
3374 .instance_finalize = migration_instance_finalize,
3377 static void register_migration_types(void)
3379 type_register_static(&migration_type);
3382 type_init(register_migration_types);