Xen: use qemu_strtoul instead of strtol
[qemu.git] / migration / migration.c
blobbc611e453bd54405989a9f438f0568ab3e07b7ff
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 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 upto 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 #if !defined(WIN32)
313 } else if (strstart(uri, "exec:", &p)) {
314 exec_start_incoming_migration(p, errp);
315 } else if (strstart(uri, "unix:", &p)) {
316 unix_start_incoming_migration(p, errp);
317 } else if (strstart(uri, "fd:", &p)) {
318 fd_start_incoming_migration(p, errp);
319 #endif
320 } else {
321 error_setg(errp, "unknown migration protocol: %s", uri);
325 static void process_incoming_migration_co(void *opaque)
327 QEMUFile *f = opaque;
328 Error *local_err = NULL;
329 MigrationIncomingState *mis;
330 PostcopyState ps;
331 int ret;
333 mis = migration_incoming_state_new(f);
334 postcopy_state_set(POSTCOPY_INCOMING_NONE);
335 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
336 MIGRATION_STATUS_ACTIVE);
337 ret = qemu_loadvm_state(f);
339 ps = postcopy_state_get();
340 trace_process_incoming_migration_co_end(ret, ps);
341 if (ps != POSTCOPY_INCOMING_NONE) {
342 if (ps == POSTCOPY_INCOMING_ADVISE) {
344 * Where a migration had postcopy enabled (and thus went to advise)
345 * but managed to complete within the precopy period, we can use
346 * the normal exit.
348 postcopy_ram_incoming_cleanup(mis);
349 } else if (ret >= 0) {
351 * Postcopy was started, cleanup should happen at the end of the
352 * postcopy thread.
354 trace_process_incoming_migration_co_postcopy_end_main();
355 return;
357 /* Else if something went wrong then just fall out of the normal exit */
360 qemu_fclose(f);
361 free_xbzrle_decoded_buf();
363 if (ret < 0) {
364 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
365 MIGRATION_STATUS_FAILED);
366 error_report("load of migration failed: %s", strerror(-ret));
367 migrate_decompress_threads_join();
368 exit(EXIT_FAILURE);
371 /* Make sure all file formats flush their mutable metadata */
372 bdrv_invalidate_cache_all(&local_err);
373 if (local_err) {
374 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
375 MIGRATION_STATUS_FAILED);
376 error_report_err(local_err);
377 migrate_decompress_threads_join();
378 exit(EXIT_FAILURE);
382 * This must happen after all error conditions are dealt with and
383 * we're sure the VM is going to be running on this host.
385 qemu_announce_self();
387 /* If global state section was not received or we are in running
388 state, we need to obey autostart. Any other state is set with
389 runstate_set. */
391 if (!global_state_received() ||
392 global_state_get_runstate() == RUN_STATE_RUNNING) {
393 if (autostart) {
394 vm_start();
395 } else {
396 runstate_set(RUN_STATE_PAUSED);
398 } else {
399 runstate_set(global_state_get_runstate());
401 migrate_decompress_threads_join();
403 * This must happen after any state changes since as soon as an external
404 * observer sees this event they might start to prod at the VM assuming
405 * it's ready to use.
407 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
408 MIGRATION_STATUS_COMPLETED);
409 migration_incoming_state_destroy();
412 void process_incoming_migration(QEMUFile *f)
414 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
415 int fd = qemu_get_fd(f);
417 assert(fd != -1);
418 migrate_decompress_threads_create();
419 qemu_set_nonblock(fd);
420 qemu_coroutine_enter(co, f);
424 * Send a message on the return channel back to the source
425 * of the migration.
427 void migrate_send_rp_message(MigrationIncomingState *mis,
428 enum mig_rp_message_type message_type,
429 uint16_t len, void *data)
431 trace_migrate_send_rp_message((int)message_type, len);
432 qemu_mutex_lock(&mis->rp_mutex);
433 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
434 qemu_put_be16(mis->to_src_file, len);
435 qemu_put_buffer(mis->to_src_file, data, len);
436 qemu_fflush(mis->to_src_file);
437 qemu_mutex_unlock(&mis->rp_mutex);
441 * Send a 'SHUT' message on the return channel with the given value
442 * to indicate that we've finished with the RP. Non-0 value indicates
443 * error.
445 void migrate_send_rp_shut(MigrationIncomingState *mis,
446 uint32_t value)
448 uint32_t buf;
450 buf = cpu_to_be32(value);
451 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
455 * Send a 'PONG' message on the return channel with the given value
456 * (normally in response to a 'PING')
458 void migrate_send_rp_pong(MigrationIncomingState *mis,
459 uint32_t value)
461 uint32_t buf;
463 buf = cpu_to_be32(value);
464 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
467 /* amount of nanoseconds we are willing to wait for migration to be down.
468 * the choice of nanoseconds is because it is the maximum resolution that
469 * get_clock() can achieve. It is an internal measure. All user-visible
470 * units must be in seconds */
471 static uint64_t max_downtime = 300000000;
473 uint64_t migrate_max_downtime(void)
475 return max_downtime;
478 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
480 MigrationCapabilityStatusList *head = NULL;
481 MigrationCapabilityStatusList *caps;
482 MigrationState *s = migrate_get_current();
483 int i;
485 caps = NULL; /* silence compiler warning */
486 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
487 if (head == NULL) {
488 head = g_malloc0(sizeof(*caps));
489 caps = head;
490 } else {
491 caps->next = g_malloc0(sizeof(*caps));
492 caps = caps->next;
494 caps->value =
495 g_malloc(sizeof(*caps->value));
496 caps->value->capability = i;
497 caps->value->state = s->enabled_capabilities[i];
500 return head;
503 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
505 MigrationParameters *params;
506 MigrationState *s = migrate_get_current();
508 params = g_malloc0(sizeof(*params));
509 params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
510 params->compress_threads =
511 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
512 params->decompress_threads =
513 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
514 params->x_cpu_throttle_initial =
515 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
516 params->x_cpu_throttle_increment =
517 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
519 return params;
523 * Return true if we're already in the middle of a migration
524 * (i.e. any of the active or setup states)
526 static bool migration_is_setup_or_active(int state)
528 switch (state) {
529 case MIGRATION_STATUS_ACTIVE:
530 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
531 case MIGRATION_STATUS_SETUP:
532 return true;
534 default:
535 return false;
540 static void get_xbzrle_cache_stats(MigrationInfo *info)
542 if (migrate_use_xbzrle()) {
543 info->has_xbzrle_cache = true;
544 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
545 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
546 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
547 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
548 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
549 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
550 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
554 MigrationInfo *qmp_query_migrate(Error **errp)
556 MigrationInfo *info = g_malloc0(sizeof(*info));
557 MigrationState *s = migrate_get_current();
559 switch (s->state) {
560 case MIGRATION_STATUS_NONE:
561 /* no migration has happened ever */
562 break;
563 case MIGRATION_STATUS_SETUP:
564 info->has_status = true;
565 info->has_total_time = false;
566 break;
567 case MIGRATION_STATUS_ACTIVE:
568 case MIGRATION_STATUS_CANCELLING:
569 info->has_status = true;
570 info->has_total_time = true;
571 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
572 - s->total_time;
573 info->has_expected_downtime = true;
574 info->expected_downtime = s->expected_downtime;
575 info->has_setup_time = true;
576 info->setup_time = s->setup_time;
578 info->has_ram = true;
579 info->ram = g_malloc0(sizeof(*info->ram));
580 info->ram->transferred = ram_bytes_transferred();
581 info->ram->remaining = ram_bytes_remaining();
582 info->ram->total = ram_bytes_total();
583 info->ram->duplicate = dup_mig_pages_transferred();
584 info->ram->skipped = skipped_mig_pages_transferred();
585 info->ram->normal = norm_mig_pages_transferred();
586 info->ram->normal_bytes = norm_mig_bytes_transferred();
587 info->ram->dirty_pages_rate = s->dirty_pages_rate;
588 info->ram->mbps = s->mbps;
589 info->ram->dirty_sync_count = s->dirty_sync_count;
591 if (blk_mig_active()) {
592 info->has_disk = true;
593 info->disk = g_malloc0(sizeof(*info->disk));
594 info->disk->transferred = blk_mig_bytes_transferred();
595 info->disk->remaining = blk_mig_bytes_remaining();
596 info->disk->total = blk_mig_bytes_total();
599 if (cpu_throttle_active()) {
600 info->has_x_cpu_throttle_percentage = true;
601 info->x_cpu_throttle_percentage = cpu_throttle_get_percentage();
604 get_xbzrle_cache_stats(info);
605 break;
606 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
607 /* Mostly the same as active; TODO add some postcopy stats */
608 info->has_status = true;
609 info->has_total_time = true;
610 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
611 - s->total_time;
612 info->has_expected_downtime = true;
613 info->expected_downtime = s->expected_downtime;
614 info->has_setup_time = true;
615 info->setup_time = s->setup_time;
617 info->has_ram = true;
618 info->ram = g_malloc0(sizeof(*info->ram));
619 info->ram->transferred = ram_bytes_transferred();
620 info->ram->remaining = ram_bytes_remaining();
621 info->ram->total = ram_bytes_total();
622 info->ram->duplicate = dup_mig_pages_transferred();
623 info->ram->skipped = skipped_mig_pages_transferred();
624 info->ram->normal = norm_mig_pages_transferred();
625 info->ram->normal_bytes = norm_mig_bytes_transferred();
626 info->ram->dirty_pages_rate = s->dirty_pages_rate;
627 info->ram->mbps = s->mbps;
629 if (blk_mig_active()) {
630 info->has_disk = true;
631 info->disk = g_malloc0(sizeof(*info->disk));
632 info->disk->transferred = blk_mig_bytes_transferred();
633 info->disk->remaining = blk_mig_bytes_remaining();
634 info->disk->total = blk_mig_bytes_total();
637 get_xbzrle_cache_stats(info);
638 break;
639 case MIGRATION_STATUS_COMPLETED:
640 get_xbzrle_cache_stats(info);
642 info->has_status = true;
643 info->has_total_time = true;
644 info->total_time = s->total_time;
645 info->has_downtime = true;
646 info->downtime = s->downtime;
647 info->has_setup_time = true;
648 info->setup_time = s->setup_time;
650 info->has_ram = true;
651 info->ram = g_malloc0(sizeof(*info->ram));
652 info->ram->transferred = ram_bytes_transferred();
653 info->ram->remaining = 0;
654 info->ram->total = ram_bytes_total();
655 info->ram->duplicate = dup_mig_pages_transferred();
656 info->ram->skipped = skipped_mig_pages_transferred();
657 info->ram->normal = norm_mig_pages_transferred();
658 info->ram->normal_bytes = norm_mig_bytes_transferred();
659 info->ram->mbps = s->mbps;
660 info->ram->dirty_sync_count = s->dirty_sync_count;
661 break;
662 case MIGRATION_STATUS_FAILED:
663 info->has_status = true;
664 break;
665 case MIGRATION_STATUS_CANCELLED:
666 info->has_status = true;
667 break;
669 info->status = s->state;
671 return info;
674 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
675 Error **errp)
677 MigrationState *s = migrate_get_current();
678 MigrationCapabilityStatusList *cap;
680 if (migration_is_setup_or_active(s->state)) {
681 error_setg(errp, QERR_MIGRATION_ACTIVE);
682 return;
685 for (cap = params; cap; cap = cap->next) {
686 s->enabled_capabilities[cap->value->capability] = cap->value->state;
689 if (migrate_postcopy_ram()) {
690 if (migrate_use_compression()) {
691 /* The decompression threads asynchronously write into RAM
692 * rather than use the atomic copies needed to avoid
693 * userfaulting. It should be possible to fix the decompression
694 * threads for compatibility in future.
696 error_report("Postcopy is not currently compatible with "
697 "compression");
698 s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM] =
699 false;
704 void qmp_migrate_set_parameters(bool has_compress_level,
705 int64_t compress_level,
706 bool has_compress_threads,
707 int64_t compress_threads,
708 bool has_decompress_threads,
709 int64_t decompress_threads,
710 bool has_x_cpu_throttle_initial,
711 int64_t x_cpu_throttle_initial,
712 bool has_x_cpu_throttle_increment,
713 int64_t x_cpu_throttle_increment, Error **errp)
715 MigrationState *s = migrate_get_current();
717 if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
718 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
719 "is invalid, it should be in the range of 0 to 9");
720 return;
722 if (has_compress_threads &&
723 (compress_threads < 1 || compress_threads > 255)) {
724 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
725 "compress_threads",
726 "is invalid, it should be in the range of 1 to 255");
727 return;
729 if (has_decompress_threads &&
730 (decompress_threads < 1 || decompress_threads > 255)) {
731 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
732 "decompress_threads",
733 "is invalid, it should be in the range of 1 to 255");
734 return;
736 if (has_x_cpu_throttle_initial &&
737 (x_cpu_throttle_initial < 1 || x_cpu_throttle_initial > 99)) {
738 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
739 "x_cpu_throttle_initial",
740 "an integer in the range of 1 to 99");
742 if (has_x_cpu_throttle_increment &&
743 (x_cpu_throttle_increment < 1 || x_cpu_throttle_increment > 99)) {
744 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
745 "x_cpu_throttle_increment",
746 "an integer in the range of 1 to 99");
749 if (has_compress_level) {
750 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
752 if (has_compress_threads) {
753 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
755 if (has_decompress_threads) {
756 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
757 decompress_threads;
759 if (has_x_cpu_throttle_initial) {
760 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
761 x_cpu_throttle_initial;
764 if (has_x_cpu_throttle_increment) {
765 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
766 x_cpu_throttle_increment;
770 void qmp_migrate_start_postcopy(Error **errp)
772 MigrationState *s = migrate_get_current();
774 if (!migrate_postcopy_ram()) {
775 error_setg(errp, "Enable postcopy with migrate_set_capability before"
776 " the start of migration");
777 return;
780 if (s->state == MIGRATION_STATUS_NONE) {
781 error_setg(errp, "Postcopy must be started after migration has been"
782 " started");
783 return;
786 * we don't error if migration has finished since that would be racy
787 * with issuing this command.
789 atomic_set(&s->start_postcopy, true);
792 /* shared migration helpers */
794 void migrate_set_state(int *state, int old_state, int new_state)
796 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
797 trace_migrate_set_state(new_state);
798 migrate_generate_event(new_state);
802 static void migrate_fd_cleanup(void *opaque)
804 MigrationState *s = opaque;
806 qemu_bh_delete(s->cleanup_bh);
807 s->cleanup_bh = NULL;
809 flush_page_queue(s);
811 if (s->file) {
812 trace_migrate_fd_cleanup();
813 qemu_mutex_unlock_iothread();
814 if (s->migration_thread_running) {
815 qemu_thread_join(&s->thread);
816 s->migration_thread_running = false;
818 qemu_mutex_lock_iothread();
820 migrate_compress_threads_join();
821 qemu_fclose(s->file);
822 s->file = NULL;
825 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
826 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
828 if (s->state == MIGRATION_STATUS_CANCELLING) {
829 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
830 MIGRATION_STATUS_CANCELLED);
833 notifier_list_notify(&migration_state_notifiers, s);
836 void migrate_fd_error(MigrationState *s)
838 trace_migrate_fd_error();
839 assert(s->file == NULL);
840 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
841 MIGRATION_STATUS_FAILED);
842 notifier_list_notify(&migration_state_notifiers, s);
845 static void migrate_fd_cancel(MigrationState *s)
847 int old_state ;
848 QEMUFile *f = migrate_get_current()->file;
849 trace_migrate_fd_cancel();
851 if (s->rp_state.from_dst_file) {
852 /* shutdown the rp socket, so causing the rp thread to shutdown */
853 qemu_file_shutdown(s->rp_state.from_dst_file);
856 do {
857 old_state = s->state;
858 if (!migration_is_setup_or_active(old_state)) {
859 break;
861 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
862 } while (s->state != MIGRATION_STATUS_CANCELLING);
865 * If we're unlucky the migration code might be stuck somewhere in a
866 * send/write while the network has failed and is waiting to timeout;
867 * if we've got shutdown(2) available then we can force it to quit.
868 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
869 * called in a bh, so there is no race against this cancel.
871 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
872 qemu_file_shutdown(f);
876 void add_migration_state_change_notifier(Notifier *notify)
878 notifier_list_add(&migration_state_notifiers, notify);
881 void remove_migration_state_change_notifier(Notifier *notify)
883 notifier_remove(notify);
886 bool migration_in_setup(MigrationState *s)
888 return s->state == MIGRATION_STATUS_SETUP;
891 bool migration_has_finished(MigrationState *s)
893 return s->state == MIGRATION_STATUS_COMPLETED;
896 bool migration_has_failed(MigrationState *s)
898 return (s->state == MIGRATION_STATUS_CANCELLED ||
899 s->state == MIGRATION_STATUS_FAILED);
902 bool migration_in_postcopy(MigrationState *s)
904 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
907 MigrationState *migrate_init(const MigrationParams *params)
909 MigrationState *s = migrate_get_current();
912 * Reinitialise all migration state, except
913 * parameters/capabilities that the user set, and
914 * locks.
916 s->bytes_xfer = 0;
917 s->xfer_limit = 0;
918 s->cleanup_bh = 0;
919 s->file = NULL;
920 s->state = MIGRATION_STATUS_NONE;
921 s->params = *params;
922 s->rp_state.from_dst_file = NULL;
923 s->rp_state.error = false;
924 s->mbps = 0.0;
925 s->downtime = 0;
926 s->expected_downtime = 0;
927 s->dirty_pages_rate = 0;
928 s->dirty_bytes_rate = 0;
929 s->setup_time = 0;
930 s->dirty_sync_count = 0;
931 s->start_postcopy = false;
932 s->migration_thread_running = false;
933 s->last_req_rb = NULL;
935 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
937 QSIMPLEQ_INIT(&s->src_page_requests);
939 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
940 return s;
943 static GSList *migration_blockers;
945 void migrate_add_blocker(Error *reason)
947 migration_blockers = g_slist_prepend(migration_blockers, reason);
950 void migrate_del_blocker(Error *reason)
952 migration_blockers = g_slist_remove(migration_blockers, reason);
955 void qmp_migrate_incoming(const char *uri, Error **errp)
957 Error *local_err = NULL;
958 static bool once = true;
960 if (!deferred_incoming) {
961 error_setg(errp, "For use with '-incoming defer'");
962 return;
964 if (!once) {
965 error_setg(errp, "The incoming migration has already been started");
968 qemu_start_incoming_migration(uri, &local_err);
970 if (local_err) {
971 error_propagate(errp, local_err);
972 return;
975 once = false;
978 void qmp_migrate(const char *uri, bool has_blk, bool blk,
979 bool has_inc, bool inc, bool has_detach, bool detach,
980 Error **errp)
982 Error *local_err = NULL;
983 MigrationState *s = migrate_get_current();
984 MigrationParams params;
985 const char *p;
987 params.blk = has_blk && blk;
988 params.shared = has_inc && inc;
990 if (migration_is_setup_or_active(s->state) ||
991 s->state == MIGRATION_STATUS_CANCELLING) {
992 error_setg(errp, QERR_MIGRATION_ACTIVE);
993 return;
995 if (runstate_check(RUN_STATE_INMIGRATE)) {
996 error_setg(errp, "Guest is waiting for an incoming migration");
997 return;
1000 if (qemu_savevm_state_blocked(errp)) {
1001 return;
1004 if (migration_blockers) {
1005 *errp = error_copy(migration_blockers->data);
1006 return;
1009 /* We are starting a new migration, so we want to start in a clean
1010 state. This change is only needed if previous migration
1011 failed/was cancelled. We don't use migrate_set_state() because
1012 we are setting the initial state, not changing it. */
1013 s->state = MIGRATION_STATUS_NONE;
1015 s = migrate_init(&params);
1017 if (strstart(uri, "tcp:", &p)) {
1018 tcp_start_outgoing_migration(s, p, &local_err);
1019 #ifdef CONFIG_RDMA
1020 } else if (strstart(uri, "rdma:", &p)) {
1021 rdma_start_outgoing_migration(s, p, &local_err);
1022 #endif
1023 #if !defined(WIN32)
1024 } else if (strstart(uri, "exec:", &p)) {
1025 exec_start_outgoing_migration(s, p, &local_err);
1026 } else if (strstart(uri, "unix:", &p)) {
1027 unix_start_outgoing_migration(s, p, &local_err);
1028 } else if (strstart(uri, "fd:", &p)) {
1029 fd_start_outgoing_migration(s, p, &local_err);
1030 #endif
1031 } else {
1032 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1033 "a valid migration protocol");
1034 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1035 MIGRATION_STATUS_FAILED);
1036 return;
1039 if (local_err) {
1040 migrate_fd_error(s);
1041 error_propagate(errp, local_err);
1042 return;
1046 void qmp_migrate_cancel(Error **errp)
1048 migrate_fd_cancel(migrate_get_current());
1051 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1053 MigrationState *s = migrate_get_current();
1054 int64_t new_size;
1056 /* Check for truncation */
1057 if (value != (size_t)value) {
1058 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1059 "exceeding address space");
1060 return;
1063 /* Cache should not be larger than guest ram size */
1064 if (value > ram_bytes_total()) {
1065 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1066 "exceeds guest ram size ");
1067 return;
1070 new_size = xbzrle_cache_resize(value);
1071 if (new_size < 0) {
1072 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1073 "is smaller than page size");
1074 return;
1077 s->xbzrle_cache_size = new_size;
1080 int64_t qmp_query_migrate_cache_size(Error **errp)
1082 return migrate_xbzrle_cache_size();
1085 void qmp_migrate_set_speed(int64_t value, Error **errp)
1087 MigrationState *s;
1089 if (value < 0) {
1090 value = 0;
1092 if (value > SIZE_MAX) {
1093 value = SIZE_MAX;
1096 s = migrate_get_current();
1097 s->bandwidth_limit = value;
1098 if (s->file) {
1099 qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
1103 void qmp_migrate_set_downtime(double value, Error **errp)
1105 value *= 1e9;
1106 value = MAX(0, MIN(UINT64_MAX, value));
1107 max_downtime = (uint64_t)value;
1110 bool migrate_postcopy_ram(void)
1112 MigrationState *s;
1114 s = migrate_get_current();
1116 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM];
1119 bool migrate_auto_converge(void)
1121 MigrationState *s;
1123 s = migrate_get_current();
1125 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1128 bool migrate_zero_blocks(void)
1130 MigrationState *s;
1132 s = migrate_get_current();
1134 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1137 bool migrate_use_compression(void)
1139 MigrationState *s;
1141 s = migrate_get_current();
1143 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1146 int migrate_compress_level(void)
1148 MigrationState *s;
1150 s = migrate_get_current();
1152 return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
1155 int migrate_compress_threads(void)
1157 MigrationState *s;
1159 s = migrate_get_current();
1161 return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
1164 int migrate_decompress_threads(void)
1166 MigrationState *s;
1168 s = migrate_get_current();
1170 return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1173 bool migrate_use_events(void)
1175 MigrationState *s;
1177 s = migrate_get_current();
1179 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1182 int migrate_use_xbzrle(void)
1184 MigrationState *s;
1186 s = migrate_get_current();
1188 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1191 int64_t migrate_xbzrle_cache_size(void)
1193 MigrationState *s;
1195 s = migrate_get_current();
1197 return s->xbzrle_cache_size;
1200 /* migration thread support */
1202 * Something bad happened to the RP stream, mark an error
1203 * The caller shall print or trace something to indicate why
1205 static void mark_source_rp_bad(MigrationState *s)
1207 s->rp_state.error = true;
1210 static struct rp_cmd_args {
1211 ssize_t len; /* -1 = variable */
1212 const char *name;
1213 } rp_cmd_args[] = {
1214 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1215 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1216 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1217 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1218 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1219 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1223 * Process a request for pages received on the return path,
1224 * We're allowed to send more than requested (e.g. to round to our page size)
1225 * and we don't need to send pages that have already been sent.
1227 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1228 ram_addr_t start, size_t len)
1230 long our_host_ps = getpagesize();
1232 trace_migrate_handle_rp_req_pages(rbname, start, len);
1235 * Since we currently insist on matching page sizes, just sanity check
1236 * we're being asked for whole host pages.
1238 if (start & (our_host_ps-1) ||
1239 (len & (our_host_ps-1))) {
1240 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1241 " len: %zd", __func__, start, len);
1242 mark_source_rp_bad(ms);
1243 return;
1246 if (ram_save_queue_pages(ms, rbname, start, len)) {
1247 mark_source_rp_bad(ms);
1252 * Handles messages sent on the return path towards the source VM
1255 static void *source_return_path_thread(void *opaque)
1257 MigrationState *ms = opaque;
1258 QEMUFile *rp = ms->rp_state.from_dst_file;
1259 uint16_t header_len, header_type;
1260 const int max_len = 512;
1261 uint8_t buf[max_len];
1262 uint32_t tmp32, sibling_error;
1263 ram_addr_t start = 0; /* =0 to silence warning */
1264 size_t len = 0, expected_len;
1265 int res;
1267 trace_source_return_path_thread_entry();
1268 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1269 migration_is_setup_or_active(ms->state)) {
1270 trace_source_return_path_thread_loop_top();
1271 header_type = qemu_get_be16(rp);
1272 header_len = qemu_get_be16(rp);
1274 if (header_type >= MIG_RP_MSG_MAX ||
1275 header_type == MIG_RP_MSG_INVALID) {
1276 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1277 header_type, header_len);
1278 mark_source_rp_bad(ms);
1279 goto out;
1282 if ((rp_cmd_args[header_type].len != -1 &&
1283 header_len != rp_cmd_args[header_type].len) ||
1284 header_len > max_len) {
1285 error_report("RP: Received '%s' message (0x%04x) with"
1286 "incorrect length %d expecting %zu",
1287 rp_cmd_args[header_type].name, header_type, header_len,
1288 (size_t)rp_cmd_args[header_type].len);
1289 mark_source_rp_bad(ms);
1290 goto out;
1293 /* We know we've got a valid header by this point */
1294 res = qemu_get_buffer(rp, buf, header_len);
1295 if (res != header_len) {
1296 error_report("RP: Failed reading data for message 0x%04x"
1297 " read %d expected %d",
1298 header_type, res, header_len);
1299 mark_source_rp_bad(ms);
1300 goto out;
1303 /* OK, we have the message and the data */
1304 switch (header_type) {
1305 case MIG_RP_MSG_SHUT:
1306 sibling_error = be32_to_cpup((uint32_t *)buf);
1307 trace_source_return_path_thread_shut(sibling_error);
1308 if (sibling_error) {
1309 error_report("RP: Sibling indicated error %d", sibling_error);
1310 mark_source_rp_bad(ms);
1313 * We'll let the main thread deal with closing the RP
1314 * we could do a shutdown(2) on it, but we're the only user
1315 * anyway, so there's nothing gained.
1317 goto out;
1319 case MIG_RP_MSG_PONG:
1320 tmp32 = be32_to_cpup((uint32_t *)buf);
1321 trace_source_return_path_thread_pong(tmp32);
1322 break;
1324 case MIG_RP_MSG_REQ_PAGES:
1325 start = be64_to_cpup((uint64_t *)buf);
1326 len = be32_to_cpup((uint32_t *)(buf + 8));
1327 migrate_handle_rp_req_pages(ms, NULL, start, len);
1328 break;
1330 case MIG_RP_MSG_REQ_PAGES_ID:
1331 expected_len = 12 + 1; /* header + termination */
1333 if (header_len >= expected_len) {
1334 start = be64_to_cpup((uint64_t *)buf);
1335 len = be32_to_cpup((uint32_t *)(buf + 8));
1336 /* Now we expect an idstr */
1337 tmp32 = buf[12]; /* Length of the following idstr */
1338 buf[13 + tmp32] = '\0';
1339 expected_len += tmp32;
1341 if (header_len != expected_len) {
1342 error_report("RP: Req_Page_id with length %d expecting %zd",
1343 header_len, expected_len);
1344 mark_source_rp_bad(ms);
1345 goto out;
1347 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1348 break;
1350 default:
1351 break;
1354 if (qemu_file_get_error(rp)) {
1355 trace_source_return_path_thread_bad_end();
1356 mark_source_rp_bad(ms);
1359 trace_source_return_path_thread_end();
1360 out:
1361 ms->rp_state.from_dst_file = NULL;
1362 qemu_fclose(rp);
1363 return NULL;
1366 static int open_return_path_on_source(MigrationState *ms)
1369 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->file);
1370 if (!ms->rp_state.from_dst_file) {
1371 return -1;
1374 trace_open_return_path_on_source();
1375 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1376 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1378 trace_open_return_path_on_source_continue();
1380 return 0;
1383 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1384 static int await_return_path_close_on_source(MigrationState *ms)
1387 * If this is a normal exit then the destination will send a SHUT and the
1388 * rp_thread will exit, however if there's an error we need to cause
1389 * it to exit.
1391 if (qemu_file_get_error(ms->file) && ms->rp_state.from_dst_file) {
1393 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1394 * waiting for the destination.
1396 qemu_file_shutdown(ms->rp_state.from_dst_file);
1397 mark_source_rp_bad(ms);
1399 trace_await_return_path_close_on_source_joining();
1400 qemu_thread_join(&ms->rp_state.rp_thread);
1401 trace_await_return_path_close_on_source_close();
1402 return ms->rp_state.error;
1406 * Switch from normal iteration to postcopy
1407 * Returns non-0 on error
1409 static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1411 int ret;
1412 const QEMUSizedBuffer *qsb;
1413 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1414 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1415 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1417 trace_postcopy_start();
1418 qemu_mutex_lock_iothread();
1419 trace_postcopy_start_set_run();
1421 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1422 *old_vm_running = runstate_is_running();
1423 global_state_store();
1424 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1426 if (ret < 0) {
1427 goto fail;
1431 * Cause any non-postcopiable, but iterative devices to
1432 * send out their final data.
1434 qemu_savevm_state_complete_precopy(ms->file, true);
1437 * in Finish migrate and with the io-lock held everything should
1438 * be quiet, but we've potentially still got dirty pages and we
1439 * need to tell the destination to throw any pages it's already received
1440 * that are dirty
1442 if (ram_postcopy_send_discard_bitmap(ms)) {
1443 error_report("postcopy send discard bitmap failed");
1444 goto fail;
1448 * send rest of state - note things that are doing postcopy
1449 * will notice we're in POSTCOPY_ACTIVE and not actually
1450 * wrap their state up here
1452 qemu_file_set_rate_limit(ms->file, INT64_MAX);
1453 /* Ping just for debugging, helps line traces up */
1454 qemu_savevm_send_ping(ms->file, 2);
1457 * While loading the device state we may trigger page transfer
1458 * requests and the fd must be free to process those, and thus
1459 * the destination must read the whole device state off the fd before
1460 * it starts processing it. Unfortunately the ad-hoc migration format
1461 * doesn't allow the destination to know the size to read without fully
1462 * parsing it through each devices load-state code (especially the open
1463 * coded devices that use get/put).
1464 * So we wrap the device state up in a package with a length at the start;
1465 * to do this we use a qemu_buf to hold the whole of the device state.
1467 QEMUFile *fb = qemu_bufopen("w", NULL);
1468 if (!fb) {
1469 error_report("Failed to create buffered file");
1470 goto fail;
1474 * Make sure the receiver can get incoming pages before we send the rest
1475 * of the state
1477 qemu_savevm_send_postcopy_listen(fb);
1479 qemu_savevm_state_complete_precopy(fb, false);
1480 qemu_savevm_send_ping(fb, 3);
1482 qemu_savevm_send_postcopy_run(fb);
1484 /* <><> end of stuff going into the package */
1485 qsb = qemu_buf_get(fb);
1487 /* Now send that blob */
1488 if (qemu_savevm_send_packaged(ms->file, qsb)) {
1489 goto fail_closefb;
1491 qemu_fclose(fb);
1492 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1494 qemu_mutex_unlock_iothread();
1497 * Although this ping is just for debug, it could potentially be
1498 * used for getting a better measurement of downtime at the source.
1500 qemu_savevm_send_ping(ms->file, 4);
1502 ret = qemu_file_get_error(ms->file);
1503 if (ret) {
1504 error_report("postcopy_start: Migration stream errored");
1505 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1506 MIGRATION_STATUS_FAILED);
1509 return ret;
1511 fail_closefb:
1512 qemu_fclose(fb);
1513 fail:
1514 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1515 MIGRATION_STATUS_FAILED);
1516 qemu_mutex_unlock_iothread();
1517 return -1;
1521 * migration_completion: Used by migration_thread when there's not much left.
1522 * The caller 'breaks' the loop when this returns.
1524 * @s: Current migration state
1525 * @current_active_state: The migration state we expect to be in
1526 * @*old_vm_running: Pointer to old_vm_running flag
1527 * @*start_time: Pointer to time to update
1529 static void migration_completion(MigrationState *s, int current_active_state,
1530 bool *old_vm_running,
1531 int64_t *start_time)
1533 int ret;
1535 if (s->state == MIGRATION_STATUS_ACTIVE) {
1536 qemu_mutex_lock_iothread();
1537 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1538 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1539 *old_vm_running = runstate_is_running();
1540 ret = global_state_store();
1542 if (!ret) {
1543 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1544 if (ret >= 0) {
1545 qemu_file_set_rate_limit(s->file, INT64_MAX);
1546 qemu_savevm_state_complete_precopy(s->file, false);
1549 qemu_mutex_unlock_iothread();
1551 if (ret < 0) {
1552 goto fail;
1554 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1555 trace_migration_completion_postcopy_end();
1557 qemu_savevm_state_complete_postcopy(s->file);
1558 trace_migration_completion_postcopy_end_after_complete();
1562 * If rp was opened we must clean up the thread before
1563 * cleaning everything else up (since if there are no failures
1564 * it will wait for the destination to send it's status in
1565 * a SHUT command).
1566 * Postcopy opens rp if enabled (even if it's not avtivated)
1568 if (migrate_postcopy_ram()) {
1569 int rp_error;
1570 trace_migration_completion_postcopy_end_before_rp();
1571 rp_error = await_return_path_close_on_source(s);
1572 trace_migration_completion_postcopy_end_after_rp(rp_error);
1573 if (rp_error) {
1574 goto fail;
1578 if (qemu_file_get_error(s->file)) {
1579 trace_migration_completion_file_err();
1580 goto fail;
1583 migrate_set_state(&s->state, current_active_state,
1584 MIGRATION_STATUS_COMPLETED);
1585 return;
1587 fail:
1588 migrate_set_state(&s->state, current_active_state,
1589 MIGRATION_STATUS_FAILED);
1593 * Master migration thread on the source VM.
1594 * It drives the migration and pumps the data down the outgoing channel.
1596 static void *migration_thread(void *opaque)
1598 MigrationState *s = opaque;
1599 /* Used by the bandwidth calcs, updated later */
1600 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1601 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
1602 int64_t initial_bytes = 0;
1603 int64_t max_size = 0;
1604 int64_t start_time = initial_time;
1605 int64_t end_time;
1606 bool old_vm_running = false;
1607 bool entered_postcopy = false;
1608 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1609 enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
1611 rcu_register_thread();
1613 qemu_savevm_state_header(s->file);
1615 if (migrate_postcopy_ram()) {
1616 /* Now tell the dest that it should open its end so it can reply */
1617 qemu_savevm_send_open_return_path(s->file);
1619 /* And do a ping that will make stuff easier to debug */
1620 qemu_savevm_send_ping(s->file, 1);
1623 * Tell the destination that we *might* want to do postcopy later;
1624 * if the other end can't do postcopy it should fail now, nice and
1625 * early.
1627 qemu_savevm_send_postcopy_advise(s->file);
1630 qemu_savevm_state_begin(s->file, &s->params);
1632 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
1633 current_active_state = MIGRATION_STATUS_ACTIVE;
1634 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1635 MIGRATION_STATUS_ACTIVE);
1637 trace_migration_thread_setup_complete();
1639 while (s->state == MIGRATION_STATUS_ACTIVE ||
1640 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1641 int64_t current_time;
1642 uint64_t pending_size;
1644 if (!qemu_file_rate_limit(s->file)) {
1645 uint64_t pend_post, pend_nonpost;
1647 qemu_savevm_state_pending(s->file, max_size, &pend_nonpost,
1648 &pend_post);
1649 pending_size = pend_nonpost + pend_post;
1650 trace_migrate_pending(pending_size, max_size,
1651 pend_post, pend_nonpost);
1652 if (pending_size && pending_size >= max_size) {
1653 /* Still a significant amount to transfer */
1655 if (migrate_postcopy_ram() &&
1656 s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
1657 pend_nonpost <= max_size &&
1658 atomic_read(&s->start_postcopy)) {
1660 if (!postcopy_start(s, &old_vm_running)) {
1661 current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1662 entered_postcopy = true;
1665 continue;
1667 /* Just another iteration step */
1668 qemu_savevm_state_iterate(s->file, entered_postcopy);
1669 } else {
1670 trace_migration_thread_low_pending(pending_size);
1671 migration_completion(s, current_active_state,
1672 &old_vm_running, &start_time);
1673 break;
1677 if (qemu_file_get_error(s->file)) {
1678 migrate_set_state(&s->state, current_active_state,
1679 MIGRATION_STATUS_FAILED);
1680 trace_migration_thread_file_err();
1681 break;
1683 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1684 if (current_time >= initial_time + BUFFER_DELAY) {
1685 uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
1686 uint64_t time_spent = current_time - initial_time;
1687 double bandwidth = (double)transferred_bytes / time_spent;
1688 max_size = bandwidth * migrate_max_downtime() / 1000000;
1690 s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1691 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1693 trace_migrate_transferred(transferred_bytes, time_spent,
1694 bandwidth, max_size);
1695 /* if we haven't sent anything, we don't want to recalculate
1696 10000 is a small enough number for our purposes */
1697 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1698 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1701 qemu_file_reset_rate_limit(s->file);
1702 initial_time = current_time;
1703 initial_bytes = qemu_ftell(s->file);
1705 if (qemu_file_rate_limit(s->file)) {
1706 /* usleep expects microseconds */
1707 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1711 trace_migration_thread_after_loop();
1712 /* If we enabled cpu throttling for auto-converge, turn it off. */
1713 cpu_throttle_stop();
1714 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1716 qemu_mutex_lock_iothread();
1717 qemu_savevm_state_cleanup();
1718 if (s->state == MIGRATION_STATUS_COMPLETED) {
1719 uint64_t transferred_bytes = qemu_ftell(s->file);
1720 s->total_time = end_time - s->total_time;
1721 if (!entered_postcopy) {
1722 s->downtime = end_time - start_time;
1724 if (s->total_time) {
1725 s->mbps = (((double) transferred_bytes * 8.0) /
1726 ((double) s->total_time)) / 1000;
1728 runstate_set(RUN_STATE_POSTMIGRATE);
1729 } else {
1730 if (old_vm_running && !entered_postcopy) {
1731 vm_start();
1734 qemu_bh_schedule(s->cleanup_bh);
1735 qemu_mutex_unlock_iothread();
1737 rcu_unregister_thread();
1738 return NULL;
1741 void migrate_fd_connect(MigrationState *s)
1743 /* This is a best 1st approximation. ns to ms */
1744 s->expected_downtime = max_downtime/1000000;
1745 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1747 qemu_file_set_rate_limit(s->file,
1748 s->bandwidth_limit / XFER_LIMIT_RATIO);
1750 /* Notify before starting migration thread */
1751 notifier_list_notify(&migration_state_notifiers, s);
1754 * Open the return path; currently for postcopy but other things might
1755 * also want it.
1757 if (migrate_postcopy_ram()) {
1758 if (open_return_path_on_source(s)) {
1759 error_report("Unable to open return-path for postcopy");
1760 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1761 MIGRATION_STATUS_FAILED);
1762 migrate_fd_cleanup(s);
1763 return;
1767 migrate_compress_threads_create();
1768 qemu_thread_create(&s->thread, "migration", migration_thread, s,
1769 QEMU_THREAD_JOINABLE);
1770 s->migration_thread_running = true;
1773 PostcopyState postcopy_state_get(void)
1775 return atomic_mb_read(&incoming_postcopy_state);
1778 /* Set the state and return the old state */
1779 PostcopyState postcopy_state_set(PostcopyState new_state)
1781 return atomic_xchg(&incoming_postcopy_state, new_state);