usb-serial: chunk data to wMaxPacketSize
[qemu/ar7.git] / migration / migration.c
blobc1d88ace7f841874a3d9452c0a31cdbea41abf24
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 "qemu/main-loop.h"
20 #include "migration/blocker.h"
21 #include "exec.h"
22 #include "fd.h"
23 #include "socket.h"
24 #include "sysemu/runstate.h"
25 #include "sysemu/sysemu.h"
26 #include "rdma.h"
27 #include "ram.h"
28 #include "migration/global_state.h"
29 #include "migration/misc.h"
30 #include "migration.h"
31 #include "savevm.h"
32 #include "qemu-file-channel.h"
33 #include "qemu-file.h"
34 #include "migration/vmstate.h"
35 #include "block/block.h"
36 #include "qapi/error.h"
37 #include "qapi/clone-visitor.h"
38 #include "qapi/qapi-visit-sockets.h"
39 #include "qapi/qapi-commands-migration.h"
40 #include "qapi/qapi-events-migration.h"
41 #include "qapi/qmp/qerror.h"
42 #include "qapi/qmp/qnull.h"
43 #include "qemu/rcu.h"
44 #include "block.h"
45 #include "postcopy-ram.h"
46 #include "qemu/thread.h"
47 #include "trace.h"
48 #include "exec/target_page.h"
49 #include "io/channel-buffer.h"
50 #include "migration/colo.h"
51 #include "hw/boards.h"
52 #include "hw/qdev-properties.h"
53 #include "monitor/monitor.h"
54 #include "net/announce.h"
55 #include "qemu/queue.h"
56 #include "multifd.h"
58 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
60 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
61 * data. */
62 #define BUFFER_DELAY 100
63 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
65 /* Time in milliseconds we are allowed to stop the source,
66 * for sending the last part */
67 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
69 /* Maximum migrate downtime set to 2000 seconds */
70 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
71 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
73 /* Default compression thread count */
74 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
75 /* Default decompression thread count, usually decompression is at
76 * least 4 times as fast as compression.*/
77 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
78 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
79 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
80 /* Define default autoconverge cpu throttle migration parameters */
81 #define DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD 50
82 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
83 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
84 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
86 /* Migration XBZRLE default cache size */
87 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
89 /* The delay time (in ms) between two COLO checkpoints */
90 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
91 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
92 #define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE
93 /* 0: means nocompress, 1: best speed, ... 9: best compress ratio */
94 #define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1
95 /* 0: means nocompress, 1: best speed, ... 20: best compress ratio */
96 #define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1
98 /* Background transfer rate for postcopy, 0 means unlimited, note
99 * that page requests can still exceed this limit.
101 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
104 * Parameters for self_announce_delay giving a stream of RARP/ARP
105 * packets after migration.
107 #define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50
108 #define DEFAULT_MIGRATE_ANNOUNCE_MAX 550
109 #define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5
110 #define DEFAULT_MIGRATE_ANNOUNCE_STEP 100
112 static NotifierList migration_state_notifiers =
113 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
115 static bool deferred_incoming;
117 /* Messages sent on the return path from destination to source */
118 enum mig_rp_message_type {
119 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
120 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
121 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
123 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
124 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
125 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
126 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
128 MIG_RP_MSG_MAX
131 /* When we add fault tolerance, we could have several
132 migrations at once. For now we don't need to add
133 dynamic creation of migration */
135 static MigrationState *current_migration;
136 static MigrationIncomingState *current_incoming;
138 static bool migration_object_check(MigrationState *ms, Error **errp);
139 static int migration_maybe_pause(MigrationState *s,
140 int *current_active_state,
141 int new_state);
142 static void migrate_fd_cancel(MigrationState *s);
144 void migration_object_init(void)
146 MachineState *ms = MACHINE(qdev_get_machine());
147 Error *err = NULL;
149 /* This can only be called once. */
150 assert(!current_migration);
151 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
154 * Init the migrate incoming object as well no matter whether
155 * we'll use it or not.
157 assert(!current_incoming);
158 current_incoming = g_new0(MigrationIncomingState, 1);
159 current_incoming->state = MIGRATION_STATUS_NONE;
160 current_incoming->postcopy_remote_fds =
161 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
162 qemu_mutex_init(&current_incoming->rp_mutex);
163 qemu_event_init(&current_incoming->main_thread_load_event, false);
164 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
165 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
167 init_dirty_bitmap_incoming_migration();
169 if (!migration_object_check(current_migration, &err)) {
170 error_report_err(err);
171 exit(1);
175 * We cannot really do this in migration_instance_init() since at
176 * that time global properties are not yet applied, then this
177 * value will be definitely replaced by something else.
179 if (ms->enforce_config_section) {
180 current_migration->send_configuration = true;
184 void migration_shutdown(void)
187 * Cancel the current migration - that will (eventually)
188 * stop the migration using this structure
190 migrate_fd_cancel(current_migration);
191 object_unref(OBJECT(current_migration));
194 /* For outgoing */
195 MigrationState *migrate_get_current(void)
197 /* This can only be called after the object created. */
198 assert(current_migration);
199 return current_migration;
202 MigrationIncomingState *migration_incoming_get_current(void)
204 assert(current_incoming);
205 return current_incoming;
208 void migration_incoming_state_destroy(void)
210 struct MigrationIncomingState *mis = migration_incoming_get_current();
212 if (mis->to_src_file) {
213 /* Tell source that we are done */
214 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
215 qemu_fclose(mis->to_src_file);
216 mis->to_src_file = NULL;
219 if (mis->from_src_file) {
220 qemu_fclose(mis->from_src_file);
221 mis->from_src_file = NULL;
223 if (mis->postcopy_remote_fds) {
224 g_array_free(mis->postcopy_remote_fds, TRUE);
225 mis->postcopy_remote_fds = NULL;
228 qemu_event_reset(&mis->main_thread_load_event);
230 if (mis->socket_address_list) {
231 qapi_free_SocketAddressList(mis->socket_address_list);
232 mis->socket_address_list = NULL;
236 static void migrate_generate_event(int new_state)
238 if (migrate_use_events()) {
239 qapi_event_send_migration(new_state);
243 static bool migrate_late_block_activate(void)
245 MigrationState *s;
247 s = migrate_get_current();
249 return s->enabled_capabilities[
250 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
254 * Called on -incoming with a defer: uri.
255 * The migration can be started later after any parameters have been
256 * changed.
258 static void deferred_incoming_migration(Error **errp)
260 if (deferred_incoming) {
261 error_setg(errp, "Incoming migration already deferred");
263 deferred_incoming = true;
267 * Send a message on the return channel back to the source
268 * of the migration.
270 static int migrate_send_rp_message(MigrationIncomingState *mis,
271 enum mig_rp_message_type message_type,
272 uint16_t len, void *data)
274 int ret = 0;
276 trace_migrate_send_rp_message((int)message_type, len);
277 qemu_mutex_lock(&mis->rp_mutex);
280 * It's possible that the file handle got lost due to network
281 * failures.
283 if (!mis->to_src_file) {
284 ret = -EIO;
285 goto error;
288 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
289 qemu_put_be16(mis->to_src_file, len);
290 qemu_put_buffer(mis->to_src_file, data, len);
291 qemu_fflush(mis->to_src_file);
293 /* It's possible that qemu file got error during sending */
294 ret = qemu_file_get_error(mis->to_src_file);
296 error:
297 qemu_mutex_unlock(&mis->rp_mutex);
298 return ret;
301 /* Request a range of pages from the source VM at the given
302 * start address.
303 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
304 * as the last request (a name must have been given previously)
305 * Start: Address offset within the RB
306 * Len: Length in bytes required - must be a multiple of pagesize
308 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
309 ram_addr_t start, size_t len)
311 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
312 size_t msglen = 12; /* start + len */
313 enum mig_rp_message_type msg_type;
315 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
316 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
318 if (rbname) {
319 int rbname_len = strlen(rbname);
320 assert(rbname_len < 256);
322 bufc[msglen++] = rbname_len;
323 memcpy(bufc + msglen, rbname, rbname_len);
324 msglen += rbname_len;
325 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
326 } else {
327 msg_type = MIG_RP_MSG_REQ_PAGES;
330 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
333 static bool migration_colo_enabled;
334 bool migration_incoming_colo_enabled(void)
336 return migration_colo_enabled;
339 void migration_incoming_disable_colo(void)
341 migration_colo_enabled = false;
344 void migration_incoming_enable_colo(void)
346 migration_colo_enabled = true;
349 void migrate_add_address(SocketAddress *address)
351 MigrationIncomingState *mis = migration_incoming_get_current();
352 SocketAddressList *addrs;
354 addrs = g_new0(SocketAddressList, 1);
355 addrs->next = mis->socket_address_list;
356 mis->socket_address_list = addrs;
357 addrs->value = QAPI_CLONE(SocketAddress, address);
360 void qemu_start_incoming_migration(const char *uri, Error **errp)
362 const char *p;
364 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
365 if (!strcmp(uri, "defer")) {
366 deferred_incoming_migration(errp);
367 } else if (strstart(uri, "tcp:", &p)) {
368 tcp_start_incoming_migration(p, errp);
369 #ifdef CONFIG_RDMA
370 } else if (strstart(uri, "rdma:", &p)) {
371 rdma_start_incoming_migration(p, errp);
372 #endif
373 } else if (strstart(uri, "exec:", &p)) {
374 exec_start_incoming_migration(p, errp);
375 } else if (strstart(uri, "unix:", &p)) {
376 unix_start_incoming_migration(p, errp);
377 } else if (strstart(uri, "fd:", &p)) {
378 fd_start_incoming_migration(p, errp);
379 } else {
380 error_setg(errp, "unknown migration protocol: %s", uri);
384 static void process_incoming_migration_bh(void *opaque)
386 Error *local_err = NULL;
387 MigrationIncomingState *mis = opaque;
389 /* If capability late_block_activate is set:
390 * Only fire up the block code now if we're going to restart the
391 * VM, else 'cont' will do it.
392 * This causes file locking to happen; so we don't want it to happen
393 * unless we really are starting the VM.
395 if (!migrate_late_block_activate() ||
396 (autostart && (!global_state_received() ||
397 global_state_get_runstate() == RUN_STATE_RUNNING))) {
398 /* Make sure all file formats flush their mutable metadata.
399 * If we get an error here, just don't restart the VM yet. */
400 bdrv_invalidate_cache_all(&local_err);
401 if (local_err) {
402 error_report_err(local_err);
403 local_err = NULL;
404 autostart = false;
409 * This must happen after all error conditions are dealt with and
410 * we're sure the VM is going to be running on this host.
412 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
414 if (multifd_load_cleanup(&local_err) != 0) {
415 error_report_err(local_err);
416 autostart = false;
418 /* If global state section was not received or we are in running
419 state, we need to obey autostart. Any other state is set with
420 runstate_set. */
422 dirty_bitmap_mig_before_vm_start();
424 if (!global_state_received() ||
425 global_state_get_runstate() == RUN_STATE_RUNNING) {
426 if (autostart) {
427 vm_start();
428 } else {
429 runstate_set(RUN_STATE_PAUSED);
431 } else if (migration_incoming_colo_enabled()) {
432 migration_incoming_disable_colo();
433 vm_start();
434 } else {
435 runstate_set(global_state_get_runstate());
438 * This must happen after any state changes since as soon as an external
439 * observer sees this event they might start to prod at the VM assuming
440 * it's ready to use.
442 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
443 MIGRATION_STATUS_COMPLETED);
444 qemu_bh_delete(mis->bh);
445 migration_incoming_state_destroy();
448 static void process_incoming_migration_co(void *opaque)
450 MigrationIncomingState *mis = migration_incoming_get_current();
451 PostcopyState ps;
452 int ret;
453 Error *local_err = NULL;
455 assert(mis->from_src_file);
456 mis->migration_incoming_co = qemu_coroutine_self();
457 mis->largest_page_size = qemu_ram_pagesize_largest();
458 postcopy_state_set(POSTCOPY_INCOMING_NONE);
459 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
460 MIGRATION_STATUS_ACTIVE);
461 ret = qemu_loadvm_state(mis->from_src_file);
463 ps = postcopy_state_get();
464 trace_process_incoming_migration_co_end(ret, ps);
465 if (ps != POSTCOPY_INCOMING_NONE) {
466 if (ps == POSTCOPY_INCOMING_ADVISE) {
468 * Where a migration had postcopy enabled (and thus went to advise)
469 * but managed to complete within the precopy period, we can use
470 * the normal exit.
472 postcopy_ram_incoming_cleanup(mis);
473 } else if (ret >= 0) {
475 * Postcopy was started, cleanup should happen at the end of the
476 * postcopy thread.
478 trace_process_incoming_migration_co_postcopy_end_main();
479 return;
481 /* Else if something went wrong then just fall out of the normal exit */
484 /* we get COLO info, and know if we are in COLO mode */
485 if (!ret && migration_incoming_colo_enabled()) {
486 /* Make sure all file formats flush their mutable metadata */
487 bdrv_invalidate_cache_all(&local_err);
488 if (local_err) {
489 error_report_err(local_err);
490 goto fail;
493 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
494 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
495 mis->have_colo_incoming_thread = true;
496 qemu_coroutine_yield();
498 /* Wait checkpoint incoming thread exit before free resource */
499 qemu_thread_join(&mis->colo_incoming_thread);
500 /* We hold the global iothread lock, so it is safe here */
501 colo_release_ram_cache();
504 if (ret < 0) {
505 error_report("load of migration failed: %s", strerror(-ret));
506 goto fail;
508 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
509 qemu_bh_schedule(mis->bh);
510 mis->migration_incoming_co = NULL;
511 return;
512 fail:
513 local_err = NULL;
514 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
515 MIGRATION_STATUS_FAILED);
516 qemu_fclose(mis->from_src_file);
517 if (multifd_load_cleanup(&local_err) != 0) {
518 error_report_err(local_err);
520 exit(EXIT_FAILURE);
524 * @migration_incoming_setup: Setup incoming migration
526 * Returns 0 for no error or 1 for error
528 * @f: file for main migration channel
529 * @errp: where to put errors
531 static int migration_incoming_setup(QEMUFile *f, Error **errp)
533 MigrationIncomingState *mis = migration_incoming_get_current();
534 Error *local_err = NULL;
536 if (multifd_load_setup(&local_err) != 0) {
537 /* We haven't been able to create multifd threads
538 nothing better to do */
539 error_report_err(local_err);
540 exit(EXIT_FAILURE);
543 if (!mis->from_src_file) {
544 mis->from_src_file = f;
546 qemu_file_set_blocking(f, false);
547 return 0;
550 void migration_incoming_process(void)
552 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
553 qemu_coroutine_enter(co);
556 /* Returns true if recovered from a paused migration, otherwise false */
557 static bool postcopy_try_recover(QEMUFile *f)
559 MigrationIncomingState *mis = migration_incoming_get_current();
561 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
562 /* Resumed from a paused postcopy migration */
564 mis->from_src_file = f;
565 /* Postcopy has standalone thread to do vm load */
566 qemu_file_set_blocking(f, true);
568 /* Re-configure the return path */
569 mis->to_src_file = qemu_file_get_return_path(f);
571 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
572 MIGRATION_STATUS_POSTCOPY_RECOVER);
575 * Here, we only wake up the main loading thread (while the
576 * fault thread will still be waiting), so that we can receive
577 * commands from source now, and answer it if needed. The
578 * fault thread will be woken up afterwards until we are sure
579 * that source is ready to reply to page requests.
581 qemu_sem_post(&mis->postcopy_pause_sem_dst);
582 return true;
585 return false;
588 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
590 Error *local_err = NULL;
592 if (postcopy_try_recover(f)) {
593 return;
596 if (migration_incoming_setup(f, &local_err)) {
597 if (local_err) {
598 error_propagate(errp, local_err);
600 return;
602 migration_incoming_process();
605 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
607 MigrationIncomingState *mis = migration_incoming_get_current();
608 Error *local_err = NULL;
609 bool start_migration;
611 if (!mis->from_src_file) {
612 /* The first connection (multifd may have multiple) */
613 QEMUFile *f = qemu_fopen_channel_input(ioc);
615 /* If it's a recovery, we're done */
616 if (postcopy_try_recover(f)) {
617 return;
620 if (migration_incoming_setup(f, &local_err)) {
621 if (local_err) {
622 error_propagate(errp, local_err);
624 return;
628 * Common migration only needs one channel, so we can start
629 * right now. Multifd needs more than one channel, we wait.
631 start_migration = !migrate_use_multifd();
632 } else {
633 /* Multiple connections */
634 assert(migrate_use_multifd());
635 start_migration = multifd_recv_new_channel(ioc, &local_err);
636 if (local_err) {
637 error_propagate(errp, local_err);
638 return;
642 if (start_migration) {
643 migration_incoming_process();
648 * @migration_has_all_channels: We have received all channels that we need
650 * Returns true when we have got connections to all the channels that
651 * we need for migration.
653 bool migration_has_all_channels(void)
655 MigrationIncomingState *mis = migration_incoming_get_current();
656 bool all_channels;
658 all_channels = multifd_recv_all_channels_created();
660 return all_channels && mis->from_src_file != NULL;
664 * Send a 'SHUT' message on the return channel with the given value
665 * to indicate that we've finished with the RP. Non-0 value indicates
666 * error.
668 void migrate_send_rp_shut(MigrationIncomingState *mis,
669 uint32_t value)
671 uint32_t buf;
673 buf = cpu_to_be32(value);
674 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
678 * Send a 'PONG' message on the return channel with the given value
679 * (normally in response to a 'PING')
681 void migrate_send_rp_pong(MigrationIncomingState *mis,
682 uint32_t value)
684 uint32_t buf;
686 buf = cpu_to_be32(value);
687 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
690 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
691 char *block_name)
693 char buf[512];
694 int len;
695 int64_t res;
698 * First, we send the header part. It contains only the len of
699 * idstr, and the idstr itself.
701 len = strlen(block_name);
702 buf[0] = len;
703 memcpy(buf + 1, block_name, len);
705 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
706 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
707 __func__);
708 return;
711 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
714 * Next, we dump the received bitmap to the stream.
716 * TODO: currently we are safe since we are the only one that is
717 * using the to_src_file handle (fault thread is still paused),
718 * and it's ok even not taking the mutex. However the best way is
719 * to take the lock before sending the message header, and release
720 * the lock after sending the bitmap.
722 qemu_mutex_lock(&mis->rp_mutex);
723 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
724 qemu_mutex_unlock(&mis->rp_mutex);
726 trace_migrate_send_rp_recv_bitmap(block_name, res);
729 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
731 uint32_t buf;
733 buf = cpu_to_be32(value);
734 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
737 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
739 MigrationCapabilityStatusList *head = NULL;
740 MigrationCapabilityStatusList *caps;
741 MigrationState *s = migrate_get_current();
742 int i;
744 caps = NULL; /* silence compiler warning */
745 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
746 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
747 if (i == MIGRATION_CAPABILITY_BLOCK) {
748 continue;
750 #endif
751 if (head == NULL) {
752 head = g_malloc0(sizeof(*caps));
753 caps = head;
754 } else {
755 caps->next = g_malloc0(sizeof(*caps));
756 caps = caps->next;
758 caps->value =
759 g_malloc(sizeof(*caps->value));
760 caps->value->capability = i;
761 caps->value->state = s->enabled_capabilities[i];
764 return head;
767 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
769 MigrationParameters *params;
770 MigrationState *s = migrate_get_current();
772 /* TODO use QAPI_CLONE() instead of duplicating it inline */
773 params = g_malloc0(sizeof(*params));
774 params->has_compress_level = true;
775 params->compress_level = s->parameters.compress_level;
776 params->has_compress_threads = true;
777 params->compress_threads = s->parameters.compress_threads;
778 params->has_compress_wait_thread = true;
779 params->compress_wait_thread = s->parameters.compress_wait_thread;
780 params->has_decompress_threads = true;
781 params->decompress_threads = s->parameters.decompress_threads;
782 params->has_throttle_trigger_threshold = true;
783 params->throttle_trigger_threshold = s->parameters.throttle_trigger_threshold;
784 params->has_cpu_throttle_initial = true;
785 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
786 params->has_cpu_throttle_increment = true;
787 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
788 params->has_tls_creds = true;
789 params->tls_creds = g_strdup(s->parameters.tls_creds);
790 params->has_tls_hostname = true;
791 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
792 params->has_tls_authz = true;
793 params->tls_authz = g_strdup(s->parameters.tls_authz);
794 params->has_max_bandwidth = true;
795 params->max_bandwidth = s->parameters.max_bandwidth;
796 params->has_downtime_limit = true;
797 params->downtime_limit = s->parameters.downtime_limit;
798 params->has_x_checkpoint_delay = true;
799 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
800 params->has_block_incremental = true;
801 params->block_incremental = s->parameters.block_incremental;
802 params->has_multifd_channels = true;
803 params->multifd_channels = s->parameters.multifd_channels;
804 params->has_multifd_compression = true;
805 params->multifd_compression = s->parameters.multifd_compression;
806 params->has_multifd_zlib_level = true;
807 params->multifd_zlib_level = s->parameters.multifd_zlib_level;
808 params->has_multifd_zstd_level = true;
809 params->multifd_zstd_level = s->parameters.multifd_zstd_level;
810 params->has_xbzrle_cache_size = true;
811 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
812 params->has_max_postcopy_bandwidth = true;
813 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
814 params->has_max_cpu_throttle = true;
815 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
816 params->has_announce_initial = true;
817 params->announce_initial = s->parameters.announce_initial;
818 params->has_announce_max = true;
819 params->announce_max = s->parameters.announce_max;
820 params->has_announce_rounds = true;
821 params->announce_rounds = s->parameters.announce_rounds;
822 params->has_announce_step = true;
823 params->announce_step = s->parameters.announce_step;
825 return params;
828 AnnounceParameters *migrate_announce_params(void)
830 static AnnounceParameters ap;
832 MigrationState *s = migrate_get_current();
834 ap.initial = s->parameters.announce_initial;
835 ap.max = s->parameters.announce_max;
836 ap.rounds = s->parameters.announce_rounds;
837 ap.step = s->parameters.announce_step;
839 return &ap;
843 * Return true if we're already in the middle of a migration
844 * (i.e. any of the active or setup states)
846 bool migration_is_setup_or_active(int state)
848 switch (state) {
849 case MIGRATION_STATUS_ACTIVE:
850 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
851 case MIGRATION_STATUS_POSTCOPY_PAUSED:
852 case MIGRATION_STATUS_POSTCOPY_RECOVER:
853 case MIGRATION_STATUS_SETUP:
854 case MIGRATION_STATUS_PRE_SWITCHOVER:
855 case MIGRATION_STATUS_DEVICE:
856 case MIGRATION_STATUS_WAIT_UNPLUG:
857 case MIGRATION_STATUS_COLO:
858 return true;
860 default:
861 return false;
866 bool migration_is_running(int state)
868 switch (state) {
869 case MIGRATION_STATUS_ACTIVE:
870 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
871 case MIGRATION_STATUS_POSTCOPY_PAUSED:
872 case MIGRATION_STATUS_POSTCOPY_RECOVER:
873 case MIGRATION_STATUS_SETUP:
874 case MIGRATION_STATUS_PRE_SWITCHOVER:
875 case MIGRATION_STATUS_DEVICE:
876 case MIGRATION_STATUS_WAIT_UNPLUG:
877 case MIGRATION_STATUS_CANCELLING:
878 return true;
880 default:
881 return false;
886 static void populate_time_info(MigrationInfo *info, MigrationState *s)
888 info->has_status = true;
889 info->has_setup_time = true;
890 info->setup_time = s->setup_time;
891 if (s->state == MIGRATION_STATUS_COMPLETED) {
892 info->has_total_time = true;
893 info->total_time = s->total_time;
894 info->has_downtime = true;
895 info->downtime = s->downtime;
896 } else {
897 info->has_total_time = true;
898 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
899 s->start_time;
900 info->has_expected_downtime = true;
901 info->expected_downtime = s->expected_downtime;
905 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
907 info->has_ram = true;
908 info->ram = g_malloc0(sizeof(*info->ram));
909 info->ram->transferred = ram_counters.transferred;
910 info->ram->total = ram_bytes_total();
911 info->ram->duplicate = ram_counters.duplicate;
912 /* legacy value. It is not used anymore */
913 info->ram->skipped = 0;
914 info->ram->normal = ram_counters.normal;
915 info->ram->normal_bytes = ram_counters.normal *
916 qemu_target_page_size();
917 info->ram->mbps = s->mbps;
918 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
919 info->ram->postcopy_requests = ram_counters.postcopy_requests;
920 info->ram->page_size = qemu_target_page_size();
921 info->ram->multifd_bytes = ram_counters.multifd_bytes;
922 info->ram->pages_per_second = s->pages_per_second;
924 if (migrate_use_xbzrle()) {
925 info->has_xbzrle_cache = true;
926 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
927 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
928 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
929 info->xbzrle_cache->pages = xbzrle_counters.pages;
930 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
931 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
932 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
935 if (migrate_use_compression()) {
936 info->has_compression = true;
937 info->compression = g_malloc0(sizeof(*info->compression));
938 info->compression->pages = compression_counters.pages;
939 info->compression->busy = compression_counters.busy;
940 info->compression->busy_rate = compression_counters.busy_rate;
941 info->compression->compressed_size =
942 compression_counters.compressed_size;
943 info->compression->compression_rate =
944 compression_counters.compression_rate;
947 if (cpu_throttle_active()) {
948 info->has_cpu_throttle_percentage = true;
949 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
952 if (s->state != MIGRATION_STATUS_COMPLETED) {
953 info->ram->remaining = ram_bytes_remaining();
954 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
958 static void populate_disk_info(MigrationInfo *info)
960 if (blk_mig_active()) {
961 info->has_disk = true;
962 info->disk = g_malloc0(sizeof(*info->disk));
963 info->disk->transferred = blk_mig_bytes_transferred();
964 info->disk->remaining = blk_mig_bytes_remaining();
965 info->disk->total = blk_mig_bytes_total();
969 static void fill_source_migration_info(MigrationInfo *info)
971 MigrationState *s = migrate_get_current();
973 switch (s->state) {
974 case MIGRATION_STATUS_NONE:
975 /* no migration has happened ever */
976 /* do not overwrite destination migration status */
977 return;
978 break;
979 case MIGRATION_STATUS_SETUP:
980 info->has_status = true;
981 info->has_total_time = false;
982 break;
983 case MIGRATION_STATUS_ACTIVE:
984 case MIGRATION_STATUS_CANCELLING:
985 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
986 case MIGRATION_STATUS_PRE_SWITCHOVER:
987 case MIGRATION_STATUS_DEVICE:
988 case MIGRATION_STATUS_POSTCOPY_PAUSED:
989 case MIGRATION_STATUS_POSTCOPY_RECOVER:
990 /* TODO add some postcopy stats */
991 populate_time_info(info, s);
992 populate_ram_info(info, s);
993 populate_disk_info(info);
994 break;
995 case MIGRATION_STATUS_COLO:
996 info->has_status = true;
997 /* TODO: display COLO specific information (checkpoint info etc.) */
998 break;
999 case MIGRATION_STATUS_COMPLETED:
1000 populate_time_info(info, s);
1001 populate_ram_info(info, s);
1002 break;
1003 case MIGRATION_STATUS_FAILED:
1004 info->has_status = true;
1005 if (s->error) {
1006 info->has_error_desc = true;
1007 info->error_desc = g_strdup(error_get_pretty(s->error));
1009 break;
1010 case MIGRATION_STATUS_CANCELLED:
1011 info->has_status = true;
1012 break;
1013 case MIGRATION_STATUS_WAIT_UNPLUG:
1014 info->has_status = true;
1015 break;
1017 info->status = s->state;
1021 * @migration_caps_check - check capability validity
1023 * @cap_list: old capability list, array of bool
1024 * @params: new capabilities to be applied soon
1025 * @errp: set *errp if the check failed, with reason
1027 * Returns true if check passed, otherwise false.
1029 static bool migrate_caps_check(bool *cap_list,
1030 MigrationCapabilityStatusList *params,
1031 Error **errp)
1033 MigrationCapabilityStatusList *cap;
1034 bool old_postcopy_cap;
1035 MigrationIncomingState *mis = migration_incoming_get_current();
1037 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1039 for (cap = params; cap; cap = cap->next) {
1040 cap_list[cap->value->capability] = cap->value->state;
1043 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
1044 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
1045 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
1046 "block migration");
1047 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
1048 return false;
1050 #endif
1052 #ifndef CONFIG_REPLICATION
1053 if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
1054 error_setg(errp, "QEMU compiled without replication module"
1055 " can't enable COLO");
1056 error_append_hint(errp, "Please enable replication before COLO.\n");
1057 return false;
1059 #endif
1061 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1062 /* This check is reasonably expensive, so only when it's being
1063 * set the first time, also it's only the destination that needs
1064 * special support.
1066 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
1067 !postcopy_ram_supported_by_host(mis)) {
1068 /* postcopy_ram_supported_by_host will have emitted a more
1069 * detailed message
1071 error_setg(errp, "Postcopy is not supported");
1072 return false;
1075 if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1076 error_setg(errp, "Postcopy is not compatible with ignore-shared");
1077 return false;
1081 return true;
1084 static void fill_destination_migration_info(MigrationInfo *info)
1086 MigrationIncomingState *mis = migration_incoming_get_current();
1088 if (mis->socket_address_list) {
1089 info->has_socket_address = true;
1090 info->socket_address =
1091 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1094 switch (mis->state) {
1095 case MIGRATION_STATUS_NONE:
1096 return;
1097 break;
1098 case MIGRATION_STATUS_SETUP:
1099 case MIGRATION_STATUS_CANCELLING:
1100 case MIGRATION_STATUS_CANCELLED:
1101 case MIGRATION_STATUS_ACTIVE:
1102 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1103 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1104 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1105 case MIGRATION_STATUS_FAILED:
1106 case MIGRATION_STATUS_COLO:
1107 info->has_status = true;
1108 break;
1109 case MIGRATION_STATUS_COMPLETED:
1110 info->has_status = true;
1111 fill_destination_postcopy_migration_info(info);
1112 break;
1114 info->status = mis->state;
1117 MigrationInfo *qmp_query_migrate(Error **errp)
1119 MigrationInfo *info = g_malloc0(sizeof(*info));
1121 fill_destination_migration_info(info);
1122 fill_source_migration_info(info);
1124 return info;
1127 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1128 Error **errp)
1130 MigrationState *s = migrate_get_current();
1131 MigrationCapabilityStatusList *cap;
1132 bool cap_list[MIGRATION_CAPABILITY__MAX];
1134 if (migration_is_running(s->state)) {
1135 error_setg(errp, QERR_MIGRATION_ACTIVE);
1136 return;
1139 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1140 if (!migrate_caps_check(cap_list, params, errp)) {
1141 return;
1144 for (cap = params; cap; cap = cap->next) {
1145 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1150 * Check whether the parameters are valid. Error will be put into errp
1151 * (if provided). Return true if valid, otherwise false.
1153 static bool migrate_params_check(MigrationParameters *params, Error **errp)
1155 if (params->has_compress_level &&
1156 (params->compress_level > 9)) {
1157 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1158 "is invalid, it should be in the range of 0 to 9");
1159 return false;
1162 if (params->has_compress_threads && (params->compress_threads < 1)) {
1163 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1164 "compress_threads",
1165 "is invalid, it should be in the range of 1 to 255");
1166 return false;
1169 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1170 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1171 "decompress_threads",
1172 "is invalid, it should be in the range of 1 to 255");
1173 return false;
1176 if (params->has_throttle_trigger_threshold &&
1177 (params->throttle_trigger_threshold < 1 ||
1178 params->throttle_trigger_threshold > 100)) {
1179 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1180 "throttle_trigger_threshold",
1181 "an integer in the range of 1 to 100");
1182 return false;
1185 if (params->has_cpu_throttle_initial &&
1186 (params->cpu_throttle_initial < 1 ||
1187 params->cpu_throttle_initial > 99)) {
1188 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1189 "cpu_throttle_initial",
1190 "an integer in the range of 1 to 99");
1191 return false;
1194 if (params->has_cpu_throttle_increment &&
1195 (params->cpu_throttle_increment < 1 ||
1196 params->cpu_throttle_increment > 99)) {
1197 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1198 "cpu_throttle_increment",
1199 "an integer in the range of 1 to 99");
1200 return false;
1203 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1204 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
1205 " range of 0 to %zu bytes/second", SIZE_MAX);
1206 return false;
1209 if (params->has_downtime_limit &&
1210 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1211 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1212 "the range of 0 to %d milliseconds",
1213 MAX_MIGRATE_DOWNTIME);
1214 return false;
1217 /* x_checkpoint_delay is now always positive */
1219 if (params->has_multifd_channels && (params->multifd_channels < 1)) {
1220 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1221 "multifd_channels",
1222 "is invalid, it should be in the range of 1 to 255");
1223 return false;
1226 if (params->has_multifd_zlib_level &&
1227 (params->multifd_zlib_level > 9)) {
1228 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level",
1229 "is invalid, it should be in the range of 0 to 9");
1230 return false;
1233 if (params->has_multifd_zstd_level &&
1234 (params->multifd_zstd_level > 20)) {
1235 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level",
1236 "is invalid, it should be in the range of 0 to 20");
1237 return false;
1240 if (params->has_xbzrle_cache_size &&
1241 (params->xbzrle_cache_size < qemu_target_page_size() ||
1242 !is_power_of_2(params->xbzrle_cache_size))) {
1243 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1244 "xbzrle_cache_size",
1245 "is invalid, it should be bigger than target page size"
1246 " and a power of two");
1247 return false;
1250 if (params->has_max_cpu_throttle &&
1251 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1252 params->max_cpu_throttle > 99)) {
1253 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1254 "max_cpu_throttle",
1255 "an integer in the range of cpu_throttle_initial to 99");
1256 return false;
1259 if (params->has_announce_initial &&
1260 params->announce_initial > 100000) {
1261 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1262 "announce_initial",
1263 "is invalid, it must be less than 100000 ms");
1264 return false;
1266 if (params->has_announce_max &&
1267 params->announce_max > 100000) {
1268 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1269 "announce_max",
1270 "is invalid, it must be less than 100000 ms");
1271 return false;
1273 if (params->has_announce_rounds &&
1274 params->announce_rounds > 1000) {
1275 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1276 "announce_rounds",
1277 "is invalid, it must be in the range of 0 to 1000");
1278 return false;
1280 if (params->has_announce_step &&
1281 (params->announce_step < 1 ||
1282 params->announce_step > 10000)) {
1283 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1284 "announce_step",
1285 "is invalid, it must be in the range of 1 to 10000 ms");
1286 return false;
1288 return true;
1291 static void migrate_params_test_apply(MigrateSetParameters *params,
1292 MigrationParameters *dest)
1294 *dest = migrate_get_current()->parameters;
1296 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1298 if (params->has_compress_level) {
1299 dest->compress_level = params->compress_level;
1302 if (params->has_compress_threads) {
1303 dest->compress_threads = params->compress_threads;
1306 if (params->has_compress_wait_thread) {
1307 dest->compress_wait_thread = params->compress_wait_thread;
1310 if (params->has_decompress_threads) {
1311 dest->decompress_threads = params->decompress_threads;
1314 if (params->has_throttle_trigger_threshold) {
1315 dest->throttle_trigger_threshold = params->throttle_trigger_threshold;
1318 if (params->has_cpu_throttle_initial) {
1319 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1322 if (params->has_cpu_throttle_increment) {
1323 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1326 if (params->has_tls_creds) {
1327 assert(params->tls_creds->type == QTYPE_QSTRING);
1328 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1331 if (params->has_tls_hostname) {
1332 assert(params->tls_hostname->type == QTYPE_QSTRING);
1333 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1336 if (params->has_max_bandwidth) {
1337 dest->max_bandwidth = params->max_bandwidth;
1340 if (params->has_downtime_limit) {
1341 dest->downtime_limit = params->downtime_limit;
1344 if (params->has_x_checkpoint_delay) {
1345 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1348 if (params->has_block_incremental) {
1349 dest->block_incremental = params->block_incremental;
1351 if (params->has_multifd_channels) {
1352 dest->multifd_channels = params->multifd_channels;
1354 if (params->has_multifd_compression) {
1355 dest->multifd_compression = params->multifd_compression;
1357 if (params->has_xbzrle_cache_size) {
1358 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1360 if (params->has_max_postcopy_bandwidth) {
1361 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1363 if (params->has_max_cpu_throttle) {
1364 dest->max_cpu_throttle = params->max_cpu_throttle;
1366 if (params->has_announce_initial) {
1367 dest->announce_initial = params->announce_initial;
1369 if (params->has_announce_max) {
1370 dest->announce_max = params->announce_max;
1372 if (params->has_announce_rounds) {
1373 dest->announce_rounds = params->announce_rounds;
1375 if (params->has_announce_step) {
1376 dest->announce_step = params->announce_step;
1380 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1382 MigrationState *s = migrate_get_current();
1384 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1386 if (params->has_compress_level) {
1387 s->parameters.compress_level = params->compress_level;
1390 if (params->has_compress_threads) {
1391 s->parameters.compress_threads = params->compress_threads;
1394 if (params->has_compress_wait_thread) {
1395 s->parameters.compress_wait_thread = params->compress_wait_thread;
1398 if (params->has_decompress_threads) {
1399 s->parameters.decompress_threads = params->decompress_threads;
1402 if (params->has_throttle_trigger_threshold) {
1403 s->parameters.throttle_trigger_threshold = params->throttle_trigger_threshold;
1406 if (params->has_cpu_throttle_initial) {
1407 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1410 if (params->has_cpu_throttle_increment) {
1411 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1414 if (params->has_tls_creds) {
1415 g_free(s->parameters.tls_creds);
1416 assert(params->tls_creds->type == QTYPE_QSTRING);
1417 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1420 if (params->has_tls_hostname) {
1421 g_free(s->parameters.tls_hostname);
1422 assert(params->tls_hostname->type == QTYPE_QSTRING);
1423 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1426 if (params->has_tls_authz) {
1427 g_free(s->parameters.tls_authz);
1428 assert(params->tls_authz->type == QTYPE_QSTRING);
1429 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1432 if (params->has_max_bandwidth) {
1433 s->parameters.max_bandwidth = params->max_bandwidth;
1434 if (s->to_dst_file && !migration_in_postcopy()) {
1435 qemu_file_set_rate_limit(s->to_dst_file,
1436 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1440 if (params->has_downtime_limit) {
1441 s->parameters.downtime_limit = params->downtime_limit;
1444 if (params->has_x_checkpoint_delay) {
1445 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1446 if (migration_in_colo_state()) {
1447 colo_checkpoint_notify(s);
1451 if (params->has_block_incremental) {
1452 s->parameters.block_incremental = params->block_incremental;
1454 if (params->has_multifd_channels) {
1455 s->parameters.multifd_channels = params->multifd_channels;
1457 if (params->has_multifd_compression) {
1458 s->parameters.multifd_compression = params->multifd_compression;
1460 if (params->has_xbzrle_cache_size) {
1461 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1462 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1464 if (params->has_max_postcopy_bandwidth) {
1465 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1466 if (s->to_dst_file && migration_in_postcopy()) {
1467 qemu_file_set_rate_limit(s->to_dst_file,
1468 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1471 if (params->has_max_cpu_throttle) {
1472 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1474 if (params->has_announce_initial) {
1475 s->parameters.announce_initial = params->announce_initial;
1477 if (params->has_announce_max) {
1478 s->parameters.announce_max = params->announce_max;
1480 if (params->has_announce_rounds) {
1481 s->parameters.announce_rounds = params->announce_rounds;
1483 if (params->has_announce_step) {
1484 s->parameters.announce_step = params->announce_step;
1488 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1490 MigrationParameters tmp;
1492 /* TODO Rewrite "" to null instead */
1493 if (params->has_tls_creds
1494 && params->tls_creds->type == QTYPE_QNULL) {
1495 qobject_unref(params->tls_creds->u.n);
1496 params->tls_creds->type = QTYPE_QSTRING;
1497 params->tls_creds->u.s = strdup("");
1499 /* TODO Rewrite "" to null instead */
1500 if (params->has_tls_hostname
1501 && params->tls_hostname->type == QTYPE_QNULL) {
1502 qobject_unref(params->tls_hostname->u.n);
1503 params->tls_hostname->type = QTYPE_QSTRING;
1504 params->tls_hostname->u.s = strdup("");
1507 migrate_params_test_apply(params, &tmp);
1509 if (!migrate_params_check(&tmp, errp)) {
1510 /* Invalid parameter */
1511 return;
1514 migrate_params_apply(params, errp);
1518 void qmp_migrate_start_postcopy(Error **errp)
1520 MigrationState *s = migrate_get_current();
1522 if (!migrate_postcopy()) {
1523 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1524 " the start of migration");
1525 return;
1528 if (s->state == MIGRATION_STATUS_NONE) {
1529 error_setg(errp, "Postcopy must be started after migration has been"
1530 " started");
1531 return;
1534 * we don't error if migration has finished since that would be racy
1535 * with issuing this command.
1537 atomic_set(&s->start_postcopy, true);
1540 /* shared migration helpers */
1542 void migrate_set_state(int *state, int old_state, int new_state)
1544 assert(new_state < MIGRATION_STATUS__MAX);
1545 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1546 trace_migrate_set_state(MigrationStatus_str(new_state));
1547 migrate_generate_event(new_state);
1551 static MigrationCapabilityStatusList *migrate_cap_add(
1552 MigrationCapabilityStatusList *list,
1553 MigrationCapability index,
1554 bool state)
1556 MigrationCapabilityStatusList *cap;
1558 cap = g_new0(MigrationCapabilityStatusList, 1);
1559 cap->value = g_new0(MigrationCapabilityStatus, 1);
1560 cap->value->capability = index;
1561 cap->value->state = state;
1562 cap->next = list;
1564 return cap;
1567 void migrate_set_block_enabled(bool value, Error **errp)
1569 MigrationCapabilityStatusList *cap;
1571 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1572 qmp_migrate_set_capabilities(cap, errp);
1573 qapi_free_MigrationCapabilityStatusList(cap);
1576 static void migrate_set_block_incremental(MigrationState *s, bool value)
1578 s->parameters.block_incremental = value;
1581 static void block_cleanup_parameters(MigrationState *s)
1583 if (s->must_remove_block_options) {
1584 /* setting to false can never fail */
1585 migrate_set_block_enabled(false, &error_abort);
1586 migrate_set_block_incremental(s, false);
1587 s->must_remove_block_options = false;
1591 static void migrate_fd_cleanup(MigrationState *s)
1593 qemu_bh_delete(s->cleanup_bh);
1594 s->cleanup_bh = NULL;
1596 qemu_savevm_state_cleanup();
1598 if (s->to_dst_file) {
1599 QEMUFile *tmp;
1601 trace_migrate_fd_cleanup();
1602 qemu_mutex_unlock_iothread();
1603 if (s->migration_thread_running) {
1604 qemu_thread_join(&s->thread);
1605 s->migration_thread_running = false;
1607 qemu_mutex_lock_iothread();
1609 multifd_save_cleanup();
1610 qemu_mutex_lock(&s->qemu_file_lock);
1611 tmp = s->to_dst_file;
1612 s->to_dst_file = NULL;
1613 qemu_mutex_unlock(&s->qemu_file_lock);
1615 * Close the file handle without the lock to make sure the
1616 * critical section won't block for long.
1618 qemu_fclose(tmp);
1621 assert(!migration_is_active(s));
1623 if (s->state == MIGRATION_STATUS_CANCELLING) {
1624 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1625 MIGRATION_STATUS_CANCELLED);
1628 if (s->error) {
1629 /* It is used on info migrate. We can't free it */
1630 error_report_err(error_copy(s->error));
1632 notifier_list_notify(&migration_state_notifiers, s);
1633 block_cleanup_parameters(s);
1636 static void migrate_fd_cleanup_schedule(MigrationState *s)
1639 * Ref the state for bh, because it may be called when
1640 * there're already no other refs
1642 object_ref(OBJECT(s));
1643 qemu_bh_schedule(s->cleanup_bh);
1646 static void migrate_fd_cleanup_bh(void *opaque)
1648 MigrationState *s = opaque;
1649 migrate_fd_cleanup(s);
1650 object_unref(OBJECT(s));
1653 void migrate_set_error(MigrationState *s, const Error *error)
1655 qemu_mutex_lock(&s->error_mutex);
1656 if (!s->error) {
1657 s->error = error_copy(error);
1659 qemu_mutex_unlock(&s->error_mutex);
1662 void migrate_fd_error(MigrationState *s, const Error *error)
1664 trace_migrate_fd_error(error_get_pretty(error));
1665 assert(s->to_dst_file == NULL);
1666 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1667 MIGRATION_STATUS_FAILED);
1668 migrate_set_error(s, error);
1671 static void migrate_fd_cancel(MigrationState *s)
1673 int old_state ;
1674 QEMUFile *f = migrate_get_current()->to_dst_file;
1675 trace_migrate_fd_cancel();
1677 if (s->rp_state.from_dst_file) {
1678 /* shutdown the rp socket, so causing the rp thread to shutdown */
1679 qemu_file_shutdown(s->rp_state.from_dst_file);
1682 do {
1683 old_state = s->state;
1684 if (!migration_is_running(old_state)) {
1685 break;
1687 /* If the migration is paused, kick it out of the pause */
1688 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1689 qemu_sem_post(&s->pause_sem);
1691 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1692 } while (s->state != MIGRATION_STATUS_CANCELLING);
1695 * If we're unlucky the migration code might be stuck somewhere in a
1696 * send/write while the network has failed and is waiting to timeout;
1697 * if we've got shutdown(2) available then we can force it to quit.
1698 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1699 * called in a bh, so there is no race against this cancel.
1701 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1702 qemu_file_shutdown(f);
1704 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1705 Error *local_err = NULL;
1707 bdrv_invalidate_cache_all(&local_err);
1708 if (local_err) {
1709 error_report_err(local_err);
1710 } else {
1711 s->block_inactive = false;
1716 void add_migration_state_change_notifier(Notifier *notify)
1718 notifier_list_add(&migration_state_notifiers, notify);
1721 void remove_migration_state_change_notifier(Notifier *notify)
1723 notifier_remove(notify);
1726 bool migration_in_setup(MigrationState *s)
1728 return s->state == MIGRATION_STATUS_SETUP;
1731 bool migration_has_finished(MigrationState *s)
1733 return s->state == MIGRATION_STATUS_COMPLETED;
1736 bool migration_has_failed(MigrationState *s)
1738 return (s->state == MIGRATION_STATUS_CANCELLED ||
1739 s->state == MIGRATION_STATUS_FAILED);
1742 bool migration_in_postcopy(void)
1744 MigrationState *s = migrate_get_current();
1746 switch (s->state) {
1747 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1748 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1749 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1750 return true;
1751 default:
1752 return false;
1756 bool migration_in_postcopy_after_devices(MigrationState *s)
1758 return migration_in_postcopy() && s->postcopy_after_devices;
1761 bool migration_is_idle(void)
1763 MigrationState *s = current_migration;
1765 if (!s) {
1766 return true;
1769 switch (s->state) {
1770 case MIGRATION_STATUS_NONE:
1771 case MIGRATION_STATUS_CANCELLED:
1772 case MIGRATION_STATUS_COMPLETED:
1773 case MIGRATION_STATUS_FAILED:
1774 return true;
1775 case MIGRATION_STATUS_SETUP:
1776 case MIGRATION_STATUS_CANCELLING:
1777 case MIGRATION_STATUS_ACTIVE:
1778 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1779 case MIGRATION_STATUS_COLO:
1780 case MIGRATION_STATUS_PRE_SWITCHOVER:
1781 case MIGRATION_STATUS_DEVICE:
1782 case MIGRATION_STATUS_WAIT_UNPLUG:
1783 return false;
1784 case MIGRATION_STATUS__MAX:
1785 g_assert_not_reached();
1788 return false;
1791 bool migration_is_active(MigrationState *s)
1793 return (s->state == MIGRATION_STATUS_ACTIVE ||
1794 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1797 void migrate_init(MigrationState *s)
1800 * Reinitialise all migration state, except
1801 * parameters/capabilities that the user set, and
1802 * locks.
1804 s->cleanup_bh = 0;
1805 s->to_dst_file = NULL;
1806 s->state = MIGRATION_STATUS_NONE;
1807 s->rp_state.from_dst_file = NULL;
1808 s->rp_state.error = false;
1809 s->mbps = 0.0;
1810 s->pages_per_second = 0.0;
1811 s->downtime = 0;
1812 s->expected_downtime = 0;
1813 s->setup_time = 0;
1814 s->start_postcopy = false;
1815 s->postcopy_after_devices = false;
1816 s->migration_thread_running = false;
1817 error_free(s->error);
1818 s->error = NULL;
1820 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1822 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1823 s->total_time = 0;
1824 s->vm_was_running = false;
1825 s->iteration_initial_bytes = 0;
1826 s->threshold_size = 0;
1829 static GSList *migration_blockers;
1831 int migrate_add_blocker(Error *reason, Error **errp)
1833 if (only_migratable) {
1834 error_propagate_prepend(errp, error_copy(reason),
1835 "disallowing migration blocker "
1836 "(--only-migratable) for: ");
1837 return -EACCES;
1840 if (migration_is_idle()) {
1841 migration_blockers = g_slist_prepend(migration_blockers, reason);
1842 return 0;
1845 error_propagate_prepend(errp, error_copy(reason),
1846 "disallowing migration blocker "
1847 "(migration in progress) for: ");
1848 return -EBUSY;
1851 void migrate_del_blocker(Error *reason)
1853 migration_blockers = g_slist_remove(migration_blockers, reason);
1856 void qmp_migrate_incoming(const char *uri, Error **errp)
1858 Error *local_err = NULL;
1859 static bool once = true;
1861 if (!deferred_incoming) {
1862 error_setg(errp, "For use with '-incoming defer'");
1863 return;
1865 if (!once) {
1866 error_setg(errp, "The incoming migration has already been started");
1867 return;
1870 qemu_start_incoming_migration(uri, &local_err);
1872 if (local_err) {
1873 error_propagate(errp, local_err);
1874 return;
1877 once = false;
1880 void qmp_migrate_recover(const char *uri, Error **errp)
1882 MigrationIncomingState *mis = migration_incoming_get_current();
1884 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1885 error_setg(errp, "Migrate recover can only be run "
1886 "when postcopy is paused.");
1887 return;
1890 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1891 false, true) == true) {
1892 error_setg(errp, "Migrate recovery is triggered already");
1893 return;
1897 * Note that this call will never start a real migration; it will
1898 * only re-setup the migration stream and poke existing migration
1899 * to continue using that newly established channel.
1901 qemu_start_incoming_migration(uri, errp);
1904 void qmp_migrate_pause(Error **errp)
1906 MigrationState *ms = migrate_get_current();
1907 MigrationIncomingState *mis = migration_incoming_get_current();
1908 int ret;
1910 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1911 /* Source side, during postcopy */
1912 qemu_mutex_lock(&ms->qemu_file_lock);
1913 ret = qemu_file_shutdown(ms->to_dst_file);
1914 qemu_mutex_unlock(&ms->qemu_file_lock);
1915 if (ret) {
1916 error_setg(errp, "Failed to pause source migration");
1918 return;
1921 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1922 ret = qemu_file_shutdown(mis->from_src_file);
1923 if (ret) {
1924 error_setg(errp, "Failed to pause destination migration");
1926 return;
1929 error_setg(errp, "migrate-pause is currently only supported "
1930 "during postcopy-active state");
1933 bool migration_is_blocked(Error **errp)
1935 if (qemu_savevm_state_blocked(errp)) {
1936 return true;
1939 if (migration_blockers) {
1940 error_propagate(errp, error_copy(migration_blockers->data));
1941 return true;
1944 return false;
1947 /* Returns true if continue to migrate, or false if error detected */
1948 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1949 bool resume, Error **errp)
1951 Error *local_err = NULL;
1953 if (resume) {
1954 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1955 error_setg(errp, "Cannot resume if there is no "
1956 "paused migration");
1957 return false;
1961 * Postcopy recovery won't work well with release-ram
1962 * capability since release-ram will drop the page buffer as
1963 * long as the page is put into the send buffer. So if there
1964 * is a network failure happened, any page buffers that have
1965 * not yet reached the destination VM but have already been
1966 * sent from the source VM will be lost forever. Let's refuse
1967 * the client from resuming such a postcopy migration.
1968 * Luckily release-ram was designed to only be used when src
1969 * and destination VMs are on the same host, so it should be
1970 * fine.
1972 if (migrate_release_ram()) {
1973 error_setg(errp, "Postcopy recovery cannot work "
1974 "when release-ram capability is set");
1975 return false;
1978 /* This is a resume, skip init status */
1979 return true;
1982 if (migration_is_running(s->state)) {
1983 error_setg(errp, QERR_MIGRATION_ACTIVE);
1984 return false;
1987 if (runstate_check(RUN_STATE_INMIGRATE)) {
1988 error_setg(errp, "Guest is waiting for an incoming migration");
1989 return false;
1992 if (migration_is_blocked(errp)) {
1993 return false;
1996 if (blk || blk_inc) {
1997 if (migrate_use_block() || migrate_use_block_incremental()) {
1998 error_setg(errp, "Command options are incompatible with "
1999 "current migration capabilities");
2000 return false;
2002 migrate_set_block_enabled(true, &local_err);
2003 if (local_err) {
2004 error_propagate(errp, local_err);
2005 return false;
2007 s->must_remove_block_options = true;
2010 if (blk_inc) {
2011 migrate_set_block_incremental(s, true);
2014 migrate_init(s);
2016 * set ram_counters memory to zero for a
2017 * new migration
2019 memset(&ram_counters, 0, sizeof(ram_counters));
2021 return true;
2024 void qmp_migrate(const char *uri, bool has_blk, bool blk,
2025 bool has_inc, bool inc, bool has_detach, bool detach,
2026 bool has_resume, bool resume, Error **errp)
2028 Error *local_err = NULL;
2029 MigrationState *s = migrate_get_current();
2030 const char *p;
2032 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2033 has_resume && resume, errp)) {
2034 /* Error detected, put into errp */
2035 return;
2038 if (strstart(uri, "tcp:", &p)) {
2039 tcp_start_outgoing_migration(s, p, &local_err);
2040 #ifdef CONFIG_RDMA
2041 } else if (strstart(uri, "rdma:", &p)) {
2042 rdma_start_outgoing_migration(s, p, &local_err);
2043 #endif
2044 } else if (strstart(uri, "exec:", &p)) {
2045 exec_start_outgoing_migration(s, p, &local_err);
2046 } else if (strstart(uri, "unix:", &p)) {
2047 unix_start_outgoing_migration(s, p, &local_err);
2048 } else if (strstart(uri, "fd:", &p)) {
2049 fd_start_outgoing_migration(s, p, &local_err);
2050 } else {
2051 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2052 "a valid migration protocol");
2053 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2054 MIGRATION_STATUS_FAILED);
2055 block_cleanup_parameters(s);
2056 return;
2059 if (local_err) {
2060 migrate_fd_error(s, local_err);
2061 error_propagate(errp, local_err);
2062 return;
2066 void qmp_migrate_cancel(Error **errp)
2068 migrate_fd_cancel(migrate_get_current());
2071 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2073 MigrationState *s = migrate_get_current();
2074 if (s->state != state) {
2075 error_setg(errp, "Migration not in expected state: %s",
2076 MigrationStatus_str(s->state));
2077 return;
2079 qemu_sem_post(&s->pause_sem);
2082 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
2084 MigrateSetParameters p = {
2085 .has_xbzrle_cache_size = true,
2086 .xbzrle_cache_size = value,
2089 qmp_migrate_set_parameters(&p, errp);
2092 int64_t qmp_query_migrate_cache_size(Error **errp)
2094 return migrate_xbzrle_cache_size();
2097 void qmp_migrate_set_speed(int64_t value, Error **errp)
2099 MigrateSetParameters p = {
2100 .has_max_bandwidth = true,
2101 .max_bandwidth = value,
2104 qmp_migrate_set_parameters(&p, errp);
2107 void qmp_migrate_set_downtime(double value, Error **errp)
2109 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
2110 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
2111 "the range of 0 to %d seconds",
2112 MAX_MIGRATE_DOWNTIME_SECONDS);
2113 return;
2116 value *= 1000; /* Convert to milliseconds */
2118 MigrateSetParameters p = {
2119 .has_downtime_limit = true,
2120 .downtime_limit = (int64_t)value,
2123 qmp_migrate_set_parameters(&p, errp);
2126 bool migrate_release_ram(void)
2128 MigrationState *s;
2130 s = migrate_get_current();
2132 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2135 bool migrate_postcopy_ram(void)
2137 MigrationState *s;
2139 s = migrate_get_current();
2141 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
2144 bool migrate_postcopy(void)
2146 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
2149 bool migrate_auto_converge(void)
2151 MigrationState *s;
2153 s = migrate_get_current();
2155 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2158 bool migrate_zero_blocks(void)
2160 MigrationState *s;
2162 s = migrate_get_current();
2164 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2167 bool migrate_postcopy_blocktime(void)
2169 MigrationState *s;
2171 s = migrate_get_current();
2173 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2176 bool migrate_use_compression(void)
2178 MigrationState *s;
2180 s = migrate_get_current();
2182 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
2185 int migrate_compress_level(void)
2187 MigrationState *s;
2189 s = migrate_get_current();
2191 return s->parameters.compress_level;
2194 int migrate_compress_threads(void)
2196 MigrationState *s;
2198 s = migrate_get_current();
2200 return s->parameters.compress_threads;
2203 int migrate_compress_wait_thread(void)
2205 MigrationState *s;
2207 s = migrate_get_current();
2209 return s->parameters.compress_wait_thread;
2212 int migrate_decompress_threads(void)
2214 MigrationState *s;
2216 s = migrate_get_current();
2218 return s->parameters.decompress_threads;
2221 bool migrate_dirty_bitmaps(void)
2223 MigrationState *s;
2225 s = migrate_get_current();
2227 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2230 bool migrate_ignore_shared(void)
2232 MigrationState *s;
2234 s = migrate_get_current();
2236 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2239 bool migrate_validate_uuid(void)
2241 MigrationState *s;
2243 s = migrate_get_current();
2245 return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2248 bool migrate_use_events(void)
2250 MigrationState *s;
2252 s = migrate_get_current();
2254 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2257 bool migrate_use_multifd(void)
2259 MigrationState *s;
2261 s = migrate_get_current();
2263 return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
2266 bool migrate_pause_before_switchover(void)
2268 MigrationState *s;
2270 s = migrate_get_current();
2272 return s->enabled_capabilities[
2273 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2276 int migrate_multifd_channels(void)
2278 MigrationState *s;
2280 s = migrate_get_current();
2282 return s->parameters.multifd_channels;
2285 MultiFDCompression migrate_multifd_compression(void)
2287 MigrationState *s;
2289 s = migrate_get_current();
2291 return s->parameters.multifd_compression;
2294 int migrate_multifd_zlib_level(void)
2296 MigrationState *s;
2298 s = migrate_get_current();
2300 return s->parameters.multifd_zlib_level;
2303 int migrate_multifd_zstd_level(void)
2305 MigrationState *s;
2307 s = migrate_get_current();
2309 return s->parameters.multifd_zstd_level;
2312 int migrate_use_xbzrle(void)
2314 MigrationState *s;
2316 s = migrate_get_current();
2318 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2321 int64_t migrate_xbzrle_cache_size(void)
2323 MigrationState *s;
2325 s = migrate_get_current();
2327 return s->parameters.xbzrle_cache_size;
2330 static int64_t migrate_max_postcopy_bandwidth(void)
2332 MigrationState *s;
2334 s = migrate_get_current();
2336 return s->parameters.max_postcopy_bandwidth;
2339 bool migrate_use_block(void)
2341 MigrationState *s;
2343 s = migrate_get_current();
2345 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2348 bool migrate_use_return_path(void)
2350 MigrationState *s;
2352 s = migrate_get_current();
2354 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2357 bool migrate_use_block_incremental(void)
2359 MigrationState *s;
2361 s = migrate_get_current();
2363 return s->parameters.block_incremental;
2366 /* migration thread support */
2368 * Something bad happened to the RP stream, mark an error
2369 * The caller shall print or trace something to indicate why
2371 static void mark_source_rp_bad(MigrationState *s)
2373 s->rp_state.error = true;
2376 static struct rp_cmd_args {
2377 ssize_t len; /* -1 = variable */
2378 const char *name;
2379 } rp_cmd_args[] = {
2380 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2381 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2382 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2383 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2384 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2385 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2386 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2387 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2391 * Process a request for pages received on the return path,
2392 * We're allowed to send more than requested (e.g. to round to our page size)
2393 * and we don't need to send pages that have already been sent.
2395 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2396 ram_addr_t start, size_t len)
2398 long our_host_ps = qemu_real_host_page_size;
2400 trace_migrate_handle_rp_req_pages(rbname, start, len);
2403 * Since we currently insist on matching page sizes, just sanity check
2404 * we're being asked for whole host pages.
2406 if (start & (our_host_ps-1) ||
2407 (len & (our_host_ps-1))) {
2408 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2409 " len: %zd", __func__, start, len);
2410 mark_source_rp_bad(ms);
2411 return;
2414 if (ram_save_queue_pages(rbname, start, len)) {
2415 mark_source_rp_bad(ms);
2419 /* Return true to retry, false to quit */
2420 static bool postcopy_pause_return_path_thread(MigrationState *s)
2422 trace_postcopy_pause_return_path();
2424 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2426 trace_postcopy_pause_return_path_continued();
2428 return true;
2431 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2433 RAMBlock *block = qemu_ram_block_by_name(block_name);
2435 if (!block) {
2436 error_report("%s: invalid block name '%s'", __func__, block_name);
2437 return -EINVAL;
2440 /* Fetch the received bitmap and refresh the dirty bitmap */
2441 return ram_dirty_bitmap_reload(s, block);
2444 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2446 trace_source_return_path_thread_resume_ack(value);
2448 if (value != MIGRATION_RESUME_ACK_VALUE) {
2449 error_report("%s: illegal resume_ack value %"PRIu32,
2450 __func__, value);
2451 return -1;
2454 /* Now both sides are active. */
2455 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2456 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2458 /* Notify send thread that time to continue send pages */
2459 qemu_sem_post(&s->rp_state.rp_sem);
2461 return 0;
2465 * Handles messages sent on the return path towards the source VM
2468 static void *source_return_path_thread(void *opaque)
2470 MigrationState *ms = opaque;
2471 QEMUFile *rp = ms->rp_state.from_dst_file;
2472 uint16_t header_len, header_type;
2473 uint8_t buf[512];
2474 uint32_t tmp32, sibling_error;
2475 ram_addr_t start = 0; /* =0 to silence warning */
2476 size_t len = 0, expected_len;
2477 int res;
2479 trace_source_return_path_thread_entry();
2480 rcu_register_thread();
2482 retry:
2483 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2484 migration_is_setup_or_active(ms->state)) {
2485 trace_source_return_path_thread_loop_top();
2486 header_type = qemu_get_be16(rp);
2487 header_len = qemu_get_be16(rp);
2489 if (qemu_file_get_error(rp)) {
2490 mark_source_rp_bad(ms);
2491 goto out;
2494 if (header_type >= MIG_RP_MSG_MAX ||
2495 header_type == MIG_RP_MSG_INVALID) {
2496 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2497 header_type, header_len);
2498 mark_source_rp_bad(ms);
2499 goto out;
2502 if ((rp_cmd_args[header_type].len != -1 &&
2503 header_len != rp_cmd_args[header_type].len) ||
2504 header_len > sizeof(buf)) {
2505 error_report("RP: Received '%s' message (0x%04x) with"
2506 "incorrect length %d expecting %zu",
2507 rp_cmd_args[header_type].name, header_type, header_len,
2508 (size_t)rp_cmd_args[header_type].len);
2509 mark_source_rp_bad(ms);
2510 goto out;
2513 /* We know we've got a valid header by this point */
2514 res = qemu_get_buffer(rp, buf, header_len);
2515 if (res != header_len) {
2516 error_report("RP: Failed reading data for message 0x%04x"
2517 " read %d expected %d",
2518 header_type, res, header_len);
2519 mark_source_rp_bad(ms);
2520 goto out;
2523 /* OK, we have the message and the data */
2524 switch (header_type) {
2525 case MIG_RP_MSG_SHUT:
2526 sibling_error = ldl_be_p(buf);
2527 trace_source_return_path_thread_shut(sibling_error);
2528 if (sibling_error) {
2529 error_report("RP: Sibling indicated error %d", sibling_error);
2530 mark_source_rp_bad(ms);
2533 * We'll let the main thread deal with closing the RP
2534 * we could do a shutdown(2) on it, but we're the only user
2535 * anyway, so there's nothing gained.
2537 goto out;
2539 case MIG_RP_MSG_PONG:
2540 tmp32 = ldl_be_p(buf);
2541 trace_source_return_path_thread_pong(tmp32);
2542 break;
2544 case MIG_RP_MSG_REQ_PAGES:
2545 start = ldq_be_p(buf);
2546 len = ldl_be_p(buf + 8);
2547 migrate_handle_rp_req_pages(ms, NULL, start, len);
2548 break;
2550 case MIG_RP_MSG_REQ_PAGES_ID:
2551 expected_len = 12 + 1; /* header + termination */
2553 if (header_len >= expected_len) {
2554 start = ldq_be_p(buf);
2555 len = ldl_be_p(buf + 8);
2556 /* Now we expect an idstr */
2557 tmp32 = buf[12]; /* Length of the following idstr */
2558 buf[13 + tmp32] = '\0';
2559 expected_len += tmp32;
2561 if (header_len != expected_len) {
2562 error_report("RP: Req_Page_id with length %d expecting %zd",
2563 header_len, expected_len);
2564 mark_source_rp_bad(ms);
2565 goto out;
2567 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2568 break;
2570 case MIG_RP_MSG_RECV_BITMAP:
2571 if (header_len < 1) {
2572 error_report("%s: missing block name", __func__);
2573 mark_source_rp_bad(ms);
2574 goto out;
2576 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2577 buf[buf[0] + 1] = '\0';
2578 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2579 mark_source_rp_bad(ms);
2580 goto out;
2582 break;
2584 case MIG_RP_MSG_RESUME_ACK:
2585 tmp32 = ldl_be_p(buf);
2586 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2587 mark_source_rp_bad(ms);
2588 goto out;
2590 break;
2592 default:
2593 break;
2597 out:
2598 res = qemu_file_get_error(rp);
2599 if (res) {
2600 if (res == -EIO && migration_in_postcopy()) {
2602 * Maybe there is something we can do: it looks like a
2603 * network down issue, and we pause for a recovery.
2605 if (postcopy_pause_return_path_thread(ms)) {
2606 /* Reload rp, reset the rest */
2607 if (rp != ms->rp_state.from_dst_file) {
2608 qemu_fclose(rp);
2609 rp = ms->rp_state.from_dst_file;
2611 ms->rp_state.error = false;
2612 goto retry;
2616 trace_source_return_path_thread_bad_end();
2617 mark_source_rp_bad(ms);
2620 trace_source_return_path_thread_end();
2621 ms->rp_state.from_dst_file = NULL;
2622 qemu_fclose(rp);
2623 rcu_unregister_thread();
2624 return NULL;
2627 static int open_return_path_on_source(MigrationState *ms,
2628 bool create_thread)
2631 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2632 if (!ms->rp_state.from_dst_file) {
2633 return -1;
2636 trace_open_return_path_on_source();
2638 if (!create_thread) {
2639 /* We're done */
2640 return 0;
2643 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2644 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2646 trace_open_return_path_on_source_continue();
2648 return 0;
2651 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2652 static int await_return_path_close_on_source(MigrationState *ms)
2655 * If this is a normal exit then the destination will send a SHUT and the
2656 * rp_thread will exit, however if there's an error we need to cause
2657 * it to exit.
2659 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2661 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2662 * waiting for the destination.
2664 qemu_file_shutdown(ms->rp_state.from_dst_file);
2665 mark_source_rp_bad(ms);
2667 trace_await_return_path_close_on_source_joining();
2668 qemu_thread_join(&ms->rp_state.rp_thread);
2669 trace_await_return_path_close_on_source_close();
2670 return ms->rp_state.error;
2674 * Switch from normal iteration to postcopy
2675 * Returns non-0 on error
2677 static int postcopy_start(MigrationState *ms)
2679 int ret;
2680 QIOChannelBuffer *bioc;
2681 QEMUFile *fb;
2682 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2683 int64_t bandwidth = migrate_max_postcopy_bandwidth();
2684 bool restart_block = false;
2685 int cur_state = MIGRATION_STATUS_ACTIVE;
2686 if (!migrate_pause_before_switchover()) {
2687 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2688 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2691 trace_postcopy_start();
2692 qemu_mutex_lock_iothread();
2693 trace_postcopy_start_set_run();
2695 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2696 global_state_store();
2697 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2698 if (ret < 0) {
2699 goto fail;
2702 ret = migration_maybe_pause(ms, &cur_state,
2703 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2704 if (ret < 0) {
2705 goto fail;
2708 ret = bdrv_inactivate_all();
2709 if (ret < 0) {
2710 goto fail;
2712 restart_block = true;
2715 * Cause any non-postcopiable, but iterative devices to
2716 * send out their final data.
2718 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2721 * in Finish migrate and with the io-lock held everything should
2722 * be quiet, but we've potentially still got dirty pages and we
2723 * need to tell the destination to throw any pages it's already received
2724 * that are dirty
2726 if (migrate_postcopy_ram()) {
2727 if (ram_postcopy_send_discard_bitmap(ms)) {
2728 error_report("postcopy send discard bitmap failed");
2729 goto fail;
2734 * send rest of state - note things that are doing postcopy
2735 * will notice we're in POSTCOPY_ACTIVE and not actually
2736 * wrap their state up here
2738 /* 0 max-postcopy-bandwidth means unlimited */
2739 if (!bandwidth) {
2740 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2741 } else {
2742 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2744 if (migrate_postcopy_ram()) {
2745 /* Ping just for debugging, helps line traces up */
2746 qemu_savevm_send_ping(ms->to_dst_file, 2);
2750 * While loading the device state we may trigger page transfer
2751 * requests and the fd must be free to process those, and thus
2752 * the destination must read the whole device state off the fd before
2753 * it starts processing it. Unfortunately the ad-hoc migration format
2754 * doesn't allow the destination to know the size to read without fully
2755 * parsing it through each devices load-state code (especially the open
2756 * coded devices that use get/put).
2757 * So we wrap the device state up in a package with a length at the start;
2758 * to do this we use a qemu_buf to hold the whole of the device state.
2760 bioc = qio_channel_buffer_new(4096);
2761 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2762 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2763 object_unref(OBJECT(bioc));
2766 * Make sure the receiver can get incoming pages before we send the rest
2767 * of the state
2769 qemu_savevm_send_postcopy_listen(fb);
2771 qemu_savevm_state_complete_precopy(fb, false, false);
2772 if (migrate_postcopy_ram()) {
2773 qemu_savevm_send_ping(fb, 3);
2776 qemu_savevm_send_postcopy_run(fb);
2778 /* <><> end of stuff going into the package */
2780 /* Last point of recovery; as soon as we send the package the destination
2781 * can open devices and potentially start running.
2782 * Lets just check again we've not got any errors.
2784 ret = qemu_file_get_error(ms->to_dst_file);
2785 if (ret) {
2786 error_report("postcopy_start: Migration stream errored (pre package)");
2787 goto fail_closefb;
2790 restart_block = false;
2792 /* Now send that blob */
2793 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2794 goto fail_closefb;
2796 qemu_fclose(fb);
2798 /* Send a notify to give a chance for anything that needs to happen
2799 * at the transition to postcopy and after the device state; in particular
2800 * spice needs to trigger a transition now
2802 ms->postcopy_after_devices = true;
2803 notifier_list_notify(&migration_state_notifiers, ms);
2805 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2807 qemu_mutex_unlock_iothread();
2809 if (migrate_postcopy_ram()) {
2811 * Although this ping is just for debug, it could potentially be
2812 * used for getting a better measurement of downtime at the source.
2814 qemu_savevm_send_ping(ms->to_dst_file, 4);
2817 if (migrate_release_ram()) {
2818 ram_postcopy_migrated_memory_release(ms);
2821 ret = qemu_file_get_error(ms->to_dst_file);
2822 if (ret) {
2823 error_report("postcopy_start: Migration stream errored");
2824 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2825 MIGRATION_STATUS_FAILED);
2828 return ret;
2830 fail_closefb:
2831 qemu_fclose(fb);
2832 fail:
2833 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2834 MIGRATION_STATUS_FAILED);
2835 if (restart_block) {
2836 /* A failure happened early enough that we know the destination hasn't
2837 * accessed block devices, so we're safe to recover.
2839 Error *local_err = NULL;
2841 bdrv_invalidate_cache_all(&local_err);
2842 if (local_err) {
2843 error_report_err(local_err);
2846 qemu_mutex_unlock_iothread();
2847 return -1;
2851 * migration_maybe_pause: Pause if required to by
2852 * migrate_pause_before_switchover called with the iothread locked
2853 * Returns: 0 on success
2855 static int migration_maybe_pause(MigrationState *s,
2856 int *current_active_state,
2857 int new_state)
2859 if (!migrate_pause_before_switchover()) {
2860 return 0;
2863 /* Since leaving this state is not atomic with posting the semaphore
2864 * it's possible that someone could have issued multiple migrate_continue
2865 * and the semaphore is incorrectly positive at this point;
2866 * the docs say it's undefined to reinit a semaphore that's already
2867 * init'd, so use timedwait to eat up any existing posts.
2869 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2870 /* This block intentionally left blank */
2874 * If the migration is cancelled when it is in the completion phase,
2875 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2876 * So we don't need to wait a semaphore, otherwise we would always
2877 * wait for the 'pause_sem' semaphore.
2879 if (s->state != MIGRATION_STATUS_CANCELLING) {
2880 qemu_mutex_unlock_iothread();
2881 migrate_set_state(&s->state, *current_active_state,
2882 MIGRATION_STATUS_PRE_SWITCHOVER);
2883 qemu_sem_wait(&s->pause_sem);
2884 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2885 new_state);
2886 *current_active_state = new_state;
2887 qemu_mutex_lock_iothread();
2890 return s->state == new_state ? 0 : -EINVAL;
2894 * migration_completion: Used by migration_thread when there's not much left.
2895 * The caller 'breaks' the loop when this returns.
2897 * @s: Current migration state
2899 static void migration_completion(MigrationState *s)
2901 int ret;
2902 int current_active_state = s->state;
2904 if (s->state == MIGRATION_STATUS_ACTIVE) {
2905 qemu_mutex_lock_iothread();
2906 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2907 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2908 s->vm_was_running = runstate_is_running();
2909 ret = global_state_store();
2911 if (!ret) {
2912 bool inactivate = !migrate_colo_enabled();
2913 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2914 if (ret >= 0) {
2915 ret = migration_maybe_pause(s, &current_active_state,
2916 MIGRATION_STATUS_DEVICE);
2918 if (ret >= 0) {
2919 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2920 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2921 inactivate);
2923 if (inactivate && ret >= 0) {
2924 s->block_inactive = true;
2927 qemu_mutex_unlock_iothread();
2929 if (ret < 0) {
2930 goto fail;
2932 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2933 trace_migration_completion_postcopy_end();
2935 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2936 trace_migration_completion_postcopy_end_after_complete();
2940 * If rp was opened we must clean up the thread before
2941 * cleaning everything else up (since if there are no failures
2942 * it will wait for the destination to send it's status in
2943 * a SHUT command).
2945 if (s->rp_state.from_dst_file) {
2946 int rp_error;
2947 trace_migration_return_path_end_before();
2948 rp_error = await_return_path_close_on_source(s);
2949 trace_migration_return_path_end_after(rp_error);
2950 if (rp_error) {
2951 goto fail_invalidate;
2955 if (qemu_file_get_error(s->to_dst_file)) {
2956 trace_migration_completion_file_err();
2957 goto fail_invalidate;
2960 if (!migrate_colo_enabled()) {
2961 migrate_set_state(&s->state, current_active_state,
2962 MIGRATION_STATUS_COMPLETED);
2965 return;
2967 fail_invalidate:
2968 /* If not doing postcopy, vm_start() will be called: let's regain
2969 * control on images.
2971 if (s->state == MIGRATION_STATUS_ACTIVE ||
2972 s->state == MIGRATION_STATUS_DEVICE) {
2973 Error *local_err = NULL;
2975 qemu_mutex_lock_iothread();
2976 bdrv_invalidate_cache_all(&local_err);
2977 if (local_err) {
2978 error_report_err(local_err);
2979 } else {
2980 s->block_inactive = false;
2982 qemu_mutex_unlock_iothread();
2985 fail:
2986 migrate_set_state(&s->state, current_active_state,
2987 MIGRATION_STATUS_FAILED);
2990 bool migrate_colo_enabled(void)
2992 MigrationState *s = migrate_get_current();
2993 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2996 typedef enum MigThrError {
2997 /* No error detected */
2998 MIG_THR_ERR_NONE = 0,
2999 /* Detected error, but resumed successfully */
3000 MIG_THR_ERR_RECOVERED = 1,
3001 /* Detected fatal error, need to exit */
3002 MIG_THR_ERR_FATAL = 2,
3003 } MigThrError;
3005 static int postcopy_resume_handshake(MigrationState *s)
3007 qemu_savevm_send_postcopy_resume(s->to_dst_file);
3009 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3010 qemu_sem_wait(&s->rp_state.rp_sem);
3013 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3014 return 0;
3017 return -1;
3020 /* Return zero if success, or <0 for error */
3021 static int postcopy_do_resume(MigrationState *s)
3023 int ret;
3026 * Call all the resume_prepare() hooks, so that modules can be
3027 * ready for the migration resume.
3029 ret = qemu_savevm_state_resume_prepare(s);
3030 if (ret) {
3031 error_report("%s: resume_prepare() failure detected: %d",
3032 __func__, ret);
3033 return ret;
3037 * Last handshake with destination on the resume (destination will
3038 * switch to postcopy-active afterwards)
3040 ret = postcopy_resume_handshake(s);
3041 if (ret) {
3042 error_report("%s: handshake failed: %d", __func__, ret);
3043 return ret;
3046 return 0;
3050 * We don't return until we are in a safe state to continue current
3051 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
3052 * MIG_THR_ERR_FATAL if unrecovery failure happened.
3054 static MigThrError postcopy_pause(MigrationState *s)
3056 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3058 while (true) {
3059 QEMUFile *file;
3061 migrate_set_state(&s->state, s->state,
3062 MIGRATION_STATUS_POSTCOPY_PAUSED);
3064 /* Current channel is possibly broken. Release it. */
3065 assert(s->to_dst_file);
3066 qemu_mutex_lock(&s->qemu_file_lock);
3067 file = s->to_dst_file;
3068 s->to_dst_file = NULL;
3069 qemu_mutex_unlock(&s->qemu_file_lock);
3071 qemu_file_shutdown(file);
3072 qemu_fclose(file);
3074 error_report("Detected IO failure for postcopy. "
3075 "Migration paused.");
3078 * We wait until things fixed up. Then someone will setup the
3079 * status back for us.
3081 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3082 qemu_sem_wait(&s->postcopy_pause_sem);
3085 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3086 /* Woken up by a recover procedure. Give it a shot */
3089 * Firstly, let's wake up the return path now, with a new
3090 * return path channel.
3092 qemu_sem_post(&s->postcopy_pause_rp_sem);
3094 /* Do the resume logic */
3095 if (postcopy_do_resume(s) == 0) {
3096 /* Let's continue! */
3097 trace_postcopy_pause_continued();
3098 return MIG_THR_ERR_RECOVERED;
3099 } else {
3101 * Something wrong happened during the recovery, let's
3102 * pause again. Pause is always better than throwing
3103 * data away.
3105 continue;
3107 } else {
3108 /* This is not right... Time to quit. */
3109 return MIG_THR_ERR_FATAL;
3114 static MigThrError migration_detect_error(MigrationState *s)
3116 int ret;
3117 int state = s->state;
3118 Error *local_error = NULL;
3120 if (state == MIGRATION_STATUS_CANCELLING ||
3121 state == MIGRATION_STATUS_CANCELLED) {
3122 /* End the migration, but don't set the state to failed */
3123 return MIG_THR_ERR_FATAL;
3126 /* Try to detect any file errors */
3127 ret = qemu_file_get_error_obj(s->to_dst_file, &local_error);
3128 if (!ret) {
3129 /* Everything is fine */
3130 assert(!local_error);
3131 return MIG_THR_ERR_NONE;
3134 if (local_error) {
3135 migrate_set_error(s, local_error);
3136 error_free(local_error);
3139 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
3141 * For postcopy, we allow the network to be down for a
3142 * while. After that, it can be continued by a
3143 * recovery phase.
3145 return postcopy_pause(s);
3146 } else {
3148 * For precopy (or postcopy with error outside IO), we fail
3149 * with no time.
3151 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3152 trace_migration_thread_file_err();
3154 /* Time to stop the migration, now. */
3155 return MIG_THR_ERR_FATAL;
3159 /* How many bytes have we transferred since the beginning of the migration */
3160 static uint64_t migration_total_bytes(MigrationState *s)
3162 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
3165 static void migration_calculate_complete(MigrationState *s)
3167 uint64_t bytes = migration_total_bytes(s);
3168 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3169 int64_t transfer_time;
3171 s->total_time = end_time - s->start_time;
3172 if (!s->downtime) {
3174 * It's still not set, so we are precopy migration. For
3175 * postcopy, downtime is calculated during postcopy_start().
3177 s->downtime = end_time - s->downtime_start;
3180 transfer_time = s->total_time - s->setup_time;
3181 if (transfer_time) {
3182 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3186 static void update_iteration_initial_status(MigrationState *s)
3189 * Update these three fields at the same time to avoid mismatch info lead
3190 * wrong speed calculation.
3192 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3193 s->iteration_initial_bytes = migration_total_bytes(s);
3194 s->iteration_initial_pages = ram_get_total_transferred_pages();
3197 static void migration_update_counters(MigrationState *s,
3198 int64_t current_time)
3200 uint64_t transferred, transferred_pages, time_spent;
3201 uint64_t current_bytes; /* bytes transferred since the beginning */
3202 double bandwidth;
3204 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3205 return;
3208 current_bytes = migration_total_bytes(s);
3209 transferred = current_bytes - s->iteration_initial_bytes;
3210 time_spent = current_time - s->iteration_start_time;
3211 bandwidth = (double)transferred / time_spent;
3212 s->threshold_size = bandwidth * s->parameters.downtime_limit;
3214 s->mbps = (((double) transferred * 8.0) /
3215 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3217 transferred_pages = ram_get_total_transferred_pages() -
3218 s->iteration_initial_pages;
3219 s->pages_per_second = (double) transferred_pages /
3220 (((double) time_spent / 1000.0));
3223 * if we haven't sent anything, we don't want to
3224 * recalculate. 10000 is a small enough number for our purposes
3226 if (ram_counters.dirty_pages_rate && transferred > 10000) {
3227 s->expected_downtime = ram_counters.remaining / bandwidth;
3230 qemu_file_reset_rate_limit(s->to_dst_file);
3232 update_iteration_initial_status(s);
3234 trace_migrate_transferred(transferred, time_spent,
3235 bandwidth, s->threshold_size);
3238 /* Migration thread iteration status */
3239 typedef enum {
3240 MIG_ITERATE_RESUME, /* Resume current iteration */
3241 MIG_ITERATE_SKIP, /* Skip current iteration */
3242 MIG_ITERATE_BREAK, /* Break the loop */
3243 } MigIterateState;
3246 * Return true if continue to the next iteration directly, false
3247 * otherwise.
3249 static MigIterateState migration_iteration_run(MigrationState *s)
3251 uint64_t pending_size, pend_pre, pend_compat, pend_post;
3252 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3254 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
3255 &pend_compat, &pend_post);
3256 pending_size = pend_pre + pend_compat + pend_post;
3258 trace_migrate_pending(pending_size, s->threshold_size,
3259 pend_pre, pend_compat, pend_post);
3261 if (pending_size && pending_size >= s->threshold_size) {
3262 /* Still a significant amount to transfer */
3263 if (!in_postcopy && pend_pre <= s->threshold_size &&
3264 atomic_read(&s->start_postcopy)) {
3265 if (postcopy_start(s)) {
3266 error_report("%s: postcopy failed to start", __func__);
3268 return MIG_ITERATE_SKIP;
3270 /* Just another iteration step */
3271 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3272 } else {
3273 trace_migration_thread_low_pending(pending_size);
3274 migration_completion(s);
3275 return MIG_ITERATE_BREAK;
3278 return MIG_ITERATE_RESUME;
3281 static void migration_iteration_finish(MigrationState *s)
3283 /* If we enabled cpu throttling for auto-converge, turn it off. */
3284 cpu_throttle_stop();
3286 qemu_mutex_lock_iothread();
3287 switch (s->state) {
3288 case MIGRATION_STATUS_COMPLETED:
3289 migration_calculate_complete(s);
3290 runstate_set(RUN_STATE_POSTMIGRATE);
3291 break;
3293 case MIGRATION_STATUS_ACTIVE:
3295 * We should really assert here, but since it's during
3296 * migration, let's try to reduce the usage of assertions.
3298 if (!migrate_colo_enabled()) {
3299 error_report("%s: critical error: calling COLO code without "
3300 "COLO enabled", __func__);
3302 migrate_start_colo_process(s);
3304 * Fixme: we will run VM in COLO no matter its old running state.
3305 * After exited COLO, we will keep running.
3307 s->vm_was_running = true;
3308 /* Fallthrough */
3309 case MIGRATION_STATUS_FAILED:
3310 case MIGRATION_STATUS_CANCELLED:
3311 case MIGRATION_STATUS_CANCELLING:
3312 if (s->vm_was_running) {
3313 vm_start();
3314 } else {
3315 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3316 runstate_set(RUN_STATE_POSTMIGRATE);
3319 break;
3321 default:
3322 /* Should not reach here, but if so, forgive the VM. */
3323 error_report("%s: Unknown ending state %d", __func__, s->state);
3324 break;
3326 migrate_fd_cleanup_schedule(s);
3327 qemu_mutex_unlock_iothread();
3330 void migration_make_urgent_request(void)
3332 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3335 void migration_consume_urgent_request(void)
3337 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3340 /* Returns true if the rate limiting was broken by an urgent request */
3341 bool migration_rate_limit(void)
3343 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3344 MigrationState *s = migrate_get_current();
3346 bool urgent = false;
3347 migration_update_counters(s, now);
3348 if (qemu_file_rate_limit(s->to_dst_file)) {
3350 * Wait for a delay to do rate limiting OR
3351 * something urgent to post the semaphore.
3353 int ms = s->iteration_start_time + BUFFER_DELAY - now;
3354 trace_migration_rate_limit_pre(ms);
3355 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3357 * We were woken by one or more urgent things but
3358 * the timedwait will have consumed one of them.
3359 * The service routine for the urgent wake will dec
3360 * the semaphore itself for each item it consumes,
3361 * so add this one we just eat back.
3363 qemu_sem_post(&s->rate_limit_sem);
3364 urgent = true;
3366 trace_migration_rate_limit_post(urgent);
3368 return urgent;
3372 * Master migration thread on the source VM.
3373 * It drives the migration and pumps the data down the outgoing channel.
3375 static void *migration_thread(void *opaque)
3377 MigrationState *s = opaque;
3378 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3379 MigThrError thr_error;
3380 bool urgent = false;
3382 rcu_register_thread();
3384 object_ref(OBJECT(s));
3385 update_iteration_initial_status(s);
3387 qemu_savevm_state_header(s->to_dst_file);
3390 * If we opened the return path, we need to make sure dst has it
3391 * opened as well.
3393 if (s->rp_state.from_dst_file) {
3394 /* Now tell the dest that it should open its end so it can reply */
3395 qemu_savevm_send_open_return_path(s->to_dst_file);
3397 /* And do a ping that will make stuff easier to debug */
3398 qemu_savevm_send_ping(s->to_dst_file, 1);
3401 if (migrate_postcopy()) {
3403 * Tell the destination that we *might* want to do postcopy later;
3404 * if the other end can't do postcopy it should fail now, nice and
3405 * early.
3407 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3410 if (migrate_colo_enabled()) {
3411 /* Notify migration destination that we enable COLO */
3412 qemu_savevm_send_colo_enable(s->to_dst_file);
3415 qemu_savevm_state_setup(s->to_dst_file);
3417 if (qemu_savevm_state_guest_unplug_pending()) {
3418 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3419 MIGRATION_STATUS_WAIT_UNPLUG);
3421 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3422 qemu_savevm_state_guest_unplug_pending()) {
3423 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3426 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG,
3427 MIGRATION_STATUS_ACTIVE);
3430 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3431 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3432 MIGRATION_STATUS_ACTIVE);
3434 trace_migration_thread_setup_complete();
3436 while (migration_is_active(s)) {
3437 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3438 MigIterateState iter_state = migration_iteration_run(s);
3439 if (iter_state == MIG_ITERATE_SKIP) {
3440 continue;
3441 } else if (iter_state == MIG_ITERATE_BREAK) {
3442 break;
3447 * Try to detect any kind of failures, and see whether we
3448 * should stop the migration now.
3450 thr_error = migration_detect_error(s);
3451 if (thr_error == MIG_THR_ERR_FATAL) {
3452 /* Stop migration */
3453 break;
3454 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3456 * Just recovered from a e.g. network failure, reset all
3457 * the local variables. This is important to avoid
3458 * breaking transferred_bytes and bandwidth calculation
3460 update_iteration_initial_status(s);
3463 urgent = migration_rate_limit();
3466 trace_migration_thread_after_loop();
3467 migration_iteration_finish(s);
3468 object_unref(OBJECT(s));
3469 rcu_unregister_thread();
3470 return NULL;
3473 void migrate_fd_connect(MigrationState *s, Error *error_in)
3475 Error *local_err = NULL;
3476 int64_t rate_limit;
3477 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3479 s->expected_downtime = s->parameters.downtime_limit;
3480 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
3481 if (error_in) {
3482 migrate_fd_error(s, error_in);
3483 migrate_fd_cleanup(s);
3484 return;
3487 if (resume) {
3488 /* This is a resumed migration */
3489 rate_limit = s->parameters.max_postcopy_bandwidth /
3490 XFER_LIMIT_RATIO;
3491 } else {
3492 /* This is a fresh new migration */
3493 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3495 /* Notify before starting migration thread */
3496 notifier_list_notify(&migration_state_notifiers, s);
3499 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3500 qemu_file_set_blocking(s->to_dst_file, true);
3503 * Open the return path. For postcopy, it is used exclusively. For
3504 * precopy, only if user specified "return-path" capability would
3505 * QEMU uses the return path.
3507 if (migrate_postcopy_ram() || migrate_use_return_path()) {
3508 if (open_return_path_on_source(s, !resume)) {
3509 error_report("Unable to open return-path for postcopy");
3510 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3511 migrate_fd_cleanup(s);
3512 return;
3516 if (resume) {
3517 /* Wakeup the main migration thread to do the recovery */
3518 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3519 MIGRATION_STATUS_POSTCOPY_RECOVER);
3520 qemu_sem_post(&s->postcopy_pause_sem);
3521 return;
3524 if (multifd_save_setup(&local_err) != 0) {
3525 error_report_err(local_err);
3526 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3527 MIGRATION_STATUS_FAILED);
3528 migrate_fd_cleanup(s);
3529 return;
3531 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3532 QEMU_THREAD_JOINABLE);
3533 s->migration_thread_running = true;
3536 void migration_global_dump(Monitor *mon)
3538 MigrationState *ms = migrate_get_current();
3540 monitor_printf(mon, "globals:\n");
3541 monitor_printf(mon, "store-global-state: %s\n",
3542 ms->store_global_state ? "on" : "off");
3543 monitor_printf(mon, "only-migratable: %s\n",
3544 only_migratable ? "on" : "off");
3545 monitor_printf(mon, "send-configuration: %s\n",
3546 ms->send_configuration ? "on" : "off");
3547 monitor_printf(mon, "send-section-footer: %s\n",
3548 ms->send_section_footer ? "on" : "off");
3549 monitor_printf(mon, "decompress-error-check: %s\n",
3550 ms->decompress_error_check ? "on" : "off");
3551 monitor_printf(mon, "clear-bitmap-shift: %u\n",
3552 ms->clear_bitmap_shift);
3555 #define DEFINE_PROP_MIG_CAP(name, x) \
3556 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3558 static Property migration_properties[] = {
3559 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3560 store_global_state, true),
3561 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3562 send_configuration, true),
3563 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3564 send_section_footer, true),
3565 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3566 decompress_error_check, true),
3567 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
3568 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
3570 /* Migration parameters */
3571 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3572 parameters.compress_level,
3573 DEFAULT_MIGRATE_COMPRESS_LEVEL),
3574 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3575 parameters.compress_threads,
3576 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3577 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3578 parameters.compress_wait_thread, true),
3579 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3580 parameters.decompress_threads,
3581 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3582 DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
3583 parameters.throttle_trigger_threshold,
3584 DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
3585 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3586 parameters.cpu_throttle_initial,
3587 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3588 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3589 parameters.cpu_throttle_increment,
3590 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3591 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3592 parameters.max_bandwidth, MAX_THROTTLE),
3593 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3594 parameters.downtime_limit,
3595 DEFAULT_MIGRATE_SET_DOWNTIME),
3596 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3597 parameters.x_checkpoint_delay,
3598 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3599 DEFINE_PROP_UINT8("multifd-channels", MigrationState,
3600 parameters.multifd_channels,
3601 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3602 DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
3603 parameters.multifd_compression,
3604 DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
3605 DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
3606 parameters.multifd_zlib_level,
3607 DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
3608 DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
3609 parameters.multifd_zstd_level,
3610 DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
3611 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3612 parameters.xbzrle_cache_size,
3613 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3614 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3615 parameters.max_postcopy_bandwidth,
3616 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3617 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3618 parameters.max_cpu_throttle,
3619 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3620 DEFINE_PROP_SIZE("announce-initial", MigrationState,
3621 parameters.announce_initial,
3622 DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
3623 DEFINE_PROP_SIZE("announce-max", MigrationState,
3624 parameters.announce_max,
3625 DEFAULT_MIGRATE_ANNOUNCE_MAX),
3626 DEFINE_PROP_SIZE("announce-rounds", MigrationState,
3627 parameters.announce_rounds,
3628 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
3629 DEFINE_PROP_SIZE("announce-step", MigrationState,
3630 parameters.announce_step,
3631 DEFAULT_MIGRATE_ANNOUNCE_STEP),
3633 /* Migration capabilities */
3634 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3635 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3636 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3637 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3638 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3639 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3640 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3641 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3642 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3643 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3644 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3645 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
3647 DEFINE_PROP_END_OF_LIST(),
3650 static void migration_class_init(ObjectClass *klass, void *data)
3652 DeviceClass *dc = DEVICE_CLASS(klass);
3654 dc->user_creatable = false;
3655 device_class_set_props(dc, migration_properties);
3658 static void migration_instance_finalize(Object *obj)
3660 MigrationState *ms = MIGRATION_OBJ(obj);
3661 MigrationParameters *params = &ms->parameters;
3663 qemu_mutex_destroy(&ms->error_mutex);
3664 qemu_mutex_destroy(&ms->qemu_file_lock);
3665 g_free(params->tls_hostname);
3666 g_free(params->tls_creds);
3667 qemu_sem_destroy(&ms->wait_unplug_sem);
3668 qemu_sem_destroy(&ms->rate_limit_sem);
3669 qemu_sem_destroy(&ms->pause_sem);
3670 qemu_sem_destroy(&ms->postcopy_pause_sem);
3671 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3672 qemu_sem_destroy(&ms->rp_state.rp_sem);
3673 error_free(ms->error);
3676 static void migration_instance_init(Object *obj)
3678 MigrationState *ms = MIGRATION_OBJ(obj);
3679 MigrationParameters *params = &ms->parameters;
3681 ms->state = MIGRATION_STATUS_NONE;
3682 ms->mbps = -1;
3683 ms->pages_per_second = -1;
3684 qemu_sem_init(&ms->pause_sem, 0);
3685 qemu_mutex_init(&ms->error_mutex);
3687 params->tls_hostname = g_strdup("");
3688 params->tls_creds = g_strdup("");
3690 /* Set has_* up only for parameter checks */
3691 params->has_compress_level = true;
3692 params->has_compress_threads = true;
3693 params->has_decompress_threads = true;
3694 params->has_throttle_trigger_threshold = true;
3695 params->has_cpu_throttle_initial = true;
3696 params->has_cpu_throttle_increment = true;
3697 params->has_max_bandwidth = true;
3698 params->has_downtime_limit = true;
3699 params->has_x_checkpoint_delay = true;
3700 params->has_block_incremental = true;
3701 params->has_multifd_channels = true;
3702 params->has_multifd_compression = true;
3703 params->has_multifd_zlib_level = true;
3704 params->has_multifd_zstd_level = true;
3705 params->has_xbzrle_cache_size = true;
3706 params->has_max_postcopy_bandwidth = true;
3707 params->has_max_cpu_throttle = true;
3708 params->has_announce_initial = true;
3709 params->has_announce_max = true;
3710 params->has_announce_rounds = true;
3711 params->has_announce_step = true;
3713 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3714 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3715 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3716 qemu_sem_init(&ms->rate_limit_sem, 0);
3717 qemu_sem_init(&ms->wait_unplug_sem, 0);
3718 qemu_mutex_init(&ms->qemu_file_lock);
3722 * Return true if check pass, false otherwise. Error will be put
3723 * inside errp if provided.
3725 static bool migration_object_check(MigrationState *ms, Error **errp)
3727 MigrationCapabilityStatusList *head = NULL;
3728 /* Assuming all off */
3729 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3730 int i;
3732 if (!migrate_params_check(&ms->parameters, errp)) {
3733 return false;
3736 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3737 if (ms->enabled_capabilities[i]) {
3738 head = migrate_cap_add(head, i, true);
3742 ret = migrate_caps_check(cap_list, head, errp);
3744 /* It works with head == NULL */
3745 qapi_free_MigrationCapabilityStatusList(head);
3747 return ret;
3750 static const TypeInfo migration_type = {
3751 .name = TYPE_MIGRATION,
3753 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3754 * not created using qdev_create(), it is not attached to the qdev
3755 * device tree, and it is never realized.
3757 * TODO: Make this TYPE_OBJECT once QOM provides something like
3758 * TYPE_DEVICE's "-global" properties.
3760 .parent = TYPE_DEVICE,
3761 .class_init = migration_class_init,
3762 .class_size = sizeof(MigrationClass),
3763 .instance_size = sizeof(MigrationState),
3764 .instance_init = migration_instance_init,
3765 .instance_finalize = migration_instance_finalize,
3768 static void register_migration_types(void)
3770 type_register_static(&migration_type);
3773 type_init(register_migration_types);