migration: Create x-multifd-page-count parameter
[qemu/ar7.git] / migration / migration.c
blob494c6eb435ea9a83986a95b387e53018c20f238a
1 /*
2 * QEMU live migration
4 * Copyright IBM, Corp. 2008
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "migration/blocker.h"
20 #include "exec.h"
21 #include "fd.h"
22 #include "socket.h"
23 #include "rdma.h"
24 #include "ram.h"
25 #include "migration/global_state.h"
26 #include "migration/misc.h"
27 #include "migration.h"
28 #include "savevm.h"
29 #include "qemu-file-channel.h"
30 #include "qemu-file.h"
31 #include "migration/vmstate.h"
32 #include "block/block.h"
33 #include "qapi/qmp/qerror.h"
34 #include "qemu/rcu.h"
35 #include "block.h"
36 #include "postcopy-ram.h"
37 #include "qemu/thread.h"
38 #include "qmp-commands.h"
39 #include "trace.h"
40 #include "qapi-event.h"
41 #include "exec/target_page.h"
42 #include "io/channel-buffer.h"
43 #include "migration/colo.h"
44 #include "hw/boards.h"
45 #include "monitor/monitor.h"
47 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
49 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
50 * data. */
51 #define BUFFER_DELAY 100
52 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
54 /* Time in milliseconds we are allowed to stop the source,
55 * for sending the last part */
56 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
58 /* Maximum migrate downtime set to 2000 seconds */
59 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
60 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
62 /* Default compression thread count */
63 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
64 /* Default decompression thread count, usually decompression is at
65 * least 4 times as fast as compression.*/
66 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
67 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
68 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
69 /* Define default autoconverge cpu throttle migration parameters */
70 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
71 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
73 /* Migration XBZRLE default cache size */
74 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
76 /* The delay time (in ms) between two COLO checkpoints
77 * Note: Please change this default value to 10000 when we support hybrid mode.
79 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
80 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
81 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
83 static NotifierList migration_state_notifiers =
84 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
86 static bool deferred_incoming;
88 /* Messages sent on the return path from destination to source */
89 enum mig_rp_message_type {
90 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
91 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
92 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
94 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
95 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
97 MIG_RP_MSG_MAX
100 /* When we add fault tolerance, we could have several
101 migrations at once. For now we don't need to add
102 dynamic creation of migration */
104 static MigrationState *current_migration;
106 static bool migration_object_check(MigrationState *ms, Error **errp);
108 void migration_object_init(void)
110 MachineState *ms = MACHINE(qdev_get_machine());
111 Error *err = NULL;
113 /* This can only be called once. */
114 assert(!current_migration);
115 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
117 if (!migration_object_check(current_migration, &err)) {
118 error_report_err(err);
119 exit(1);
123 * We cannot really do this in migration_instance_init() since at
124 * that time global properties are not yet applied, then this
125 * value will be definitely replaced by something else.
127 if (ms->enforce_config_section) {
128 current_migration->send_configuration = true;
132 /* For outgoing */
133 MigrationState *migrate_get_current(void)
135 /* This can only be called after the object created. */
136 assert(current_migration);
137 return current_migration;
140 MigrationIncomingState *migration_incoming_get_current(void)
142 static bool once;
143 static MigrationIncomingState mis_current;
145 if (!once) {
146 mis_current.state = MIGRATION_STATUS_NONE;
147 memset(&mis_current, 0, sizeof(MigrationIncomingState));
148 qemu_mutex_init(&mis_current.rp_mutex);
149 qemu_event_init(&mis_current.main_thread_load_event, false);
150 once = true;
152 return &mis_current;
155 void migration_incoming_state_destroy(void)
157 struct MigrationIncomingState *mis = migration_incoming_get_current();
159 if (mis->to_src_file) {
160 /* Tell source that we are done */
161 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
162 qemu_fclose(mis->to_src_file);
163 mis->to_src_file = NULL;
166 if (mis->from_src_file) {
167 qemu_fclose(mis->from_src_file);
168 mis->from_src_file = NULL;
171 qemu_event_reset(&mis->main_thread_load_event);
174 static void migrate_generate_event(int new_state)
176 if (migrate_use_events()) {
177 qapi_event_send_migration(new_state, &error_abort);
182 * Called on -incoming with a defer: uri.
183 * The migration can be started later after any parameters have been
184 * changed.
186 static void deferred_incoming_migration(Error **errp)
188 if (deferred_incoming) {
189 error_setg(errp, "Incoming migration already deferred");
191 deferred_incoming = true;
195 * Send a message on the return channel back to the source
196 * of the migration.
198 static void migrate_send_rp_message(MigrationIncomingState *mis,
199 enum mig_rp_message_type message_type,
200 uint16_t len, void *data)
202 trace_migrate_send_rp_message((int)message_type, len);
203 qemu_mutex_lock(&mis->rp_mutex);
204 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
205 qemu_put_be16(mis->to_src_file, len);
206 qemu_put_buffer(mis->to_src_file, data, len);
207 qemu_fflush(mis->to_src_file);
208 qemu_mutex_unlock(&mis->rp_mutex);
211 /* Request a range of pages from the source VM at the given
212 * start address.
213 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
214 * as the last request (a name must have been given previously)
215 * Start: Address offset within the RB
216 * Len: Length in bytes required - must be a multiple of pagesize
218 void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
219 ram_addr_t start, size_t len)
221 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
222 size_t msglen = 12; /* start + len */
224 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
225 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
227 if (rbname) {
228 int rbname_len = strlen(rbname);
229 assert(rbname_len < 256);
231 bufc[msglen++] = rbname_len;
232 memcpy(bufc + msglen, rbname, rbname_len);
233 msglen += rbname_len;
234 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES_ID, msglen, bufc);
235 } else {
236 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES, msglen, bufc);
240 void qemu_start_incoming_migration(const char *uri, Error **errp)
242 const char *p;
244 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
245 if (!strcmp(uri, "defer")) {
246 deferred_incoming_migration(errp);
247 } else if (strstart(uri, "tcp:", &p)) {
248 tcp_start_incoming_migration(p, errp);
249 #ifdef CONFIG_RDMA
250 } else if (strstart(uri, "rdma:", &p)) {
251 rdma_start_incoming_migration(p, errp);
252 #endif
253 } else if (strstart(uri, "exec:", &p)) {
254 exec_start_incoming_migration(p, errp);
255 } else if (strstart(uri, "unix:", &p)) {
256 unix_start_incoming_migration(p, errp);
257 } else if (strstart(uri, "fd:", &p)) {
258 fd_start_incoming_migration(p, errp);
259 } else {
260 error_setg(errp, "unknown migration protocol: %s", uri);
264 static void process_incoming_migration_bh(void *opaque)
266 Error *local_err = NULL;
267 MigrationIncomingState *mis = opaque;
269 /* Make sure all file formats flush their mutable metadata.
270 * If we get an error here, just don't restart the VM yet. */
271 bdrv_invalidate_cache_all(&local_err);
272 if (local_err) {
273 error_report_err(local_err);
274 local_err = NULL;
275 autostart = false;
279 * This must happen after all error conditions are dealt with and
280 * we're sure the VM is going to be running on this host.
282 qemu_announce_self();
284 /* If global state section was not received or we are in running
285 state, we need to obey autostart. Any other state is set with
286 runstate_set. */
288 if (!global_state_received() ||
289 global_state_get_runstate() == RUN_STATE_RUNNING) {
290 if (autostart) {
291 vm_start();
292 } else {
293 runstate_set(RUN_STATE_PAUSED);
295 } else {
296 runstate_set(global_state_get_runstate());
299 * This must happen after any state changes since as soon as an external
300 * observer sees this event they might start to prod at the VM assuming
301 * it's ready to use.
303 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
304 MIGRATION_STATUS_COMPLETED);
305 qemu_bh_delete(mis->bh);
306 migration_incoming_state_destroy();
309 static void process_incoming_migration_co(void *opaque)
311 MigrationIncomingState *mis = migration_incoming_get_current();
312 PostcopyState ps;
313 int ret;
315 assert(mis->from_src_file);
316 mis->largest_page_size = qemu_ram_pagesize_largest();
317 postcopy_state_set(POSTCOPY_INCOMING_NONE);
318 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
319 MIGRATION_STATUS_ACTIVE);
320 ret = qemu_loadvm_state(mis->from_src_file);
322 ps = postcopy_state_get();
323 trace_process_incoming_migration_co_end(ret, ps);
324 if (ps != POSTCOPY_INCOMING_NONE) {
325 if (ps == POSTCOPY_INCOMING_ADVISE) {
327 * Where a migration had postcopy enabled (and thus went to advise)
328 * but managed to complete within the precopy period, we can use
329 * the normal exit.
331 postcopy_ram_incoming_cleanup(mis);
332 } else if (ret >= 0) {
334 * Postcopy was started, cleanup should happen at the end of the
335 * postcopy thread.
337 trace_process_incoming_migration_co_postcopy_end_main();
338 return;
340 /* Else if something went wrong then just fall out of the normal exit */
343 /* we get COLO info, and know if we are in COLO mode */
344 if (!ret && migration_incoming_enable_colo()) {
345 mis->migration_incoming_co = qemu_coroutine_self();
346 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
347 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
348 mis->have_colo_incoming_thread = true;
349 qemu_coroutine_yield();
351 /* Wait checkpoint incoming thread exit before free resource */
352 qemu_thread_join(&mis->colo_incoming_thread);
355 if (ret < 0) {
356 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
357 MIGRATION_STATUS_FAILED);
358 error_report("load of migration failed: %s", strerror(-ret));
359 qemu_fclose(mis->from_src_file);
360 exit(EXIT_FAILURE);
362 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
363 qemu_bh_schedule(mis->bh);
366 void migration_fd_process_incoming(QEMUFile *f)
368 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
369 MigrationIncomingState *mis = migration_incoming_get_current();
371 if (!mis->from_src_file) {
372 mis->from_src_file = f;
374 qemu_file_set_blocking(f, false);
375 qemu_coroutine_enter(co);
378 void migration_ioc_process_incoming(QIOChannel *ioc)
380 MigrationIncomingState *mis = migration_incoming_get_current();
382 if (!mis->from_src_file) {
383 QEMUFile *f = qemu_fopen_channel_input(ioc);
384 migration_fd_process_incoming(f);
386 /* We still only have a single channel. Nothing to do here yet */
390 * @migration_has_all_channels: We have received all channels that we need
392 * Returns true when we have got connections to all the channels that
393 * we need for migration.
395 bool migration_has_all_channels(void)
397 return true;
401 * Send a 'SHUT' message on the return channel with the given value
402 * to indicate that we've finished with the RP. Non-0 value indicates
403 * error.
405 void migrate_send_rp_shut(MigrationIncomingState *mis,
406 uint32_t value)
408 uint32_t buf;
410 buf = cpu_to_be32(value);
411 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
415 * Send a 'PONG' message on the return channel with the given value
416 * (normally in response to a 'PING')
418 void migrate_send_rp_pong(MigrationIncomingState *mis,
419 uint32_t value)
421 uint32_t buf;
423 buf = cpu_to_be32(value);
424 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
427 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
429 MigrationCapabilityStatusList *head = NULL;
430 MigrationCapabilityStatusList *caps;
431 MigrationState *s = migrate_get_current();
432 int i;
434 caps = NULL; /* silence compiler warning */
435 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
436 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
437 if (i == MIGRATION_CAPABILITY_BLOCK) {
438 continue;
440 #endif
441 if (head == NULL) {
442 head = g_malloc0(sizeof(*caps));
443 caps = head;
444 } else {
445 caps->next = g_malloc0(sizeof(*caps));
446 caps = caps->next;
448 caps->value =
449 g_malloc(sizeof(*caps->value));
450 caps->value->capability = i;
451 caps->value->state = s->enabled_capabilities[i];
454 return head;
457 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
459 MigrationParameters *params;
460 MigrationState *s = migrate_get_current();
462 /* TODO use QAPI_CLONE() instead of duplicating it inline */
463 params = g_malloc0(sizeof(*params));
464 params->has_compress_level = true;
465 params->compress_level = s->parameters.compress_level;
466 params->has_compress_threads = true;
467 params->compress_threads = s->parameters.compress_threads;
468 params->has_decompress_threads = true;
469 params->decompress_threads = s->parameters.decompress_threads;
470 params->has_cpu_throttle_initial = true;
471 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
472 params->has_cpu_throttle_increment = true;
473 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
474 params->has_tls_creds = true;
475 params->tls_creds = g_strdup(s->parameters.tls_creds);
476 params->has_tls_hostname = true;
477 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
478 params->has_max_bandwidth = true;
479 params->max_bandwidth = s->parameters.max_bandwidth;
480 params->has_downtime_limit = true;
481 params->downtime_limit = s->parameters.downtime_limit;
482 params->has_x_checkpoint_delay = true;
483 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
484 params->has_block_incremental = true;
485 params->block_incremental = s->parameters.block_incremental;
486 params->has_x_multifd_channels = true;
487 params->x_multifd_channels = s->parameters.x_multifd_channels;
488 params->has_x_multifd_page_count = true;
489 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
491 return params;
495 * Return true if we're already in the middle of a migration
496 * (i.e. any of the active or setup states)
498 static bool migration_is_setup_or_active(int state)
500 switch (state) {
501 case MIGRATION_STATUS_ACTIVE:
502 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
503 case MIGRATION_STATUS_SETUP:
504 return true;
506 default:
507 return false;
512 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
514 info->has_ram = true;
515 info->ram = g_malloc0(sizeof(*info->ram));
516 info->ram->transferred = ram_counters.transferred;
517 info->ram->total = ram_bytes_total();
518 info->ram->duplicate = ram_counters.duplicate;
519 /* legacy value. It is not used anymore */
520 info->ram->skipped = 0;
521 info->ram->normal = ram_counters.normal;
522 info->ram->normal_bytes = ram_counters.normal *
523 qemu_target_page_size();
524 info->ram->mbps = s->mbps;
525 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
526 info->ram->postcopy_requests = ram_counters.postcopy_requests;
527 info->ram->page_size = qemu_target_page_size();
529 if (migrate_use_xbzrle()) {
530 info->has_xbzrle_cache = true;
531 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
532 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
533 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
534 info->xbzrle_cache->pages = xbzrle_counters.pages;
535 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
536 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
537 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
540 if (cpu_throttle_active()) {
541 info->has_cpu_throttle_percentage = true;
542 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
545 if (s->state != MIGRATION_STATUS_COMPLETED) {
546 info->ram->remaining = ram_bytes_remaining();
547 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
551 static void populate_disk_info(MigrationInfo *info)
553 if (blk_mig_active()) {
554 info->has_disk = true;
555 info->disk = g_malloc0(sizeof(*info->disk));
556 info->disk->transferred = blk_mig_bytes_transferred();
557 info->disk->remaining = blk_mig_bytes_remaining();
558 info->disk->total = blk_mig_bytes_total();
562 MigrationInfo *qmp_query_migrate(Error **errp)
564 MigrationInfo *info = g_malloc0(sizeof(*info));
565 MigrationState *s = migrate_get_current();
567 switch (s->state) {
568 case MIGRATION_STATUS_NONE:
569 /* no migration has happened ever */
570 break;
571 case MIGRATION_STATUS_SETUP:
572 info->has_status = true;
573 info->has_total_time = false;
574 break;
575 case MIGRATION_STATUS_ACTIVE:
576 case MIGRATION_STATUS_CANCELLING:
577 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
578 /* TODO add some postcopy stats */
579 info->has_status = true;
580 info->has_total_time = true;
581 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
582 - s->total_time;
583 info->has_expected_downtime = true;
584 info->expected_downtime = s->expected_downtime;
585 info->has_setup_time = true;
586 info->setup_time = s->setup_time;
588 populate_ram_info(info, s);
589 populate_disk_info(info);
590 break;
591 case MIGRATION_STATUS_COLO:
592 info->has_status = true;
593 /* TODO: display COLO specific information (checkpoint info etc.) */
594 break;
595 case MIGRATION_STATUS_COMPLETED:
596 info->has_status = true;
597 info->has_total_time = true;
598 info->total_time = s->total_time;
599 info->has_downtime = true;
600 info->downtime = s->downtime;
601 info->has_setup_time = true;
602 info->setup_time = s->setup_time;
604 populate_ram_info(info, s);
605 break;
606 case MIGRATION_STATUS_FAILED:
607 info->has_status = true;
608 if (s->error) {
609 info->has_error_desc = true;
610 info->error_desc = g_strdup(error_get_pretty(s->error));
612 break;
613 case MIGRATION_STATUS_CANCELLED:
614 info->has_status = true;
615 break;
617 info->status = s->state;
619 return info;
623 * @migration_caps_check - check capability validity
625 * @cap_list: old capability list, array of bool
626 * @params: new capabilities to be applied soon
627 * @errp: set *errp if the check failed, with reason
629 * Returns true if check passed, otherwise false.
631 static bool migrate_caps_check(bool *cap_list,
632 MigrationCapabilityStatusList *params,
633 Error **errp)
635 MigrationCapabilityStatusList *cap;
636 bool old_postcopy_cap;
638 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
640 for (cap = params; cap; cap = cap->next) {
641 cap_list[cap->value->capability] = cap->value->state;
644 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
645 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
646 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
647 "block migration");
648 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
649 return false;
651 #endif
653 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
654 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
655 /* The decompression threads asynchronously write into RAM
656 * rather than use the atomic copies needed to avoid
657 * userfaulting. It should be possible to fix the decompression
658 * threads for compatibility in future.
660 error_setg(errp, "Postcopy is not currently compatible "
661 "with compression");
662 return false;
665 /* This check is reasonably expensive, so only when it's being
666 * set the first time, also it's only the destination that needs
667 * special support.
669 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
670 !postcopy_ram_supported_by_host()) {
671 /* postcopy_ram_supported_by_host will have emitted a more
672 * detailed message
674 error_setg(errp, "Postcopy is not supported");
675 return false;
679 return true;
682 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
683 Error **errp)
685 MigrationState *s = migrate_get_current();
686 MigrationCapabilityStatusList *cap;
688 if (migration_is_setup_or_active(s->state)) {
689 error_setg(errp, QERR_MIGRATION_ACTIVE);
690 return;
693 if (!migrate_caps_check(s->enabled_capabilities, params, errp)) {
694 return;
697 for (cap = params; cap; cap = cap->next) {
698 s->enabled_capabilities[cap->value->capability] = cap->value->state;
703 * Check whether the parameters are valid. Error will be put into errp
704 * (if provided). Return true if valid, otherwise false.
706 static bool migrate_params_check(MigrationParameters *params, Error **errp)
708 if (params->has_compress_level &&
709 (params->compress_level < 0 || params->compress_level > 9)) {
710 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
711 "is invalid, it should be in the range of 0 to 9");
712 return false;
715 if (params->has_compress_threads &&
716 (params->compress_threads < 1 || params->compress_threads > 255)) {
717 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
718 "compress_threads",
719 "is invalid, it should be in the range of 1 to 255");
720 return false;
723 if (params->has_decompress_threads &&
724 (params->decompress_threads < 1 || params->decompress_threads > 255)) {
725 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
726 "decompress_threads",
727 "is invalid, it should be in the range of 1 to 255");
728 return false;
731 if (params->has_cpu_throttle_initial &&
732 (params->cpu_throttle_initial < 1 ||
733 params->cpu_throttle_initial > 99)) {
734 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
735 "cpu_throttle_initial",
736 "an integer in the range of 1 to 99");
737 return false;
740 if (params->has_cpu_throttle_increment &&
741 (params->cpu_throttle_increment < 1 ||
742 params->cpu_throttle_increment > 99)) {
743 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
744 "cpu_throttle_increment",
745 "an integer in the range of 1 to 99");
746 return false;
749 if (params->has_max_bandwidth &&
750 (params->max_bandwidth < 0 || params->max_bandwidth > SIZE_MAX)) {
751 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
752 " range of 0 to %zu bytes/second", SIZE_MAX);
753 return false;
756 if (params->has_downtime_limit &&
757 (params->downtime_limit < 0 ||
758 params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
759 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
760 "the range of 0 to %d milliseconds",
761 MAX_MIGRATE_DOWNTIME);
762 return false;
765 if (params->has_x_checkpoint_delay && (params->x_checkpoint_delay < 0)) {
766 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
767 "x_checkpoint_delay",
768 "is invalid, it should be positive");
769 return false;
771 if (params->has_x_multifd_channels &&
772 (params->x_multifd_channels < 1 || params->x_multifd_channels > 255)) {
773 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
774 "multifd_channels",
775 "is invalid, it should be in the range of 1 to 255");
776 return false;
778 if (params->has_x_multifd_page_count &&
779 (params->x_multifd_page_count < 1 ||
780 params->x_multifd_page_count > 10000)) {
781 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
782 "multifd_page_count",
783 "is invalid, it should be in the range of 1 to 10000");
784 return false;
787 return true;
790 static void migrate_params_test_apply(MigrateSetParameters *params,
791 MigrationParameters *dest)
793 *dest = migrate_get_current()->parameters;
795 /* TODO use QAPI_CLONE() instead of duplicating it inline */
797 if (params->has_compress_level) {
798 dest->compress_level = params->compress_level;
801 if (params->has_compress_threads) {
802 dest->compress_threads = params->compress_threads;
805 if (params->has_decompress_threads) {
806 dest->decompress_threads = params->decompress_threads;
809 if (params->has_cpu_throttle_initial) {
810 dest->cpu_throttle_initial = params->cpu_throttle_initial;
813 if (params->has_cpu_throttle_increment) {
814 dest->cpu_throttle_increment = params->cpu_throttle_increment;
817 if (params->has_tls_creds) {
818 assert(params->tls_creds->type == QTYPE_QSTRING);
819 dest->tls_creds = g_strdup(params->tls_creds->u.s);
822 if (params->has_tls_hostname) {
823 assert(params->tls_hostname->type == QTYPE_QSTRING);
824 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
827 if (params->has_max_bandwidth) {
828 dest->max_bandwidth = params->max_bandwidth;
831 if (params->has_downtime_limit) {
832 dest->downtime_limit = params->downtime_limit;
835 if (params->has_x_checkpoint_delay) {
836 dest->x_checkpoint_delay = params->x_checkpoint_delay;
839 if (params->has_block_incremental) {
840 dest->block_incremental = params->block_incremental;
844 static void migrate_params_apply(MigrateSetParameters *params)
846 MigrationState *s = migrate_get_current();
848 /* TODO use QAPI_CLONE() instead of duplicating it inline */
850 if (params->has_compress_level) {
851 s->parameters.compress_level = params->compress_level;
854 if (params->has_compress_threads) {
855 s->parameters.compress_threads = params->compress_threads;
858 if (params->has_decompress_threads) {
859 s->parameters.decompress_threads = params->decompress_threads;
862 if (params->has_cpu_throttle_initial) {
863 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
866 if (params->has_cpu_throttle_increment) {
867 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
870 if (params->has_tls_creds) {
871 g_free(s->parameters.tls_creds);
872 assert(params->tls_creds->type == QTYPE_QSTRING);
873 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
876 if (params->has_tls_hostname) {
877 g_free(s->parameters.tls_hostname);
878 assert(params->tls_hostname->type == QTYPE_QSTRING);
879 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
882 if (params->has_max_bandwidth) {
883 s->parameters.max_bandwidth = params->max_bandwidth;
884 if (s->to_dst_file) {
885 qemu_file_set_rate_limit(s->to_dst_file,
886 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
890 if (params->has_downtime_limit) {
891 s->parameters.downtime_limit = params->downtime_limit;
894 if (params->has_x_checkpoint_delay) {
895 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
896 if (migration_in_colo_state()) {
897 colo_checkpoint_notify(s);
901 if (params->has_block_incremental) {
902 s->parameters.block_incremental = params->block_incremental;
904 if (params->has_x_multifd_channels) {
905 s->parameters.x_multifd_channels = params->x_multifd_channels;
907 if (params->has_x_multifd_page_count) {
908 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
912 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
914 MigrationParameters tmp;
916 /* TODO Rewrite "" to null instead */
917 if (params->has_tls_creds
918 && params->tls_creds->type == QTYPE_QNULL) {
919 QDECREF(params->tls_creds->u.n);
920 params->tls_creds->type = QTYPE_QSTRING;
921 params->tls_creds->u.s = strdup("");
923 /* TODO Rewrite "" to null instead */
924 if (params->has_tls_hostname
925 && params->tls_hostname->type == QTYPE_QNULL) {
926 QDECREF(params->tls_hostname->u.n);
927 params->tls_hostname->type = QTYPE_QSTRING;
928 params->tls_hostname->u.s = strdup("");
931 migrate_params_test_apply(params, &tmp);
933 if (!migrate_params_check(&tmp, errp)) {
934 /* Invalid parameter */
935 return;
938 migrate_params_apply(params);
942 void qmp_migrate_start_postcopy(Error **errp)
944 MigrationState *s = migrate_get_current();
946 if (!migrate_postcopy_ram()) {
947 error_setg(errp, "Enable postcopy with migrate_set_capability before"
948 " the start of migration");
949 return;
952 if (s->state == MIGRATION_STATUS_NONE) {
953 error_setg(errp, "Postcopy must be started after migration has been"
954 " started");
955 return;
958 * we don't error if migration has finished since that would be racy
959 * with issuing this command.
961 atomic_set(&s->start_postcopy, true);
964 /* shared migration helpers */
966 void migrate_set_state(int *state, int old_state, int new_state)
968 assert(new_state < MIGRATION_STATUS__MAX);
969 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
970 trace_migrate_set_state(MigrationStatus_str(new_state));
971 migrate_generate_event(new_state);
975 static MigrationCapabilityStatusList *migrate_cap_add(
976 MigrationCapabilityStatusList *list,
977 MigrationCapability index,
978 bool state)
980 MigrationCapabilityStatusList *cap;
982 cap = g_new0(MigrationCapabilityStatusList, 1);
983 cap->value = g_new0(MigrationCapabilityStatus, 1);
984 cap->value->capability = index;
985 cap->value->state = state;
986 cap->next = list;
988 return cap;
991 void migrate_set_block_enabled(bool value, Error **errp)
993 MigrationCapabilityStatusList *cap;
995 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
996 qmp_migrate_set_capabilities(cap, errp);
997 qapi_free_MigrationCapabilityStatusList(cap);
1000 static void migrate_set_block_incremental(MigrationState *s, bool value)
1002 s->parameters.block_incremental = value;
1005 static void block_cleanup_parameters(MigrationState *s)
1007 if (s->must_remove_block_options) {
1008 /* setting to false can never fail */
1009 migrate_set_block_enabled(false, &error_abort);
1010 migrate_set_block_incremental(s, false);
1011 s->must_remove_block_options = false;
1015 static void migrate_fd_cleanup(void *opaque)
1017 MigrationState *s = opaque;
1019 qemu_bh_delete(s->cleanup_bh);
1020 s->cleanup_bh = NULL;
1022 if (s->to_dst_file) {
1023 trace_migrate_fd_cleanup();
1024 qemu_mutex_unlock_iothread();
1025 if (s->migration_thread_running) {
1026 qemu_thread_join(&s->thread);
1027 s->migration_thread_running = false;
1029 qemu_mutex_lock_iothread();
1031 qemu_fclose(s->to_dst_file);
1032 s->to_dst_file = NULL;
1035 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1036 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1038 if (s->state == MIGRATION_STATUS_CANCELLING) {
1039 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1040 MIGRATION_STATUS_CANCELLED);
1043 notifier_list_notify(&migration_state_notifiers, s);
1044 block_cleanup_parameters(s);
1047 void migrate_fd_error(MigrationState *s, const Error *error)
1049 trace_migrate_fd_error(error_get_pretty(error));
1050 assert(s->to_dst_file == NULL);
1051 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1052 MIGRATION_STATUS_FAILED);
1053 if (!s->error) {
1054 s->error = error_copy(error);
1056 notifier_list_notify(&migration_state_notifiers, s);
1057 block_cleanup_parameters(s);
1060 static void migrate_fd_cancel(MigrationState *s)
1062 int old_state ;
1063 QEMUFile *f = migrate_get_current()->to_dst_file;
1064 trace_migrate_fd_cancel();
1066 if (s->rp_state.from_dst_file) {
1067 /* shutdown the rp socket, so causing the rp thread to shutdown */
1068 qemu_file_shutdown(s->rp_state.from_dst_file);
1071 do {
1072 old_state = s->state;
1073 if (!migration_is_setup_or_active(old_state)) {
1074 break;
1076 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1077 } while (s->state != MIGRATION_STATUS_CANCELLING);
1080 * If we're unlucky the migration code might be stuck somewhere in a
1081 * send/write while the network has failed and is waiting to timeout;
1082 * if we've got shutdown(2) available then we can force it to quit.
1083 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1084 * called in a bh, so there is no race against this cancel.
1086 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1087 qemu_file_shutdown(f);
1089 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1090 Error *local_err = NULL;
1092 bdrv_invalidate_cache_all(&local_err);
1093 if (local_err) {
1094 error_report_err(local_err);
1095 } else {
1096 s->block_inactive = false;
1099 block_cleanup_parameters(s);
1102 void add_migration_state_change_notifier(Notifier *notify)
1104 notifier_list_add(&migration_state_notifiers, notify);
1107 void remove_migration_state_change_notifier(Notifier *notify)
1109 notifier_remove(notify);
1112 bool migration_in_setup(MigrationState *s)
1114 return s->state == MIGRATION_STATUS_SETUP;
1117 bool migration_has_finished(MigrationState *s)
1119 return s->state == MIGRATION_STATUS_COMPLETED;
1122 bool migration_has_failed(MigrationState *s)
1124 return (s->state == MIGRATION_STATUS_CANCELLED ||
1125 s->state == MIGRATION_STATUS_FAILED);
1128 bool migration_in_postcopy(void)
1130 MigrationState *s = migrate_get_current();
1132 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1135 bool migration_in_postcopy_after_devices(MigrationState *s)
1137 return migration_in_postcopy() && s->postcopy_after_devices;
1140 bool migration_is_idle(void)
1142 MigrationState *s = migrate_get_current();
1144 switch (s->state) {
1145 case MIGRATION_STATUS_NONE:
1146 case MIGRATION_STATUS_CANCELLED:
1147 case MIGRATION_STATUS_COMPLETED:
1148 case MIGRATION_STATUS_FAILED:
1149 return true;
1150 case MIGRATION_STATUS_SETUP:
1151 case MIGRATION_STATUS_CANCELLING:
1152 case MIGRATION_STATUS_ACTIVE:
1153 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1154 case MIGRATION_STATUS_COLO:
1155 return false;
1156 case MIGRATION_STATUS__MAX:
1157 g_assert_not_reached();
1160 return false;
1163 MigrationState *migrate_init(void)
1165 MigrationState *s = migrate_get_current();
1168 * Reinitialise all migration state, except
1169 * parameters/capabilities that the user set, and
1170 * locks.
1172 s->bytes_xfer = 0;
1173 s->xfer_limit = 0;
1174 s->cleanup_bh = 0;
1175 s->to_dst_file = NULL;
1176 s->state = MIGRATION_STATUS_NONE;
1177 s->rp_state.from_dst_file = NULL;
1178 s->rp_state.error = false;
1179 s->mbps = 0.0;
1180 s->downtime = 0;
1181 s->expected_downtime = 0;
1182 s->setup_time = 0;
1183 s->start_postcopy = false;
1184 s->postcopy_after_devices = false;
1185 s->migration_thread_running = false;
1186 error_free(s->error);
1187 s->error = NULL;
1189 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1191 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1192 return s;
1195 static GSList *migration_blockers;
1197 int migrate_add_blocker(Error *reason, Error **errp)
1199 if (migrate_get_current()->only_migratable) {
1200 error_propagate(errp, error_copy(reason));
1201 error_prepend(errp, "disallowing migration blocker "
1202 "(--only_migratable) for: ");
1203 return -EACCES;
1206 if (migration_is_idle()) {
1207 migration_blockers = g_slist_prepend(migration_blockers, reason);
1208 return 0;
1211 error_propagate(errp, error_copy(reason));
1212 error_prepend(errp, "disallowing migration blocker (migration in "
1213 "progress) for: ");
1214 return -EBUSY;
1217 void migrate_del_blocker(Error *reason)
1219 migration_blockers = g_slist_remove(migration_blockers, reason);
1222 void qmp_migrate_incoming(const char *uri, Error **errp)
1224 Error *local_err = NULL;
1225 static bool once = true;
1227 if (!deferred_incoming) {
1228 error_setg(errp, "For use with '-incoming defer'");
1229 return;
1231 if (!once) {
1232 error_setg(errp, "The incoming migration has already been started");
1235 qemu_start_incoming_migration(uri, &local_err);
1237 if (local_err) {
1238 error_propagate(errp, local_err);
1239 return;
1242 once = false;
1245 bool migration_is_blocked(Error **errp)
1247 if (qemu_savevm_state_blocked(errp)) {
1248 return true;
1251 if (migration_blockers) {
1252 error_propagate(errp, error_copy(migration_blockers->data));
1253 return true;
1256 return false;
1259 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1260 bool has_inc, bool inc, bool has_detach, bool detach,
1261 Error **errp)
1263 Error *local_err = NULL;
1264 MigrationState *s = migrate_get_current();
1265 const char *p;
1267 if (migration_is_setup_or_active(s->state) ||
1268 s->state == MIGRATION_STATUS_CANCELLING ||
1269 s->state == MIGRATION_STATUS_COLO) {
1270 error_setg(errp, QERR_MIGRATION_ACTIVE);
1271 return;
1273 if (runstate_check(RUN_STATE_INMIGRATE)) {
1274 error_setg(errp, "Guest is waiting for an incoming migration");
1275 return;
1278 if (migration_is_blocked(errp)) {
1279 return;
1282 if ((has_blk && blk) || (has_inc && inc)) {
1283 if (migrate_use_block() || migrate_use_block_incremental()) {
1284 error_setg(errp, "Command options are incompatible with "
1285 "current migration capabilities");
1286 return;
1288 migrate_set_block_enabled(true, &local_err);
1289 if (local_err) {
1290 error_propagate(errp, local_err);
1291 return;
1293 s->must_remove_block_options = true;
1296 if (has_inc && inc) {
1297 migrate_set_block_incremental(s, true);
1300 s = migrate_init();
1302 if (strstart(uri, "tcp:", &p)) {
1303 tcp_start_outgoing_migration(s, p, &local_err);
1304 #ifdef CONFIG_RDMA
1305 } else if (strstart(uri, "rdma:", &p)) {
1306 rdma_start_outgoing_migration(s, p, &local_err);
1307 #endif
1308 } else if (strstart(uri, "exec:", &p)) {
1309 exec_start_outgoing_migration(s, p, &local_err);
1310 } else if (strstart(uri, "unix:", &p)) {
1311 unix_start_outgoing_migration(s, p, &local_err);
1312 } else if (strstart(uri, "fd:", &p)) {
1313 fd_start_outgoing_migration(s, p, &local_err);
1314 } else {
1315 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1316 "a valid migration protocol");
1317 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1318 MIGRATION_STATUS_FAILED);
1319 return;
1322 if (local_err) {
1323 migrate_fd_error(s, local_err);
1324 error_propagate(errp, local_err);
1325 return;
1329 void qmp_migrate_cancel(Error **errp)
1331 migrate_fd_cancel(migrate_get_current());
1334 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1336 MigrationState *s = migrate_get_current();
1337 int64_t new_size;
1339 /* Check for truncation */
1340 if (value != (size_t)value) {
1341 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1342 "exceeding address space");
1343 return;
1346 /* Cache should not be larger than guest ram size */
1347 if (value > ram_bytes_total()) {
1348 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1349 "exceeds guest ram size ");
1350 return;
1353 new_size = xbzrle_cache_resize(value);
1354 if (new_size < 0) {
1355 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1356 "is smaller than page size");
1357 return;
1360 s->xbzrle_cache_size = new_size;
1363 int64_t qmp_query_migrate_cache_size(Error **errp)
1365 return migrate_xbzrle_cache_size();
1368 void qmp_migrate_set_speed(int64_t value, Error **errp)
1370 MigrateSetParameters p = {
1371 .has_max_bandwidth = true,
1372 .max_bandwidth = value,
1375 qmp_migrate_set_parameters(&p, errp);
1378 void qmp_migrate_set_downtime(double value, Error **errp)
1380 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1381 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1382 "the range of 0 to %d seconds",
1383 MAX_MIGRATE_DOWNTIME_SECONDS);
1384 return;
1387 value *= 1000; /* Convert to milliseconds */
1388 value = MAX(0, MIN(INT64_MAX, value));
1390 MigrateSetParameters p = {
1391 .has_downtime_limit = true,
1392 .downtime_limit = value,
1395 qmp_migrate_set_parameters(&p, errp);
1398 bool migrate_release_ram(void)
1400 MigrationState *s;
1402 s = migrate_get_current();
1404 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1407 bool migrate_postcopy_ram(void)
1409 MigrationState *s;
1411 s = migrate_get_current();
1413 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1416 bool migrate_auto_converge(void)
1418 MigrationState *s;
1420 s = migrate_get_current();
1422 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1425 bool migrate_zero_blocks(void)
1427 MigrationState *s;
1429 s = migrate_get_current();
1431 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1434 bool migrate_use_compression(void)
1436 MigrationState *s;
1438 s = migrate_get_current();
1440 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1443 int migrate_compress_level(void)
1445 MigrationState *s;
1447 s = migrate_get_current();
1449 return s->parameters.compress_level;
1452 int migrate_compress_threads(void)
1454 MigrationState *s;
1456 s = migrate_get_current();
1458 return s->parameters.compress_threads;
1461 int migrate_decompress_threads(void)
1463 MigrationState *s;
1465 s = migrate_get_current();
1467 return s->parameters.decompress_threads;
1470 bool migrate_use_events(void)
1472 MigrationState *s;
1474 s = migrate_get_current();
1476 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1479 bool migrate_use_multifd(void)
1481 MigrationState *s;
1483 s = migrate_get_current();
1485 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1488 int migrate_multifd_channels(void)
1490 MigrationState *s;
1492 s = migrate_get_current();
1494 return s->parameters.x_multifd_channels;
1497 int migrate_multifd_page_count(void)
1499 MigrationState *s;
1501 s = migrate_get_current();
1503 return s->parameters.x_multifd_page_count;
1506 int migrate_use_xbzrle(void)
1508 MigrationState *s;
1510 s = migrate_get_current();
1512 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1515 int64_t migrate_xbzrle_cache_size(void)
1517 MigrationState *s;
1519 s = migrate_get_current();
1521 return s->xbzrle_cache_size;
1524 bool migrate_use_block(void)
1526 MigrationState *s;
1528 s = migrate_get_current();
1530 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1533 bool migrate_use_return_path(void)
1535 MigrationState *s;
1537 s = migrate_get_current();
1539 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
1542 bool migrate_use_block_incremental(void)
1544 MigrationState *s;
1546 s = migrate_get_current();
1548 return s->parameters.block_incremental;
1551 /* migration thread support */
1553 * Something bad happened to the RP stream, mark an error
1554 * The caller shall print or trace something to indicate why
1556 static void mark_source_rp_bad(MigrationState *s)
1558 s->rp_state.error = true;
1561 static struct rp_cmd_args {
1562 ssize_t len; /* -1 = variable */
1563 const char *name;
1564 } rp_cmd_args[] = {
1565 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1566 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1567 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1568 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1569 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1570 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1574 * Process a request for pages received on the return path,
1575 * We're allowed to send more than requested (e.g. to round to our page size)
1576 * and we don't need to send pages that have already been sent.
1578 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1579 ram_addr_t start, size_t len)
1581 long our_host_ps = getpagesize();
1583 trace_migrate_handle_rp_req_pages(rbname, start, len);
1586 * Since we currently insist on matching page sizes, just sanity check
1587 * we're being asked for whole host pages.
1589 if (start & (our_host_ps-1) ||
1590 (len & (our_host_ps-1))) {
1591 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1592 " len: %zd", __func__, start, len);
1593 mark_source_rp_bad(ms);
1594 return;
1597 if (ram_save_queue_pages(rbname, start, len)) {
1598 mark_source_rp_bad(ms);
1603 * Handles messages sent on the return path towards the source VM
1606 static void *source_return_path_thread(void *opaque)
1608 MigrationState *ms = opaque;
1609 QEMUFile *rp = ms->rp_state.from_dst_file;
1610 uint16_t header_len, header_type;
1611 uint8_t buf[512];
1612 uint32_t tmp32, sibling_error;
1613 ram_addr_t start = 0; /* =0 to silence warning */
1614 size_t len = 0, expected_len;
1615 int res;
1617 trace_source_return_path_thread_entry();
1618 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1619 migration_is_setup_or_active(ms->state)) {
1620 trace_source_return_path_thread_loop_top();
1621 header_type = qemu_get_be16(rp);
1622 header_len = qemu_get_be16(rp);
1624 if (header_type >= MIG_RP_MSG_MAX ||
1625 header_type == MIG_RP_MSG_INVALID) {
1626 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1627 header_type, header_len);
1628 mark_source_rp_bad(ms);
1629 goto out;
1632 if ((rp_cmd_args[header_type].len != -1 &&
1633 header_len != rp_cmd_args[header_type].len) ||
1634 header_len > sizeof(buf)) {
1635 error_report("RP: Received '%s' message (0x%04x) with"
1636 "incorrect length %d expecting %zu",
1637 rp_cmd_args[header_type].name, header_type, header_len,
1638 (size_t)rp_cmd_args[header_type].len);
1639 mark_source_rp_bad(ms);
1640 goto out;
1643 /* We know we've got a valid header by this point */
1644 res = qemu_get_buffer(rp, buf, header_len);
1645 if (res != header_len) {
1646 error_report("RP: Failed reading data for message 0x%04x"
1647 " read %d expected %d",
1648 header_type, res, header_len);
1649 mark_source_rp_bad(ms);
1650 goto out;
1653 /* OK, we have the message and the data */
1654 switch (header_type) {
1655 case MIG_RP_MSG_SHUT:
1656 sibling_error = ldl_be_p(buf);
1657 trace_source_return_path_thread_shut(sibling_error);
1658 if (sibling_error) {
1659 error_report("RP: Sibling indicated error %d", sibling_error);
1660 mark_source_rp_bad(ms);
1663 * We'll let the main thread deal with closing the RP
1664 * we could do a shutdown(2) on it, but we're the only user
1665 * anyway, so there's nothing gained.
1667 goto out;
1669 case MIG_RP_MSG_PONG:
1670 tmp32 = ldl_be_p(buf);
1671 trace_source_return_path_thread_pong(tmp32);
1672 break;
1674 case MIG_RP_MSG_REQ_PAGES:
1675 start = ldq_be_p(buf);
1676 len = ldl_be_p(buf + 8);
1677 migrate_handle_rp_req_pages(ms, NULL, start, len);
1678 break;
1680 case MIG_RP_MSG_REQ_PAGES_ID:
1681 expected_len = 12 + 1; /* header + termination */
1683 if (header_len >= expected_len) {
1684 start = ldq_be_p(buf);
1685 len = ldl_be_p(buf + 8);
1686 /* Now we expect an idstr */
1687 tmp32 = buf[12]; /* Length of the following idstr */
1688 buf[13 + tmp32] = '\0';
1689 expected_len += tmp32;
1691 if (header_len != expected_len) {
1692 error_report("RP: Req_Page_id with length %d expecting %zd",
1693 header_len, expected_len);
1694 mark_source_rp_bad(ms);
1695 goto out;
1697 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1698 break;
1700 default:
1701 break;
1704 if (qemu_file_get_error(rp)) {
1705 trace_source_return_path_thread_bad_end();
1706 mark_source_rp_bad(ms);
1709 trace_source_return_path_thread_end();
1710 out:
1711 ms->rp_state.from_dst_file = NULL;
1712 qemu_fclose(rp);
1713 return NULL;
1716 static int open_return_path_on_source(MigrationState *ms)
1719 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
1720 if (!ms->rp_state.from_dst_file) {
1721 return -1;
1724 trace_open_return_path_on_source();
1725 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1726 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1728 trace_open_return_path_on_source_continue();
1730 return 0;
1733 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1734 static int await_return_path_close_on_source(MigrationState *ms)
1737 * If this is a normal exit then the destination will send a SHUT and the
1738 * rp_thread will exit, however if there's an error we need to cause
1739 * it to exit.
1741 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
1743 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1744 * waiting for the destination.
1746 qemu_file_shutdown(ms->rp_state.from_dst_file);
1747 mark_source_rp_bad(ms);
1749 trace_await_return_path_close_on_source_joining();
1750 qemu_thread_join(&ms->rp_state.rp_thread);
1751 trace_await_return_path_close_on_source_close();
1752 return ms->rp_state.error;
1756 * Switch from normal iteration to postcopy
1757 * Returns non-0 on error
1759 static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1761 int ret;
1762 QIOChannelBuffer *bioc;
1763 QEMUFile *fb;
1764 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1765 bool restart_block = false;
1766 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1767 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1769 trace_postcopy_start();
1770 qemu_mutex_lock_iothread();
1771 trace_postcopy_start_set_run();
1773 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1774 *old_vm_running = runstate_is_running();
1775 global_state_store();
1776 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1777 if (ret < 0) {
1778 goto fail;
1781 ret = bdrv_inactivate_all();
1782 if (ret < 0) {
1783 goto fail;
1785 restart_block = true;
1788 * Cause any non-postcopiable, but iterative devices to
1789 * send out their final data.
1791 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1794 * in Finish migrate and with the io-lock held everything should
1795 * be quiet, but we've potentially still got dirty pages and we
1796 * need to tell the destination to throw any pages it's already received
1797 * that are dirty
1799 if (ram_postcopy_send_discard_bitmap(ms)) {
1800 error_report("postcopy send discard bitmap failed");
1801 goto fail;
1805 * send rest of state - note things that are doing postcopy
1806 * will notice we're in POSTCOPY_ACTIVE and not actually
1807 * wrap their state up here
1809 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
1810 /* Ping just for debugging, helps line traces up */
1811 qemu_savevm_send_ping(ms->to_dst_file, 2);
1814 * While loading the device state we may trigger page transfer
1815 * requests and the fd must be free to process those, and thus
1816 * the destination must read the whole device state off the fd before
1817 * it starts processing it. Unfortunately the ad-hoc migration format
1818 * doesn't allow the destination to know the size to read without fully
1819 * parsing it through each devices load-state code (especially the open
1820 * coded devices that use get/put).
1821 * So we wrap the device state up in a package with a length at the start;
1822 * to do this we use a qemu_buf to hold the whole of the device state.
1824 bioc = qio_channel_buffer_new(4096);
1825 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
1826 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
1827 object_unref(OBJECT(bioc));
1830 * Make sure the receiver can get incoming pages before we send the rest
1831 * of the state
1833 qemu_savevm_send_postcopy_listen(fb);
1835 qemu_savevm_state_complete_precopy(fb, false, false);
1836 qemu_savevm_send_ping(fb, 3);
1838 qemu_savevm_send_postcopy_run(fb);
1840 /* <><> end of stuff going into the package */
1842 /* Last point of recovery; as soon as we send the package the destination
1843 * can open devices and potentially start running.
1844 * Lets just check again we've not got any errors.
1846 ret = qemu_file_get_error(ms->to_dst_file);
1847 if (ret) {
1848 error_report("postcopy_start: Migration stream errored (pre package)");
1849 goto fail_closefb;
1852 restart_block = false;
1854 /* Now send that blob */
1855 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1856 goto fail_closefb;
1858 qemu_fclose(fb);
1860 /* Send a notify to give a chance for anything that needs to happen
1861 * at the transition to postcopy and after the device state; in particular
1862 * spice needs to trigger a transition now
1864 ms->postcopy_after_devices = true;
1865 notifier_list_notify(&migration_state_notifiers, ms);
1867 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1869 qemu_mutex_unlock_iothread();
1872 * Although this ping is just for debug, it could potentially be
1873 * used for getting a better measurement of downtime at the source.
1875 qemu_savevm_send_ping(ms->to_dst_file, 4);
1877 if (migrate_release_ram()) {
1878 ram_postcopy_migrated_memory_release(ms);
1881 ret = qemu_file_get_error(ms->to_dst_file);
1882 if (ret) {
1883 error_report("postcopy_start: Migration stream errored");
1884 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1885 MIGRATION_STATUS_FAILED);
1888 return ret;
1890 fail_closefb:
1891 qemu_fclose(fb);
1892 fail:
1893 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1894 MIGRATION_STATUS_FAILED);
1895 if (restart_block) {
1896 /* A failure happened early enough that we know the destination hasn't
1897 * accessed block devices, so we're safe to recover.
1899 Error *local_err = NULL;
1901 bdrv_invalidate_cache_all(&local_err);
1902 if (local_err) {
1903 error_report_err(local_err);
1906 qemu_mutex_unlock_iothread();
1907 return -1;
1911 * migration_completion: Used by migration_thread when there's not much left.
1912 * The caller 'breaks' the loop when this returns.
1914 * @s: Current migration state
1915 * @current_active_state: The migration state we expect to be in
1916 * @*old_vm_running: Pointer to old_vm_running flag
1917 * @*start_time: Pointer to time to update
1919 static void migration_completion(MigrationState *s, int current_active_state,
1920 bool *old_vm_running,
1921 int64_t *start_time)
1923 int ret;
1925 if (s->state == MIGRATION_STATUS_ACTIVE) {
1926 qemu_mutex_lock_iothread();
1927 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1928 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1929 *old_vm_running = runstate_is_running();
1930 ret = global_state_store();
1932 if (!ret) {
1933 bool inactivate = !migrate_colo_enabled();
1934 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1935 if (ret >= 0) {
1936 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
1937 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
1938 inactivate);
1940 if (inactivate && ret >= 0) {
1941 s->block_inactive = true;
1944 qemu_mutex_unlock_iothread();
1946 if (ret < 0) {
1947 goto fail;
1949 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1950 trace_migration_completion_postcopy_end();
1952 qemu_savevm_state_complete_postcopy(s->to_dst_file);
1953 trace_migration_completion_postcopy_end_after_complete();
1957 * If rp was opened we must clean up the thread before
1958 * cleaning everything else up (since if there are no failures
1959 * it will wait for the destination to send it's status in
1960 * a SHUT command).
1962 if (s->rp_state.from_dst_file) {
1963 int rp_error;
1964 trace_migration_return_path_end_before();
1965 rp_error = await_return_path_close_on_source(s);
1966 trace_migration_return_path_end_after(rp_error);
1967 if (rp_error) {
1968 goto fail_invalidate;
1972 if (qemu_file_get_error(s->to_dst_file)) {
1973 trace_migration_completion_file_err();
1974 goto fail_invalidate;
1977 if (!migrate_colo_enabled()) {
1978 migrate_set_state(&s->state, current_active_state,
1979 MIGRATION_STATUS_COMPLETED);
1982 return;
1984 fail_invalidate:
1985 /* If not doing postcopy, vm_start() will be called: let's regain
1986 * control on images.
1988 if (s->state == MIGRATION_STATUS_ACTIVE) {
1989 Error *local_err = NULL;
1991 qemu_mutex_lock_iothread();
1992 bdrv_invalidate_cache_all(&local_err);
1993 if (local_err) {
1994 error_report_err(local_err);
1995 } else {
1996 s->block_inactive = false;
1998 qemu_mutex_unlock_iothread();
2001 fail:
2002 migrate_set_state(&s->state, current_active_state,
2003 MIGRATION_STATUS_FAILED);
2006 bool migrate_colo_enabled(void)
2008 MigrationState *s = migrate_get_current();
2009 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2013 * Master migration thread on the source VM.
2014 * It drives the migration and pumps the data down the outgoing channel.
2016 static void *migration_thread(void *opaque)
2018 MigrationState *s = opaque;
2019 /* Used by the bandwidth calcs, updated later */
2020 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2021 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2022 int64_t initial_bytes = 0;
2024 * The final stage happens when the remaining data is smaller than
2025 * this threshold; it's calculated from the requested downtime and
2026 * measured bandwidth
2028 int64_t threshold_size = 0;
2029 int64_t start_time = initial_time;
2030 int64_t end_time;
2031 bool old_vm_running = false;
2032 bool entered_postcopy = false;
2033 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
2034 enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
2035 bool enable_colo = migrate_colo_enabled();
2037 rcu_register_thread();
2039 qemu_savevm_state_header(s->to_dst_file);
2042 * If we opened the return path, we need to make sure dst has it
2043 * opened as well.
2045 if (s->rp_state.from_dst_file) {
2046 /* Now tell the dest that it should open its end so it can reply */
2047 qemu_savevm_send_open_return_path(s->to_dst_file);
2049 /* And do a ping that will make stuff easier to debug */
2050 qemu_savevm_send_ping(s->to_dst_file, 1);
2053 if (migrate_postcopy_ram()) {
2055 * Tell the destination that we *might* want to do postcopy later;
2056 * if the other end can't do postcopy it should fail now, nice and
2057 * early.
2059 qemu_savevm_send_postcopy_advise(s->to_dst_file);
2062 qemu_savevm_state_setup(s->to_dst_file);
2064 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
2065 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2066 MIGRATION_STATUS_ACTIVE);
2068 trace_migration_thread_setup_complete();
2070 while (s->state == MIGRATION_STATUS_ACTIVE ||
2071 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2072 int64_t current_time;
2073 uint64_t pending_size;
2075 if (!qemu_file_rate_limit(s->to_dst_file)) {
2076 uint64_t pend_post, pend_nonpost;
2078 qemu_savevm_state_pending(s->to_dst_file, threshold_size,
2079 &pend_nonpost, &pend_post);
2080 pending_size = pend_nonpost + pend_post;
2081 trace_migrate_pending(pending_size, threshold_size,
2082 pend_post, pend_nonpost);
2083 if (pending_size && pending_size >= threshold_size) {
2084 /* Still a significant amount to transfer */
2086 if (migrate_postcopy_ram() &&
2087 s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
2088 pend_nonpost <= threshold_size &&
2089 atomic_read(&s->start_postcopy)) {
2091 if (!postcopy_start(s, &old_vm_running)) {
2092 current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
2093 entered_postcopy = true;
2096 continue;
2098 /* Just another iteration step */
2099 qemu_savevm_state_iterate(s->to_dst_file, entered_postcopy);
2100 } else {
2101 trace_migration_thread_low_pending(pending_size);
2102 migration_completion(s, current_active_state,
2103 &old_vm_running, &start_time);
2104 break;
2108 if (qemu_file_get_error(s->to_dst_file)) {
2109 migrate_set_state(&s->state, current_active_state,
2110 MIGRATION_STATUS_FAILED);
2111 trace_migration_thread_file_err();
2112 break;
2114 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2115 if (current_time >= initial_time + BUFFER_DELAY) {
2116 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file) -
2117 initial_bytes;
2118 uint64_t time_spent = current_time - initial_time;
2119 double bandwidth = (double)transferred_bytes / time_spent;
2120 threshold_size = bandwidth * s->parameters.downtime_limit;
2122 s->mbps = (((double) transferred_bytes * 8.0) /
2123 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2125 trace_migrate_transferred(transferred_bytes, time_spent,
2126 bandwidth, threshold_size);
2127 /* if we haven't sent anything, we don't want to recalculate
2128 10000 is a small enough number for our purposes */
2129 if (ram_counters.dirty_pages_rate && transferred_bytes > 10000) {
2130 s->expected_downtime = ram_counters.dirty_pages_rate *
2131 qemu_target_page_size() / bandwidth;
2134 qemu_file_reset_rate_limit(s->to_dst_file);
2135 initial_time = current_time;
2136 initial_bytes = qemu_ftell(s->to_dst_file);
2138 if (qemu_file_rate_limit(s->to_dst_file)) {
2139 /* usleep expects microseconds */
2140 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
2144 trace_migration_thread_after_loop();
2145 /* If we enabled cpu throttling for auto-converge, turn it off. */
2146 cpu_throttle_stop();
2147 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2149 qemu_mutex_lock_iothread();
2151 * The resource has been allocated by migration will be reused in COLO
2152 * process, so don't release them.
2154 if (!enable_colo) {
2155 qemu_savevm_state_cleanup();
2157 if (s->state == MIGRATION_STATUS_COMPLETED) {
2158 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file);
2159 s->total_time = end_time - s->total_time;
2160 if (!entered_postcopy) {
2161 s->downtime = end_time - start_time;
2163 if (s->total_time) {
2164 s->mbps = (((double) transferred_bytes * 8.0) /
2165 ((double) s->total_time)) / 1000;
2167 runstate_set(RUN_STATE_POSTMIGRATE);
2168 } else {
2169 if (s->state == MIGRATION_STATUS_ACTIVE && enable_colo) {
2170 migrate_start_colo_process(s);
2171 qemu_savevm_state_cleanup();
2173 * Fixme: we will run VM in COLO no matter its old running state.
2174 * After exited COLO, we will keep running.
2176 old_vm_running = true;
2178 if (old_vm_running && !entered_postcopy) {
2179 vm_start();
2180 } else {
2181 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2182 runstate_set(RUN_STATE_POSTMIGRATE);
2186 qemu_bh_schedule(s->cleanup_bh);
2187 qemu_mutex_unlock_iothread();
2189 rcu_unregister_thread();
2190 return NULL;
2193 void migrate_fd_connect(MigrationState *s)
2195 s->expected_downtime = s->parameters.downtime_limit;
2196 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
2198 qemu_file_set_blocking(s->to_dst_file, true);
2199 qemu_file_set_rate_limit(s->to_dst_file,
2200 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
2202 /* Notify before starting migration thread */
2203 notifier_list_notify(&migration_state_notifiers, s);
2206 * Open the return path. For postcopy, it is used exclusively. For
2207 * precopy, only if user specified "return-path" capability would
2208 * QEMU uses the return path.
2210 if (migrate_postcopy_ram() || migrate_use_return_path()) {
2211 if (open_return_path_on_source(s)) {
2212 error_report("Unable to open return-path for postcopy");
2213 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2214 MIGRATION_STATUS_FAILED);
2215 migrate_fd_cleanup(s);
2216 return;
2220 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
2221 QEMU_THREAD_JOINABLE);
2222 s->migration_thread_running = true;
2225 void migration_global_dump(Monitor *mon)
2227 MigrationState *ms = migrate_get_current();
2229 monitor_printf(mon, "globals: store-global-state=%d, only_migratable=%d, "
2230 "send-configuration=%d, send-section-footer=%d\n",
2231 ms->store_global_state, ms->only_migratable,
2232 ms->send_configuration, ms->send_section_footer);
2235 #define DEFINE_PROP_MIG_CAP(name, x) \
2236 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2238 static Property migration_properties[] = {
2239 DEFINE_PROP_BOOL("store-global-state", MigrationState,
2240 store_global_state, true),
2241 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
2242 DEFINE_PROP_BOOL("send-configuration", MigrationState,
2243 send_configuration, true),
2244 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
2245 send_section_footer, true),
2247 /* Migration parameters */
2248 DEFINE_PROP_INT64("x-compress-level", MigrationState,
2249 parameters.compress_level,
2250 DEFAULT_MIGRATE_COMPRESS_LEVEL),
2251 DEFINE_PROP_INT64("x-compress-threads", MigrationState,
2252 parameters.compress_threads,
2253 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
2254 DEFINE_PROP_INT64("x-decompress-threads", MigrationState,
2255 parameters.decompress_threads,
2256 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
2257 DEFINE_PROP_INT64("x-cpu-throttle-initial", MigrationState,
2258 parameters.cpu_throttle_initial,
2259 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
2260 DEFINE_PROP_INT64("x-cpu-throttle-increment", MigrationState,
2261 parameters.cpu_throttle_increment,
2262 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
2263 DEFINE_PROP_INT64("x-max-bandwidth", MigrationState,
2264 parameters.max_bandwidth, MAX_THROTTLE),
2265 DEFINE_PROP_INT64("x-downtime-limit", MigrationState,
2266 parameters.downtime_limit,
2267 DEFAULT_MIGRATE_SET_DOWNTIME),
2268 DEFINE_PROP_INT64("x-checkpoint-delay", MigrationState,
2269 parameters.x_checkpoint_delay,
2270 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
2271 DEFINE_PROP_INT64("x-multifd-channels", MigrationState,
2272 parameters.x_multifd_channels,
2273 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
2274 DEFINE_PROP_INT64("x-multifd-page-count", MigrationState,
2275 parameters.x_multifd_page_count,
2276 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
2278 /* Migration capabilities */
2279 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
2280 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
2281 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
2282 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
2283 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
2284 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
2285 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
2286 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
2287 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
2288 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
2289 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
2290 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
2292 DEFINE_PROP_END_OF_LIST(),
2295 static void migration_class_init(ObjectClass *klass, void *data)
2297 DeviceClass *dc = DEVICE_CLASS(klass);
2299 dc->user_creatable = false;
2300 dc->props = migration_properties;
2303 static void migration_instance_finalize(Object *obj)
2305 MigrationState *ms = MIGRATION_OBJ(obj);
2306 MigrationParameters *params = &ms->parameters;
2308 g_free(params->tls_hostname);
2309 g_free(params->tls_creds);
2312 static void migration_instance_init(Object *obj)
2314 MigrationState *ms = MIGRATION_OBJ(obj);
2315 MigrationParameters *params = &ms->parameters;
2317 ms->state = MIGRATION_STATUS_NONE;
2318 ms->xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE;
2319 ms->mbps = -1;
2321 params->tls_hostname = g_strdup("");
2322 params->tls_creds = g_strdup("");
2324 /* Set has_* up only for parameter checks */
2325 params->has_compress_level = true;
2326 params->has_compress_threads = true;
2327 params->has_decompress_threads = true;
2328 params->has_cpu_throttle_initial = true;
2329 params->has_cpu_throttle_increment = true;
2330 params->has_max_bandwidth = true;
2331 params->has_downtime_limit = true;
2332 params->has_x_checkpoint_delay = true;
2333 params->has_block_incremental = true;
2334 params->has_x_multifd_channels = true;
2335 params->has_x_multifd_page_count = true;
2339 * Return true if check pass, false otherwise. Error will be put
2340 * inside errp if provided.
2342 static bool migration_object_check(MigrationState *ms, Error **errp)
2344 MigrationCapabilityStatusList *head = NULL;
2345 /* Assuming all off */
2346 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
2347 int i;
2349 if (!migrate_params_check(&ms->parameters, errp)) {
2350 return false;
2353 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
2354 if (ms->enabled_capabilities[i]) {
2355 head = migrate_cap_add(head, i, true);
2359 ret = migrate_caps_check(cap_list, head, errp);
2361 /* It works with head == NULL */
2362 qapi_free_MigrationCapabilityStatusList(head);
2364 return ret;
2367 static const TypeInfo migration_type = {
2368 .name = TYPE_MIGRATION,
2370 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2371 * not created using qdev_create(), it is not attached to the qdev
2372 * device tree, and it is never realized.
2374 * TODO: Make this TYPE_OBJECT once QOM provides something like
2375 * TYPE_DEVICE's "-global" properties.
2377 .parent = TYPE_DEVICE,
2378 .class_init = migration_class_init,
2379 .class_size = sizeof(MigrationClass),
2380 .instance_size = sizeof(MigrationState),
2381 .instance_init = migration_instance_init,
2382 .instance_finalize = migration_instance_finalize,
2385 static void register_migration_types(void)
2387 type_register_static(&migration_type);
2390 type_init(register_migration_types);