Migration: Generate the completed event only when we complete
[qemu/ar7.git] / migration / migration.c
blob3d40f2455690c893e9f8516fd83e5d153e26bbad
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 "qemu/sockets.h"
25 #include "qemu/rcu.h"
26 #include "migration/block.h"
27 #include "qemu/thread.h"
28 #include "qmp-commands.h"
29 #include "trace.h"
30 #include "qapi/util.h"
31 #include "qapi-event.h"
32 #include "qom/cpu.h"
34 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
36 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
37 * data. */
38 #define BUFFER_DELAY 100
39 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
41 /* Default compression thread count */
42 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
43 /* Default decompression thread count, usually decompression is at
44 * least 4 times as fast as compression.*/
45 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
46 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
47 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
48 /* Define default autoconverge cpu throttle migration parameters */
49 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL 20
50 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT 10
52 /* Migration XBZRLE default cache size */
53 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
55 static NotifierList migration_state_notifiers =
56 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
58 static bool deferred_incoming;
60 /* When we add fault tolerance, we could have several
61 migrations at once. For now we don't need to add
62 dynamic creation of migration */
64 /* For outgoing */
65 MigrationState *migrate_get_current(void)
67 static MigrationState current_migration = {
68 .state = MIGRATION_STATUS_NONE,
69 .bandwidth_limit = MAX_THROTTLE,
70 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
71 .mbps = -1,
72 .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
73 DEFAULT_MIGRATE_COMPRESS_LEVEL,
74 .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
75 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
76 .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
77 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
78 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
79 DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL,
80 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
81 DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT,
84 return &current_migration;
87 /* For incoming */
88 static MigrationIncomingState *mis_current;
90 MigrationIncomingState *migration_incoming_get_current(void)
92 return mis_current;
95 MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
97 mis_current = g_new0(MigrationIncomingState, 1);
98 mis_current->file = f;
99 QLIST_INIT(&mis_current->loadvm_handlers);
101 return mis_current;
104 void migration_incoming_state_destroy(void)
106 loadvm_free_handlers(mis_current);
107 g_free(mis_current);
108 mis_current = NULL;
112 typedef struct {
113 bool optional;
114 uint32_t size;
115 uint8_t runstate[100];
116 RunState state;
117 bool received;
118 } GlobalState;
120 static GlobalState global_state;
122 int global_state_store(void)
124 if (!runstate_store((char *)global_state.runstate,
125 sizeof(global_state.runstate))) {
126 error_report("runstate name too big: %s", global_state.runstate);
127 trace_migrate_state_too_big();
128 return -EINVAL;
130 return 0;
133 void global_state_store_running(void)
135 const char *state = RunState_lookup[RUN_STATE_RUNNING];
136 strncpy((char *)global_state.runstate,
137 state, sizeof(global_state.runstate));
140 static bool global_state_received(void)
142 return global_state.received;
145 static RunState global_state_get_runstate(void)
147 return global_state.state;
150 void global_state_set_optional(void)
152 global_state.optional = true;
155 static bool global_state_needed(void *opaque)
157 GlobalState *s = opaque;
158 char *runstate = (char *)s->runstate;
160 /* If it is not optional, it is mandatory */
162 if (s->optional == false) {
163 return true;
166 /* If state is running or paused, it is not needed */
168 if (strcmp(runstate, "running") == 0 ||
169 strcmp(runstate, "paused") == 0) {
170 return false;
173 /* for any other state it is needed */
174 return true;
177 static int global_state_post_load(void *opaque, int version_id)
179 GlobalState *s = opaque;
180 Error *local_err = NULL;
181 int r;
182 char *runstate = (char *)s->runstate;
184 s->received = true;
185 trace_migrate_global_state_post_load(runstate);
187 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE_MAX,
188 -1, &local_err);
190 if (r == -1) {
191 if (local_err) {
192 error_report_err(local_err);
194 return -EINVAL;
196 s->state = r;
198 return 0;
201 static void global_state_pre_save(void *opaque)
203 GlobalState *s = opaque;
205 trace_migrate_global_state_pre_save((char *)s->runstate);
206 s->size = strlen((char *)s->runstate) + 1;
209 static const VMStateDescription vmstate_globalstate = {
210 .name = "globalstate",
211 .version_id = 1,
212 .minimum_version_id = 1,
213 .post_load = global_state_post_load,
214 .pre_save = global_state_pre_save,
215 .needed = global_state_needed,
216 .fields = (VMStateField[]) {
217 VMSTATE_UINT32(size, GlobalState),
218 VMSTATE_BUFFER(runstate, GlobalState),
219 VMSTATE_END_OF_LIST()
223 void register_global_state(void)
225 /* We would use it independently that we receive it */
226 strcpy((char *)&global_state.runstate, "");
227 global_state.received = false;
228 vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
231 static void migrate_generate_event(int new_state)
233 if (migrate_use_events()) {
234 qapi_event_send_migration(new_state, &error_abort);
239 * Called on -incoming with a defer: uri.
240 * The migration can be started later after any parameters have been
241 * changed.
243 static void deferred_incoming_migration(Error **errp)
245 if (deferred_incoming) {
246 error_setg(errp, "Incoming migration already deferred");
248 deferred_incoming = true;
251 void qemu_start_incoming_migration(const char *uri, Error **errp)
253 const char *p;
255 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
256 if (!strcmp(uri, "defer")) {
257 deferred_incoming_migration(errp);
258 } else if (strstart(uri, "tcp:", &p)) {
259 tcp_start_incoming_migration(p, errp);
260 #ifdef CONFIG_RDMA
261 } else if (strstart(uri, "rdma:", &p)) {
262 rdma_start_incoming_migration(p, errp);
263 #endif
264 #if !defined(WIN32)
265 } else if (strstart(uri, "exec:", &p)) {
266 exec_start_incoming_migration(p, errp);
267 } else if (strstart(uri, "unix:", &p)) {
268 unix_start_incoming_migration(p, errp);
269 } else if (strstart(uri, "fd:", &p)) {
270 fd_start_incoming_migration(p, errp);
271 #endif
272 } else {
273 error_setg(errp, "unknown migration protocol: %s", uri);
277 static void process_incoming_migration_co(void *opaque)
279 QEMUFile *f = opaque;
280 Error *local_err = NULL;
281 int ret;
283 migration_incoming_state_new(f);
284 migrate_generate_event(MIGRATION_STATUS_ACTIVE);
285 ret = qemu_loadvm_state(f);
287 qemu_fclose(f);
288 free_xbzrle_decoded_buf();
289 migration_incoming_state_destroy();
291 if (ret < 0) {
292 migrate_generate_event(MIGRATION_STATUS_FAILED);
293 error_report("load of migration failed: %s", strerror(-ret));
294 migrate_decompress_threads_join();
295 exit(EXIT_FAILURE);
297 qemu_announce_self();
299 /* Make sure all file formats flush their mutable metadata */
300 bdrv_invalidate_cache_all(&local_err);
301 if (local_err) {
302 migrate_generate_event(MIGRATION_STATUS_FAILED);
303 error_report_err(local_err);
304 migrate_decompress_threads_join();
305 exit(EXIT_FAILURE);
308 /* If global state section was not received or we are in running
309 state, we need to obey autostart. Any other state is set with
310 runstate_set. */
312 if (!global_state_received() ||
313 global_state_get_runstate() == RUN_STATE_RUNNING) {
314 if (autostart) {
315 vm_start();
316 } else {
317 runstate_set(RUN_STATE_PAUSED);
319 } else {
320 runstate_set(global_state_get_runstate());
322 migrate_decompress_threads_join();
324 * This must happen after any state changes since as soon as an external
325 * observer sees this event they might start to prod at the VM assuming
326 * it's ready to use.
328 migrate_generate_event(MIGRATION_STATUS_COMPLETED);
331 void process_incoming_migration(QEMUFile *f)
333 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
334 int fd = qemu_get_fd(f);
336 assert(fd != -1);
337 migrate_decompress_threads_create();
338 qemu_set_nonblock(fd);
339 qemu_coroutine_enter(co, f);
342 /* amount of nanoseconds we are willing to wait for migration to be down.
343 * the choice of nanoseconds is because it is the maximum resolution that
344 * get_clock() can achieve. It is an internal measure. All user-visible
345 * units must be in seconds */
346 static uint64_t max_downtime = 300000000;
348 uint64_t migrate_max_downtime(void)
350 return max_downtime;
353 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
355 MigrationCapabilityStatusList *head = NULL;
356 MigrationCapabilityStatusList *caps;
357 MigrationState *s = migrate_get_current();
358 int i;
360 caps = NULL; /* silence compiler warning */
361 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
362 if (head == NULL) {
363 head = g_malloc0(sizeof(*caps));
364 caps = head;
365 } else {
366 caps->next = g_malloc0(sizeof(*caps));
367 caps = caps->next;
369 caps->value =
370 g_malloc(sizeof(*caps->value));
371 caps->value->capability = i;
372 caps->value->state = s->enabled_capabilities[i];
375 return head;
378 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
380 MigrationParameters *params;
381 MigrationState *s = migrate_get_current();
383 params = g_malloc0(sizeof(*params));
384 params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
385 params->compress_threads =
386 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
387 params->decompress_threads =
388 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
389 params->x_cpu_throttle_initial =
390 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
391 params->x_cpu_throttle_increment =
392 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
394 return params;
397 static void get_xbzrle_cache_stats(MigrationInfo *info)
399 if (migrate_use_xbzrle()) {
400 info->has_xbzrle_cache = true;
401 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
402 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
403 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
404 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
405 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
406 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
407 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
411 MigrationInfo *qmp_query_migrate(Error **errp)
413 MigrationInfo *info = g_malloc0(sizeof(*info));
414 MigrationState *s = migrate_get_current();
416 switch (s->state) {
417 case MIGRATION_STATUS_NONE:
418 /* no migration has happened ever */
419 break;
420 case MIGRATION_STATUS_SETUP:
421 info->has_status = true;
422 info->has_total_time = false;
423 break;
424 case MIGRATION_STATUS_ACTIVE:
425 case MIGRATION_STATUS_CANCELLING:
426 info->has_status = true;
427 info->has_total_time = true;
428 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
429 - s->total_time;
430 info->has_expected_downtime = true;
431 info->expected_downtime = s->expected_downtime;
432 info->has_setup_time = true;
433 info->setup_time = s->setup_time;
435 info->has_ram = true;
436 info->ram = g_malloc0(sizeof(*info->ram));
437 info->ram->transferred = ram_bytes_transferred();
438 info->ram->remaining = ram_bytes_remaining();
439 info->ram->total = ram_bytes_total();
440 info->ram->duplicate = dup_mig_pages_transferred();
441 info->ram->skipped = skipped_mig_pages_transferred();
442 info->ram->normal = norm_mig_pages_transferred();
443 info->ram->normal_bytes = norm_mig_bytes_transferred();
444 info->ram->dirty_pages_rate = s->dirty_pages_rate;
445 info->ram->mbps = s->mbps;
446 info->ram->dirty_sync_count = s->dirty_sync_count;
448 if (blk_mig_active()) {
449 info->has_disk = true;
450 info->disk = g_malloc0(sizeof(*info->disk));
451 info->disk->transferred = blk_mig_bytes_transferred();
452 info->disk->remaining = blk_mig_bytes_remaining();
453 info->disk->total = blk_mig_bytes_total();
456 if (cpu_throttle_active()) {
457 info->has_x_cpu_throttle_percentage = true;
458 info->x_cpu_throttle_percentage = cpu_throttle_get_percentage();
461 get_xbzrle_cache_stats(info);
462 break;
463 case MIGRATION_STATUS_COMPLETED:
464 get_xbzrle_cache_stats(info);
466 info->has_status = true;
467 info->has_total_time = true;
468 info->total_time = s->total_time;
469 info->has_downtime = true;
470 info->downtime = s->downtime;
471 info->has_setup_time = true;
472 info->setup_time = s->setup_time;
474 info->has_ram = true;
475 info->ram = g_malloc0(sizeof(*info->ram));
476 info->ram->transferred = ram_bytes_transferred();
477 info->ram->remaining = 0;
478 info->ram->total = ram_bytes_total();
479 info->ram->duplicate = dup_mig_pages_transferred();
480 info->ram->skipped = skipped_mig_pages_transferred();
481 info->ram->normal = norm_mig_pages_transferred();
482 info->ram->normal_bytes = norm_mig_bytes_transferred();
483 info->ram->mbps = s->mbps;
484 info->ram->dirty_sync_count = s->dirty_sync_count;
485 break;
486 case MIGRATION_STATUS_FAILED:
487 info->has_status = true;
488 break;
489 case MIGRATION_STATUS_CANCELLED:
490 info->has_status = true;
491 break;
493 info->status = s->state;
495 return info;
498 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
499 Error **errp)
501 MigrationState *s = migrate_get_current();
502 MigrationCapabilityStatusList *cap;
504 if (s->state == MIGRATION_STATUS_ACTIVE ||
505 s->state == MIGRATION_STATUS_SETUP) {
506 error_setg(errp, QERR_MIGRATION_ACTIVE);
507 return;
510 for (cap = params; cap; cap = cap->next) {
511 s->enabled_capabilities[cap->value->capability] = cap->value->state;
515 void qmp_migrate_set_parameters(bool has_compress_level,
516 int64_t compress_level,
517 bool has_compress_threads,
518 int64_t compress_threads,
519 bool has_decompress_threads,
520 int64_t decompress_threads,
521 bool has_x_cpu_throttle_initial,
522 int64_t x_cpu_throttle_initial,
523 bool has_x_cpu_throttle_increment,
524 int64_t x_cpu_throttle_increment, Error **errp)
526 MigrationState *s = migrate_get_current();
528 if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
529 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
530 "is invalid, it should be in the range of 0 to 9");
531 return;
533 if (has_compress_threads &&
534 (compress_threads < 1 || compress_threads > 255)) {
535 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
536 "compress_threads",
537 "is invalid, it should be in the range of 1 to 255");
538 return;
540 if (has_decompress_threads &&
541 (decompress_threads < 1 || decompress_threads > 255)) {
542 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
543 "decompress_threads",
544 "is invalid, it should be in the range of 1 to 255");
545 return;
547 if (has_x_cpu_throttle_initial &&
548 (x_cpu_throttle_initial < 1 || x_cpu_throttle_initial > 99)) {
549 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
550 "x_cpu_throttle_initial",
551 "an integer in the range of 1 to 99");
553 if (has_x_cpu_throttle_increment &&
554 (x_cpu_throttle_increment < 1 || x_cpu_throttle_increment > 99)) {
555 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
556 "x_cpu_throttle_increment",
557 "an integer in the range of 1 to 99");
560 if (has_compress_level) {
561 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
563 if (has_compress_threads) {
564 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
566 if (has_decompress_threads) {
567 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
568 decompress_threads;
570 if (has_x_cpu_throttle_initial) {
571 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
572 x_cpu_throttle_initial;
575 if (has_x_cpu_throttle_increment) {
576 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
577 x_cpu_throttle_increment;
581 /* shared migration helpers */
583 static void migrate_set_state(MigrationState *s, int old_state, int new_state)
585 if (atomic_cmpxchg(&s->state, old_state, new_state) == old_state) {
586 trace_migrate_set_state(new_state);
587 migrate_generate_event(new_state);
591 static void migrate_fd_cleanup(void *opaque)
593 MigrationState *s = opaque;
595 qemu_bh_delete(s->cleanup_bh);
596 s->cleanup_bh = NULL;
598 if (s->file) {
599 trace_migrate_fd_cleanup();
600 qemu_mutex_unlock_iothread();
601 qemu_thread_join(&s->thread);
602 qemu_mutex_lock_iothread();
604 migrate_compress_threads_join();
605 qemu_fclose(s->file);
606 s->file = NULL;
609 assert(s->state != MIGRATION_STATUS_ACTIVE);
611 if (s->state != MIGRATION_STATUS_COMPLETED) {
612 qemu_savevm_state_cancel();
613 if (s->state == MIGRATION_STATUS_CANCELLING) {
614 migrate_set_state(s, MIGRATION_STATUS_CANCELLING,
615 MIGRATION_STATUS_CANCELLED);
619 notifier_list_notify(&migration_state_notifiers, s);
622 void migrate_fd_error(MigrationState *s)
624 trace_migrate_fd_error();
625 assert(s->file == NULL);
626 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
627 notifier_list_notify(&migration_state_notifiers, s);
630 static void migrate_fd_cancel(MigrationState *s)
632 int old_state ;
633 QEMUFile *f = migrate_get_current()->file;
634 trace_migrate_fd_cancel();
636 do {
637 old_state = s->state;
638 if (old_state != MIGRATION_STATUS_SETUP &&
639 old_state != MIGRATION_STATUS_ACTIVE) {
640 break;
642 migrate_set_state(s, old_state, MIGRATION_STATUS_CANCELLING);
643 } while (s->state != MIGRATION_STATUS_CANCELLING);
646 * If we're unlucky the migration code might be stuck somewhere in a
647 * send/write while the network has failed and is waiting to timeout;
648 * if we've got shutdown(2) available then we can force it to quit.
649 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
650 * called in a bh, so there is no race against this cancel.
652 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
653 qemu_file_shutdown(f);
657 void add_migration_state_change_notifier(Notifier *notify)
659 notifier_list_add(&migration_state_notifiers, notify);
662 void remove_migration_state_change_notifier(Notifier *notify)
664 notifier_remove(notify);
667 bool migration_in_setup(MigrationState *s)
669 return s->state == MIGRATION_STATUS_SETUP;
672 bool migration_has_finished(MigrationState *s)
674 return s->state == MIGRATION_STATUS_COMPLETED;
677 bool migration_has_failed(MigrationState *s)
679 return (s->state == MIGRATION_STATUS_CANCELLED ||
680 s->state == MIGRATION_STATUS_FAILED);
683 static MigrationState *migrate_init(const MigrationParams *params)
685 MigrationState *s = migrate_get_current();
686 int64_t bandwidth_limit = s->bandwidth_limit;
687 bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
688 int64_t xbzrle_cache_size = s->xbzrle_cache_size;
689 int compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
690 int compress_thread_count =
691 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
692 int decompress_thread_count =
693 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
694 int x_cpu_throttle_initial =
695 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
696 int x_cpu_throttle_increment =
697 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
699 memcpy(enabled_capabilities, s->enabled_capabilities,
700 sizeof(enabled_capabilities));
702 memset(s, 0, sizeof(*s));
703 s->params = *params;
704 memcpy(s->enabled_capabilities, enabled_capabilities,
705 sizeof(enabled_capabilities));
706 s->xbzrle_cache_size = xbzrle_cache_size;
708 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
709 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
710 compress_thread_count;
711 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
712 decompress_thread_count;
713 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
714 x_cpu_throttle_initial;
715 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
716 x_cpu_throttle_increment;
717 s->bandwidth_limit = bandwidth_limit;
718 migrate_set_state(s, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
720 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
721 return s;
724 static GSList *migration_blockers;
726 void migrate_add_blocker(Error *reason)
728 migration_blockers = g_slist_prepend(migration_blockers, reason);
731 void migrate_del_blocker(Error *reason)
733 migration_blockers = g_slist_remove(migration_blockers, reason);
736 void qmp_migrate_incoming(const char *uri, Error **errp)
738 Error *local_err = NULL;
739 static bool once = true;
741 if (!deferred_incoming) {
742 error_setg(errp, "For use with '-incoming defer'");
743 return;
745 if (!once) {
746 error_setg(errp, "The incoming migration has already been started");
749 qemu_start_incoming_migration(uri, &local_err);
751 if (local_err) {
752 error_propagate(errp, local_err);
753 return;
756 once = false;
759 void qmp_migrate(const char *uri, bool has_blk, bool blk,
760 bool has_inc, bool inc, bool has_detach, bool detach,
761 Error **errp)
763 Error *local_err = NULL;
764 MigrationState *s = migrate_get_current();
765 MigrationParams params;
766 const char *p;
768 params.blk = has_blk && blk;
769 params.shared = has_inc && inc;
771 if (s->state == MIGRATION_STATUS_ACTIVE ||
772 s->state == MIGRATION_STATUS_SETUP ||
773 s->state == MIGRATION_STATUS_CANCELLING) {
774 error_setg(errp, QERR_MIGRATION_ACTIVE);
775 return;
777 if (runstate_check(RUN_STATE_INMIGRATE)) {
778 error_setg(errp, "Guest is waiting for an incoming migration");
779 return;
782 if (qemu_savevm_state_blocked(errp)) {
783 return;
786 if (migration_blockers) {
787 *errp = error_copy(migration_blockers->data);
788 return;
791 /* We are starting a new migration, so we want to start in a clean
792 state. This change is only needed if previous migration
793 failed/was cancelled. We don't use migrate_set_state() because
794 we are setting the initial state, not changing it. */
795 s->state = MIGRATION_STATUS_NONE;
797 s = migrate_init(&params);
799 if (strstart(uri, "tcp:", &p)) {
800 tcp_start_outgoing_migration(s, p, &local_err);
801 #ifdef CONFIG_RDMA
802 } else if (strstart(uri, "rdma:", &p)) {
803 rdma_start_outgoing_migration(s, p, &local_err);
804 #endif
805 #if !defined(WIN32)
806 } else if (strstart(uri, "exec:", &p)) {
807 exec_start_outgoing_migration(s, p, &local_err);
808 } else if (strstart(uri, "unix:", &p)) {
809 unix_start_outgoing_migration(s, p, &local_err);
810 } else if (strstart(uri, "fd:", &p)) {
811 fd_start_outgoing_migration(s, p, &local_err);
812 #endif
813 } else {
814 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
815 "a valid migration protocol");
816 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
817 return;
820 if (local_err) {
821 migrate_fd_error(s);
822 error_propagate(errp, local_err);
823 return;
827 void qmp_migrate_cancel(Error **errp)
829 migrate_fd_cancel(migrate_get_current());
832 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
834 MigrationState *s = migrate_get_current();
835 int64_t new_size;
837 /* Check for truncation */
838 if (value != (size_t)value) {
839 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
840 "exceeding address space");
841 return;
844 /* Cache should not be larger than guest ram size */
845 if (value > ram_bytes_total()) {
846 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
847 "exceeds guest ram size ");
848 return;
851 new_size = xbzrle_cache_resize(value);
852 if (new_size < 0) {
853 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
854 "is smaller than page size");
855 return;
858 s->xbzrle_cache_size = new_size;
861 int64_t qmp_query_migrate_cache_size(Error **errp)
863 return migrate_xbzrle_cache_size();
866 void qmp_migrate_set_speed(int64_t value, Error **errp)
868 MigrationState *s;
870 if (value < 0) {
871 value = 0;
873 if (value > SIZE_MAX) {
874 value = SIZE_MAX;
877 s = migrate_get_current();
878 s->bandwidth_limit = value;
879 if (s->file) {
880 qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
884 void qmp_migrate_set_downtime(double value, Error **errp)
886 value *= 1e9;
887 value = MAX(0, MIN(UINT64_MAX, value));
888 max_downtime = (uint64_t)value;
891 bool migrate_auto_converge(void)
893 MigrationState *s;
895 s = migrate_get_current();
897 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
900 bool migrate_zero_blocks(void)
902 MigrationState *s;
904 s = migrate_get_current();
906 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
909 bool migrate_use_compression(void)
911 MigrationState *s;
913 s = migrate_get_current();
915 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
918 int migrate_compress_level(void)
920 MigrationState *s;
922 s = migrate_get_current();
924 return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
927 int migrate_compress_threads(void)
929 MigrationState *s;
931 s = migrate_get_current();
933 return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
936 int migrate_decompress_threads(void)
938 MigrationState *s;
940 s = migrate_get_current();
942 return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
945 bool migrate_use_events(void)
947 MigrationState *s;
949 s = migrate_get_current();
951 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
954 int migrate_use_xbzrle(void)
956 MigrationState *s;
958 s = migrate_get_current();
960 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
963 int64_t migrate_xbzrle_cache_size(void)
965 MigrationState *s;
967 s = migrate_get_current();
969 return s->xbzrle_cache_size;
973 * migration_completion: Used by migration_thread when there's not much left.
974 * The caller 'breaks' the loop when this returns.
976 * @s: Current migration state
977 * @*old_vm_running: Pointer to old_vm_running flag
978 * @*start_time: Pointer to time to update
980 static void migration_completion(MigrationState *s, bool *old_vm_running,
981 int64_t *start_time)
983 int ret;
985 qemu_mutex_lock_iothread();
986 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
987 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
988 *old_vm_running = runstate_is_running();
990 ret = global_state_store();
991 if (!ret) {
992 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
993 if (ret >= 0) {
994 qemu_file_set_rate_limit(s->file, INT64_MAX);
995 qemu_savevm_state_complete(s->file);
998 qemu_mutex_unlock_iothread();
1000 if (ret < 0) {
1001 goto fail;
1004 if (qemu_file_get_error(s->file)) {
1005 trace_migration_completion_file_err();
1006 goto fail;
1009 migrate_set_state(s, MIGRATION_STATUS_ACTIVE, MIGRATION_STATUS_COMPLETED);
1010 return;
1012 fail:
1013 migrate_set_state(s, MIGRATION_STATUS_ACTIVE, MIGRATION_STATUS_FAILED);
1016 /* migration thread support */
1018 static void *migration_thread(void *opaque)
1020 MigrationState *s = opaque;
1021 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1022 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
1023 int64_t initial_bytes = 0;
1024 int64_t max_size = 0;
1025 int64_t start_time = initial_time;
1026 bool old_vm_running = false;
1028 rcu_register_thread();
1030 qemu_savevm_state_header(s->file);
1031 qemu_savevm_state_begin(s->file, &s->params);
1033 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
1034 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_ACTIVE);
1036 while (s->state == MIGRATION_STATUS_ACTIVE) {
1037 int64_t current_time;
1038 uint64_t pending_size;
1040 if (!qemu_file_rate_limit(s->file)) {
1041 pending_size = qemu_savevm_state_pending(s->file, max_size);
1042 trace_migrate_pending(pending_size, max_size);
1043 if (pending_size && pending_size >= max_size) {
1044 qemu_savevm_state_iterate(s->file);
1045 } else {
1046 trace_migration_thread_low_pending(pending_size);
1047 migration_completion(s, &old_vm_running, &start_time);
1048 break;
1052 if (qemu_file_get_error(s->file)) {
1053 migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
1054 MIGRATION_STATUS_FAILED);
1055 break;
1057 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1058 if (current_time >= initial_time + BUFFER_DELAY) {
1059 uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
1060 uint64_t time_spent = current_time - initial_time;
1061 double bandwidth = transferred_bytes / time_spent;
1062 max_size = bandwidth * migrate_max_downtime() / 1000000;
1064 s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1065 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1067 trace_migrate_transferred(transferred_bytes, time_spent,
1068 bandwidth, max_size);
1069 /* if we haven't sent anything, we don't want to recalculate
1070 10000 is a small enough number for our purposes */
1071 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1072 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1075 qemu_file_reset_rate_limit(s->file);
1076 initial_time = current_time;
1077 initial_bytes = qemu_ftell(s->file);
1079 if (qemu_file_rate_limit(s->file)) {
1080 /* usleep expects microseconds */
1081 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1085 /* If we enabled cpu throttling for auto-converge, turn it off. */
1086 cpu_throttle_stop();
1088 qemu_mutex_lock_iothread();
1089 if (s->state == MIGRATION_STATUS_COMPLETED) {
1090 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1091 uint64_t transferred_bytes = qemu_ftell(s->file);
1092 s->total_time = end_time - s->total_time;
1093 s->downtime = end_time - start_time;
1094 if (s->total_time) {
1095 s->mbps = (((double) transferred_bytes * 8.0) /
1096 ((double) s->total_time)) / 1000;
1098 runstate_set(RUN_STATE_POSTMIGRATE);
1099 } else {
1100 if (old_vm_running) {
1101 vm_start();
1104 qemu_bh_schedule(s->cleanup_bh);
1105 qemu_mutex_unlock_iothread();
1107 rcu_unregister_thread();
1108 return NULL;
1111 void migrate_fd_connect(MigrationState *s)
1113 /* This is a best 1st approximation. ns to ms */
1114 s->expected_downtime = max_downtime/1000000;
1115 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1117 qemu_file_set_rate_limit(s->file,
1118 s->bandwidth_limit / XFER_LIMIT_RATIO);
1120 /* Notify before starting migration thread */
1121 notifier_list_notify(&migration_state_notifiers, s);
1123 migrate_compress_threads_create();
1124 qemu_thread_create(&s->thread, "migration", migration_thread, s,
1125 QEMU_THREAD_JOINABLE);