Migration: Split out ram part of qmp_query_migrate
[qemu.git] / migration / migration.c
blob19549871987cd96fadb1d422b67d74e340ced463
1 /*
2 * QEMU live migration
4 * Copyright IBM, Corp. 2008
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "qemu/main-loop.h"
20 #include "migration/migration.h"
21 #include "migration/qemu-file.h"
22 #include "sysemu/sysemu.h"
23 #include "block/block.h"
24 #include "qapi/qmp/qerror.h"
25 #include "qapi/util.h"
26 #include "qemu/sockets.h"
27 #include "qemu/rcu.h"
28 #include "migration/block.h"
29 #include "migration/postcopy-ram.h"
30 #include "qemu/thread.h"
31 #include "qmp-commands.h"
32 #include "trace.h"
33 #include "qapi-event.h"
34 #include "qom/cpu.h"
35 #include "exec/memory.h"
36 #include "exec/address-spaces.h"
37 #include "io/channel-buffer.h"
38 #include "io/channel-tls.h"
40 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
42 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
43 * data. */
44 #define BUFFER_DELAY 100
45 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
47 /* Default compression thread count */
48 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
49 /* Default decompression thread count, usually decompression is at
50 * least 4 times as fast as compression.*/
51 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
52 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
53 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
54 /* Define default autoconverge cpu throttle migration parameters */
55 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
56 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
58 /* Migration XBZRLE default cache size */
59 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
61 static NotifierList migration_state_notifiers =
62 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
64 static bool deferred_incoming;
67 * Current state of incoming postcopy; note this is not part of
68 * MigrationIncomingState since it's state is used during cleanup
69 * at the end as MIS is being freed.
71 static PostcopyState incoming_postcopy_state;
73 /* When we add fault tolerance, we could have several
74 migrations at once. For now we don't need to add
75 dynamic creation of migration */
77 /* For outgoing */
78 MigrationState *migrate_get_current(void)
80 static bool once;
81 static MigrationState current_migration = {
82 .state = MIGRATION_STATUS_NONE,
83 .bandwidth_limit = MAX_THROTTLE,
84 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
85 .mbps = -1,
86 .parameters = {
87 .compress_level = DEFAULT_MIGRATE_COMPRESS_LEVEL,
88 .compress_threads = DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
89 .decompress_threads = DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
90 .cpu_throttle_initial = DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL,
91 .cpu_throttle_increment = DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT,
95 if (!once) {
96 qemu_mutex_init(&current_migration.src_page_req_mutex);
97 once = true;
99 return &current_migration;
102 /* For incoming */
103 static MigrationIncomingState *mis_current;
105 MigrationIncomingState *migration_incoming_get_current(void)
107 return mis_current;
110 MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
112 mis_current = g_new0(MigrationIncomingState, 1);
113 mis_current->from_src_file = f;
114 mis_current->state = MIGRATION_STATUS_NONE;
115 QLIST_INIT(&mis_current->loadvm_handlers);
116 qemu_mutex_init(&mis_current->rp_mutex);
117 qemu_event_init(&mis_current->main_thread_load_event, false);
119 return mis_current;
122 void migration_incoming_state_destroy(void)
124 qemu_event_destroy(&mis_current->main_thread_load_event);
125 loadvm_free_handlers(mis_current);
126 g_free(mis_current);
127 mis_current = NULL;
131 typedef struct {
132 bool optional;
133 uint32_t size;
134 uint8_t runstate[100];
135 RunState state;
136 bool received;
137 } GlobalState;
139 static GlobalState global_state;
141 int global_state_store(void)
143 if (!runstate_store((char *)global_state.runstate,
144 sizeof(global_state.runstate))) {
145 error_report("runstate name too big: %s", global_state.runstate);
146 trace_migrate_state_too_big();
147 return -EINVAL;
149 return 0;
152 void global_state_store_running(void)
154 const char *state = RunState_lookup[RUN_STATE_RUNNING];
155 strncpy((char *)global_state.runstate,
156 state, sizeof(global_state.runstate));
159 static bool global_state_received(void)
161 return global_state.received;
164 static RunState global_state_get_runstate(void)
166 return global_state.state;
169 void global_state_set_optional(void)
171 global_state.optional = true;
174 static bool global_state_needed(void *opaque)
176 GlobalState *s = opaque;
177 char *runstate = (char *)s->runstate;
179 /* If it is not optional, it is mandatory */
181 if (s->optional == false) {
182 return true;
185 /* If state is running or paused, it is not needed */
187 if (strcmp(runstate, "running") == 0 ||
188 strcmp(runstate, "paused") == 0) {
189 return false;
192 /* for any other state it is needed */
193 return true;
196 static int global_state_post_load(void *opaque, int version_id)
198 GlobalState *s = opaque;
199 Error *local_err = NULL;
200 int r;
201 char *runstate = (char *)s->runstate;
203 s->received = true;
204 trace_migrate_global_state_post_load(runstate);
206 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE__MAX,
207 -1, &local_err);
209 if (r == -1) {
210 if (local_err) {
211 error_report_err(local_err);
213 return -EINVAL;
215 s->state = r;
217 return 0;
220 static void global_state_pre_save(void *opaque)
222 GlobalState *s = opaque;
224 trace_migrate_global_state_pre_save((char *)s->runstate);
225 s->size = strlen((char *)s->runstate) + 1;
228 static const VMStateDescription vmstate_globalstate = {
229 .name = "globalstate",
230 .version_id = 1,
231 .minimum_version_id = 1,
232 .post_load = global_state_post_load,
233 .pre_save = global_state_pre_save,
234 .needed = global_state_needed,
235 .fields = (VMStateField[]) {
236 VMSTATE_UINT32(size, GlobalState),
237 VMSTATE_BUFFER(runstate, GlobalState),
238 VMSTATE_END_OF_LIST()
242 void register_global_state(void)
244 /* We would use it independently that we receive it */
245 strcpy((char *)&global_state.runstate, "");
246 global_state.received = false;
247 vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
250 static void migrate_generate_event(int new_state)
252 if (migrate_use_events()) {
253 qapi_event_send_migration(new_state, &error_abort);
258 * Called on -incoming with a defer: uri.
259 * The migration can be started later after any parameters have been
260 * changed.
262 static void deferred_incoming_migration(Error **errp)
264 if (deferred_incoming) {
265 error_setg(errp, "Incoming migration already deferred");
267 deferred_incoming = true;
270 /* Request a range of pages from the source VM at the given
271 * start address.
272 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
273 * as the last request (a name must have been given previously)
274 * Start: Address offset within the RB
275 * Len: Length in bytes required - must be a multiple of pagesize
277 void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
278 ram_addr_t start, size_t len)
280 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
281 size_t msglen = 12; /* start + len */
283 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
284 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
286 if (rbname) {
287 int rbname_len = strlen(rbname);
288 assert(rbname_len < 256);
290 bufc[msglen++] = rbname_len;
291 memcpy(bufc + msglen, rbname, rbname_len);
292 msglen += rbname_len;
293 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES_ID, msglen, bufc);
294 } else {
295 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES, msglen, bufc);
299 void qemu_start_incoming_migration(const char *uri, Error **errp)
301 const char *p;
303 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
304 if (!strcmp(uri, "defer")) {
305 deferred_incoming_migration(errp);
306 } else if (strstart(uri, "tcp:", &p)) {
307 tcp_start_incoming_migration(p, errp);
308 #ifdef CONFIG_RDMA
309 } else if (strstart(uri, "rdma:", &p)) {
310 rdma_start_incoming_migration(p, errp);
311 #endif
312 } else if (strstart(uri, "exec:", &p)) {
313 exec_start_incoming_migration(p, errp);
314 } else if (strstart(uri, "unix:", &p)) {
315 unix_start_incoming_migration(p, errp);
316 } else if (strstart(uri, "fd:", &p)) {
317 fd_start_incoming_migration(p, errp);
318 } else {
319 error_setg(errp, "unknown migration protocol: %s", uri);
323 static void process_incoming_migration_bh(void *opaque)
325 Error *local_err = NULL;
326 MigrationIncomingState *mis = opaque;
328 /* Make sure all file formats flush their mutable metadata */
329 bdrv_invalidate_cache_all(&local_err);
330 if (local_err) {
331 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
332 MIGRATION_STATUS_FAILED);
333 error_report_err(local_err);
334 migrate_decompress_threads_join();
335 exit(EXIT_FAILURE);
339 * This must happen after all error conditions are dealt with and
340 * we're sure the VM is going to be running on this host.
342 qemu_announce_self();
344 /* If global state section was not received or we are in running
345 state, we need to obey autostart. Any other state is set with
346 runstate_set. */
348 if (!global_state_received() ||
349 global_state_get_runstate() == RUN_STATE_RUNNING) {
350 if (autostart) {
351 vm_start();
352 } else {
353 runstate_set(RUN_STATE_PAUSED);
355 } else {
356 runstate_set(global_state_get_runstate());
358 migrate_decompress_threads_join();
360 * This must happen after any state changes since as soon as an external
361 * observer sees this event they might start to prod at the VM assuming
362 * it's ready to use.
364 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
365 MIGRATION_STATUS_COMPLETED);
366 qemu_bh_delete(mis->bh);
367 migration_incoming_state_destroy();
370 static void process_incoming_migration_co(void *opaque)
372 QEMUFile *f = opaque;
373 MigrationIncomingState *mis;
374 PostcopyState ps;
375 int ret;
377 mis = migration_incoming_state_new(f);
378 postcopy_state_set(POSTCOPY_INCOMING_NONE);
379 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
380 MIGRATION_STATUS_ACTIVE);
381 ret = qemu_loadvm_state(f);
383 ps = postcopy_state_get();
384 trace_process_incoming_migration_co_end(ret, ps);
385 if (ps != POSTCOPY_INCOMING_NONE) {
386 if (ps == POSTCOPY_INCOMING_ADVISE) {
388 * Where a migration had postcopy enabled (and thus went to advise)
389 * but managed to complete within the precopy period, we can use
390 * the normal exit.
392 postcopy_ram_incoming_cleanup(mis);
393 } else if (ret >= 0) {
395 * Postcopy was started, cleanup should happen at the end of the
396 * postcopy thread.
398 trace_process_incoming_migration_co_postcopy_end_main();
399 return;
401 /* Else if something went wrong then just fall out of the normal exit */
404 qemu_fclose(f);
405 free_xbzrle_decoded_buf();
407 if (ret < 0) {
408 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
409 MIGRATION_STATUS_FAILED);
410 error_report("load of migration failed: %s", strerror(-ret));
411 migrate_decompress_threads_join();
412 exit(EXIT_FAILURE);
415 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
416 qemu_bh_schedule(mis->bh);
419 void process_incoming_migration(QEMUFile *f)
421 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
423 migrate_decompress_threads_create();
424 qemu_file_set_blocking(f, false);
425 qemu_coroutine_enter(co, f);
429 void migration_set_incoming_channel(MigrationState *s,
430 QIOChannel *ioc)
432 trace_migration_set_incoming_channel(
433 ioc, object_get_typename(OBJECT(ioc)));
435 if (s->parameters.tls_creds &&
436 !object_dynamic_cast(OBJECT(ioc),
437 TYPE_QIO_CHANNEL_TLS)) {
438 Error *local_err = NULL;
439 migration_tls_set_incoming_channel(s, ioc, &local_err);
440 if (local_err) {
441 error_report_err(local_err);
443 } else {
444 QEMUFile *f = qemu_fopen_channel_input(ioc);
445 process_incoming_migration(f);
450 void migration_set_outgoing_channel(MigrationState *s,
451 QIOChannel *ioc,
452 const char *hostname)
454 trace_migration_set_outgoing_channel(
455 ioc, object_get_typename(OBJECT(ioc)), hostname);
457 if (s->parameters.tls_creds &&
458 !object_dynamic_cast(OBJECT(ioc),
459 TYPE_QIO_CHANNEL_TLS)) {
460 Error *local_err = NULL;
461 migration_tls_set_outgoing_channel(s, ioc, hostname, &local_err);
462 if (local_err) {
463 migrate_fd_error(s, local_err);
464 error_free(local_err);
466 } else {
467 QEMUFile *f = qemu_fopen_channel_output(ioc);
469 s->to_dst_file = f;
471 migrate_fd_connect(s);
477 * Send a message on the return channel back to the source
478 * of the migration.
480 void migrate_send_rp_message(MigrationIncomingState *mis,
481 enum mig_rp_message_type message_type,
482 uint16_t len, void *data)
484 trace_migrate_send_rp_message((int)message_type, len);
485 qemu_mutex_lock(&mis->rp_mutex);
486 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
487 qemu_put_be16(mis->to_src_file, len);
488 qemu_put_buffer(mis->to_src_file, data, len);
489 qemu_fflush(mis->to_src_file);
490 qemu_mutex_unlock(&mis->rp_mutex);
494 * Send a 'SHUT' message on the return channel with the given value
495 * to indicate that we've finished with the RP. Non-0 value indicates
496 * error.
498 void migrate_send_rp_shut(MigrationIncomingState *mis,
499 uint32_t value)
501 uint32_t buf;
503 buf = cpu_to_be32(value);
504 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
508 * Send a 'PONG' message on the return channel with the given value
509 * (normally in response to a 'PING')
511 void migrate_send_rp_pong(MigrationIncomingState *mis,
512 uint32_t value)
514 uint32_t buf;
516 buf = cpu_to_be32(value);
517 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
520 /* amount of nanoseconds we are willing to wait for migration to be down.
521 * the choice of nanoseconds is because it is the maximum resolution that
522 * get_clock() can achieve. It is an internal measure. All user-visible
523 * units must be in seconds */
524 static uint64_t max_downtime = 300000000;
526 uint64_t migrate_max_downtime(void)
528 return max_downtime;
531 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
533 MigrationCapabilityStatusList *head = NULL;
534 MigrationCapabilityStatusList *caps;
535 MigrationState *s = migrate_get_current();
536 int i;
538 caps = NULL; /* silence compiler warning */
539 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
540 if (head == NULL) {
541 head = g_malloc0(sizeof(*caps));
542 caps = head;
543 } else {
544 caps->next = g_malloc0(sizeof(*caps));
545 caps = caps->next;
547 caps->value =
548 g_malloc(sizeof(*caps->value));
549 caps->value->capability = i;
550 caps->value->state = s->enabled_capabilities[i];
553 return head;
556 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
558 MigrationParameters *params;
559 MigrationState *s = migrate_get_current();
561 params = g_malloc0(sizeof(*params));
562 params->compress_level = s->parameters.compress_level;
563 params->compress_threads = s->parameters.compress_threads;
564 params->decompress_threads = s->parameters.decompress_threads;
565 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
566 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
567 params->tls_creds = g_strdup(s->parameters.tls_creds);
568 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
570 return params;
574 * Return true if we're already in the middle of a migration
575 * (i.e. any of the active or setup states)
577 static bool migration_is_setup_or_active(int state)
579 switch (state) {
580 case MIGRATION_STATUS_ACTIVE:
581 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
582 case MIGRATION_STATUS_SETUP:
583 return true;
585 default:
586 return false;
591 static void get_xbzrle_cache_stats(MigrationInfo *info)
593 if (migrate_use_xbzrle()) {
594 info->has_xbzrle_cache = true;
595 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
596 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
597 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
598 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
599 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
600 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
601 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
605 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
607 info->has_ram = true;
608 info->ram = g_malloc0(sizeof(*info->ram));
609 info->ram->transferred = ram_bytes_transferred();
610 info->ram->total = ram_bytes_total();
611 info->ram->duplicate = dup_mig_pages_transferred();
612 info->ram->skipped = skipped_mig_pages_transferred();
613 info->ram->normal = norm_mig_pages_transferred();
614 info->ram->normal_bytes = norm_mig_bytes_transferred();
615 info->ram->mbps = s->mbps;
616 info->ram->dirty_sync_count = s->dirty_sync_count;
618 if (s->state != MIGRATION_STATUS_COMPLETED) {
619 info->ram->remaining = ram_bytes_remaining();
620 info->ram->dirty_pages_rate = s->dirty_pages_rate;
624 MigrationInfo *qmp_query_migrate(Error **errp)
626 MigrationInfo *info = g_malloc0(sizeof(*info));
627 MigrationState *s = migrate_get_current();
629 switch (s->state) {
630 case MIGRATION_STATUS_NONE:
631 /* no migration has happened ever */
632 break;
633 case MIGRATION_STATUS_SETUP:
634 info->has_status = true;
635 info->has_total_time = false;
636 break;
637 case MIGRATION_STATUS_ACTIVE:
638 case MIGRATION_STATUS_CANCELLING:
639 info->has_status = true;
640 info->has_total_time = true;
641 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
642 - s->total_time;
643 info->has_expected_downtime = true;
644 info->expected_downtime = s->expected_downtime;
645 info->has_setup_time = true;
646 info->setup_time = s->setup_time;
648 populate_ram_info(info, s);
650 if (blk_mig_active()) {
651 info->has_disk = true;
652 info->disk = g_malloc0(sizeof(*info->disk));
653 info->disk->transferred = blk_mig_bytes_transferred();
654 info->disk->remaining = blk_mig_bytes_remaining();
655 info->disk->total = blk_mig_bytes_total();
658 if (cpu_throttle_active()) {
659 info->has_cpu_throttle_percentage = true;
660 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
663 get_xbzrle_cache_stats(info);
664 break;
665 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
666 /* Mostly the same as active; TODO add some postcopy stats */
667 info->has_status = true;
668 info->has_total_time = true;
669 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
670 - s->total_time;
671 info->has_expected_downtime = true;
672 info->expected_downtime = s->expected_downtime;
673 info->has_setup_time = true;
674 info->setup_time = s->setup_time;
676 populate_ram_info(info, s);
678 if (blk_mig_active()) {
679 info->has_disk = true;
680 info->disk = g_malloc0(sizeof(*info->disk));
681 info->disk->transferred = blk_mig_bytes_transferred();
682 info->disk->remaining = blk_mig_bytes_remaining();
683 info->disk->total = blk_mig_bytes_total();
686 get_xbzrle_cache_stats(info);
687 break;
688 case MIGRATION_STATUS_COMPLETED:
689 get_xbzrle_cache_stats(info);
691 info->has_status = true;
692 info->has_total_time = true;
693 info->total_time = s->total_time;
694 info->has_downtime = true;
695 info->downtime = s->downtime;
696 info->has_setup_time = true;
697 info->setup_time = s->setup_time;
699 populate_ram_info(info, s);
700 break;
701 case MIGRATION_STATUS_FAILED:
702 info->has_status = true;
703 if (s->error) {
704 info->has_error_desc = true;
705 info->error_desc = g_strdup(error_get_pretty(s->error));
707 break;
708 case MIGRATION_STATUS_CANCELLED:
709 info->has_status = true;
710 break;
712 info->status = s->state;
714 return info;
717 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
718 Error **errp)
720 MigrationState *s = migrate_get_current();
721 MigrationCapabilityStatusList *cap;
723 if (migration_is_setup_or_active(s->state)) {
724 error_setg(errp, QERR_MIGRATION_ACTIVE);
725 return;
728 for (cap = params; cap; cap = cap->next) {
729 s->enabled_capabilities[cap->value->capability] = cap->value->state;
732 if (migrate_postcopy_ram()) {
733 if (migrate_use_compression()) {
734 /* The decompression threads asynchronously write into RAM
735 * rather than use the atomic copies needed to avoid
736 * userfaulting. It should be possible to fix the decompression
737 * threads for compatibility in future.
739 error_report("Postcopy is not currently compatible with "
740 "compression");
741 s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM] =
742 false;
747 void qmp_migrate_set_parameters(bool has_compress_level,
748 int64_t compress_level,
749 bool has_compress_threads,
750 int64_t compress_threads,
751 bool has_decompress_threads,
752 int64_t decompress_threads,
753 bool has_cpu_throttle_initial,
754 int64_t cpu_throttle_initial,
755 bool has_cpu_throttle_increment,
756 int64_t cpu_throttle_increment,
757 bool has_tls_creds,
758 const char *tls_creds,
759 bool has_tls_hostname,
760 const char *tls_hostname,
761 Error **errp)
763 MigrationState *s = migrate_get_current();
765 if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
766 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
767 "is invalid, it should be in the range of 0 to 9");
768 return;
770 if (has_compress_threads &&
771 (compress_threads < 1 || compress_threads > 255)) {
772 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
773 "compress_threads",
774 "is invalid, it should be in the range of 1 to 255");
775 return;
777 if (has_decompress_threads &&
778 (decompress_threads < 1 || decompress_threads > 255)) {
779 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
780 "decompress_threads",
781 "is invalid, it should be in the range of 1 to 255");
782 return;
784 if (has_cpu_throttle_initial &&
785 (cpu_throttle_initial < 1 || cpu_throttle_initial > 99)) {
786 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
787 "cpu_throttle_initial",
788 "an integer in the range of 1 to 99");
790 if (has_cpu_throttle_increment &&
791 (cpu_throttle_increment < 1 || cpu_throttle_increment > 99)) {
792 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
793 "cpu_throttle_increment",
794 "an integer in the range of 1 to 99");
797 if (has_compress_level) {
798 s->parameters.compress_level = compress_level;
800 if (has_compress_threads) {
801 s->parameters.compress_threads = compress_threads;
803 if (has_decompress_threads) {
804 s->parameters.decompress_threads = decompress_threads;
806 if (has_cpu_throttle_initial) {
807 s->parameters.cpu_throttle_initial = cpu_throttle_initial;
809 if (has_cpu_throttle_increment) {
810 s->parameters.cpu_throttle_increment = cpu_throttle_increment;
812 if (has_tls_creds) {
813 g_free(s->parameters.tls_creds);
814 s->parameters.tls_creds = g_strdup(tls_creds);
816 if (has_tls_hostname) {
817 g_free(s->parameters.tls_hostname);
818 s->parameters.tls_hostname = g_strdup(tls_hostname);
823 void qmp_migrate_start_postcopy(Error **errp)
825 MigrationState *s = migrate_get_current();
827 if (!migrate_postcopy_ram()) {
828 error_setg(errp, "Enable postcopy with migrate_set_capability before"
829 " the start of migration");
830 return;
833 if (s->state == MIGRATION_STATUS_NONE) {
834 error_setg(errp, "Postcopy must be started after migration has been"
835 " started");
836 return;
839 * we don't error if migration has finished since that would be racy
840 * with issuing this command.
842 atomic_set(&s->start_postcopy, true);
845 /* shared migration helpers */
847 void migrate_set_state(int *state, int old_state, int new_state)
849 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
850 trace_migrate_set_state(new_state);
851 migrate_generate_event(new_state);
855 static void migrate_fd_cleanup(void *opaque)
857 MigrationState *s = opaque;
859 qemu_bh_delete(s->cleanup_bh);
860 s->cleanup_bh = NULL;
862 flush_page_queue(s);
864 if (s->to_dst_file) {
865 trace_migrate_fd_cleanup();
866 qemu_mutex_unlock_iothread();
867 if (s->migration_thread_running) {
868 qemu_thread_join(&s->thread);
869 s->migration_thread_running = false;
871 qemu_mutex_lock_iothread();
873 migrate_compress_threads_join();
874 qemu_fclose(s->to_dst_file);
875 s->to_dst_file = NULL;
878 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
879 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
881 if (s->state == MIGRATION_STATUS_CANCELLING) {
882 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
883 MIGRATION_STATUS_CANCELLED);
886 notifier_list_notify(&migration_state_notifiers, s);
889 void migrate_fd_error(MigrationState *s, const Error *error)
891 trace_migrate_fd_error(error ? error_get_pretty(error) : "");
892 assert(s->to_dst_file == NULL);
893 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
894 MIGRATION_STATUS_FAILED);
895 if (!s->error) {
896 s->error = error_copy(error);
898 notifier_list_notify(&migration_state_notifiers, s);
901 static void migrate_fd_cancel(MigrationState *s)
903 int old_state ;
904 QEMUFile *f = migrate_get_current()->to_dst_file;
905 trace_migrate_fd_cancel();
907 if (s->rp_state.from_dst_file) {
908 /* shutdown the rp socket, so causing the rp thread to shutdown */
909 qemu_file_shutdown(s->rp_state.from_dst_file);
912 do {
913 old_state = s->state;
914 if (!migration_is_setup_or_active(old_state)) {
915 break;
917 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
918 } while (s->state != MIGRATION_STATUS_CANCELLING);
921 * If we're unlucky the migration code might be stuck somewhere in a
922 * send/write while the network has failed and is waiting to timeout;
923 * if we've got shutdown(2) available then we can force it to quit.
924 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
925 * called in a bh, so there is no race against this cancel.
927 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
928 qemu_file_shutdown(f);
932 void add_migration_state_change_notifier(Notifier *notify)
934 notifier_list_add(&migration_state_notifiers, notify);
937 void remove_migration_state_change_notifier(Notifier *notify)
939 notifier_remove(notify);
942 bool migration_in_setup(MigrationState *s)
944 return s->state == MIGRATION_STATUS_SETUP;
947 bool migration_has_finished(MigrationState *s)
949 return s->state == MIGRATION_STATUS_COMPLETED;
952 bool migration_has_failed(MigrationState *s)
954 return (s->state == MIGRATION_STATUS_CANCELLED ||
955 s->state == MIGRATION_STATUS_FAILED);
958 bool migration_in_postcopy(MigrationState *s)
960 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
963 bool migration_in_postcopy_after_devices(MigrationState *s)
965 return migration_in_postcopy(s) && s->postcopy_after_devices;
968 MigrationState *migrate_init(const MigrationParams *params)
970 MigrationState *s = migrate_get_current();
973 * Reinitialise all migration state, except
974 * parameters/capabilities that the user set, and
975 * locks.
977 s->bytes_xfer = 0;
978 s->xfer_limit = 0;
979 s->cleanup_bh = 0;
980 s->to_dst_file = NULL;
981 s->state = MIGRATION_STATUS_NONE;
982 s->params = *params;
983 s->rp_state.from_dst_file = NULL;
984 s->rp_state.error = false;
985 s->mbps = 0.0;
986 s->downtime = 0;
987 s->expected_downtime = 0;
988 s->dirty_pages_rate = 0;
989 s->dirty_bytes_rate = 0;
990 s->setup_time = 0;
991 s->dirty_sync_count = 0;
992 s->start_postcopy = false;
993 s->postcopy_after_devices = false;
994 s->migration_thread_running = false;
995 s->last_req_rb = NULL;
996 error_free(s->error);
997 s->error = NULL;
999 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1001 QSIMPLEQ_INIT(&s->src_page_requests);
1003 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1004 return s;
1007 static GSList *migration_blockers;
1009 void migrate_add_blocker(Error *reason)
1011 migration_blockers = g_slist_prepend(migration_blockers, reason);
1014 void migrate_del_blocker(Error *reason)
1016 migration_blockers = g_slist_remove(migration_blockers, reason);
1019 void qmp_migrate_incoming(const char *uri, Error **errp)
1021 Error *local_err = NULL;
1022 static bool once = true;
1024 if (!deferred_incoming) {
1025 error_setg(errp, "For use with '-incoming defer'");
1026 return;
1028 if (!once) {
1029 error_setg(errp, "The incoming migration has already been started");
1032 qemu_start_incoming_migration(uri, &local_err);
1034 if (local_err) {
1035 error_propagate(errp, local_err);
1036 return;
1039 once = false;
1042 bool migration_is_blocked(Error **errp)
1044 if (qemu_savevm_state_blocked(errp)) {
1045 return true;
1048 if (migration_blockers) {
1049 *errp = error_copy(migration_blockers->data);
1050 return true;
1053 return false;
1056 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1057 bool has_inc, bool inc, bool has_detach, bool detach,
1058 Error **errp)
1060 Error *local_err = NULL;
1061 MigrationState *s = migrate_get_current();
1062 MigrationParams params;
1063 const char *p;
1065 params.blk = has_blk && blk;
1066 params.shared = has_inc && inc;
1068 if (migration_is_setup_or_active(s->state) ||
1069 s->state == MIGRATION_STATUS_CANCELLING) {
1070 error_setg(errp, QERR_MIGRATION_ACTIVE);
1071 return;
1073 if (runstate_check(RUN_STATE_INMIGRATE)) {
1074 error_setg(errp, "Guest is waiting for an incoming migration");
1075 return;
1078 if (migration_is_blocked(errp)) {
1079 return;
1082 s = migrate_init(&params);
1084 if (strstart(uri, "tcp:", &p)) {
1085 tcp_start_outgoing_migration(s, p, &local_err);
1086 #ifdef CONFIG_RDMA
1087 } else if (strstart(uri, "rdma:", &p)) {
1088 rdma_start_outgoing_migration(s, p, &local_err);
1089 #endif
1090 } else if (strstart(uri, "exec:", &p)) {
1091 exec_start_outgoing_migration(s, p, &local_err);
1092 } else if (strstart(uri, "unix:", &p)) {
1093 unix_start_outgoing_migration(s, p, &local_err);
1094 } else if (strstart(uri, "fd:", &p)) {
1095 fd_start_outgoing_migration(s, p, &local_err);
1096 } else {
1097 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1098 "a valid migration protocol");
1099 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1100 MIGRATION_STATUS_FAILED);
1101 return;
1104 if (local_err) {
1105 migrate_fd_error(s, local_err);
1106 error_propagate(errp, local_err);
1107 return;
1111 void qmp_migrate_cancel(Error **errp)
1113 migrate_fd_cancel(migrate_get_current());
1116 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1118 MigrationState *s = migrate_get_current();
1119 int64_t new_size;
1121 /* Check for truncation */
1122 if (value != (size_t)value) {
1123 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1124 "exceeding address space");
1125 return;
1128 /* Cache should not be larger than guest ram size */
1129 if (value > ram_bytes_total()) {
1130 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1131 "exceeds guest ram size ");
1132 return;
1135 new_size = xbzrle_cache_resize(value);
1136 if (new_size < 0) {
1137 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1138 "is smaller than page size");
1139 return;
1142 s->xbzrle_cache_size = new_size;
1145 int64_t qmp_query_migrate_cache_size(Error **errp)
1147 return migrate_xbzrle_cache_size();
1150 void qmp_migrate_set_speed(int64_t value, Error **errp)
1152 MigrationState *s;
1154 if (value < 0) {
1155 value = 0;
1157 if (value > SIZE_MAX) {
1158 value = SIZE_MAX;
1161 s = migrate_get_current();
1162 s->bandwidth_limit = value;
1163 if (s->to_dst_file) {
1164 qemu_file_set_rate_limit(s->to_dst_file,
1165 s->bandwidth_limit / XFER_LIMIT_RATIO);
1169 void qmp_migrate_set_downtime(double value, Error **errp)
1171 value *= 1e9;
1172 value = MAX(0, MIN(UINT64_MAX, value));
1173 max_downtime = (uint64_t)value;
1176 bool migrate_postcopy_ram(void)
1178 MigrationState *s;
1180 s = migrate_get_current();
1182 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1185 bool migrate_auto_converge(void)
1187 MigrationState *s;
1189 s = migrate_get_current();
1191 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1194 bool migrate_zero_blocks(void)
1196 MigrationState *s;
1198 s = migrate_get_current();
1200 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1203 bool migrate_use_compression(void)
1205 MigrationState *s;
1207 s = migrate_get_current();
1209 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1212 int migrate_compress_level(void)
1214 MigrationState *s;
1216 s = migrate_get_current();
1218 return s->parameters.compress_level;
1221 int migrate_compress_threads(void)
1223 MigrationState *s;
1225 s = migrate_get_current();
1227 return s->parameters.compress_threads;
1230 int migrate_decompress_threads(void)
1232 MigrationState *s;
1234 s = migrate_get_current();
1236 return s->parameters.decompress_threads;
1239 bool migrate_use_events(void)
1241 MigrationState *s;
1243 s = migrate_get_current();
1245 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1248 int migrate_use_xbzrle(void)
1250 MigrationState *s;
1252 s = migrate_get_current();
1254 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1257 int64_t migrate_xbzrle_cache_size(void)
1259 MigrationState *s;
1261 s = migrate_get_current();
1263 return s->xbzrle_cache_size;
1266 /* migration thread support */
1268 * Something bad happened to the RP stream, mark an error
1269 * The caller shall print or trace something to indicate why
1271 static void mark_source_rp_bad(MigrationState *s)
1273 s->rp_state.error = true;
1276 static struct rp_cmd_args {
1277 ssize_t len; /* -1 = variable */
1278 const char *name;
1279 } rp_cmd_args[] = {
1280 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1281 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1282 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1283 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1284 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1285 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1289 * Process a request for pages received on the return path,
1290 * We're allowed to send more than requested (e.g. to round to our page size)
1291 * and we don't need to send pages that have already been sent.
1293 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1294 ram_addr_t start, size_t len)
1296 long our_host_ps = getpagesize();
1298 trace_migrate_handle_rp_req_pages(rbname, start, len);
1301 * Since we currently insist on matching page sizes, just sanity check
1302 * we're being asked for whole host pages.
1304 if (start & (our_host_ps-1) ||
1305 (len & (our_host_ps-1))) {
1306 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1307 " len: %zd", __func__, start, len);
1308 mark_source_rp_bad(ms);
1309 return;
1312 if (ram_save_queue_pages(ms, rbname, start, len)) {
1313 mark_source_rp_bad(ms);
1318 * Handles messages sent on the return path towards the source VM
1321 static void *source_return_path_thread(void *opaque)
1323 MigrationState *ms = opaque;
1324 QEMUFile *rp = ms->rp_state.from_dst_file;
1325 uint16_t header_len, header_type;
1326 uint8_t buf[512];
1327 uint32_t tmp32, sibling_error;
1328 ram_addr_t start = 0; /* =0 to silence warning */
1329 size_t len = 0, expected_len;
1330 int res;
1332 trace_source_return_path_thread_entry();
1333 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1334 migration_is_setup_or_active(ms->state)) {
1335 trace_source_return_path_thread_loop_top();
1336 header_type = qemu_get_be16(rp);
1337 header_len = qemu_get_be16(rp);
1339 if (header_type >= MIG_RP_MSG_MAX ||
1340 header_type == MIG_RP_MSG_INVALID) {
1341 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1342 header_type, header_len);
1343 mark_source_rp_bad(ms);
1344 goto out;
1347 if ((rp_cmd_args[header_type].len != -1 &&
1348 header_len != rp_cmd_args[header_type].len) ||
1349 header_len > sizeof(buf)) {
1350 error_report("RP: Received '%s' message (0x%04x) with"
1351 "incorrect length %d expecting %zu",
1352 rp_cmd_args[header_type].name, header_type, header_len,
1353 (size_t)rp_cmd_args[header_type].len);
1354 mark_source_rp_bad(ms);
1355 goto out;
1358 /* We know we've got a valid header by this point */
1359 res = qemu_get_buffer(rp, buf, header_len);
1360 if (res != header_len) {
1361 error_report("RP: Failed reading data for message 0x%04x"
1362 " read %d expected %d",
1363 header_type, res, header_len);
1364 mark_source_rp_bad(ms);
1365 goto out;
1368 /* OK, we have the message and the data */
1369 switch (header_type) {
1370 case MIG_RP_MSG_SHUT:
1371 sibling_error = be32_to_cpup((uint32_t *)buf);
1372 trace_source_return_path_thread_shut(sibling_error);
1373 if (sibling_error) {
1374 error_report("RP: Sibling indicated error %d", sibling_error);
1375 mark_source_rp_bad(ms);
1378 * We'll let the main thread deal with closing the RP
1379 * we could do a shutdown(2) on it, but we're the only user
1380 * anyway, so there's nothing gained.
1382 goto out;
1384 case MIG_RP_MSG_PONG:
1385 tmp32 = be32_to_cpup((uint32_t *)buf);
1386 trace_source_return_path_thread_pong(tmp32);
1387 break;
1389 case MIG_RP_MSG_REQ_PAGES:
1390 start = be64_to_cpup((uint64_t *)buf);
1391 len = be32_to_cpup((uint32_t *)(buf + 8));
1392 migrate_handle_rp_req_pages(ms, NULL, start, len);
1393 break;
1395 case MIG_RP_MSG_REQ_PAGES_ID:
1396 expected_len = 12 + 1; /* header + termination */
1398 if (header_len >= expected_len) {
1399 start = be64_to_cpup((uint64_t *)buf);
1400 len = be32_to_cpup((uint32_t *)(buf + 8));
1401 /* Now we expect an idstr */
1402 tmp32 = buf[12]; /* Length of the following idstr */
1403 buf[13 + tmp32] = '\0';
1404 expected_len += tmp32;
1406 if (header_len != expected_len) {
1407 error_report("RP: Req_Page_id with length %d expecting %zd",
1408 header_len, expected_len);
1409 mark_source_rp_bad(ms);
1410 goto out;
1412 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1413 break;
1415 default:
1416 break;
1419 if (qemu_file_get_error(rp)) {
1420 trace_source_return_path_thread_bad_end();
1421 mark_source_rp_bad(ms);
1424 trace_source_return_path_thread_end();
1425 out:
1426 ms->rp_state.from_dst_file = NULL;
1427 qemu_fclose(rp);
1428 return NULL;
1431 static int open_return_path_on_source(MigrationState *ms)
1434 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
1435 if (!ms->rp_state.from_dst_file) {
1436 return -1;
1439 trace_open_return_path_on_source();
1440 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1441 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1443 trace_open_return_path_on_source_continue();
1445 return 0;
1448 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1449 static int await_return_path_close_on_source(MigrationState *ms)
1452 * If this is a normal exit then the destination will send a SHUT and the
1453 * rp_thread will exit, however if there's an error we need to cause
1454 * it to exit.
1456 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
1458 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1459 * waiting for the destination.
1461 qemu_file_shutdown(ms->rp_state.from_dst_file);
1462 mark_source_rp_bad(ms);
1464 trace_await_return_path_close_on_source_joining();
1465 qemu_thread_join(&ms->rp_state.rp_thread);
1466 trace_await_return_path_close_on_source_close();
1467 return ms->rp_state.error;
1471 * Switch from normal iteration to postcopy
1472 * Returns non-0 on error
1474 static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1476 int ret;
1477 QIOChannelBuffer *bioc;
1478 QEMUFile *fb;
1479 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1480 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1481 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1483 trace_postcopy_start();
1484 qemu_mutex_lock_iothread();
1485 trace_postcopy_start_set_run();
1487 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1488 *old_vm_running = runstate_is_running();
1489 global_state_store();
1490 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1491 if (ret < 0) {
1492 goto fail;
1495 ret = bdrv_inactivate_all();
1496 if (ret < 0) {
1497 goto fail;
1501 * Cause any non-postcopiable, but iterative devices to
1502 * send out their final data.
1504 qemu_savevm_state_complete_precopy(ms->to_dst_file, true);
1507 * in Finish migrate and with the io-lock held everything should
1508 * be quiet, but we've potentially still got dirty pages and we
1509 * need to tell the destination to throw any pages it's already received
1510 * that are dirty
1512 if (ram_postcopy_send_discard_bitmap(ms)) {
1513 error_report("postcopy send discard bitmap failed");
1514 goto fail;
1518 * send rest of state - note things that are doing postcopy
1519 * will notice we're in POSTCOPY_ACTIVE and not actually
1520 * wrap their state up here
1522 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
1523 /* Ping just for debugging, helps line traces up */
1524 qemu_savevm_send_ping(ms->to_dst_file, 2);
1527 * While loading the device state we may trigger page transfer
1528 * requests and the fd must be free to process those, and thus
1529 * the destination must read the whole device state off the fd before
1530 * it starts processing it. Unfortunately the ad-hoc migration format
1531 * doesn't allow the destination to know the size to read without fully
1532 * parsing it through each devices load-state code (especially the open
1533 * coded devices that use get/put).
1534 * So we wrap the device state up in a package with a length at the start;
1535 * to do this we use a qemu_buf to hold the whole of the device state.
1537 bioc = qio_channel_buffer_new(4096);
1538 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
1539 object_unref(OBJECT(bioc));
1542 * Make sure the receiver can get incoming pages before we send the rest
1543 * of the state
1545 qemu_savevm_send_postcopy_listen(fb);
1547 qemu_savevm_state_complete_precopy(fb, false);
1548 qemu_savevm_send_ping(fb, 3);
1550 qemu_savevm_send_postcopy_run(fb);
1552 /* <><> end of stuff going into the package */
1554 /* Now send that blob */
1555 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1556 goto fail_closefb;
1558 qemu_fclose(fb);
1560 /* Send a notify to give a chance for anything that needs to happen
1561 * at the transition to postcopy and after the device state; in particular
1562 * spice needs to trigger a transition now
1564 ms->postcopy_after_devices = true;
1565 notifier_list_notify(&migration_state_notifiers, ms);
1567 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1569 qemu_mutex_unlock_iothread();
1572 * Although this ping is just for debug, it could potentially be
1573 * used for getting a better measurement of downtime at the source.
1575 qemu_savevm_send_ping(ms->to_dst_file, 4);
1577 ret = qemu_file_get_error(ms->to_dst_file);
1578 if (ret) {
1579 error_report("postcopy_start: Migration stream errored");
1580 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1581 MIGRATION_STATUS_FAILED);
1584 return ret;
1586 fail_closefb:
1587 qemu_fclose(fb);
1588 fail:
1589 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1590 MIGRATION_STATUS_FAILED);
1591 qemu_mutex_unlock_iothread();
1592 return -1;
1596 * migration_completion: Used by migration_thread when there's not much left.
1597 * The caller 'breaks' the loop when this returns.
1599 * @s: Current migration state
1600 * @current_active_state: The migration state we expect to be in
1601 * @*old_vm_running: Pointer to old_vm_running flag
1602 * @*start_time: Pointer to time to update
1604 static void migration_completion(MigrationState *s, int current_active_state,
1605 bool *old_vm_running,
1606 int64_t *start_time)
1608 int ret;
1610 if (s->state == MIGRATION_STATUS_ACTIVE) {
1611 qemu_mutex_lock_iothread();
1612 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1613 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1614 *old_vm_running = runstate_is_running();
1615 ret = global_state_store();
1617 if (!ret) {
1618 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1619 if (ret >= 0) {
1620 ret = bdrv_inactivate_all();
1622 if (ret >= 0) {
1623 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
1624 qemu_savevm_state_complete_precopy(s->to_dst_file, false);
1627 qemu_mutex_unlock_iothread();
1629 if (ret < 0) {
1630 goto fail;
1632 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1633 trace_migration_completion_postcopy_end();
1635 qemu_savevm_state_complete_postcopy(s->to_dst_file);
1636 trace_migration_completion_postcopy_end_after_complete();
1640 * If rp was opened we must clean up the thread before
1641 * cleaning everything else up (since if there are no failures
1642 * it will wait for the destination to send it's status in
1643 * a SHUT command).
1644 * Postcopy opens rp if enabled (even if it's not avtivated)
1646 if (migrate_postcopy_ram()) {
1647 int rp_error;
1648 trace_migration_completion_postcopy_end_before_rp();
1649 rp_error = await_return_path_close_on_source(s);
1650 trace_migration_completion_postcopy_end_after_rp(rp_error);
1651 if (rp_error) {
1652 goto fail_invalidate;
1656 if (qemu_file_get_error(s->to_dst_file)) {
1657 trace_migration_completion_file_err();
1658 goto fail_invalidate;
1661 migrate_set_state(&s->state, current_active_state,
1662 MIGRATION_STATUS_COMPLETED);
1663 return;
1665 fail_invalidate:
1666 /* If not doing postcopy, vm_start() will be called: let's regain
1667 * control on images.
1669 if (s->state == MIGRATION_STATUS_ACTIVE) {
1670 Error *local_err = NULL;
1672 bdrv_invalidate_cache_all(&local_err);
1673 if (local_err) {
1674 error_report_err(local_err);
1678 fail:
1679 migrate_set_state(&s->state, current_active_state,
1680 MIGRATION_STATUS_FAILED);
1684 * Master migration thread on the source VM.
1685 * It drives the migration and pumps the data down the outgoing channel.
1687 static void *migration_thread(void *opaque)
1689 MigrationState *s = opaque;
1690 /* Used by the bandwidth calcs, updated later */
1691 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1692 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
1693 int64_t initial_bytes = 0;
1694 int64_t max_size = 0;
1695 int64_t start_time = initial_time;
1696 int64_t end_time;
1697 bool old_vm_running = false;
1698 bool entered_postcopy = false;
1699 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1700 enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
1702 rcu_register_thread();
1704 qemu_savevm_state_header(s->to_dst_file);
1706 if (migrate_postcopy_ram()) {
1707 /* Now tell the dest that it should open its end so it can reply */
1708 qemu_savevm_send_open_return_path(s->to_dst_file);
1710 /* And do a ping that will make stuff easier to debug */
1711 qemu_savevm_send_ping(s->to_dst_file, 1);
1714 * Tell the destination that we *might* want to do postcopy later;
1715 * if the other end can't do postcopy it should fail now, nice and
1716 * early.
1718 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1721 qemu_savevm_state_begin(s->to_dst_file, &s->params);
1723 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
1724 current_active_state = MIGRATION_STATUS_ACTIVE;
1725 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1726 MIGRATION_STATUS_ACTIVE);
1728 trace_migration_thread_setup_complete();
1730 while (s->state == MIGRATION_STATUS_ACTIVE ||
1731 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1732 int64_t current_time;
1733 uint64_t pending_size;
1735 if (!qemu_file_rate_limit(s->to_dst_file)) {
1736 uint64_t pend_post, pend_nonpost;
1738 qemu_savevm_state_pending(s->to_dst_file, max_size, &pend_nonpost,
1739 &pend_post);
1740 pending_size = pend_nonpost + pend_post;
1741 trace_migrate_pending(pending_size, max_size,
1742 pend_post, pend_nonpost);
1743 if (pending_size && pending_size >= max_size) {
1744 /* Still a significant amount to transfer */
1746 if (migrate_postcopy_ram() &&
1747 s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
1748 pend_nonpost <= max_size &&
1749 atomic_read(&s->start_postcopy)) {
1751 if (!postcopy_start(s, &old_vm_running)) {
1752 current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1753 entered_postcopy = true;
1756 continue;
1758 /* Just another iteration step */
1759 qemu_savevm_state_iterate(s->to_dst_file, entered_postcopy);
1760 } else {
1761 trace_migration_thread_low_pending(pending_size);
1762 migration_completion(s, current_active_state,
1763 &old_vm_running, &start_time);
1764 break;
1768 if (qemu_file_get_error(s->to_dst_file)) {
1769 migrate_set_state(&s->state, current_active_state,
1770 MIGRATION_STATUS_FAILED);
1771 trace_migration_thread_file_err();
1772 break;
1774 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1775 if (current_time >= initial_time + BUFFER_DELAY) {
1776 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file) -
1777 initial_bytes;
1778 uint64_t time_spent = current_time - initial_time;
1779 double bandwidth = (double)transferred_bytes / time_spent;
1780 max_size = bandwidth * migrate_max_downtime() / 1000000;
1782 s->mbps = (((double) transferred_bytes * 8.0) /
1783 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
1785 trace_migrate_transferred(transferred_bytes, time_spent,
1786 bandwidth, max_size);
1787 /* if we haven't sent anything, we don't want to recalculate
1788 10000 is a small enough number for our purposes */
1789 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1790 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1793 qemu_file_reset_rate_limit(s->to_dst_file);
1794 initial_time = current_time;
1795 initial_bytes = qemu_ftell(s->to_dst_file);
1797 if (qemu_file_rate_limit(s->to_dst_file)) {
1798 /* usleep expects microseconds */
1799 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1803 trace_migration_thread_after_loop();
1804 /* If we enabled cpu throttling for auto-converge, turn it off. */
1805 cpu_throttle_stop();
1806 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1808 qemu_mutex_lock_iothread();
1809 qemu_savevm_state_cleanup();
1810 if (s->state == MIGRATION_STATUS_COMPLETED) {
1811 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file);
1812 s->total_time = end_time - s->total_time;
1813 if (!entered_postcopy) {
1814 s->downtime = end_time - start_time;
1816 if (s->total_time) {
1817 s->mbps = (((double) transferred_bytes * 8.0) /
1818 ((double) s->total_time)) / 1000;
1820 runstate_set(RUN_STATE_POSTMIGRATE);
1821 } else {
1822 if (old_vm_running && !entered_postcopy) {
1823 vm_start();
1826 qemu_bh_schedule(s->cleanup_bh);
1827 qemu_mutex_unlock_iothread();
1829 rcu_unregister_thread();
1830 return NULL;
1833 void migrate_fd_connect(MigrationState *s)
1835 /* This is a best 1st approximation. ns to ms */
1836 s->expected_downtime = max_downtime/1000000;
1837 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1839 qemu_file_set_blocking(s->to_dst_file, true);
1840 qemu_file_set_rate_limit(s->to_dst_file,
1841 s->bandwidth_limit / XFER_LIMIT_RATIO);
1843 /* Notify before starting migration thread */
1844 notifier_list_notify(&migration_state_notifiers, s);
1847 * Open the return path; currently for postcopy but other things might
1848 * also want it.
1850 if (migrate_postcopy_ram()) {
1851 if (open_return_path_on_source(s)) {
1852 error_report("Unable to open return-path for postcopy");
1853 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1854 MIGRATION_STATUS_FAILED);
1855 migrate_fd_cleanup(s);
1856 return;
1860 migrate_compress_threads_create();
1861 qemu_thread_create(&s->thread, "migration", migration_thread, s,
1862 QEMU_THREAD_JOINABLE);
1863 s->migration_thread_running = true;
1866 PostcopyState postcopy_state_get(void)
1868 return atomic_mb_read(&incoming_postcopy_state);
1871 /* Set the state and return the old state */
1872 PostcopyState postcopy_state_set(PostcopyState new_state)
1874 return atomic_xchg(&incoming_postcopy_state, new_state);