Merge remote-tracking branch 'remotes/qmp-unstable/queue/qmp' into staging
[qemu.git] / migration / migration.c
blobb3adbc653a0071fa971a86d768a97315289c2a2c
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/main-loop.h"
18 #include "migration/migration.h"
19 #include "monitor/monitor.h"
20 #include "migration/qemu-file.h"
21 #include "sysemu/sysemu.h"
22 #include "block/block.h"
23 #include "qemu/sockets.h"
24 #include "migration/block.h"
25 #include "qemu/thread.h"
26 #include "qmp-commands.h"
27 #include "trace.h"
29 enum {
30 MIG_STATE_ERROR = -1,
31 MIG_STATE_NONE,
32 MIG_STATE_SETUP,
33 MIG_STATE_CANCELLING,
34 MIG_STATE_CANCELLED,
35 MIG_STATE_ACTIVE,
36 MIG_STATE_COMPLETED,
39 #define MAX_THROTTLE (32 << 20) /* Migration speed throttling */
41 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
42 * data. */
43 #define BUFFER_DELAY 100
44 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
46 /* Migration XBZRLE default cache size */
47 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
49 static NotifierList migration_state_notifiers =
50 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
52 /* When we add fault tolerance, we could have several
53 migrations at once. For now we don't need to add
54 dynamic creation of migration */
56 MigrationState *migrate_get_current(void)
58 static MigrationState current_migration = {
59 .state = MIG_STATE_NONE,
60 .bandwidth_limit = MAX_THROTTLE,
61 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
62 .mbps = -1,
65 return &current_migration;
68 void qemu_start_incoming_migration(const char *uri, Error **errp)
70 const char *p;
72 if (strstart(uri, "tcp:", &p))
73 tcp_start_incoming_migration(p, errp);
74 #ifdef CONFIG_RDMA
75 else if (strstart(uri, "rdma:", &p))
76 rdma_start_incoming_migration(p, errp);
77 #endif
78 #if !defined(WIN32)
79 else if (strstart(uri, "exec:", &p))
80 exec_start_incoming_migration(p, errp);
81 else if (strstart(uri, "unix:", &p))
82 unix_start_incoming_migration(p, errp);
83 else if (strstart(uri, "fd:", &p))
84 fd_start_incoming_migration(p, errp);
85 #endif
86 else {
87 error_setg(errp, "unknown migration protocol: %s", uri);
91 static void process_incoming_migration_co(void *opaque)
93 QEMUFile *f = opaque;
94 Error *local_err = NULL;
95 int ret;
97 ret = qemu_loadvm_state(f);
98 qemu_fclose(f);
99 free_xbzrle_decoded_buf();
100 if (ret < 0) {
101 error_report("load of migration failed: %s", strerror(-ret));
102 exit(EXIT_FAILURE);
104 qemu_announce_self();
106 /* Make sure all file formats flush their mutable metadata */
107 bdrv_invalidate_cache_all(&local_err);
108 if (local_err) {
109 qerror_report_err(local_err);
110 error_free(local_err);
111 exit(EXIT_FAILURE);
114 if (autostart) {
115 vm_start();
116 } else {
117 runstate_set(RUN_STATE_PAUSED);
121 void process_incoming_migration(QEMUFile *f)
123 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
124 int fd = qemu_get_fd(f);
126 assert(fd != -1);
127 qemu_set_nonblock(fd);
128 qemu_coroutine_enter(co, f);
131 /* amount of nanoseconds we are willing to wait for migration to be down.
132 * the choice of nanoseconds is because it is the maximum resolution that
133 * get_clock() can achieve. It is an internal measure. All user-visible
134 * units must be in seconds */
135 static uint64_t max_downtime = 300000000;
137 uint64_t migrate_max_downtime(void)
139 return max_downtime;
142 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
144 MigrationCapabilityStatusList *head = NULL;
145 MigrationCapabilityStatusList *caps;
146 MigrationState *s = migrate_get_current();
147 int i;
149 caps = NULL; /* silence compiler warning */
150 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
151 if (head == NULL) {
152 head = g_malloc0(sizeof(*caps));
153 caps = head;
154 } else {
155 caps->next = g_malloc0(sizeof(*caps));
156 caps = caps->next;
158 caps->value =
159 g_malloc(sizeof(*caps->value));
160 caps->value->capability = i;
161 caps->value->state = s->enabled_capabilities[i];
164 return head;
167 static void get_xbzrle_cache_stats(MigrationInfo *info)
169 if (migrate_use_xbzrle()) {
170 info->has_xbzrle_cache = true;
171 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
172 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
173 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
174 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
175 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
176 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
177 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
181 MigrationInfo *qmp_query_migrate(Error **errp)
183 MigrationInfo *info = g_malloc0(sizeof(*info));
184 MigrationState *s = migrate_get_current();
186 switch (s->state) {
187 case MIG_STATE_NONE:
188 /* no migration has happened ever */
189 break;
190 case MIG_STATE_SETUP:
191 info->has_status = true;
192 info->status = g_strdup("setup");
193 info->has_total_time = false;
194 break;
195 case MIG_STATE_ACTIVE:
196 case MIG_STATE_CANCELLING:
197 info->has_status = true;
198 info->status = g_strdup("active");
199 info->has_total_time = true;
200 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
201 - s->total_time;
202 info->has_expected_downtime = true;
203 info->expected_downtime = s->expected_downtime;
204 info->has_setup_time = true;
205 info->setup_time = s->setup_time;
207 info->has_ram = true;
208 info->ram = g_malloc0(sizeof(*info->ram));
209 info->ram->transferred = ram_bytes_transferred();
210 info->ram->remaining = ram_bytes_remaining();
211 info->ram->total = ram_bytes_total();
212 info->ram->duplicate = dup_mig_pages_transferred();
213 info->ram->skipped = skipped_mig_pages_transferred();
214 info->ram->normal = norm_mig_pages_transferred();
215 info->ram->normal_bytes = norm_mig_bytes_transferred();
216 info->ram->dirty_pages_rate = s->dirty_pages_rate;
217 info->ram->mbps = s->mbps;
218 info->ram->dirty_sync_count = s->dirty_sync_count;
220 if (blk_mig_active()) {
221 info->has_disk = true;
222 info->disk = g_malloc0(sizeof(*info->disk));
223 info->disk->transferred = blk_mig_bytes_transferred();
224 info->disk->remaining = blk_mig_bytes_remaining();
225 info->disk->total = blk_mig_bytes_total();
228 get_xbzrle_cache_stats(info);
229 break;
230 case MIG_STATE_COMPLETED:
231 get_xbzrle_cache_stats(info);
233 info->has_status = true;
234 info->status = g_strdup("completed");
235 info->has_total_time = true;
236 info->total_time = s->total_time;
237 info->has_downtime = true;
238 info->downtime = s->downtime;
239 info->has_setup_time = true;
240 info->setup_time = s->setup_time;
242 info->has_ram = true;
243 info->ram = g_malloc0(sizeof(*info->ram));
244 info->ram->transferred = ram_bytes_transferred();
245 info->ram->remaining = 0;
246 info->ram->total = ram_bytes_total();
247 info->ram->duplicate = dup_mig_pages_transferred();
248 info->ram->skipped = skipped_mig_pages_transferred();
249 info->ram->normal = norm_mig_pages_transferred();
250 info->ram->normal_bytes = norm_mig_bytes_transferred();
251 info->ram->mbps = s->mbps;
252 info->ram->dirty_sync_count = s->dirty_sync_count;
253 break;
254 case MIG_STATE_ERROR:
255 info->has_status = true;
256 info->status = g_strdup("failed");
257 break;
258 case MIG_STATE_CANCELLED:
259 info->has_status = true;
260 info->status = g_strdup("cancelled");
261 break;
264 return info;
267 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
268 Error **errp)
270 MigrationState *s = migrate_get_current();
271 MigrationCapabilityStatusList *cap;
273 if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP) {
274 error_set(errp, QERR_MIGRATION_ACTIVE);
275 return;
278 for (cap = params; cap; cap = cap->next) {
279 s->enabled_capabilities[cap->value->capability] = cap->value->state;
283 /* shared migration helpers */
285 static void migrate_set_state(MigrationState *s, int old_state, int new_state)
287 if (atomic_cmpxchg(&s->state, old_state, new_state) == new_state) {
288 trace_migrate_set_state(new_state);
292 static void migrate_fd_cleanup(void *opaque)
294 MigrationState *s = opaque;
296 qemu_bh_delete(s->cleanup_bh);
297 s->cleanup_bh = NULL;
299 if (s->file) {
300 trace_migrate_fd_cleanup();
301 qemu_mutex_unlock_iothread();
302 qemu_thread_join(&s->thread);
303 qemu_mutex_lock_iothread();
305 qemu_fclose(s->file);
306 s->file = NULL;
309 assert(s->state != MIG_STATE_ACTIVE);
311 if (s->state != MIG_STATE_COMPLETED) {
312 qemu_savevm_state_cancel();
313 if (s->state == MIG_STATE_CANCELLING) {
314 migrate_set_state(s, MIG_STATE_CANCELLING, MIG_STATE_CANCELLED);
318 notifier_list_notify(&migration_state_notifiers, s);
321 void migrate_fd_error(MigrationState *s)
323 trace_migrate_fd_error();
324 assert(s->file == NULL);
325 s->state = MIG_STATE_ERROR;
326 trace_migrate_set_state(MIG_STATE_ERROR);
327 notifier_list_notify(&migration_state_notifiers, s);
330 static void migrate_fd_cancel(MigrationState *s)
332 int old_state ;
333 QEMUFile *f = migrate_get_current()->file;
334 trace_migrate_fd_cancel();
336 do {
337 old_state = s->state;
338 if (old_state != MIG_STATE_SETUP && old_state != MIG_STATE_ACTIVE) {
339 break;
341 migrate_set_state(s, old_state, MIG_STATE_CANCELLING);
342 } while (s->state != MIG_STATE_CANCELLING);
345 * If we're unlucky the migration code might be stuck somewhere in a
346 * send/write while the network has failed and is waiting to timeout;
347 * if we've got shutdown(2) available then we can force it to quit.
348 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
349 * called in a bh, so there is no race against this cancel.
351 if (s->state == MIG_STATE_CANCELLING && f) {
352 qemu_file_shutdown(f);
356 void add_migration_state_change_notifier(Notifier *notify)
358 notifier_list_add(&migration_state_notifiers, notify);
361 void remove_migration_state_change_notifier(Notifier *notify)
363 notifier_remove(notify);
366 bool migration_in_setup(MigrationState *s)
368 return s->state == MIG_STATE_SETUP;
371 bool migration_has_finished(MigrationState *s)
373 return s->state == MIG_STATE_COMPLETED;
376 bool migration_has_failed(MigrationState *s)
378 return (s->state == MIG_STATE_CANCELLED ||
379 s->state == MIG_STATE_ERROR);
382 static MigrationState *migrate_init(const MigrationParams *params)
384 MigrationState *s = migrate_get_current();
385 int64_t bandwidth_limit = s->bandwidth_limit;
386 bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
387 int64_t xbzrle_cache_size = s->xbzrle_cache_size;
389 memcpy(enabled_capabilities, s->enabled_capabilities,
390 sizeof(enabled_capabilities));
392 memset(s, 0, sizeof(*s));
393 s->params = *params;
394 memcpy(s->enabled_capabilities, enabled_capabilities,
395 sizeof(enabled_capabilities));
396 s->xbzrle_cache_size = xbzrle_cache_size;
398 s->bandwidth_limit = bandwidth_limit;
399 s->state = MIG_STATE_SETUP;
400 trace_migrate_set_state(MIG_STATE_SETUP);
402 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
403 return s;
406 static GSList *migration_blockers;
408 void migrate_add_blocker(Error *reason)
410 migration_blockers = g_slist_prepend(migration_blockers, reason);
413 void migrate_del_blocker(Error *reason)
415 migration_blockers = g_slist_remove(migration_blockers, reason);
418 void qmp_migrate(const char *uri, bool has_blk, bool blk,
419 bool has_inc, bool inc, bool has_detach, bool detach,
420 Error **errp)
422 Error *local_err = NULL;
423 MigrationState *s = migrate_get_current();
424 MigrationParams params;
425 const char *p;
427 params.blk = has_blk && blk;
428 params.shared = has_inc && inc;
430 if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP ||
431 s->state == MIG_STATE_CANCELLING) {
432 error_set(errp, QERR_MIGRATION_ACTIVE);
433 return;
436 if (runstate_check(RUN_STATE_INMIGRATE)) {
437 error_setg(errp, "Guest is waiting for an incoming migration");
438 return;
441 if (qemu_savevm_state_blocked(errp)) {
442 return;
445 if (migration_blockers) {
446 *errp = error_copy(migration_blockers->data);
447 return;
450 s = migrate_init(&params);
452 if (strstart(uri, "tcp:", &p)) {
453 tcp_start_outgoing_migration(s, p, &local_err);
454 #ifdef CONFIG_RDMA
455 } else if (strstart(uri, "rdma:", &p)) {
456 rdma_start_outgoing_migration(s, p, &local_err);
457 #endif
458 #if !defined(WIN32)
459 } else if (strstart(uri, "exec:", &p)) {
460 exec_start_outgoing_migration(s, p, &local_err);
461 } else if (strstart(uri, "unix:", &p)) {
462 unix_start_outgoing_migration(s, p, &local_err);
463 } else if (strstart(uri, "fd:", &p)) {
464 fd_start_outgoing_migration(s, p, &local_err);
465 #endif
466 } else {
467 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "uri", "a valid migration protocol");
468 s->state = MIG_STATE_ERROR;
469 return;
472 if (local_err) {
473 migrate_fd_error(s);
474 error_propagate(errp, local_err);
475 return;
479 void qmp_migrate_cancel(Error **errp)
481 migrate_fd_cancel(migrate_get_current());
484 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
486 MigrationState *s = migrate_get_current();
487 int64_t new_size;
489 /* Check for truncation */
490 if (value != (size_t)value) {
491 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
492 "exceeding address space");
493 return;
496 /* Cache should not be larger than guest ram size */
497 if (value > ram_bytes_total()) {
498 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
499 "exceeds guest ram size ");
500 return;
503 new_size = xbzrle_cache_resize(value);
504 if (new_size < 0) {
505 error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
506 "is smaller than page size");
507 return;
510 s->xbzrle_cache_size = new_size;
513 int64_t qmp_query_migrate_cache_size(Error **errp)
515 return migrate_xbzrle_cache_size();
518 void qmp_migrate_set_speed(int64_t value, Error **errp)
520 MigrationState *s;
522 if (value < 0) {
523 value = 0;
525 if (value > SIZE_MAX) {
526 value = SIZE_MAX;
529 s = migrate_get_current();
530 s->bandwidth_limit = value;
531 if (s->file) {
532 qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
536 void qmp_migrate_set_downtime(double value, Error **errp)
538 value *= 1e9;
539 value = MAX(0, MIN(UINT64_MAX, value));
540 max_downtime = (uint64_t)value;
543 bool migrate_rdma_pin_all(void)
545 MigrationState *s;
547 s = migrate_get_current();
549 return s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL];
552 bool migrate_auto_converge(void)
554 MigrationState *s;
556 s = migrate_get_current();
558 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
561 bool migrate_zero_blocks(void)
563 MigrationState *s;
565 s = migrate_get_current();
567 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
570 int migrate_use_xbzrle(void)
572 MigrationState *s;
574 s = migrate_get_current();
576 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
579 int64_t migrate_xbzrle_cache_size(void)
581 MigrationState *s;
583 s = migrate_get_current();
585 return s->xbzrle_cache_size;
588 /* migration thread support */
590 static void *migration_thread(void *opaque)
592 MigrationState *s = opaque;
593 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
594 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
595 int64_t initial_bytes = 0;
596 int64_t max_size = 0;
597 int64_t start_time = initial_time;
598 bool old_vm_running = false;
600 qemu_savevm_state_begin(s->file, &s->params);
602 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
603 migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ACTIVE);
605 while (s->state == MIG_STATE_ACTIVE) {
606 int64_t current_time;
607 uint64_t pending_size;
609 if (!qemu_file_rate_limit(s->file)) {
610 pending_size = qemu_savevm_state_pending(s->file, max_size);
611 trace_migrate_pending(pending_size, max_size);
612 if (pending_size && pending_size >= max_size) {
613 qemu_savevm_state_iterate(s->file);
614 } else {
615 int ret;
617 qemu_mutex_lock_iothread();
618 start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
619 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
620 old_vm_running = runstate_is_running();
622 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
623 if (ret >= 0) {
624 qemu_file_set_rate_limit(s->file, INT64_MAX);
625 qemu_savevm_state_complete(s->file);
627 qemu_mutex_unlock_iothread();
629 if (ret < 0) {
630 migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
631 break;
634 if (!qemu_file_get_error(s->file)) {
635 migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_COMPLETED);
636 break;
641 if (qemu_file_get_error(s->file)) {
642 migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
643 break;
645 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
646 if (current_time >= initial_time + BUFFER_DELAY) {
647 uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
648 uint64_t time_spent = current_time - initial_time;
649 double bandwidth = transferred_bytes / time_spent;
650 max_size = bandwidth * migrate_max_downtime() / 1000000;
652 s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
653 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
655 trace_migrate_transferred(transferred_bytes, time_spent,
656 bandwidth, max_size);
657 /* if we haven't sent anything, we don't want to recalculate
658 10000 is a small enough number for our purposes */
659 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
660 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
663 qemu_file_reset_rate_limit(s->file);
664 initial_time = current_time;
665 initial_bytes = qemu_ftell(s->file);
667 if (qemu_file_rate_limit(s->file)) {
668 /* usleep expects microseconds */
669 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
673 qemu_mutex_lock_iothread();
674 if (s->state == MIG_STATE_COMPLETED) {
675 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
676 uint64_t transferred_bytes = qemu_ftell(s->file);
677 s->total_time = end_time - s->total_time;
678 s->downtime = end_time - start_time;
679 if (s->total_time) {
680 s->mbps = (((double) transferred_bytes * 8.0) /
681 ((double) s->total_time)) / 1000;
683 runstate_set(RUN_STATE_POSTMIGRATE);
684 } else {
685 if (old_vm_running) {
686 vm_start();
689 qemu_bh_schedule(s->cleanup_bh);
690 qemu_mutex_unlock_iothread();
692 return NULL;
695 void migrate_fd_connect(MigrationState *s)
697 s->state = MIG_STATE_SETUP;
698 trace_migrate_set_state(MIG_STATE_SETUP);
700 /* This is a best 1st approximation. ns to ms */
701 s->expected_downtime = max_downtime/1000000;
702 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
704 qemu_file_set_rate_limit(s->file,
705 s->bandwidth_limit / XFER_LIMIT_RATIO);
707 /* Notify before starting migration thread */
708 notifier_list_notify(&migration_state_notifiers, s);
710 qemu_thread_create(&s->thread, "migration", migration_thread, s,
711 QEMU_THREAD_JOINABLE);