postcopy_ram.c: place_page and helpers
[qemu/ar7.git] / migration / migration.c
blob7d64cd324063b0bf9c6027e11f868f42b97193d2
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-common.h"
17 #include "qemu/error-report.h"
18 #include "qemu/main-loop.h"
19 #include "migration/migration.h"
20 #include "migration/qemu-file.h"
21 #include "sysemu/sysemu.h"
22 #include "block/block.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qapi/util.h"
25 #include "qemu/sockets.h"
26 #include "qemu/rcu.h"
27 #include "migration/block.h"
28 #include "migration/postcopy-ram.h"
29 #include "qemu/thread.h"
30 #include "qmp-commands.h"
31 #include "trace.h"
32 #include "qapi-event.h"
33 #include "qom/cpu.h"
34 #include "exec/memory.h"
35 #include "exec/address-spaces.h"
37 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
39 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
40 * data. */
41 #define BUFFER_DELAY 100
42 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
44 /* Default compression thread count */
45 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
46 /* Default decompression thread count, usually decompression is at
47 * least 4 times as fast as compression.*/
48 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
49 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
50 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
51 /* Define default autoconverge cpu throttle migration parameters */
52 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL 20
53 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT 10
55 /* Migration XBZRLE default cache size */
56 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
58 static NotifierList migration_state_notifiers =
59 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
61 static bool deferred_incoming;
64 * Current state of incoming postcopy; note this is not part of
65 * MigrationIncomingState since it's state is used during cleanup
66 * at the end as MIS is being freed.
68 static PostcopyState incoming_postcopy_state;
70 /* When we add fault tolerance, we could have several
71 migrations at once. For now we don't need to add
72 dynamic creation of migration */
74 /* For outgoing */
75 MigrationState *migrate_get_current(void)
77 static bool once;
78 static MigrationState current_migration = {
79 .state = MIGRATION_STATUS_NONE,
80 .bandwidth_limit = MAX_THROTTLE,
81 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
82 .mbps = -1,
83 .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
84 DEFAULT_MIGRATE_COMPRESS_LEVEL,
85 .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
86 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
87 .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
88 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
89 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
90 DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL,
91 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
92 DEFAULT_MIGRATE_X_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 QLIST_INIT(&mis_current->loadvm_handlers);
115 qemu_mutex_init(&mis_current->rp_mutex);
116 qemu_event_init(&mis_current->main_thread_load_event, false);
118 return mis_current;
121 void migration_incoming_state_destroy(void)
123 qemu_event_destroy(&mis_current->main_thread_load_event);
124 loadvm_free_handlers(mis_current);
125 g_free(mis_current);
126 mis_current = NULL;
130 typedef struct {
131 bool optional;
132 uint32_t size;
133 uint8_t runstate[100];
134 RunState state;
135 bool received;
136 } GlobalState;
138 static GlobalState global_state;
140 int global_state_store(void)
142 if (!runstate_store((char *)global_state.runstate,
143 sizeof(global_state.runstate))) {
144 error_report("runstate name too big: %s", global_state.runstate);
145 trace_migrate_state_too_big();
146 return -EINVAL;
148 return 0;
151 void global_state_store_running(void)
153 const char *state = RunState_lookup[RUN_STATE_RUNNING];
154 strncpy((char *)global_state.runstate,
155 state, sizeof(global_state.runstate));
158 static bool global_state_received(void)
160 return global_state.received;
163 static RunState global_state_get_runstate(void)
165 return global_state.state;
168 void global_state_set_optional(void)
170 global_state.optional = true;
173 static bool global_state_needed(void *opaque)
175 GlobalState *s = opaque;
176 char *runstate = (char *)s->runstate;
178 /* If it is not optional, it is mandatory */
180 if (s->optional == false) {
181 return true;
184 /* If state is running or paused, it is not needed */
186 if (strcmp(runstate, "running") == 0 ||
187 strcmp(runstate, "paused") == 0) {
188 return false;
191 /* for any other state it is needed */
192 return true;
195 static int global_state_post_load(void *opaque, int version_id)
197 GlobalState *s = opaque;
198 Error *local_err = NULL;
199 int r;
200 char *runstate = (char *)s->runstate;
202 s->received = true;
203 trace_migrate_global_state_post_load(runstate);
205 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE_MAX,
206 -1, &local_err);
208 if (r == -1) {
209 if (local_err) {
210 error_report_err(local_err);
212 return -EINVAL;
214 s->state = r;
216 return 0;
219 static void global_state_pre_save(void *opaque)
221 GlobalState *s = opaque;
223 trace_migrate_global_state_pre_save((char *)s->runstate);
224 s->size = strlen((char *)s->runstate) + 1;
227 static const VMStateDescription vmstate_globalstate = {
228 .name = "globalstate",
229 .version_id = 1,
230 .minimum_version_id = 1,
231 .post_load = global_state_post_load,
232 .pre_save = global_state_pre_save,
233 .needed = global_state_needed,
234 .fields = (VMStateField[]) {
235 VMSTATE_UINT32(size, GlobalState),
236 VMSTATE_BUFFER(runstate, GlobalState),
237 VMSTATE_END_OF_LIST()
241 void register_global_state(void)
243 /* We would use it independently that we receive it */
244 strcpy((char *)&global_state.runstate, "");
245 global_state.received = false;
246 vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
249 static void migrate_generate_event(int new_state)
251 if (migrate_use_events()) {
252 qapi_event_send_migration(new_state, &error_abort);
257 * Called on -incoming with a defer: uri.
258 * The migration can be started later after any parameters have been
259 * changed.
261 static void deferred_incoming_migration(Error **errp)
263 if (deferred_incoming) {
264 error_setg(errp, "Incoming migration already deferred");
266 deferred_incoming = true;
269 /* Request a range of pages from the source VM at the given
270 * start address.
271 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
272 * as the last request (a name must have been given previously)
273 * Start: Address offset within the RB
274 * Len: Length in bytes required - must be a multiple of pagesize
276 void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
277 ram_addr_t start, size_t len)
279 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname upto 256 */
280 size_t msglen = 12; /* start + len */
282 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
283 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
285 if (rbname) {
286 int rbname_len = strlen(rbname);
287 assert(rbname_len < 256);
289 bufc[msglen++] = rbname_len;
290 memcpy(bufc + msglen, rbname, rbname_len);
291 msglen += rbname_len;
292 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES_ID, msglen, bufc);
293 } else {
294 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES, msglen, bufc);
298 void qemu_start_incoming_migration(const char *uri, Error **errp)
300 const char *p;
302 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
303 if (!strcmp(uri, "defer")) {
304 deferred_incoming_migration(errp);
305 } else if (strstart(uri, "tcp:", &p)) {
306 tcp_start_incoming_migration(p, errp);
307 #ifdef CONFIG_RDMA
308 } else if (strstart(uri, "rdma:", &p)) {
309 rdma_start_incoming_migration(p, errp);
310 #endif
311 #if !defined(WIN32)
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 #endif
319 } else {
320 error_setg(errp, "unknown migration protocol: %s", uri);
324 static void process_incoming_migration_co(void *opaque)
326 QEMUFile *f = opaque;
327 Error *local_err = NULL;
328 int ret;
330 migration_incoming_state_new(f);
331 postcopy_state_set(POSTCOPY_INCOMING_NONE);
332 migrate_generate_event(MIGRATION_STATUS_ACTIVE);
333 ret = qemu_loadvm_state(f);
335 qemu_fclose(f);
336 free_xbzrle_decoded_buf();
337 migration_incoming_state_destroy();
339 if (ret < 0) {
340 migrate_generate_event(MIGRATION_STATUS_FAILED);
341 error_report("load of migration failed: %s", strerror(-ret));
342 migrate_decompress_threads_join();
343 exit(EXIT_FAILURE);
346 /* Make sure all file formats flush their mutable metadata */
347 bdrv_invalidate_cache_all(&local_err);
348 if (local_err) {
349 migrate_generate_event(MIGRATION_STATUS_FAILED);
350 error_report_err(local_err);
351 migrate_decompress_threads_join();
352 exit(EXIT_FAILURE);
356 * This must happen after all error conditions are dealt with and
357 * we're sure the VM is going to be running on this host.
359 qemu_announce_self();
361 /* If global state section was not received or we are in running
362 state, we need to obey autostart. Any other state is set with
363 runstate_set. */
365 if (!global_state_received() ||
366 global_state_get_runstate() == RUN_STATE_RUNNING) {
367 if (autostart) {
368 vm_start();
369 } else {
370 runstate_set(RUN_STATE_PAUSED);
372 } else {
373 runstate_set(global_state_get_runstate());
375 migrate_decompress_threads_join();
377 * This must happen after any state changes since as soon as an external
378 * observer sees this event they might start to prod at the VM assuming
379 * it's ready to use.
381 migrate_generate_event(MIGRATION_STATUS_COMPLETED);
384 void process_incoming_migration(QEMUFile *f)
386 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
387 int fd = qemu_get_fd(f);
389 assert(fd != -1);
390 migrate_decompress_threads_create();
391 qemu_set_nonblock(fd);
392 qemu_coroutine_enter(co, f);
396 * Send a message on the return channel back to the source
397 * of the migration.
399 void migrate_send_rp_message(MigrationIncomingState *mis,
400 enum mig_rp_message_type message_type,
401 uint16_t len, void *data)
403 trace_migrate_send_rp_message((int)message_type, len);
404 qemu_mutex_lock(&mis->rp_mutex);
405 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
406 qemu_put_be16(mis->to_src_file, len);
407 qemu_put_buffer(mis->to_src_file, data, len);
408 qemu_fflush(mis->to_src_file);
409 qemu_mutex_unlock(&mis->rp_mutex);
413 * Send a 'SHUT' message on the return channel with the given value
414 * to indicate that we've finished with the RP. Non-0 value indicates
415 * error.
417 void migrate_send_rp_shut(MigrationIncomingState *mis,
418 uint32_t value)
420 uint32_t buf;
422 buf = cpu_to_be32(value);
423 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
427 * Send a 'PONG' message on the return channel with the given value
428 * (normally in response to a 'PING')
430 void migrate_send_rp_pong(MigrationIncomingState *mis,
431 uint32_t value)
433 uint32_t buf;
435 buf = cpu_to_be32(value);
436 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
439 /* amount of nanoseconds we are willing to wait for migration to be down.
440 * the choice of nanoseconds is because it is the maximum resolution that
441 * get_clock() can achieve. It is an internal measure. All user-visible
442 * units must be in seconds */
443 static uint64_t max_downtime = 300000000;
445 uint64_t migrate_max_downtime(void)
447 return max_downtime;
450 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
452 MigrationCapabilityStatusList *head = NULL;
453 MigrationCapabilityStatusList *caps;
454 MigrationState *s = migrate_get_current();
455 int i;
457 caps = NULL; /* silence compiler warning */
458 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
459 if (head == NULL) {
460 head = g_malloc0(sizeof(*caps));
461 caps = head;
462 } else {
463 caps->next = g_malloc0(sizeof(*caps));
464 caps = caps->next;
466 caps->value =
467 g_malloc(sizeof(*caps->value));
468 caps->value->capability = i;
469 caps->value->state = s->enabled_capabilities[i];
472 return head;
475 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
477 MigrationParameters *params;
478 MigrationState *s = migrate_get_current();
480 params = g_malloc0(sizeof(*params));
481 params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
482 params->compress_threads =
483 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
484 params->decompress_threads =
485 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
486 params->x_cpu_throttle_initial =
487 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
488 params->x_cpu_throttle_increment =
489 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
491 return params;
495 * Return true if we're already in the middle of a migration
496 * (i.e. any of the active or setup states)
498 static bool migration_is_setup_or_active(int state)
500 switch (state) {
501 case MIGRATION_STATUS_ACTIVE:
502 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
503 case MIGRATION_STATUS_SETUP:
504 return true;
506 default:
507 return false;
512 static void get_xbzrle_cache_stats(MigrationInfo *info)
514 if (migrate_use_xbzrle()) {
515 info->has_xbzrle_cache = true;
516 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
517 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
518 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
519 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
520 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
521 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
522 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
526 MigrationInfo *qmp_query_migrate(Error **errp)
528 MigrationInfo *info = g_malloc0(sizeof(*info));
529 MigrationState *s = migrate_get_current();
531 switch (s->state) {
532 case MIGRATION_STATUS_NONE:
533 /* no migration has happened ever */
534 break;
535 case MIGRATION_STATUS_SETUP:
536 info->has_status = true;
537 info->has_total_time = false;
538 break;
539 case MIGRATION_STATUS_ACTIVE:
540 case MIGRATION_STATUS_CANCELLING:
541 info->has_status = true;
542 info->has_total_time = true;
543 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
544 - s->total_time;
545 info->has_expected_downtime = true;
546 info->expected_downtime = s->expected_downtime;
547 info->has_setup_time = true;
548 info->setup_time = s->setup_time;
550 info->has_ram = true;
551 info->ram = g_malloc0(sizeof(*info->ram));
552 info->ram->transferred = ram_bytes_transferred();
553 info->ram->remaining = ram_bytes_remaining();
554 info->ram->total = ram_bytes_total();
555 info->ram->duplicate = dup_mig_pages_transferred();
556 info->ram->skipped = skipped_mig_pages_transferred();
557 info->ram->normal = norm_mig_pages_transferred();
558 info->ram->normal_bytes = norm_mig_bytes_transferred();
559 info->ram->dirty_pages_rate = s->dirty_pages_rate;
560 info->ram->mbps = s->mbps;
561 info->ram->dirty_sync_count = s->dirty_sync_count;
563 if (blk_mig_active()) {
564 info->has_disk = true;
565 info->disk = g_malloc0(sizeof(*info->disk));
566 info->disk->transferred = blk_mig_bytes_transferred();
567 info->disk->remaining = blk_mig_bytes_remaining();
568 info->disk->total = blk_mig_bytes_total();
571 if (cpu_throttle_active()) {
572 info->has_x_cpu_throttle_percentage = true;
573 info->x_cpu_throttle_percentage = cpu_throttle_get_percentage();
576 get_xbzrle_cache_stats(info);
577 break;
578 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
579 /* Mostly the same as active; TODO add some postcopy stats */
580 info->has_status = true;
581 info->has_total_time = true;
582 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
583 - s->total_time;
584 info->has_expected_downtime = true;
585 info->expected_downtime = s->expected_downtime;
586 info->has_setup_time = true;
587 info->setup_time = s->setup_time;
589 info->has_ram = true;
590 info->ram = g_malloc0(sizeof(*info->ram));
591 info->ram->transferred = ram_bytes_transferred();
592 info->ram->remaining = ram_bytes_remaining();
593 info->ram->total = ram_bytes_total();
594 info->ram->duplicate = dup_mig_pages_transferred();
595 info->ram->skipped = skipped_mig_pages_transferred();
596 info->ram->normal = norm_mig_pages_transferred();
597 info->ram->normal_bytes = norm_mig_bytes_transferred();
598 info->ram->dirty_pages_rate = s->dirty_pages_rate;
599 info->ram->mbps = s->mbps;
601 if (blk_mig_active()) {
602 info->has_disk = true;
603 info->disk = g_malloc0(sizeof(*info->disk));
604 info->disk->transferred = blk_mig_bytes_transferred();
605 info->disk->remaining = blk_mig_bytes_remaining();
606 info->disk->total = blk_mig_bytes_total();
609 get_xbzrle_cache_stats(info);
610 break;
611 case MIGRATION_STATUS_COMPLETED:
612 get_xbzrle_cache_stats(info);
614 info->has_status = true;
615 info->has_total_time = true;
616 info->total_time = s->total_time;
617 info->has_downtime = true;
618 info->downtime = s->downtime;
619 info->has_setup_time = true;
620 info->setup_time = s->setup_time;
622 info->has_ram = true;
623 info->ram = g_malloc0(sizeof(*info->ram));
624 info->ram->transferred = ram_bytes_transferred();
625 info->ram->remaining = 0;
626 info->ram->total = ram_bytes_total();
627 info->ram->duplicate = dup_mig_pages_transferred();
628 info->ram->skipped = skipped_mig_pages_transferred();
629 info->ram->normal = norm_mig_pages_transferred();
630 info->ram->normal_bytes = norm_mig_bytes_transferred();
631 info->ram->mbps = s->mbps;
632 info->ram->dirty_sync_count = s->dirty_sync_count;
633 break;
634 case MIGRATION_STATUS_FAILED:
635 info->has_status = true;
636 break;
637 case MIGRATION_STATUS_CANCELLED:
638 info->has_status = true;
639 break;
641 info->status = s->state;
643 return info;
646 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
647 Error **errp)
649 MigrationState *s = migrate_get_current();
650 MigrationCapabilityStatusList *cap;
652 if (migration_is_setup_or_active(s->state)) {
653 error_setg(errp, QERR_MIGRATION_ACTIVE);
654 return;
657 for (cap = params; cap; cap = cap->next) {
658 s->enabled_capabilities[cap->value->capability] = cap->value->state;
661 if (migrate_postcopy_ram()) {
662 if (migrate_use_compression()) {
663 /* The decompression threads asynchronously write into RAM
664 * rather than use the atomic copies needed to avoid
665 * userfaulting. It should be possible to fix the decompression
666 * threads for compatibility in future.
668 error_report("Postcopy is not currently compatible with "
669 "compression");
670 s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM] =
671 false;
676 void qmp_migrate_set_parameters(bool has_compress_level,
677 int64_t compress_level,
678 bool has_compress_threads,
679 int64_t compress_threads,
680 bool has_decompress_threads,
681 int64_t decompress_threads,
682 bool has_x_cpu_throttle_initial,
683 int64_t x_cpu_throttle_initial,
684 bool has_x_cpu_throttle_increment,
685 int64_t x_cpu_throttle_increment, Error **errp)
687 MigrationState *s = migrate_get_current();
689 if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
690 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
691 "is invalid, it should be in the range of 0 to 9");
692 return;
694 if (has_compress_threads &&
695 (compress_threads < 1 || compress_threads > 255)) {
696 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
697 "compress_threads",
698 "is invalid, it should be in the range of 1 to 255");
699 return;
701 if (has_decompress_threads &&
702 (decompress_threads < 1 || decompress_threads > 255)) {
703 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
704 "decompress_threads",
705 "is invalid, it should be in the range of 1 to 255");
706 return;
708 if (has_x_cpu_throttle_initial &&
709 (x_cpu_throttle_initial < 1 || x_cpu_throttle_initial > 99)) {
710 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
711 "x_cpu_throttle_initial",
712 "an integer in the range of 1 to 99");
714 if (has_x_cpu_throttle_increment &&
715 (x_cpu_throttle_increment < 1 || x_cpu_throttle_increment > 99)) {
716 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
717 "x_cpu_throttle_increment",
718 "an integer in the range of 1 to 99");
721 if (has_compress_level) {
722 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
724 if (has_compress_threads) {
725 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
727 if (has_decompress_threads) {
728 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
729 decompress_threads;
731 if (has_x_cpu_throttle_initial) {
732 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
733 x_cpu_throttle_initial;
736 if (has_x_cpu_throttle_increment) {
737 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
738 x_cpu_throttle_increment;
742 void qmp_migrate_start_postcopy(Error **errp)
744 MigrationState *s = migrate_get_current();
746 if (!migrate_postcopy_ram()) {
747 error_setg(errp, "Enable postcopy with migration_set_capability before"
748 " the start of migration");
749 return;
752 if (s->state == MIGRATION_STATUS_NONE) {
753 error_setg(errp, "Postcopy must be started after migration has been"
754 " started");
755 return;
758 * we don't error if migration has finished since that would be racy
759 * with issuing this command.
761 atomic_set(&s->start_postcopy, true);
764 /* shared migration helpers */
766 static void migrate_set_state(MigrationState *s, int old_state, int new_state)
768 if (atomic_cmpxchg(&s->state, old_state, new_state) == old_state) {
769 trace_migrate_set_state(new_state);
770 migrate_generate_event(new_state);
774 static void migrate_fd_cleanup(void *opaque)
776 MigrationState *s = opaque;
778 qemu_bh_delete(s->cleanup_bh);
779 s->cleanup_bh = NULL;
781 flush_page_queue(s);
783 if (s->file) {
784 trace_migrate_fd_cleanup();
785 qemu_mutex_unlock_iothread();
786 if (s->migration_thread_running) {
787 qemu_thread_join(&s->thread);
788 s->migration_thread_running = false;
790 qemu_mutex_lock_iothread();
792 migrate_compress_threads_join();
793 qemu_fclose(s->file);
794 s->file = NULL;
797 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
798 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
800 if (s->state == MIGRATION_STATUS_CANCELLING) {
801 migrate_set_state(s, MIGRATION_STATUS_CANCELLING,
802 MIGRATION_STATUS_CANCELLED);
805 notifier_list_notify(&migration_state_notifiers, s);
808 void migrate_fd_error(MigrationState *s)
810 trace_migrate_fd_error();
811 assert(s->file == NULL);
812 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
813 notifier_list_notify(&migration_state_notifiers, s);
816 static void migrate_fd_cancel(MigrationState *s)
818 int old_state ;
819 QEMUFile *f = migrate_get_current()->file;
820 trace_migrate_fd_cancel();
822 if (s->rp_state.from_dst_file) {
823 /* shutdown the rp socket, so causing the rp thread to shutdown */
824 qemu_file_shutdown(s->rp_state.from_dst_file);
827 do {
828 old_state = s->state;
829 if (!migration_is_setup_or_active(old_state)) {
830 break;
832 migrate_set_state(s, old_state, MIGRATION_STATUS_CANCELLING);
833 } while (s->state != MIGRATION_STATUS_CANCELLING);
836 * If we're unlucky the migration code might be stuck somewhere in a
837 * send/write while the network has failed and is waiting to timeout;
838 * if we've got shutdown(2) available then we can force it to quit.
839 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
840 * called in a bh, so there is no race against this cancel.
842 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
843 qemu_file_shutdown(f);
847 void add_migration_state_change_notifier(Notifier *notify)
849 notifier_list_add(&migration_state_notifiers, notify);
852 void remove_migration_state_change_notifier(Notifier *notify)
854 notifier_remove(notify);
857 bool migration_in_setup(MigrationState *s)
859 return s->state == MIGRATION_STATUS_SETUP;
862 bool migration_has_finished(MigrationState *s)
864 return s->state == MIGRATION_STATUS_COMPLETED;
867 bool migration_has_failed(MigrationState *s)
869 return (s->state == MIGRATION_STATUS_CANCELLED ||
870 s->state == MIGRATION_STATUS_FAILED);
873 bool migration_in_postcopy(MigrationState *s)
875 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
878 MigrationState *migrate_init(const MigrationParams *params)
880 MigrationState *s = migrate_get_current();
881 int64_t bandwidth_limit = s->bandwidth_limit;
882 bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
883 int64_t xbzrle_cache_size = s->xbzrle_cache_size;
884 int compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
885 int compress_thread_count =
886 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
887 int decompress_thread_count =
888 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
889 int x_cpu_throttle_initial =
890 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
891 int x_cpu_throttle_increment =
892 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
894 memcpy(enabled_capabilities, s->enabled_capabilities,
895 sizeof(enabled_capabilities));
897 memset(s, 0, sizeof(*s));
898 s->params = *params;
899 memcpy(s->enabled_capabilities, enabled_capabilities,
900 sizeof(enabled_capabilities));
901 s->xbzrle_cache_size = xbzrle_cache_size;
903 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
904 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
905 compress_thread_count;
906 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
907 decompress_thread_count;
908 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
909 x_cpu_throttle_initial;
910 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
911 x_cpu_throttle_increment;
912 s->bandwidth_limit = bandwidth_limit;
913 migrate_set_state(s, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
915 QSIMPLEQ_INIT(&s->src_page_requests);
917 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
918 return s;
921 static GSList *migration_blockers;
923 void migrate_add_blocker(Error *reason)
925 migration_blockers = g_slist_prepend(migration_blockers, reason);
928 void migrate_del_blocker(Error *reason)
930 migration_blockers = g_slist_remove(migration_blockers, reason);
933 void qmp_migrate_incoming(const char *uri, Error **errp)
935 Error *local_err = NULL;
936 static bool once = true;
938 if (!deferred_incoming) {
939 error_setg(errp, "For use with '-incoming defer'");
940 return;
942 if (!once) {
943 error_setg(errp, "The incoming migration has already been started");
946 qemu_start_incoming_migration(uri, &local_err);
948 if (local_err) {
949 error_propagate(errp, local_err);
950 return;
953 once = false;
956 void qmp_migrate(const char *uri, bool has_blk, bool blk,
957 bool has_inc, bool inc, bool has_detach, bool detach,
958 Error **errp)
960 Error *local_err = NULL;
961 MigrationState *s = migrate_get_current();
962 MigrationParams params;
963 const char *p;
965 params.blk = has_blk && blk;
966 params.shared = has_inc && inc;
968 if (migration_is_setup_or_active(s->state) ||
969 s->state == MIGRATION_STATUS_CANCELLING) {
970 error_setg(errp, QERR_MIGRATION_ACTIVE);
971 return;
973 if (runstate_check(RUN_STATE_INMIGRATE)) {
974 error_setg(errp, "Guest is waiting for an incoming migration");
975 return;
978 if (qemu_savevm_state_blocked(errp)) {
979 return;
982 if (migration_blockers) {
983 *errp = error_copy(migration_blockers->data);
984 return;
987 /* We are starting a new migration, so we want to start in a clean
988 state. This change is only needed if previous migration
989 failed/was cancelled. We don't use migrate_set_state() because
990 we are setting the initial state, not changing it. */
991 s->state = MIGRATION_STATUS_NONE;
993 s = migrate_init(&params);
995 if (strstart(uri, "tcp:", &p)) {
996 tcp_start_outgoing_migration(s, p, &local_err);
997 #ifdef CONFIG_RDMA
998 } else if (strstart(uri, "rdma:", &p)) {
999 rdma_start_outgoing_migration(s, p, &local_err);
1000 #endif
1001 #if !defined(WIN32)
1002 } else if (strstart(uri, "exec:", &p)) {
1003 exec_start_outgoing_migration(s, p, &local_err);
1004 } else if (strstart(uri, "unix:", &p)) {
1005 unix_start_outgoing_migration(s, p, &local_err);
1006 } else if (strstart(uri, "fd:", &p)) {
1007 fd_start_outgoing_migration(s, p, &local_err);
1008 #endif
1009 } else {
1010 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1011 "a valid migration protocol");
1012 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
1013 return;
1016 if (local_err) {
1017 migrate_fd_error(s);
1018 error_propagate(errp, local_err);
1019 return;
1023 void qmp_migrate_cancel(Error **errp)
1025 migrate_fd_cancel(migrate_get_current());
1028 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1030 MigrationState *s = migrate_get_current();
1031 int64_t new_size;
1033 /* Check for truncation */
1034 if (value != (size_t)value) {
1035 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1036 "exceeding address space");
1037 return;
1040 /* Cache should not be larger than guest ram size */
1041 if (value > ram_bytes_total()) {
1042 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1043 "exceeds guest ram size ");
1044 return;
1047 new_size = xbzrle_cache_resize(value);
1048 if (new_size < 0) {
1049 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1050 "is smaller than page size");
1051 return;
1054 s->xbzrle_cache_size = new_size;
1057 int64_t qmp_query_migrate_cache_size(Error **errp)
1059 return migrate_xbzrle_cache_size();
1062 void qmp_migrate_set_speed(int64_t value, Error **errp)
1064 MigrationState *s;
1066 if (value < 0) {
1067 value = 0;
1069 if (value > SIZE_MAX) {
1070 value = SIZE_MAX;
1073 s = migrate_get_current();
1074 s->bandwidth_limit = value;
1075 if (s->file) {
1076 qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
1080 void qmp_migrate_set_downtime(double value, Error **errp)
1082 value *= 1e9;
1083 value = MAX(0, MIN(UINT64_MAX, value));
1084 max_downtime = (uint64_t)value;
1087 bool migrate_postcopy_ram(void)
1089 MigrationState *s;
1091 s = migrate_get_current();
1093 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM];
1096 bool migrate_auto_converge(void)
1098 MigrationState *s;
1100 s = migrate_get_current();
1102 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1105 bool migrate_zero_blocks(void)
1107 MigrationState *s;
1109 s = migrate_get_current();
1111 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1114 bool migrate_use_compression(void)
1116 MigrationState *s;
1118 s = migrate_get_current();
1120 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1123 int migrate_compress_level(void)
1125 MigrationState *s;
1127 s = migrate_get_current();
1129 return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
1132 int migrate_compress_threads(void)
1134 MigrationState *s;
1136 s = migrate_get_current();
1138 return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
1141 int migrate_decompress_threads(void)
1143 MigrationState *s;
1145 s = migrate_get_current();
1147 return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1150 bool migrate_use_events(void)
1152 MigrationState *s;
1154 s = migrate_get_current();
1156 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1159 int migrate_use_xbzrle(void)
1161 MigrationState *s;
1163 s = migrate_get_current();
1165 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1168 int64_t migrate_xbzrle_cache_size(void)
1170 MigrationState *s;
1172 s = migrate_get_current();
1174 return s->xbzrle_cache_size;
1177 /* migration thread support */
1179 * Something bad happened to the RP stream, mark an error
1180 * The caller shall print or trace something to indicate why
1182 static void mark_source_rp_bad(MigrationState *s)
1184 s->rp_state.error = true;
1187 static struct rp_cmd_args {
1188 ssize_t len; /* -1 = variable */
1189 const char *name;
1190 } rp_cmd_args[] = {
1191 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1192 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1193 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1194 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1195 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1196 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1200 * Process a request for pages received on the return path,
1201 * We're allowed to send more than requested (e.g. to round to our page size)
1202 * and we don't need to send pages that have already been sent.
1204 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1205 ram_addr_t start, size_t len)
1207 long our_host_ps = getpagesize();
1209 trace_migrate_handle_rp_req_pages(rbname, start, len);
1212 * Since we currently insist on matching page sizes, just sanity check
1213 * we're being asked for whole host pages.
1215 if (start & (our_host_ps-1) ||
1216 (len & (our_host_ps-1))) {
1217 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1218 " len: %zd", __func__, start, len);
1219 mark_source_rp_bad(ms);
1220 return;
1223 if (ram_save_queue_pages(ms, rbname, start, len)) {
1224 mark_source_rp_bad(ms);
1229 * Handles messages sent on the return path towards the source VM
1232 static void *source_return_path_thread(void *opaque)
1234 MigrationState *ms = opaque;
1235 QEMUFile *rp = ms->rp_state.from_dst_file;
1236 uint16_t header_len, header_type;
1237 const int max_len = 512;
1238 uint8_t buf[max_len];
1239 uint32_t tmp32, sibling_error;
1240 ram_addr_t start = 0; /* =0 to silence warning */
1241 size_t len = 0, expected_len;
1242 int res;
1244 trace_source_return_path_thread_entry();
1245 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1246 migration_is_setup_or_active(ms->state)) {
1247 trace_source_return_path_thread_loop_top();
1248 header_type = qemu_get_be16(rp);
1249 header_len = qemu_get_be16(rp);
1251 if (header_type >= MIG_RP_MSG_MAX ||
1252 header_type == MIG_RP_MSG_INVALID) {
1253 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1254 header_type, header_len);
1255 mark_source_rp_bad(ms);
1256 goto out;
1259 if ((rp_cmd_args[header_type].len != -1 &&
1260 header_len != rp_cmd_args[header_type].len) ||
1261 header_len > max_len) {
1262 error_report("RP: Received '%s' message (0x%04x) with"
1263 "incorrect length %d expecting %zu",
1264 rp_cmd_args[header_type].name, header_type, header_len,
1265 (size_t)rp_cmd_args[header_type].len);
1266 mark_source_rp_bad(ms);
1267 goto out;
1270 /* We know we've got a valid header by this point */
1271 res = qemu_get_buffer(rp, buf, header_len);
1272 if (res != header_len) {
1273 error_report("RP: Failed reading data for message 0x%04x"
1274 " read %d expected %d",
1275 header_type, res, header_len);
1276 mark_source_rp_bad(ms);
1277 goto out;
1280 /* OK, we have the message and the data */
1281 switch (header_type) {
1282 case MIG_RP_MSG_SHUT:
1283 sibling_error = be32_to_cpup((uint32_t *)buf);
1284 trace_source_return_path_thread_shut(sibling_error);
1285 if (sibling_error) {
1286 error_report("RP: Sibling indicated error %d", sibling_error);
1287 mark_source_rp_bad(ms);
1290 * We'll let the main thread deal with closing the RP
1291 * we could do a shutdown(2) on it, but we're the only user
1292 * anyway, so there's nothing gained.
1294 goto out;
1296 case MIG_RP_MSG_PONG:
1297 tmp32 = be32_to_cpup((uint32_t *)buf);
1298 trace_source_return_path_thread_pong(tmp32);
1299 break;
1301 case MIG_RP_MSG_REQ_PAGES:
1302 start = be64_to_cpup((uint64_t *)buf);
1303 len = be32_to_cpup((uint32_t *)(buf + 8));
1304 migrate_handle_rp_req_pages(ms, NULL, start, len);
1305 break;
1307 case MIG_RP_MSG_REQ_PAGES_ID:
1308 expected_len = 12 + 1; /* header + termination */
1310 if (header_len >= expected_len) {
1311 start = be64_to_cpup((uint64_t *)buf);
1312 len = be32_to_cpup((uint32_t *)(buf + 8));
1313 /* Now we expect an idstr */
1314 tmp32 = buf[12]; /* Length of the following idstr */
1315 buf[13 + tmp32] = '\0';
1316 expected_len += tmp32;
1318 if (header_len != expected_len) {
1319 error_report("RP: Req_Page_id with length %d expecting %zd",
1320 header_len, expected_len);
1321 mark_source_rp_bad(ms);
1322 goto out;
1324 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1325 break;
1327 default:
1328 break;
1331 if (rp && qemu_file_get_error(rp)) {
1332 trace_source_return_path_thread_bad_end();
1333 mark_source_rp_bad(ms);
1336 trace_source_return_path_thread_end();
1337 out:
1338 ms->rp_state.from_dst_file = NULL;
1339 qemu_fclose(rp);
1340 return NULL;
1343 static int open_return_path_on_source(MigrationState *ms)
1346 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->file);
1347 if (!ms->rp_state.from_dst_file) {
1348 return -1;
1351 trace_open_return_path_on_source();
1352 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1353 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1355 trace_open_return_path_on_source_continue();
1357 return 0;
1360 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1361 static int await_return_path_close_on_source(MigrationState *ms)
1364 * If this is a normal exit then the destination will send a SHUT and the
1365 * rp_thread will exit, however if there's an error we need to cause
1366 * it to exit.
1368 if (qemu_file_get_error(ms->file) && ms->rp_state.from_dst_file) {
1370 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1371 * waiting for the destination.
1373 qemu_file_shutdown(ms->rp_state.from_dst_file);
1374 mark_source_rp_bad(ms);
1376 trace_await_return_path_close_on_source_joining();
1377 qemu_thread_join(&ms->rp_state.rp_thread);
1378 trace_await_return_path_close_on_source_close();
1379 return ms->rp_state.error;
1383 * Switch from normal iteration to postcopy
1384 * Returns non-0 on error
1386 static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1388 int ret;
1389 const QEMUSizedBuffer *qsb;
1390 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1391 migrate_set_state(ms, MIGRATION_STATUS_ACTIVE,
1392 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1394 trace_postcopy_start();
1395 qemu_mutex_lock_iothread();
1396 trace_postcopy_start_set_run();
1398 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1399 *old_vm_running = runstate_is_running();
1400 global_state_store();
1401 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1403 if (ret < 0) {
1404 goto fail;
1408 * in Finish migrate and with the io-lock held everything should
1409 * be quiet, but we've potentially still got dirty pages and we
1410 * need to tell the destination to throw any pages it's already received
1411 * that are dirty
1413 if (ram_postcopy_send_discard_bitmap(ms)) {
1414 error_report("postcopy send discard bitmap failed");
1415 goto fail;
1419 * send rest of state - note things that are doing postcopy
1420 * will notice we're in POSTCOPY_ACTIVE and not actually
1421 * wrap their state up here
1423 qemu_file_set_rate_limit(ms->file, INT64_MAX);
1424 /* Ping just for debugging, helps line traces up */
1425 qemu_savevm_send_ping(ms->file, 2);
1428 * While loading the device state we may trigger page transfer
1429 * requests and the fd must be free to process those, and thus
1430 * the destination must read the whole device state off the fd before
1431 * it starts processing it. Unfortunately the ad-hoc migration format
1432 * doesn't allow the destination to know the size to read without fully
1433 * parsing it through each devices load-state code (especially the open
1434 * coded devices that use get/put).
1435 * So we wrap the device state up in a package with a length at the start;
1436 * to do this we use a qemu_buf to hold the whole of the device state.
1438 QEMUFile *fb = qemu_bufopen("w", NULL);
1439 if (!fb) {
1440 error_report("Failed to create buffered file");
1441 goto fail;
1444 qemu_savevm_state_complete_precopy(fb);
1445 qemu_savevm_send_ping(fb, 3);
1447 qemu_savevm_send_postcopy_run(fb);
1449 /* <><> end of stuff going into the package */
1450 qsb = qemu_buf_get(fb);
1452 /* Now send that blob */
1453 if (qemu_savevm_send_packaged(ms->file, qsb)) {
1454 goto fail_closefb;
1456 qemu_fclose(fb);
1457 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1459 qemu_mutex_unlock_iothread();
1462 * Although this ping is just for debug, it could potentially be
1463 * used for getting a better measurement of downtime at the source.
1465 qemu_savevm_send_ping(ms->file, 4);
1467 ret = qemu_file_get_error(ms->file);
1468 if (ret) {
1469 error_report("postcopy_start: Migration stream errored");
1470 migrate_set_state(ms, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1471 MIGRATION_STATUS_FAILED);
1474 return ret;
1476 fail_closefb:
1477 qemu_fclose(fb);
1478 fail:
1479 migrate_set_state(ms, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1480 MIGRATION_STATUS_FAILED);
1481 qemu_mutex_unlock_iothread();
1482 return -1;
1486 * migration_completion: Used by migration_thread when there's not much left.
1487 * The caller 'breaks' the loop when this returns.
1489 * @s: Current migration state
1490 * @current_active_state: The migration state we expect to be in
1491 * @*old_vm_running: Pointer to old_vm_running flag
1492 * @*start_time: Pointer to time to update
1494 static void migration_completion(MigrationState *s, int current_active_state,
1495 bool *old_vm_running,
1496 int64_t *start_time)
1498 int ret;
1500 if (s->state == MIGRATION_STATUS_ACTIVE) {
1501 qemu_mutex_lock_iothread();
1502 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1503 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1504 *old_vm_running = runstate_is_running();
1505 ret = global_state_store();
1507 if (!ret) {
1508 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1509 if (ret >= 0) {
1510 qemu_file_set_rate_limit(s->file, INT64_MAX);
1511 qemu_savevm_state_complete_precopy(s->file);
1514 qemu_mutex_unlock_iothread();
1516 if (ret < 0) {
1517 goto fail;
1519 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1520 trace_migration_completion_postcopy_end();
1522 qemu_savevm_state_complete_postcopy(s->file);
1523 trace_migration_completion_postcopy_end_after_complete();
1527 * If rp was opened we must clean up the thread before
1528 * cleaning everything else up (since if there are no failures
1529 * it will wait for the destination to send it's status in
1530 * a SHUT command).
1531 * Postcopy opens rp if enabled (even if it's not avtivated)
1533 if (migrate_postcopy_ram()) {
1534 int rp_error;
1535 trace_migration_completion_postcopy_end_before_rp();
1536 rp_error = await_return_path_close_on_source(s);
1537 trace_migration_completion_postcopy_end_after_rp(rp_error);
1538 if (rp_error) {
1539 goto fail;
1543 if (qemu_file_get_error(s->file)) {
1544 trace_migration_completion_file_err();
1545 goto fail;
1548 migrate_set_state(s, current_active_state, MIGRATION_STATUS_COMPLETED);
1549 return;
1551 fail:
1552 migrate_set_state(s, current_active_state, MIGRATION_STATUS_FAILED);
1556 * Master migration thread on the source VM.
1557 * It drives the migration and pumps the data down the outgoing channel.
1559 static void *migration_thread(void *opaque)
1561 MigrationState *s = opaque;
1562 /* Used by the bandwidth calcs, updated later */
1563 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1564 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
1565 int64_t initial_bytes = 0;
1566 int64_t max_size = 0;
1567 int64_t start_time = initial_time;
1568 int64_t end_time;
1569 bool old_vm_running = false;
1570 bool entered_postcopy = false;
1571 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1572 enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
1574 rcu_register_thread();
1576 qemu_savevm_state_header(s->file);
1578 if (migrate_postcopy_ram()) {
1579 /* Now tell the dest that it should open its end so it can reply */
1580 qemu_savevm_send_open_return_path(s->file);
1582 /* And do a ping that will make stuff easier to debug */
1583 qemu_savevm_send_ping(s->file, 1);
1586 * Tell the destination that we *might* want to do postcopy later;
1587 * if the other end can't do postcopy it should fail now, nice and
1588 * early.
1590 qemu_savevm_send_postcopy_advise(s->file);
1593 qemu_savevm_state_begin(s->file, &s->params);
1595 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
1596 current_active_state = MIGRATION_STATUS_ACTIVE;
1597 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_ACTIVE);
1599 trace_migration_thread_setup_complete();
1601 while (s->state == MIGRATION_STATUS_ACTIVE ||
1602 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1603 int64_t current_time;
1604 uint64_t pending_size;
1606 if (!qemu_file_rate_limit(s->file)) {
1607 uint64_t pend_post, pend_nonpost;
1609 qemu_savevm_state_pending(s->file, max_size, &pend_nonpost,
1610 &pend_post);
1611 pending_size = pend_nonpost + pend_post;
1612 trace_migrate_pending(pending_size, max_size,
1613 pend_post, pend_nonpost);
1614 if (pending_size && pending_size >= max_size) {
1615 /* Still a significant amount to transfer */
1617 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1618 if (migrate_postcopy_ram() &&
1619 s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
1620 pend_nonpost <= max_size &&
1621 atomic_read(&s->start_postcopy)) {
1623 if (!postcopy_start(s, &old_vm_running)) {
1624 current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1625 entered_postcopy = true;
1628 continue;
1630 /* Just another iteration step */
1631 qemu_savevm_state_iterate(s->file);
1632 } else {
1633 trace_migration_thread_low_pending(pending_size);
1634 migration_completion(s, current_active_state,
1635 &old_vm_running, &start_time);
1636 break;
1640 if (qemu_file_get_error(s->file)) {
1641 migrate_set_state(s, current_active_state, MIGRATION_STATUS_FAILED);
1642 trace_migration_thread_file_err();
1643 break;
1645 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1646 if (current_time >= initial_time + BUFFER_DELAY) {
1647 uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
1648 uint64_t time_spent = current_time - initial_time;
1649 double bandwidth = transferred_bytes / time_spent;
1650 max_size = bandwidth * migrate_max_downtime() / 1000000;
1652 s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1653 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1655 trace_migrate_transferred(transferred_bytes, time_spent,
1656 bandwidth, max_size);
1657 /* if we haven't sent anything, we don't want to recalculate
1658 10000 is a small enough number for our purposes */
1659 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1660 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1663 qemu_file_reset_rate_limit(s->file);
1664 initial_time = current_time;
1665 initial_bytes = qemu_ftell(s->file);
1667 if (qemu_file_rate_limit(s->file)) {
1668 /* usleep expects microseconds */
1669 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1673 trace_migration_thread_after_loop();
1674 /* If we enabled cpu throttling for auto-converge, turn it off. */
1675 cpu_throttle_stop();
1676 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1678 qemu_mutex_lock_iothread();
1679 qemu_savevm_state_cleanup();
1680 if (s->state == MIGRATION_STATUS_COMPLETED) {
1681 uint64_t transferred_bytes = qemu_ftell(s->file);
1682 s->total_time = end_time - s->total_time;
1683 if (!entered_postcopy) {
1684 s->downtime = end_time - start_time;
1686 if (s->total_time) {
1687 s->mbps = (((double) transferred_bytes * 8.0) /
1688 ((double) s->total_time)) / 1000;
1690 runstate_set(RUN_STATE_POSTMIGRATE);
1691 } else {
1692 if (old_vm_running && !entered_postcopy) {
1693 vm_start();
1696 qemu_bh_schedule(s->cleanup_bh);
1697 qemu_mutex_unlock_iothread();
1699 rcu_unregister_thread();
1700 return NULL;
1703 void migrate_fd_connect(MigrationState *s)
1705 /* This is a best 1st approximation. ns to ms */
1706 s->expected_downtime = max_downtime/1000000;
1707 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1709 qemu_file_set_rate_limit(s->file,
1710 s->bandwidth_limit / XFER_LIMIT_RATIO);
1712 /* Notify before starting migration thread */
1713 notifier_list_notify(&migration_state_notifiers, s);
1716 * Open the return path; currently for postcopy but other things might
1717 * also want it.
1719 if (migrate_postcopy_ram()) {
1720 if (open_return_path_on_source(s)) {
1721 error_report("Unable to open return-path for postcopy");
1722 migrate_set_state(s, MIGRATION_STATUS_SETUP,
1723 MIGRATION_STATUS_FAILED);
1724 migrate_fd_cleanup(s);
1725 return;
1729 migrate_compress_threads_create();
1730 qemu_thread_create(&s->thread, "migration", migration_thread, s,
1731 QEMU_THREAD_JOINABLE);
1732 s->migration_thread_running = true;
1735 PostcopyState postcopy_state_get(void)
1737 return atomic_mb_read(&incoming_postcopy_state);
1740 /* Set the state and return the old state */
1741 PostcopyState postcopy_state_set(PostcopyState new_state)
1743 return atomic_xchg(&incoming_postcopy_state, new_state);