migration: fix COLO broken caused by a previous commit
[qemu/kevin.git] / migration / migration.c
blob92272250f45e00eed7f8dae2878543c6233d4159
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_CPU_THROTTLE_INITIAL 20
82 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
83 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
85 /* Migration XBZRLE default cache size */
86 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
88 /* The delay time (in ms) between two COLO checkpoints */
89 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
90 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
91 #define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE
92 /* 0: means nocompress, 1: best speed, ... 9: best compress ratio */
93 #define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1
94 /* 0: means nocompress, 1: best speed, ... 20: best compress ratio */
95 #define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1
97 /* Background transfer rate for postcopy, 0 means unlimited, note
98 * that page requests can still exceed this limit.
100 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
103 * Parameters for self_announce_delay giving a stream of RARP/ARP
104 * packets after migration.
106 #define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50
107 #define DEFAULT_MIGRATE_ANNOUNCE_MAX 550
108 #define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5
109 #define DEFAULT_MIGRATE_ANNOUNCE_STEP 100
111 static NotifierList migration_state_notifiers =
112 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
114 static bool deferred_incoming;
116 /* Messages sent on the return path from destination to source */
117 enum mig_rp_message_type {
118 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
119 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
120 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
122 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
123 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
124 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
125 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
127 MIG_RP_MSG_MAX
130 /* When we add fault tolerance, we could have several
131 migrations at once. For now we don't need to add
132 dynamic creation of migration */
134 static MigrationState *current_migration;
135 static MigrationIncomingState *current_incoming;
137 static bool migration_object_check(MigrationState *ms, Error **errp);
138 static int migration_maybe_pause(MigrationState *s,
139 int *current_active_state,
140 int new_state);
141 static void migrate_fd_cancel(MigrationState *s);
143 void migration_object_init(void)
145 MachineState *ms = MACHINE(qdev_get_machine());
146 Error *err = NULL;
148 /* This can only be called once. */
149 assert(!current_migration);
150 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
153 * Init the migrate incoming object as well no matter whether
154 * we'll use it or not.
156 assert(!current_incoming);
157 current_incoming = g_new0(MigrationIncomingState, 1);
158 current_incoming->state = MIGRATION_STATUS_NONE;
159 current_incoming->postcopy_remote_fds =
160 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
161 qemu_mutex_init(&current_incoming->rp_mutex);
162 qemu_event_init(&current_incoming->main_thread_load_event, false);
163 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
164 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
166 init_dirty_bitmap_incoming_migration();
168 if (!migration_object_check(current_migration, &err)) {
169 error_report_err(err);
170 exit(1);
174 * We cannot really do this in migration_instance_init() since at
175 * that time global properties are not yet applied, then this
176 * value will be definitely replaced by something else.
178 if (ms->enforce_config_section) {
179 current_migration->send_configuration = true;
183 void migration_shutdown(void)
186 * Cancel the current migration - that will (eventually)
187 * stop the migration using this structure
189 migrate_fd_cancel(current_migration);
190 object_unref(OBJECT(current_migration));
193 /* For outgoing */
194 MigrationState *migrate_get_current(void)
196 /* This can only be called after the object created. */
197 assert(current_migration);
198 return current_migration;
201 MigrationIncomingState *migration_incoming_get_current(void)
203 assert(current_incoming);
204 return current_incoming;
207 void migration_incoming_state_destroy(void)
209 struct MigrationIncomingState *mis = migration_incoming_get_current();
211 if (mis->to_src_file) {
212 /* Tell source that we are done */
213 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
214 qemu_fclose(mis->to_src_file);
215 mis->to_src_file = NULL;
218 if (mis->from_src_file) {
219 qemu_fclose(mis->from_src_file);
220 mis->from_src_file = NULL;
222 if (mis->postcopy_remote_fds) {
223 g_array_free(mis->postcopy_remote_fds, TRUE);
224 mis->postcopy_remote_fds = NULL;
227 qemu_event_reset(&mis->main_thread_load_event);
229 if (mis->socket_address_list) {
230 qapi_free_SocketAddressList(mis->socket_address_list);
231 mis->socket_address_list = NULL;
235 static void migrate_generate_event(int new_state)
237 if (migrate_use_events()) {
238 qapi_event_send_migration(new_state);
242 static bool migrate_late_block_activate(void)
244 MigrationState *s;
246 s = migrate_get_current();
248 return s->enabled_capabilities[
249 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
253 * Called on -incoming with a defer: uri.
254 * The migration can be started later after any parameters have been
255 * changed.
257 static void deferred_incoming_migration(Error **errp)
259 if (deferred_incoming) {
260 error_setg(errp, "Incoming migration already deferred");
262 deferred_incoming = true;
266 * Send a message on the return channel back to the source
267 * of the migration.
269 static int migrate_send_rp_message(MigrationIncomingState *mis,
270 enum mig_rp_message_type message_type,
271 uint16_t len, void *data)
273 int ret = 0;
275 trace_migrate_send_rp_message((int)message_type, len);
276 qemu_mutex_lock(&mis->rp_mutex);
279 * It's possible that the file handle got lost due to network
280 * failures.
282 if (!mis->to_src_file) {
283 ret = -EIO;
284 goto error;
287 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
288 qemu_put_be16(mis->to_src_file, len);
289 qemu_put_buffer(mis->to_src_file, data, len);
290 qemu_fflush(mis->to_src_file);
292 /* It's possible that qemu file got error during sending */
293 ret = qemu_file_get_error(mis->to_src_file);
295 error:
296 qemu_mutex_unlock(&mis->rp_mutex);
297 return ret;
300 /* Request a range of pages from the source VM at the given
301 * start address.
302 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
303 * as the last request (a name must have been given previously)
304 * Start: Address offset within the RB
305 * Len: Length in bytes required - must be a multiple of pagesize
307 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
308 ram_addr_t start, size_t len)
310 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
311 size_t msglen = 12; /* start + len */
312 enum mig_rp_message_type msg_type;
314 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
315 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
317 if (rbname) {
318 int rbname_len = strlen(rbname);
319 assert(rbname_len < 256);
321 bufc[msglen++] = rbname_len;
322 memcpy(bufc + msglen, rbname, rbname_len);
323 msglen += rbname_len;
324 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
325 } else {
326 msg_type = MIG_RP_MSG_REQ_PAGES;
329 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
332 static bool migration_colo_enabled;
333 bool migration_incoming_colo_enabled(void)
335 return migration_colo_enabled;
338 void migration_incoming_disable_colo(void)
340 migration_colo_enabled = false;
343 void migration_incoming_enable_colo(void)
345 migration_colo_enabled = true;
348 void migrate_add_address(SocketAddress *address)
350 MigrationIncomingState *mis = migration_incoming_get_current();
351 SocketAddressList *addrs;
353 addrs = g_new0(SocketAddressList, 1);
354 addrs->next = mis->socket_address_list;
355 mis->socket_address_list = addrs;
356 addrs->value = QAPI_CLONE(SocketAddress, address);
359 void qemu_start_incoming_migration(const char *uri, Error **errp)
361 const char *p;
363 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
364 if (!strcmp(uri, "defer")) {
365 deferred_incoming_migration(errp);
366 } else if (strstart(uri, "tcp:", &p)) {
367 tcp_start_incoming_migration(p, errp);
368 #ifdef CONFIG_RDMA
369 } else if (strstart(uri, "rdma:", &p)) {
370 rdma_start_incoming_migration(p, errp);
371 #endif
372 } else if (strstart(uri, "exec:", &p)) {
373 exec_start_incoming_migration(p, errp);
374 } else if (strstart(uri, "unix:", &p)) {
375 unix_start_incoming_migration(p, errp);
376 } else if (strstart(uri, "fd:", &p)) {
377 fd_start_incoming_migration(p, errp);
378 } else {
379 error_setg(errp, "unknown migration protocol: %s", uri);
383 static void process_incoming_migration_bh(void *opaque)
385 Error *local_err = NULL;
386 MigrationIncomingState *mis = opaque;
388 /* If capability late_block_activate is set:
389 * Only fire up the block code now if we're going to restart the
390 * VM, else 'cont' will do it.
391 * This causes file locking to happen; so we don't want it to happen
392 * unless we really are starting the VM.
394 if (!migrate_late_block_activate() ||
395 (autostart && (!global_state_received() ||
396 global_state_get_runstate() == RUN_STATE_RUNNING))) {
397 /* Make sure all file formats flush their mutable metadata.
398 * If we get an error here, just don't restart the VM yet. */
399 bdrv_invalidate_cache_all(&local_err);
400 if (local_err) {
401 error_report_err(local_err);
402 local_err = NULL;
403 autostart = false;
408 * This must happen after all error conditions are dealt with and
409 * we're sure the VM is going to be running on this host.
411 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
413 if (multifd_load_cleanup(&local_err) != 0) {
414 error_report_err(local_err);
415 autostart = false;
417 /* If global state section was not received or we are in running
418 state, we need to obey autostart. Any other state is set with
419 runstate_set. */
421 dirty_bitmap_mig_before_vm_start();
423 if (!global_state_received() ||
424 global_state_get_runstate() == RUN_STATE_RUNNING) {
425 if (autostart) {
426 vm_start();
427 } else {
428 runstate_set(RUN_STATE_PAUSED);
430 } else if (migration_incoming_colo_enabled()) {
431 migration_incoming_disable_colo();
432 vm_start();
433 } else {
434 runstate_set(global_state_get_runstate());
437 * This must happen after any state changes since as soon as an external
438 * observer sees this event they might start to prod at the VM assuming
439 * it's ready to use.
441 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
442 MIGRATION_STATUS_COMPLETED);
443 qemu_bh_delete(mis->bh);
444 migration_incoming_state_destroy();
447 static void process_incoming_migration_co(void *opaque)
449 MigrationIncomingState *mis = migration_incoming_get_current();
450 PostcopyState ps;
451 int ret;
452 Error *local_err = NULL;
454 assert(mis->from_src_file);
455 mis->migration_incoming_co = qemu_coroutine_self();
456 mis->largest_page_size = qemu_ram_pagesize_largest();
457 postcopy_state_set(POSTCOPY_INCOMING_NONE);
458 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
459 MIGRATION_STATUS_ACTIVE);
460 ret = qemu_loadvm_state(mis->from_src_file);
462 ps = postcopy_state_get();
463 trace_process_incoming_migration_co_end(ret, ps);
464 if (ps != POSTCOPY_INCOMING_NONE) {
465 if (ps == POSTCOPY_INCOMING_ADVISE) {
467 * Where a migration had postcopy enabled (and thus went to advise)
468 * but managed to complete within the precopy period, we can use
469 * the normal exit.
471 postcopy_ram_incoming_cleanup(mis);
472 } else if (ret >= 0) {
474 * Postcopy was started, cleanup should happen at the end of the
475 * postcopy thread.
477 trace_process_incoming_migration_co_postcopy_end_main();
478 return;
480 /* Else if something went wrong then just fall out of the normal exit */
483 /* we get COLO info, and know if we are in COLO mode */
484 if (!ret && migration_incoming_colo_enabled()) {
485 /* Make sure all file formats flush their mutable metadata */
486 bdrv_invalidate_cache_all(&local_err);
487 if (local_err) {
488 error_report_err(local_err);
489 goto fail;
492 if (colo_init_ram_cache() < 0) {
493 error_report("Init ram cache failed");
494 goto fail;
497 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
498 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
499 mis->have_colo_incoming_thread = true;
500 qemu_coroutine_yield();
502 /* Wait checkpoint incoming thread exit before free resource */
503 qemu_thread_join(&mis->colo_incoming_thread);
504 /* We hold the global iothread lock, so it is safe here */
505 colo_release_ram_cache();
508 if (ret < 0) {
509 error_report("load of migration failed: %s", strerror(-ret));
510 goto fail;
512 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
513 qemu_bh_schedule(mis->bh);
514 mis->migration_incoming_co = NULL;
515 return;
516 fail:
517 local_err = NULL;
518 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
519 MIGRATION_STATUS_FAILED);
520 qemu_fclose(mis->from_src_file);
521 if (multifd_load_cleanup(&local_err) != 0) {
522 error_report_err(local_err);
524 exit(EXIT_FAILURE);
528 * @migration_incoming_setup: Setup incoming migration
530 * Returns 0 for no error or 1 for error
532 * @f: file for main migration channel
533 * @errp: where to put errors
535 static int migration_incoming_setup(QEMUFile *f, Error **errp)
537 MigrationIncomingState *mis = migration_incoming_get_current();
538 Error *local_err = NULL;
540 if (multifd_load_setup(&local_err) != 0) {
541 /* We haven't been able to create multifd threads
542 nothing better to do */
543 error_report_err(local_err);
544 exit(EXIT_FAILURE);
547 if (!mis->from_src_file) {
548 mis->from_src_file = f;
550 qemu_file_set_blocking(f, false);
551 return 0;
554 void migration_incoming_process(void)
556 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
557 qemu_coroutine_enter(co);
560 /* Returns true if recovered from a paused migration, otherwise false */
561 static bool postcopy_try_recover(QEMUFile *f)
563 MigrationIncomingState *mis = migration_incoming_get_current();
565 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
566 /* Resumed from a paused postcopy migration */
568 mis->from_src_file = f;
569 /* Postcopy has standalone thread to do vm load */
570 qemu_file_set_blocking(f, true);
572 /* Re-configure the return path */
573 mis->to_src_file = qemu_file_get_return_path(f);
575 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
576 MIGRATION_STATUS_POSTCOPY_RECOVER);
579 * Here, we only wake up the main loading thread (while the
580 * fault thread will still be waiting), so that we can receive
581 * commands from source now, and answer it if needed. The
582 * fault thread will be woken up afterwards until we are sure
583 * that source is ready to reply to page requests.
585 qemu_sem_post(&mis->postcopy_pause_sem_dst);
586 return true;
589 return false;
592 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
594 Error *local_err = NULL;
596 if (postcopy_try_recover(f)) {
597 return;
600 if (migration_incoming_setup(f, &local_err)) {
601 if (local_err) {
602 error_propagate(errp, local_err);
604 return;
606 migration_incoming_process();
609 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
611 MigrationIncomingState *mis = migration_incoming_get_current();
612 Error *local_err = NULL;
613 bool start_migration;
615 if (!mis->from_src_file) {
616 /* The first connection (multifd may have multiple) */
617 QEMUFile *f = qemu_fopen_channel_input(ioc);
619 /* If it's a recovery, we're done */
620 if (postcopy_try_recover(f)) {
621 return;
624 if (migration_incoming_setup(f, &local_err)) {
625 if (local_err) {
626 error_propagate(errp, local_err);
628 return;
632 * Common migration only needs one channel, so we can start
633 * right now. Multifd needs more than one channel, we wait.
635 start_migration = !migrate_use_multifd();
636 } else {
637 /* Multiple connections */
638 assert(migrate_use_multifd());
639 start_migration = multifd_recv_new_channel(ioc, &local_err);
640 if (local_err) {
641 error_propagate(errp, local_err);
642 return;
646 if (start_migration) {
647 migration_incoming_process();
652 * @migration_has_all_channels: We have received all channels that we need
654 * Returns true when we have got connections to all the channels that
655 * we need for migration.
657 bool migration_has_all_channels(void)
659 MigrationIncomingState *mis = migration_incoming_get_current();
660 bool all_channels;
662 all_channels = multifd_recv_all_channels_created();
664 return all_channels && mis->from_src_file != NULL;
668 * Send a 'SHUT' message on the return channel with the given value
669 * to indicate that we've finished with the RP. Non-0 value indicates
670 * error.
672 void migrate_send_rp_shut(MigrationIncomingState *mis,
673 uint32_t value)
675 uint32_t buf;
677 buf = cpu_to_be32(value);
678 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
682 * Send a 'PONG' message on the return channel with the given value
683 * (normally in response to a 'PING')
685 void migrate_send_rp_pong(MigrationIncomingState *mis,
686 uint32_t value)
688 uint32_t buf;
690 buf = cpu_to_be32(value);
691 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
694 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
695 char *block_name)
697 char buf[512];
698 int len;
699 int64_t res;
702 * First, we send the header part. It contains only the len of
703 * idstr, and the idstr itself.
705 len = strlen(block_name);
706 buf[0] = len;
707 memcpy(buf + 1, block_name, len);
709 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
710 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
711 __func__);
712 return;
715 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
718 * Next, we dump the received bitmap to the stream.
720 * TODO: currently we are safe since we are the only one that is
721 * using the to_src_file handle (fault thread is still paused),
722 * and it's ok even not taking the mutex. However the best way is
723 * to take the lock before sending the message header, and release
724 * the lock after sending the bitmap.
726 qemu_mutex_lock(&mis->rp_mutex);
727 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
728 qemu_mutex_unlock(&mis->rp_mutex);
730 trace_migrate_send_rp_recv_bitmap(block_name, res);
733 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
735 uint32_t buf;
737 buf = cpu_to_be32(value);
738 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
741 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
743 MigrationCapabilityStatusList *head = NULL;
744 MigrationCapabilityStatusList *caps;
745 MigrationState *s = migrate_get_current();
746 int i;
748 caps = NULL; /* silence compiler warning */
749 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
750 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
751 if (i == MIGRATION_CAPABILITY_BLOCK) {
752 continue;
754 #endif
755 if (head == NULL) {
756 head = g_malloc0(sizeof(*caps));
757 caps = head;
758 } else {
759 caps->next = g_malloc0(sizeof(*caps));
760 caps = caps->next;
762 caps->value =
763 g_malloc(sizeof(*caps->value));
764 caps->value->capability = i;
765 caps->value->state = s->enabled_capabilities[i];
768 return head;
771 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
773 MigrationParameters *params;
774 MigrationState *s = migrate_get_current();
776 /* TODO use QAPI_CLONE() instead of duplicating it inline */
777 params = g_malloc0(sizeof(*params));
778 params->has_compress_level = true;
779 params->compress_level = s->parameters.compress_level;
780 params->has_compress_threads = true;
781 params->compress_threads = s->parameters.compress_threads;
782 params->has_compress_wait_thread = true;
783 params->compress_wait_thread = s->parameters.compress_wait_thread;
784 params->has_decompress_threads = true;
785 params->decompress_threads = s->parameters.decompress_threads;
786 params->has_cpu_throttle_initial = true;
787 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
788 params->has_cpu_throttle_increment = true;
789 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
790 params->has_tls_creds = true;
791 params->tls_creds = g_strdup(s->parameters.tls_creds);
792 params->has_tls_hostname = true;
793 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
794 params->has_tls_authz = true;
795 params->tls_authz = g_strdup(s->parameters.tls_authz);
796 params->has_max_bandwidth = true;
797 params->max_bandwidth = s->parameters.max_bandwidth;
798 params->has_downtime_limit = true;
799 params->downtime_limit = s->parameters.downtime_limit;
800 params->has_x_checkpoint_delay = true;
801 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
802 params->has_block_incremental = true;
803 params->block_incremental = s->parameters.block_incremental;
804 params->has_multifd_channels = true;
805 params->multifd_channels = s->parameters.multifd_channels;
806 params->has_multifd_compression = true;
807 params->multifd_compression = s->parameters.multifd_compression;
808 params->has_multifd_zlib_level = true;
809 params->multifd_zlib_level = s->parameters.multifd_zlib_level;
810 params->has_multifd_zstd_level = true;
811 params->multifd_zstd_level = s->parameters.multifd_zstd_level;
812 params->has_xbzrle_cache_size = true;
813 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
814 params->has_max_postcopy_bandwidth = true;
815 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
816 params->has_max_cpu_throttle = true;
817 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
818 params->has_announce_initial = true;
819 params->announce_initial = s->parameters.announce_initial;
820 params->has_announce_max = true;
821 params->announce_max = s->parameters.announce_max;
822 params->has_announce_rounds = true;
823 params->announce_rounds = s->parameters.announce_rounds;
824 params->has_announce_step = true;
825 params->announce_step = s->parameters.announce_step;
827 return params;
830 AnnounceParameters *migrate_announce_params(void)
832 static AnnounceParameters ap;
834 MigrationState *s = migrate_get_current();
836 ap.initial = s->parameters.announce_initial;
837 ap.max = s->parameters.announce_max;
838 ap.rounds = s->parameters.announce_rounds;
839 ap.step = s->parameters.announce_step;
841 return &ap;
845 * Return true if we're already in the middle of a migration
846 * (i.e. any of the active or setup states)
848 bool migration_is_setup_or_active(int state)
850 switch (state) {
851 case MIGRATION_STATUS_ACTIVE:
852 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
853 case MIGRATION_STATUS_POSTCOPY_PAUSED:
854 case MIGRATION_STATUS_POSTCOPY_RECOVER:
855 case MIGRATION_STATUS_SETUP:
856 case MIGRATION_STATUS_PRE_SWITCHOVER:
857 case MIGRATION_STATUS_DEVICE:
858 case MIGRATION_STATUS_WAIT_UNPLUG:
859 return true;
861 default:
862 return false;
867 bool migration_is_running(int state)
869 switch (state) {
870 case MIGRATION_STATUS_ACTIVE:
871 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
872 case MIGRATION_STATUS_POSTCOPY_PAUSED:
873 case MIGRATION_STATUS_POSTCOPY_RECOVER:
874 case MIGRATION_STATUS_SETUP:
875 case MIGRATION_STATUS_PRE_SWITCHOVER:
876 case MIGRATION_STATUS_DEVICE:
877 case MIGRATION_STATUS_WAIT_UNPLUG:
878 case MIGRATION_STATUS_CANCELLING:
879 return true;
881 default:
882 return false;
887 static void populate_time_info(MigrationInfo *info, MigrationState *s)
889 info->has_status = true;
890 info->has_setup_time = true;
891 info->setup_time = s->setup_time;
892 if (s->state == MIGRATION_STATUS_COMPLETED) {
893 info->has_total_time = true;
894 info->total_time = s->total_time;
895 info->has_downtime = true;
896 info->downtime = s->downtime;
897 } else {
898 info->has_total_time = true;
899 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
900 s->start_time;
901 info->has_expected_downtime = true;
902 info->expected_downtime = s->expected_downtime;
906 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
908 info->has_ram = true;
909 info->ram = g_malloc0(sizeof(*info->ram));
910 info->ram->transferred = ram_counters.transferred;
911 info->ram->total = ram_bytes_total();
912 info->ram->duplicate = ram_counters.duplicate;
913 /* legacy value. It is not used anymore */
914 info->ram->skipped = 0;
915 info->ram->normal = ram_counters.normal;
916 info->ram->normal_bytes = ram_counters.normal *
917 qemu_target_page_size();
918 info->ram->mbps = s->mbps;
919 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
920 info->ram->postcopy_requests = ram_counters.postcopy_requests;
921 info->ram->page_size = qemu_target_page_size();
922 info->ram->multifd_bytes = ram_counters.multifd_bytes;
923 info->ram->pages_per_second = s->pages_per_second;
925 if (migrate_use_xbzrle()) {
926 info->has_xbzrle_cache = true;
927 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
928 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
929 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
930 info->xbzrle_cache->pages = xbzrle_counters.pages;
931 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
932 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
933 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
936 if (migrate_use_compression()) {
937 info->has_compression = true;
938 info->compression = g_malloc0(sizeof(*info->compression));
939 info->compression->pages = compression_counters.pages;
940 info->compression->busy = compression_counters.busy;
941 info->compression->busy_rate = compression_counters.busy_rate;
942 info->compression->compressed_size =
943 compression_counters.compressed_size;
944 info->compression->compression_rate =
945 compression_counters.compression_rate;
948 if (cpu_throttle_active()) {
949 info->has_cpu_throttle_percentage = true;
950 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
953 if (s->state != MIGRATION_STATUS_COMPLETED) {
954 info->ram->remaining = ram_bytes_remaining();
955 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
959 static void populate_disk_info(MigrationInfo *info)
961 if (blk_mig_active()) {
962 info->has_disk = true;
963 info->disk = g_malloc0(sizeof(*info->disk));
964 info->disk->transferred = blk_mig_bytes_transferred();
965 info->disk->remaining = blk_mig_bytes_remaining();
966 info->disk->total = blk_mig_bytes_total();
970 static void fill_source_migration_info(MigrationInfo *info)
972 MigrationState *s = migrate_get_current();
974 switch (s->state) {
975 case MIGRATION_STATUS_NONE:
976 /* no migration has happened ever */
977 /* do not overwrite destination migration status */
978 return;
979 break;
980 case MIGRATION_STATUS_SETUP:
981 info->has_status = true;
982 info->has_total_time = false;
983 break;
984 case MIGRATION_STATUS_ACTIVE:
985 case MIGRATION_STATUS_CANCELLING:
986 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
987 case MIGRATION_STATUS_PRE_SWITCHOVER:
988 case MIGRATION_STATUS_DEVICE:
989 case MIGRATION_STATUS_POSTCOPY_PAUSED:
990 case MIGRATION_STATUS_POSTCOPY_RECOVER:
991 /* TODO add some postcopy stats */
992 populate_time_info(info, s);
993 populate_ram_info(info, s);
994 populate_disk_info(info);
995 break;
996 case MIGRATION_STATUS_COLO:
997 info->has_status = true;
998 /* TODO: display COLO specific information (checkpoint info etc.) */
999 break;
1000 case MIGRATION_STATUS_COMPLETED:
1001 populate_time_info(info, s);
1002 populate_ram_info(info, s);
1003 break;
1004 case MIGRATION_STATUS_FAILED:
1005 info->has_status = true;
1006 if (s->error) {
1007 info->has_error_desc = true;
1008 info->error_desc = g_strdup(error_get_pretty(s->error));
1010 break;
1011 case MIGRATION_STATUS_CANCELLED:
1012 info->has_status = true;
1013 break;
1014 case MIGRATION_STATUS_WAIT_UNPLUG:
1015 info->has_status = true;
1016 break;
1018 info->status = s->state;
1022 * @migration_caps_check - check capability validity
1024 * @cap_list: old capability list, array of bool
1025 * @params: new capabilities to be applied soon
1026 * @errp: set *errp if the check failed, with reason
1028 * Returns true if check passed, otherwise false.
1030 static bool migrate_caps_check(bool *cap_list,
1031 MigrationCapabilityStatusList *params,
1032 Error **errp)
1034 MigrationCapabilityStatusList *cap;
1035 bool old_postcopy_cap;
1036 MigrationIncomingState *mis = migration_incoming_get_current();
1038 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1040 for (cap = params; cap; cap = cap->next) {
1041 cap_list[cap->value->capability] = cap->value->state;
1044 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
1045 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
1046 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
1047 "block migration");
1048 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
1049 return false;
1051 #endif
1053 #ifndef CONFIG_REPLICATION
1054 if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
1055 error_setg(errp, "QEMU compiled without replication module"
1056 " can't enable COLO");
1057 error_append_hint(errp, "Please enable replication before COLO.\n");
1058 return false;
1060 #endif
1062 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1063 /* This check is reasonably expensive, so only when it's being
1064 * set the first time, also it's only the destination that needs
1065 * special support.
1067 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
1068 !postcopy_ram_supported_by_host(mis)) {
1069 /* postcopy_ram_supported_by_host will have emitted a more
1070 * detailed message
1072 error_setg(errp, "Postcopy is not supported");
1073 return false;
1076 if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1077 error_setg(errp, "Postcopy is not compatible with ignore-shared");
1078 return false;
1082 return true;
1085 static void fill_destination_migration_info(MigrationInfo *info)
1087 MigrationIncomingState *mis = migration_incoming_get_current();
1089 if (mis->socket_address_list) {
1090 info->has_socket_address = true;
1091 info->socket_address =
1092 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1095 switch (mis->state) {
1096 case MIGRATION_STATUS_NONE:
1097 return;
1098 break;
1099 case MIGRATION_STATUS_SETUP:
1100 case MIGRATION_STATUS_CANCELLING:
1101 case MIGRATION_STATUS_CANCELLED:
1102 case MIGRATION_STATUS_ACTIVE:
1103 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1104 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1105 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1106 case MIGRATION_STATUS_FAILED:
1107 case MIGRATION_STATUS_COLO:
1108 info->has_status = true;
1109 break;
1110 case MIGRATION_STATUS_COMPLETED:
1111 info->has_status = true;
1112 fill_destination_postcopy_migration_info(info);
1113 break;
1115 info->status = mis->state;
1118 MigrationInfo *qmp_query_migrate(Error **errp)
1120 MigrationInfo *info = g_malloc0(sizeof(*info));
1122 fill_destination_migration_info(info);
1123 fill_source_migration_info(info);
1125 return info;
1128 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1129 Error **errp)
1131 MigrationState *s = migrate_get_current();
1132 MigrationCapabilityStatusList *cap;
1133 bool cap_list[MIGRATION_CAPABILITY__MAX];
1135 if (migration_is_running(s->state)) {
1136 error_setg(errp, QERR_MIGRATION_ACTIVE);
1137 return;
1140 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1141 if (!migrate_caps_check(cap_list, params, errp)) {
1142 return;
1145 for (cap = params; cap; cap = cap->next) {
1146 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1151 * Check whether the parameters are valid. Error will be put into errp
1152 * (if provided). Return true if valid, otherwise false.
1154 static bool migrate_params_check(MigrationParameters *params, Error **errp)
1156 if (params->has_compress_level &&
1157 (params->compress_level > 9)) {
1158 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1159 "is invalid, it should be in the range of 0 to 9");
1160 return false;
1163 if (params->has_compress_threads && (params->compress_threads < 1)) {
1164 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1165 "compress_threads",
1166 "is invalid, it should be in the range of 1 to 255");
1167 return false;
1170 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1171 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1172 "decompress_threads",
1173 "is invalid, it should be in the range of 1 to 255");
1174 return false;
1177 if (params->has_cpu_throttle_initial &&
1178 (params->cpu_throttle_initial < 1 ||
1179 params->cpu_throttle_initial > 99)) {
1180 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1181 "cpu_throttle_initial",
1182 "an integer in the range of 1 to 99");
1183 return false;
1186 if (params->has_cpu_throttle_increment &&
1187 (params->cpu_throttle_increment < 1 ||
1188 params->cpu_throttle_increment > 99)) {
1189 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1190 "cpu_throttle_increment",
1191 "an integer in the range of 1 to 99");
1192 return false;
1195 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1196 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
1197 " range of 0 to %zu bytes/second", SIZE_MAX);
1198 return false;
1201 if (params->has_downtime_limit &&
1202 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1203 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1204 "the range of 0 to %d milliseconds",
1205 MAX_MIGRATE_DOWNTIME);
1206 return false;
1209 /* x_checkpoint_delay is now always positive */
1211 if (params->has_multifd_channels && (params->multifd_channels < 1)) {
1212 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1213 "multifd_channels",
1214 "is invalid, it should be in the range of 1 to 255");
1215 return false;
1218 if (params->has_multifd_zlib_level &&
1219 (params->multifd_zlib_level > 9)) {
1220 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level",
1221 "is invalid, it should be in the range of 0 to 9");
1222 return false;
1225 if (params->has_multifd_zstd_level &&
1226 (params->multifd_zstd_level > 20)) {
1227 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level",
1228 "is invalid, it should be in the range of 0 to 20");
1229 return false;
1232 if (params->has_xbzrle_cache_size &&
1233 (params->xbzrle_cache_size < qemu_target_page_size() ||
1234 !is_power_of_2(params->xbzrle_cache_size))) {
1235 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1236 "xbzrle_cache_size",
1237 "is invalid, it should be bigger than target page size"
1238 " and a power of two");
1239 return false;
1242 if (params->has_max_cpu_throttle &&
1243 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1244 params->max_cpu_throttle > 99)) {
1245 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1246 "max_cpu_throttle",
1247 "an integer in the range of cpu_throttle_initial to 99");
1248 return false;
1251 if (params->has_announce_initial &&
1252 params->announce_initial > 100000) {
1253 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1254 "announce_initial",
1255 "is invalid, it must be less than 100000 ms");
1256 return false;
1258 if (params->has_announce_max &&
1259 params->announce_max > 100000) {
1260 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1261 "announce_max",
1262 "is invalid, it must be less than 100000 ms");
1263 return false;
1265 if (params->has_announce_rounds &&
1266 params->announce_rounds > 1000) {
1267 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1268 "announce_rounds",
1269 "is invalid, it must be in the range of 0 to 1000");
1270 return false;
1272 if (params->has_announce_step &&
1273 (params->announce_step < 1 ||
1274 params->announce_step > 10000)) {
1275 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1276 "announce_step",
1277 "is invalid, it must be in the range of 1 to 10000 ms");
1278 return false;
1280 return true;
1283 static void migrate_params_test_apply(MigrateSetParameters *params,
1284 MigrationParameters *dest)
1286 *dest = migrate_get_current()->parameters;
1288 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1290 if (params->has_compress_level) {
1291 dest->compress_level = params->compress_level;
1294 if (params->has_compress_threads) {
1295 dest->compress_threads = params->compress_threads;
1298 if (params->has_compress_wait_thread) {
1299 dest->compress_wait_thread = params->compress_wait_thread;
1302 if (params->has_decompress_threads) {
1303 dest->decompress_threads = params->decompress_threads;
1306 if (params->has_cpu_throttle_initial) {
1307 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1310 if (params->has_cpu_throttle_increment) {
1311 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1314 if (params->has_tls_creds) {
1315 assert(params->tls_creds->type == QTYPE_QSTRING);
1316 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1319 if (params->has_tls_hostname) {
1320 assert(params->tls_hostname->type == QTYPE_QSTRING);
1321 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1324 if (params->has_max_bandwidth) {
1325 dest->max_bandwidth = params->max_bandwidth;
1328 if (params->has_downtime_limit) {
1329 dest->downtime_limit = params->downtime_limit;
1332 if (params->has_x_checkpoint_delay) {
1333 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1336 if (params->has_block_incremental) {
1337 dest->block_incremental = params->block_incremental;
1339 if (params->has_multifd_channels) {
1340 dest->multifd_channels = params->multifd_channels;
1342 if (params->has_multifd_compression) {
1343 dest->multifd_compression = params->multifd_compression;
1345 if (params->has_xbzrle_cache_size) {
1346 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1348 if (params->has_max_postcopy_bandwidth) {
1349 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1351 if (params->has_max_cpu_throttle) {
1352 dest->max_cpu_throttle = params->max_cpu_throttle;
1354 if (params->has_announce_initial) {
1355 dest->announce_initial = params->announce_initial;
1357 if (params->has_announce_max) {
1358 dest->announce_max = params->announce_max;
1360 if (params->has_announce_rounds) {
1361 dest->announce_rounds = params->announce_rounds;
1363 if (params->has_announce_step) {
1364 dest->announce_step = params->announce_step;
1368 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1370 MigrationState *s = migrate_get_current();
1372 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1374 if (params->has_compress_level) {
1375 s->parameters.compress_level = params->compress_level;
1378 if (params->has_compress_threads) {
1379 s->parameters.compress_threads = params->compress_threads;
1382 if (params->has_compress_wait_thread) {
1383 s->parameters.compress_wait_thread = params->compress_wait_thread;
1386 if (params->has_decompress_threads) {
1387 s->parameters.decompress_threads = params->decompress_threads;
1390 if (params->has_cpu_throttle_initial) {
1391 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1394 if (params->has_cpu_throttle_increment) {
1395 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1398 if (params->has_tls_creds) {
1399 g_free(s->parameters.tls_creds);
1400 assert(params->tls_creds->type == QTYPE_QSTRING);
1401 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1404 if (params->has_tls_hostname) {
1405 g_free(s->parameters.tls_hostname);
1406 assert(params->tls_hostname->type == QTYPE_QSTRING);
1407 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1410 if (params->has_tls_authz) {
1411 g_free(s->parameters.tls_authz);
1412 assert(params->tls_authz->type == QTYPE_QSTRING);
1413 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1416 if (params->has_max_bandwidth) {
1417 s->parameters.max_bandwidth = params->max_bandwidth;
1418 if (s->to_dst_file && !migration_in_postcopy()) {
1419 qemu_file_set_rate_limit(s->to_dst_file,
1420 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1424 if (params->has_downtime_limit) {
1425 s->parameters.downtime_limit = params->downtime_limit;
1428 if (params->has_x_checkpoint_delay) {
1429 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1430 if (migration_in_colo_state()) {
1431 colo_checkpoint_notify(s);
1435 if (params->has_block_incremental) {
1436 s->parameters.block_incremental = params->block_incremental;
1438 if (params->has_multifd_channels) {
1439 s->parameters.multifd_channels = params->multifd_channels;
1441 if (params->has_multifd_compression) {
1442 s->parameters.multifd_compression = params->multifd_compression;
1444 if (params->has_xbzrle_cache_size) {
1445 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1446 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1448 if (params->has_max_postcopy_bandwidth) {
1449 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1450 if (s->to_dst_file && migration_in_postcopy()) {
1451 qemu_file_set_rate_limit(s->to_dst_file,
1452 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1455 if (params->has_max_cpu_throttle) {
1456 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1458 if (params->has_announce_initial) {
1459 s->parameters.announce_initial = params->announce_initial;
1461 if (params->has_announce_max) {
1462 s->parameters.announce_max = params->announce_max;
1464 if (params->has_announce_rounds) {
1465 s->parameters.announce_rounds = params->announce_rounds;
1467 if (params->has_announce_step) {
1468 s->parameters.announce_step = params->announce_step;
1472 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1474 MigrationParameters tmp;
1476 /* TODO Rewrite "" to null instead */
1477 if (params->has_tls_creds
1478 && params->tls_creds->type == QTYPE_QNULL) {
1479 qobject_unref(params->tls_creds->u.n);
1480 params->tls_creds->type = QTYPE_QSTRING;
1481 params->tls_creds->u.s = strdup("");
1483 /* TODO Rewrite "" to null instead */
1484 if (params->has_tls_hostname
1485 && params->tls_hostname->type == QTYPE_QNULL) {
1486 qobject_unref(params->tls_hostname->u.n);
1487 params->tls_hostname->type = QTYPE_QSTRING;
1488 params->tls_hostname->u.s = strdup("");
1491 migrate_params_test_apply(params, &tmp);
1493 if (!migrate_params_check(&tmp, errp)) {
1494 /* Invalid parameter */
1495 return;
1498 migrate_params_apply(params, errp);
1502 void qmp_migrate_start_postcopy(Error **errp)
1504 MigrationState *s = migrate_get_current();
1506 if (!migrate_postcopy()) {
1507 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1508 " the start of migration");
1509 return;
1512 if (s->state == MIGRATION_STATUS_NONE) {
1513 error_setg(errp, "Postcopy must be started after migration has been"
1514 " started");
1515 return;
1518 * we don't error if migration has finished since that would be racy
1519 * with issuing this command.
1521 atomic_set(&s->start_postcopy, true);
1524 /* shared migration helpers */
1526 void migrate_set_state(int *state, int old_state, int new_state)
1528 assert(new_state < MIGRATION_STATUS__MAX);
1529 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1530 trace_migrate_set_state(MigrationStatus_str(new_state));
1531 migrate_generate_event(new_state);
1535 static MigrationCapabilityStatusList *migrate_cap_add(
1536 MigrationCapabilityStatusList *list,
1537 MigrationCapability index,
1538 bool state)
1540 MigrationCapabilityStatusList *cap;
1542 cap = g_new0(MigrationCapabilityStatusList, 1);
1543 cap->value = g_new0(MigrationCapabilityStatus, 1);
1544 cap->value->capability = index;
1545 cap->value->state = state;
1546 cap->next = list;
1548 return cap;
1551 void migrate_set_block_enabled(bool value, Error **errp)
1553 MigrationCapabilityStatusList *cap;
1555 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1556 qmp_migrate_set_capabilities(cap, errp);
1557 qapi_free_MigrationCapabilityStatusList(cap);
1560 static void migrate_set_block_incremental(MigrationState *s, bool value)
1562 s->parameters.block_incremental = value;
1565 static void block_cleanup_parameters(MigrationState *s)
1567 if (s->must_remove_block_options) {
1568 /* setting to false can never fail */
1569 migrate_set_block_enabled(false, &error_abort);
1570 migrate_set_block_incremental(s, false);
1571 s->must_remove_block_options = false;
1575 static void migrate_fd_cleanup(MigrationState *s)
1577 qemu_bh_delete(s->cleanup_bh);
1578 s->cleanup_bh = NULL;
1580 qemu_savevm_state_cleanup();
1582 if (s->to_dst_file) {
1583 QEMUFile *tmp;
1585 trace_migrate_fd_cleanup();
1586 qemu_mutex_unlock_iothread();
1587 if (s->migration_thread_running) {
1588 qemu_thread_join(&s->thread);
1589 s->migration_thread_running = false;
1591 qemu_mutex_lock_iothread();
1593 multifd_save_cleanup();
1594 qemu_mutex_lock(&s->qemu_file_lock);
1595 tmp = s->to_dst_file;
1596 s->to_dst_file = NULL;
1597 qemu_mutex_unlock(&s->qemu_file_lock);
1599 * Close the file handle without the lock to make sure the
1600 * critical section won't block for long.
1602 qemu_fclose(tmp);
1605 assert(!migration_is_active(s));
1607 if (s->state == MIGRATION_STATUS_CANCELLING) {
1608 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1609 MIGRATION_STATUS_CANCELLED);
1612 if (s->error) {
1613 /* It is used on info migrate. We can't free it */
1614 error_report_err(error_copy(s->error));
1616 notifier_list_notify(&migration_state_notifiers, s);
1617 block_cleanup_parameters(s);
1620 static void migrate_fd_cleanup_schedule(MigrationState *s)
1623 * Ref the state for bh, because it may be called when
1624 * there're already no other refs
1626 object_ref(OBJECT(s));
1627 qemu_bh_schedule(s->cleanup_bh);
1630 static void migrate_fd_cleanup_bh(void *opaque)
1632 MigrationState *s = opaque;
1633 migrate_fd_cleanup(s);
1634 object_unref(OBJECT(s));
1637 void migrate_set_error(MigrationState *s, const Error *error)
1639 qemu_mutex_lock(&s->error_mutex);
1640 if (!s->error) {
1641 s->error = error_copy(error);
1643 qemu_mutex_unlock(&s->error_mutex);
1646 void migrate_fd_error(MigrationState *s, const Error *error)
1648 trace_migrate_fd_error(error_get_pretty(error));
1649 assert(s->to_dst_file == NULL);
1650 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1651 MIGRATION_STATUS_FAILED);
1652 migrate_set_error(s, error);
1655 static void migrate_fd_cancel(MigrationState *s)
1657 int old_state ;
1658 QEMUFile *f = migrate_get_current()->to_dst_file;
1659 trace_migrate_fd_cancel();
1661 if (s->rp_state.from_dst_file) {
1662 /* shutdown the rp socket, so causing the rp thread to shutdown */
1663 qemu_file_shutdown(s->rp_state.from_dst_file);
1666 do {
1667 old_state = s->state;
1668 if (!migration_is_running(old_state)) {
1669 break;
1671 /* If the migration is paused, kick it out of the pause */
1672 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1673 qemu_sem_post(&s->pause_sem);
1675 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1676 } while (s->state != MIGRATION_STATUS_CANCELLING);
1679 * If we're unlucky the migration code might be stuck somewhere in a
1680 * send/write while the network has failed and is waiting to timeout;
1681 * if we've got shutdown(2) available then we can force it to quit.
1682 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1683 * called in a bh, so there is no race against this cancel.
1685 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1686 qemu_file_shutdown(f);
1688 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1689 Error *local_err = NULL;
1691 bdrv_invalidate_cache_all(&local_err);
1692 if (local_err) {
1693 error_report_err(local_err);
1694 } else {
1695 s->block_inactive = false;
1700 void add_migration_state_change_notifier(Notifier *notify)
1702 notifier_list_add(&migration_state_notifiers, notify);
1705 void remove_migration_state_change_notifier(Notifier *notify)
1707 notifier_remove(notify);
1710 bool migration_in_setup(MigrationState *s)
1712 return s->state == MIGRATION_STATUS_SETUP;
1715 bool migration_has_finished(MigrationState *s)
1717 return s->state == MIGRATION_STATUS_COMPLETED;
1720 bool migration_has_failed(MigrationState *s)
1722 return (s->state == MIGRATION_STATUS_CANCELLED ||
1723 s->state == MIGRATION_STATUS_FAILED);
1726 bool migration_in_postcopy(void)
1728 MigrationState *s = migrate_get_current();
1730 switch (s->state) {
1731 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1732 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1733 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1734 return true;
1735 default:
1736 return false;
1740 bool migration_in_postcopy_after_devices(MigrationState *s)
1742 return migration_in_postcopy() && s->postcopy_after_devices;
1745 bool migration_is_idle(void)
1747 MigrationState *s = current_migration;
1749 if (!s) {
1750 return true;
1753 switch (s->state) {
1754 case MIGRATION_STATUS_NONE:
1755 case MIGRATION_STATUS_CANCELLED:
1756 case MIGRATION_STATUS_COMPLETED:
1757 case MIGRATION_STATUS_FAILED:
1758 return true;
1759 case MIGRATION_STATUS_SETUP:
1760 case MIGRATION_STATUS_CANCELLING:
1761 case MIGRATION_STATUS_ACTIVE:
1762 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1763 case MIGRATION_STATUS_COLO:
1764 case MIGRATION_STATUS_PRE_SWITCHOVER:
1765 case MIGRATION_STATUS_DEVICE:
1766 case MIGRATION_STATUS_WAIT_UNPLUG:
1767 return false;
1768 case MIGRATION_STATUS__MAX:
1769 g_assert_not_reached();
1772 return false;
1775 bool migration_is_active(MigrationState *s)
1777 return (s->state == MIGRATION_STATUS_ACTIVE ||
1778 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1781 void migrate_init(MigrationState *s)
1784 * Reinitialise all migration state, except
1785 * parameters/capabilities that the user set, and
1786 * locks.
1788 s->cleanup_bh = 0;
1789 s->to_dst_file = NULL;
1790 s->state = MIGRATION_STATUS_NONE;
1791 s->rp_state.from_dst_file = NULL;
1792 s->rp_state.error = false;
1793 s->mbps = 0.0;
1794 s->pages_per_second = 0.0;
1795 s->downtime = 0;
1796 s->expected_downtime = 0;
1797 s->setup_time = 0;
1798 s->start_postcopy = false;
1799 s->postcopy_after_devices = false;
1800 s->migration_thread_running = false;
1801 error_free(s->error);
1802 s->error = NULL;
1804 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1806 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1807 s->total_time = 0;
1808 s->vm_was_running = false;
1809 s->iteration_initial_bytes = 0;
1810 s->threshold_size = 0;
1813 static GSList *migration_blockers;
1815 int migrate_add_blocker(Error *reason, Error **errp)
1817 if (only_migratable) {
1818 error_propagate_prepend(errp, error_copy(reason),
1819 "disallowing migration blocker "
1820 "(--only-migratable) for: ");
1821 return -EACCES;
1824 if (migration_is_idle()) {
1825 migration_blockers = g_slist_prepend(migration_blockers, reason);
1826 return 0;
1829 error_propagate_prepend(errp, error_copy(reason),
1830 "disallowing migration blocker "
1831 "(migration in progress) for: ");
1832 return -EBUSY;
1835 void migrate_del_blocker(Error *reason)
1837 migration_blockers = g_slist_remove(migration_blockers, reason);
1840 void qmp_migrate_incoming(const char *uri, Error **errp)
1842 Error *local_err = NULL;
1843 static bool once = true;
1845 if (!deferred_incoming) {
1846 error_setg(errp, "For use with '-incoming defer'");
1847 return;
1849 if (!once) {
1850 error_setg(errp, "The incoming migration has already been started");
1851 return;
1854 qemu_start_incoming_migration(uri, &local_err);
1856 if (local_err) {
1857 error_propagate(errp, local_err);
1858 return;
1861 once = false;
1864 void qmp_migrate_recover(const char *uri, Error **errp)
1866 MigrationIncomingState *mis = migration_incoming_get_current();
1868 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1869 error_setg(errp, "Migrate recover can only be run "
1870 "when postcopy is paused.");
1871 return;
1874 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1875 false, true) == true) {
1876 error_setg(errp, "Migrate recovery is triggered already");
1877 return;
1881 * Note that this call will never start a real migration; it will
1882 * only re-setup the migration stream and poke existing migration
1883 * to continue using that newly established channel.
1885 qemu_start_incoming_migration(uri, errp);
1888 void qmp_migrate_pause(Error **errp)
1890 MigrationState *ms = migrate_get_current();
1891 MigrationIncomingState *mis = migration_incoming_get_current();
1892 int ret;
1894 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1895 /* Source side, during postcopy */
1896 qemu_mutex_lock(&ms->qemu_file_lock);
1897 ret = qemu_file_shutdown(ms->to_dst_file);
1898 qemu_mutex_unlock(&ms->qemu_file_lock);
1899 if (ret) {
1900 error_setg(errp, "Failed to pause source migration");
1902 return;
1905 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1906 ret = qemu_file_shutdown(mis->from_src_file);
1907 if (ret) {
1908 error_setg(errp, "Failed to pause destination migration");
1910 return;
1913 error_setg(errp, "migrate-pause is currently only supported "
1914 "during postcopy-active state");
1917 bool migration_is_blocked(Error **errp)
1919 if (qemu_savevm_state_blocked(errp)) {
1920 return true;
1923 if (migration_blockers) {
1924 error_propagate(errp, error_copy(migration_blockers->data));
1925 return true;
1928 return false;
1931 /* Returns true if continue to migrate, or false if error detected */
1932 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1933 bool resume, Error **errp)
1935 Error *local_err = NULL;
1937 if (resume) {
1938 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1939 error_setg(errp, "Cannot resume if there is no "
1940 "paused migration");
1941 return false;
1945 * Postcopy recovery won't work well with release-ram
1946 * capability since release-ram will drop the page buffer as
1947 * long as the page is put into the send buffer. So if there
1948 * is a network failure happened, any page buffers that have
1949 * not yet reached the destination VM but have already been
1950 * sent from the source VM will be lost forever. Let's refuse
1951 * the client from resuming such a postcopy migration.
1952 * Luckily release-ram was designed to only be used when src
1953 * and destination VMs are on the same host, so it should be
1954 * fine.
1956 if (migrate_release_ram()) {
1957 error_setg(errp, "Postcopy recovery cannot work "
1958 "when release-ram capability is set");
1959 return false;
1962 /* This is a resume, skip init status */
1963 return true;
1966 if (migration_is_running(s->state)) {
1967 error_setg(errp, QERR_MIGRATION_ACTIVE);
1968 return false;
1971 if (runstate_check(RUN_STATE_INMIGRATE)) {
1972 error_setg(errp, "Guest is waiting for an incoming migration");
1973 return false;
1976 if (migration_is_blocked(errp)) {
1977 return false;
1980 if (blk || blk_inc) {
1981 if (migrate_use_block() || migrate_use_block_incremental()) {
1982 error_setg(errp, "Command options are incompatible with "
1983 "current migration capabilities");
1984 return false;
1986 migrate_set_block_enabled(true, &local_err);
1987 if (local_err) {
1988 error_propagate(errp, local_err);
1989 return false;
1991 s->must_remove_block_options = true;
1994 if (blk_inc) {
1995 migrate_set_block_incremental(s, true);
1998 migrate_init(s);
2000 * set ram_counters memory to zero for a
2001 * new migration
2003 memset(&ram_counters, 0, sizeof(ram_counters));
2005 return true;
2008 void qmp_migrate(const char *uri, bool has_blk, bool blk,
2009 bool has_inc, bool inc, bool has_detach, bool detach,
2010 bool has_resume, bool resume, Error **errp)
2012 Error *local_err = NULL;
2013 MigrationState *s = migrate_get_current();
2014 const char *p;
2016 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2017 has_resume && resume, errp)) {
2018 /* Error detected, put into errp */
2019 return;
2022 if (strstart(uri, "tcp:", &p)) {
2023 tcp_start_outgoing_migration(s, p, &local_err);
2024 #ifdef CONFIG_RDMA
2025 } else if (strstart(uri, "rdma:", &p)) {
2026 rdma_start_outgoing_migration(s, p, &local_err);
2027 #endif
2028 } else if (strstart(uri, "exec:", &p)) {
2029 exec_start_outgoing_migration(s, p, &local_err);
2030 } else if (strstart(uri, "unix:", &p)) {
2031 unix_start_outgoing_migration(s, p, &local_err);
2032 } else if (strstart(uri, "fd:", &p)) {
2033 fd_start_outgoing_migration(s, p, &local_err);
2034 } else {
2035 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2036 "a valid migration protocol");
2037 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2038 MIGRATION_STATUS_FAILED);
2039 block_cleanup_parameters(s);
2040 return;
2043 if (local_err) {
2044 migrate_fd_error(s, local_err);
2045 error_propagate(errp, local_err);
2046 return;
2050 void qmp_migrate_cancel(Error **errp)
2052 migrate_fd_cancel(migrate_get_current());
2055 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2057 MigrationState *s = migrate_get_current();
2058 if (s->state != state) {
2059 error_setg(errp, "Migration not in expected state: %s",
2060 MigrationStatus_str(s->state));
2061 return;
2063 qemu_sem_post(&s->pause_sem);
2066 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
2068 MigrateSetParameters p = {
2069 .has_xbzrle_cache_size = true,
2070 .xbzrle_cache_size = value,
2073 qmp_migrate_set_parameters(&p, errp);
2076 int64_t qmp_query_migrate_cache_size(Error **errp)
2078 return migrate_xbzrle_cache_size();
2081 void qmp_migrate_set_speed(int64_t value, Error **errp)
2083 MigrateSetParameters p = {
2084 .has_max_bandwidth = true,
2085 .max_bandwidth = value,
2088 qmp_migrate_set_parameters(&p, errp);
2091 void qmp_migrate_set_downtime(double value, Error **errp)
2093 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
2094 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
2095 "the range of 0 to %d seconds",
2096 MAX_MIGRATE_DOWNTIME_SECONDS);
2097 return;
2100 value *= 1000; /* Convert to milliseconds */
2102 MigrateSetParameters p = {
2103 .has_downtime_limit = true,
2104 .downtime_limit = (int64_t)value,
2107 qmp_migrate_set_parameters(&p, errp);
2110 bool migrate_release_ram(void)
2112 MigrationState *s;
2114 s = migrate_get_current();
2116 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2119 bool migrate_postcopy_ram(void)
2121 MigrationState *s;
2123 s = migrate_get_current();
2125 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
2128 bool migrate_postcopy(void)
2130 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
2133 bool migrate_auto_converge(void)
2135 MigrationState *s;
2137 s = migrate_get_current();
2139 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2142 bool migrate_zero_blocks(void)
2144 MigrationState *s;
2146 s = migrate_get_current();
2148 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2151 bool migrate_postcopy_blocktime(void)
2153 MigrationState *s;
2155 s = migrate_get_current();
2157 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2160 bool migrate_use_compression(void)
2162 MigrationState *s;
2164 s = migrate_get_current();
2166 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
2169 int migrate_compress_level(void)
2171 MigrationState *s;
2173 s = migrate_get_current();
2175 return s->parameters.compress_level;
2178 int migrate_compress_threads(void)
2180 MigrationState *s;
2182 s = migrate_get_current();
2184 return s->parameters.compress_threads;
2187 int migrate_compress_wait_thread(void)
2189 MigrationState *s;
2191 s = migrate_get_current();
2193 return s->parameters.compress_wait_thread;
2196 int migrate_decompress_threads(void)
2198 MigrationState *s;
2200 s = migrate_get_current();
2202 return s->parameters.decompress_threads;
2205 bool migrate_dirty_bitmaps(void)
2207 MigrationState *s;
2209 s = migrate_get_current();
2211 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2214 bool migrate_ignore_shared(void)
2216 MigrationState *s;
2218 s = migrate_get_current();
2220 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2223 bool migrate_validate_uuid(void)
2225 MigrationState *s;
2227 s = migrate_get_current();
2229 return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2232 bool migrate_use_events(void)
2234 MigrationState *s;
2236 s = migrate_get_current();
2238 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2241 bool migrate_use_multifd(void)
2243 MigrationState *s;
2245 s = migrate_get_current();
2247 return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
2250 bool migrate_pause_before_switchover(void)
2252 MigrationState *s;
2254 s = migrate_get_current();
2256 return s->enabled_capabilities[
2257 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2260 int migrate_multifd_channels(void)
2262 MigrationState *s;
2264 s = migrate_get_current();
2266 return s->parameters.multifd_channels;
2269 MultiFDCompression migrate_multifd_compression(void)
2271 MigrationState *s;
2273 s = migrate_get_current();
2275 return s->parameters.multifd_compression;
2278 int migrate_multifd_zlib_level(void)
2280 MigrationState *s;
2282 s = migrate_get_current();
2284 return s->parameters.multifd_zlib_level;
2287 int migrate_multifd_zstd_level(void)
2289 MigrationState *s;
2291 s = migrate_get_current();
2293 return s->parameters.multifd_zstd_level;
2296 int migrate_use_xbzrle(void)
2298 MigrationState *s;
2300 s = migrate_get_current();
2302 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2305 int64_t migrate_xbzrle_cache_size(void)
2307 MigrationState *s;
2309 s = migrate_get_current();
2311 return s->parameters.xbzrle_cache_size;
2314 static int64_t migrate_max_postcopy_bandwidth(void)
2316 MigrationState *s;
2318 s = migrate_get_current();
2320 return s->parameters.max_postcopy_bandwidth;
2323 bool migrate_use_block(void)
2325 MigrationState *s;
2327 s = migrate_get_current();
2329 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2332 bool migrate_use_return_path(void)
2334 MigrationState *s;
2336 s = migrate_get_current();
2338 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2341 bool migrate_use_block_incremental(void)
2343 MigrationState *s;
2345 s = migrate_get_current();
2347 return s->parameters.block_incremental;
2350 /* migration thread support */
2352 * Something bad happened to the RP stream, mark an error
2353 * The caller shall print or trace something to indicate why
2355 static void mark_source_rp_bad(MigrationState *s)
2357 s->rp_state.error = true;
2360 static struct rp_cmd_args {
2361 ssize_t len; /* -1 = variable */
2362 const char *name;
2363 } rp_cmd_args[] = {
2364 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2365 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2366 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2367 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2368 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2369 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2370 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2371 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2375 * Process a request for pages received on the return path,
2376 * We're allowed to send more than requested (e.g. to round to our page size)
2377 * and we don't need to send pages that have already been sent.
2379 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2380 ram_addr_t start, size_t len)
2382 long our_host_ps = qemu_real_host_page_size;
2384 trace_migrate_handle_rp_req_pages(rbname, start, len);
2387 * Since we currently insist on matching page sizes, just sanity check
2388 * we're being asked for whole host pages.
2390 if (start & (our_host_ps-1) ||
2391 (len & (our_host_ps-1))) {
2392 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2393 " len: %zd", __func__, start, len);
2394 mark_source_rp_bad(ms);
2395 return;
2398 if (ram_save_queue_pages(rbname, start, len)) {
2399 mark_source_rp_bad(ms);
2403 /* Return true to retry, false to quit */
2404 static bool postcopy_pause_return_path_thread(MigrationState *s)
2406 trace_postcopy_pause_return_path();
2408 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2410 trace_postcopy_pause_return_path_continued();
2412 return true;
2415 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2417 RAMBlock *block = qemu_ram_block_by_name(block_name);
2419 if (!block) {
2420 error_report("%s: invalid block name '%s'", __func__, block_name);
2421 return -EINVAL;
2424 /* Fetch the received bitmap and refresh the dirty bitmap */
2425 return ram_dirty_bitmap_reload(s, block);
2428 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2430 trace_source_return_path_thread_resume_ack(value);
2432 if (value != MIGRATION_RESUME_ACK_VALUE) {
2433 error_report("%s: illegal resume_ack value %"PRIu32,
2434 __func__, value);
2435 return -1;
2438 /* Now both sides are active. */
2439 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2440 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2442 /* Notify send thread that time to continue send pages */
2443 qemu_sem_post(&s->rp_state.rp_sem);
2445 return 0;
2449 * Handles messages sent on the return path towards the source VM
2452 static void *source_return_path_thread(void *opaque)
2454 MigrationState *ms = opaque;
2455 QEMUFile *rp = ms->rp_state.from_dst_file;
2456 uint16_t header_len, header_type;
2457 uint8_t buf[512];
2458 uint32_t tmp32, sibling_error;
2459 ram_addr_t start = 0; /* =0 to silence warning */
2460 size_t len = 0, expected_len;
2461 int res;
2463 trace_source_return_path_thread_entry();
2464 rcu_register_thread();
2466 retry:
2467 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2468 migration_is_setup_or_active(ms->state)) {
2469 trace_source_return_path_thread_loop_top();
2470 header_type = qemu_get_be16(rp);
2471 header_len = qemu_get_be16(rp);
2473 if (qemu_file_get_error(rp)) {
2474 mark_source_rp_bad(ms);
2475 goto out;
2478 if (header_type >= MIG_RP_MSG_MAX ||
2479 header_type == MIG_RP_MSG_INVALID) {
2480 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2481 header_type, header_len);
2482 mark_source_rp_bad(ms);
2483 goto out;
2486 if ((rp_cmd_args[header_type].len != -1 &&
2487 header_len != rp_cmd_args[header_type].len) ||
2488 header_len > sizeof(buf)) {
2489 error_report("RP: Received '%s' message (0x%04x) with"
2490 "incorrect length %d expecting %zu",
2491 rp_cmd_args[header_type].name, header_type, header_len,
2492 (size_t)rp_cmd_args[header_type].len);
2493 mark_source_rp_bad(ms);
2494 goto out;
2497 /* We know we've got a valid header by this point */
2498 res = qemu_get_buffer(rp, buf, header_len);
2499 if (res != header_len) {
2500 error_report("RP: Failed reading data for message 0x%04x"
2501 " read %d expected %d",
2502 header_type, res, header_len);
2503 mark_source_rp_bad(ms);
2504 goto out;
2507 /* OK, we have the message and the data */
2508 switch (header_type) {
2509 case MIG_RP_MSG_SHUT:
2510 sibling_error = ldl_be_p(buf);
2511 trace_source_return_path_thread_shut(sibling_error);
2512 if (sibling_error) {
2513 error_report("RP: Sibling indicated error %d", sibling_error);
2514 mark_source_rp_bad(ms);
2517 * We'll let the main thread deal with closing the RP
2518 * we could do a shutdown(2) on it, but we're the only user
2519 * anyway, so there's nothing gained.
2521 goto out;
2523 case MIG_RP_MSG_PONG:
2524 tmp32 = ldl_be_p(buf);
2525 trace_source_return_path_thread_pong(tmp32);
2526 break;
2528 case MIG_RP_MSG_REQ_PAGES:
2529 start = ldq_be_p(buf);
2530 len = ldl_be_p(buf + 8);
2531 migrate_handle_rp_req_pages(ms, NULL, start, len);
2532 break;
2534 case MIG_RP_MSG_REQ_PAGES_ID:
2535 expected_len = 12 + 1; /* header + termination */
2537 if (header_len >= expected_len) {
2538 start = ldq_be_p(buf);
2539 len = ldl_be_p(buf + 8);
2540 /* Now we expect an idstr */
2541 tmp32 = buf[12]; /* Length of the following idstr */
2542 buf[13 + tmp32] = '\0';
2543 expected_len += tmp32;
2545 if (header_len != expected_len) {
2546 error_report("RP: Req_Page_id with length %d expecting %zd",
2547 header_len, expected_len);
2548 mark_source_rp_bad(ms);
2549 goto out;
2551 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2552 break;
2554 case MIG_RP_MSG_RECV_BITMAP:
2555 if (header_len < 1) {
2556 error_report("%s: missing block name", __func__);
2557 mark_source_rp_bad(ms);
2558 goto out;
2560 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2561 buf[buf[0] + 1] = '\0';
2562 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2563 mark_source_rp_bad(ms);
2564 goto out;
2566 break;
2568 case MIG_RP_MSG_RESUME_ACK:
2569 tmp32 = ldl_be_p(buf);
2570 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2571 mark_source_rp_bad(ms);
2572 goto out;
2574 break;
2576 default:
2577 break;
2581 out:
2582 res = qemu_file_get_error(rp);
2583 if (res) {
2584 if (res == -EIO && migration_in_postcopy()) {
2586 * Maybe there is something we can do: it looks like a
2587 * network down issue, and we pause for a recovery.
2589 if (postcopy_pause_return_path_thread(ms)) {
2590 /* Reload rp, reset the rest */
2591 if (rp != ms->rp_state.from_dst_file) {
2592 qemu_fclose(rp);
2593 rp = ms->rp_state.from_dst_file;
2595 ms->rp_state.error = false;
2596 goto retry;
2600 trace_source_return_path_thread_bad_end();
2601 mark_source_rp_bad(ms);
2604 trace_source_return_path_thread_end();
2605 ms->rp_state.from_dst_file = NULL;
2606 qemu_fclose(rp);
2607 rcu_unregister_thread();
2608 return NULL;
2611 static int open_return_path_on_source(MigrationState *ms,
2612 bool create_thread)
2615 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2616 if (!ms->rp_state.from_dst_file) {
2617 return -1;
2620 trace_open_return_path_on_source();
2622 if (!create_thread) {
2623 /* We're done */
2624 return 0;
2627 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2628 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2630 trace_open_return_path_on_source_continue();
2632 return 0;
2635 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2636 static int await_return_path_close_on_source(MigrationState *ms)
2639 * If this is a normal exit then the destination will send a SHUT and the
2640 * rp_thread will exit, however if there's an error we need to cause
2641 * it to exit.
2643 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2645 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2646 * waiting for the destination.
2648 qemu_file_shutdown(ms->rp_state.from_dst_file);
2649 mark_source_rp_bad(ms);
2651 trace_await_return_path_close_on_source_joining();
2652 qemu_thread_join(&ms->rp_state.rp_thread);
2653 trace_await_return_path_close_on_source_close();
2654 return ms->rp_state.error;
2658 * Switch from normal iteration to postcopy
2659 * Returns non-0 on error
2661 static int postcopy_start(MigrationState *ms)
2663 int ret;
2664 QIOChannelBuffer *bioc;
2665 QEMUFile *fb;
2666 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2667 int64_t bandwidth = migrate_max_postcopy_bandwidth();
2668 bool restart_block = false;
2669 int cur_state = MIGRATION_STATUS_ACTIVE;
2670 if (!migrate_pause_before_switchover()) {
2671 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2672 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2675 trace_postcopy_start();
2676 qemu_mutex_lock_iothread();
2677 trace_postcopy_start_set_run();
2679 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2680 global_state_store();
2681 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2682 if (ret < 0) {
2683 goto fail;
2686 ret = migration_maybe_pause(ms, &cur_state,
2687 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2688 if (ret < 0) {
2689 goto fail;
2692 ret = bdrv_inactivate_all();
2693 if (ret < 0) {
2694 goto fail;
2696 restart_block = true;
2699 * Cause any non-postcopiable, but iterative devices to
2700 * send out their final data.
2702 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2705 * in Finish migrate and with the io-lock held everything should
2706 * be quiet, but we've potentially still got dirty pages and we
2707 * need to tell the destination to throw any pages it's already received
2708 * that are dirty
2710 if (migrate_postcopy_ram()) {
2711 if (ram_postcopy_send_discard_bitmap(ms)) {
2712 error_report("postcopy send discard bitmap failed");
2713 goto fail;
2718 * send rest of state - note things that are doing postcopy
2719 * will notice we're in POSTCOPY_ACTIVE and not actually
2720 * wrap their state up here
2722 /* 0 max-postcopy-bandwidth means unlimited */
2723 if (!bandwidth) {
2724 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2725 } else {
2726 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2728 if (migrate_postcopy_ram()) {
2729 /* Ping just for debugging, helps line traces up */
2730 qemu_savevm_send_ping(ms->to_dst_file, 2);
2734 * While loading the device state we may trigger page transfer
2735 * requests and the fd must be free to process those, and thus
2736 * the destination must read the whole device state off the fd before
2737 * it starts processing it. Unfortunately the ad-hoc migration format
2738 * doesn't allow the destination to know the size to read without fully
2739 * parsing it through each devices load-state code (especially the open
2740 * coded devices that use get/put).
2741 * So we wrap the device state up in a package with a length at the start;
2742 * to do this we use a qemu_buf to hold the whole of the device state.
2744 bioc = qio_channel_buffer_new(4096);
2745 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2746 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2747 object_unref(OBJECT(bioc));
2750 * Make sure the receiver can get incoming pages before we send the rest
2751 * of the state
2753 qemu_savevm_send_postcopy_listen(fb);
2755 qemu_savevm_state_complete_precopy(fb, false, false);
2756 if (migrate_postcopy_ram()) {
2757 qemu_savevm_send_ping(fb, 3);
2760 qemu_savevm_send_postcopy_run(fb);
2762 /* <><> end of stuff going into the package */
2764 /* Last point of recovery; as soon as we send the package the destination
2765 * can open devices and potentially start running.
2766 * Lets just check again we've not got any errors.
2768 ret = qemu_file_get_error(ms->to_dst_file);
2769 if (ret) {
2770 error_report("postcopy_start: Migration stream errored (pre package)");
2771 goto fail_closefb;
2774 restart_block = false;
2776 /* Now send that blob */
2777 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2778 goto fail_closefb;
2780 qemu_fclose(fb);
2782 /* Send a notify to give a chance for anything that needs to happen
2783 * at the transition to postcopy and after the device state; in particular
2784 * spice needs to trigger a transition now
2786 ms->postcopy_after_devices = true;
2787 notifier_list_notify(&migration_state_notifiers, ms);
2789 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2791 qemu_mutex_unlock_iothread();
2793 if (migrate_postcopy_ram()) {
2795 * Although this ping is just for debug, it could potentially be
2796 * used for getting a better measurement of downtime at the source.
2798 qemu_savevm_send_ping(ms->to_dst_file, 4);
2801 if (migrate_release_ram()) {
2802 ram_postcopy_migrated_memory_release(ms);
2805 ret = qemu_file_get_error(ms->to_dst_file);
2806 if (ret) {
2807 error_report("postcopy_start: Migration stream errored");
2808 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2809 MIGRATION_STATUS_FAILED);
2812 return ret;
2814 fail_closefb:
2815 qemu_fclose(fb);
2816 fail:
2817 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2818 MIGRATION_STATUS_FAILED);
2819 if (restart_block) {
2820 /* A failure happened early enough that we know the destination hasn't
2821 * accessed block devices, so we're safe to recover.
2823 Error *local_err = NULL;
2825 bdrv_invalidate_cache_all(&local_err);
2826 if (local_err) {
2827 error_report_err(local_err);
2830 qemu_mutex_unlock_iothread();
2831 return -1;
2835 * migration_maybe_pause: Pause if required to by
2836 * migrate_pause_before_switchover called with the iothread locked
2837 * Returns: 0 on success
2839 static int migration_maybe_pause(MigrationState *s,
2840 int *current_active_state,
2841 int new_state)
2843 if (!migrate_pause_before_switchover()) {
2844 return 0;
2847 /* Since leaving this state is not atomic with posting the semaphore
2848 * it's possible that someone could have issued multiple migrate_continue
2849 * and the semaphore is incorrectly positive at this point;
2850 * the docs say it's undefined to reinit a semaphore that's already
2851 * init'd, so use timedwait to eat up any existing posts.
2853 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2854 /* This block intentionally left blank */
2858 * If the migration is cancelled when it is in the completion phase,
2859 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2860 * So we don't need to wait a semaphore, otherwise we would always
2861 * wait for the 'pause_sem' semaphore.
2863 if (s->state != MIGRATION_STATUS_CANCELLING) {
2864 qemu_mutex_unlock_iothread();
2865 migrate_set_state(&s->state, *current_active_state,
2866 MIGRATION_STATUS_PRE_SWITCHOVER);
2867 qemu_sem_wait(&s->pause_sem);
2868 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2869 new_state);
2870 *current_active_state = new_state;
2871 qemu_mutex_lock_iothread();
2874 return s->state == new_state ? 0 : -EINVAL;
2878 * migration_completion: Used by migration_thread when there's not much left.
2879 * The caller 'breaks' the loop when this returns.
2881 * @s: Current migration state
2883 static void migration_completion(MigrationState *s)
2885 int ret;
2886 int current_active_state = s->state;
2888 if (s->state == MIGRATION_STATUS_ACTIVE) {
2889 qemu_mutex_lock_iothread();
2890 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2891 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2892 s->vm_was_running = runstate_is_running();
2893 ret = global_state_store();
2895 if (!ret) {
2896 bool inactivate = !migrate_colo_enabled();
2897 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2898 if (ret >= 0) {
2899 ret = migration_maybe_pause(s, &current_active_state,
2900 MIGRATION_STATUS_DEVICE);
2902 if (ret >= 0) {
2903 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2904 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2905 inactivate);
2907 if (inactivate && ret >= 0) {
2908 s->block_inactive = true;
2911 qemu_mutex_unlock_iothread();
2913 if (ret < 0) {
2914 goto fail;
2916 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2917 trace_migration_completion_postcopy_end();
2919 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2920 trace_migration_completion_postcopy_end_after_complete();
2924 * If rp was opened we must clean up the thread before
2925 * cleaning everything else up (since if there are no failures
2926 * it will wait for the destination to send it's status in
2927 * a SHUT command).
2929 if (s->rp_state.from_dst_file) {
2930 int rp_error;
2931 trace_migration_return_path_end_before();
2932 rp_error = await_return_path_close_on_source(s);
2933 trace_migration_return_path_end_after(rp_error);
2934 if (rp_error) {
2935 goto fail_invalidate;
2939 if (qemu_file_get_error(s->to_dst_file)) {
2940 trace_migration_completion_file_err();
2941 goto fail_invalidate;
2944 if (!migrate_colo_enabled()) {
2945 migrate_set_state(&s->state, current_active_state,
2946 MIGRATION_STATUS_COMPLETED);
2949 return;
2951 fail_invalidate:
2952 /* If not doing postcopy, vm_start() will be called: let's regain
2953 * control on images.
2955 if (s->state == MIGRATION_STATUS_ACTIVE ||
2956 s->state == MIGRATION_STATUS_DEVICE) {
2957 Error *local_err = NULL;
2959 qemu_mutex_lock_iothread();
2960 bdrv_invalidate_cache_all(&local_err);
2961 if (local_err) {
2962 error_report_err(local_err);
2963 } else {
2964 s->block_inactive = false;
2966 qemu_mutex_unlock_iothread();
2969 fail:
2970 migrate_set_state(&s->state, current_active_state,
2971 MIGRATION_STATUS_FAILED);
2974 bool migrate_colo_enabled(void)
2976 MigrationState *s = migrate_get_current();
2977 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2980 typedef enum MigThrError {
2981 /* No error detected */
2982 MIG_THR_ERR_NONE = 0,
2983 /* Detected error, but resumed successfully */
2984 MIG_THR_ERR_RECOVERED = 1,
2985 /* Detected fatal error, need to exit */
2986 MIG_THR_ERR_FATAL = 2,
2987 } MigThrError;
2989 static int postcopy_resume_handshake(MigrationState *s)
2991 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2993 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2994 qemu_sem_wait(&s->rp_state.rp_sem);
2997 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2998 return 0;
3001 return -1;
3004 /* Return zero if success, or <0 for error */
3005 static int postcopy_do_resume(MigrationState *s)
3007 int ret;
3010 * Call all the resume_prepare() hooks, so that modules can be
3011 * ready for the migration resume.
3013 ret = qemu_savevm_state_resume_prepare(s);
3014 if (ret) {
3015 error_report("%s: resume_prepare() failure detected: %d",
3016 __func__, ret);
3017 return ret;
3021 * Last handshake with destination on the resume (destination will
3022 * switch to postcopy-active afterwards)
3024 ret = postcopy_resume_handshake(s);
3025 if (ret) {
3026 error_report("%s: handshake failed: %d", __func__, ret);
3027 return ret;
3030 return 0;
3034 * We don't return until we are in a safe state to continue current
3035 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
3036 * MIG_THR_ERR_FATAL if unrecovery failure happened.
3038 static MigThrError postcopy_pause(MigrationState *s)
3040 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3042 while (true) {
3043 QEMUFile *file;
3045 migrate_set_state(&s->state, s->state,
3046 MIGRATION_STATUS_POSTCOPY_PAUSED);
3048 /* Current channel is possibly broken. Release it. */
3049 assert(s->to_dst_file);
3050 qemu_mutex_lock(&s->qemu_file_lock);
3051 file = s->to_dst_file;
3052 s->to_dst_file = NULL;
3053 qemu_mutex_unlock(&s->qemu_file_lock);
3055 qemu_file_shutdown(file);
3056 qemu_fclose(file);
3058 error_report("Detected IO failure for postcopy. "
3059 "Migration paused.");
3062 * We wait until things fixed up. Then someone will setup the
3063 * status back for us.
3065 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3066 qemu_sem_wait(&s->postcopy_pause_sem);
3069 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3070 /* Woken up by a recover procedure. Give it a shot */
3073 * Firstly, let's wake up the return path now, with a new
3074 * return path channel.
3076 qemu_sem_post(&s->postcopy_pause_rp_sem);
3078 /* Do the resume logic */
3079 if (postcopy_do_resume(s) == 0) {
3080 /* Let's continue! */
3081 trace_postcopy_pause_continued();
3082 return MIG_THR_ERR_RECOVERED;
3083 } else {
3085 * Something wrong happened during the recovery, let's
3086 * pause again. Pause is always better than throwing
3087 * data away.
3089 continue;
3091 } else {
3092 /* This is not right... Time to quit. */
3093 return MIG_THR_ERR_FATAL;
3098 static MigThrError migration_detect_error(MigrationState *s)
3100 int ret;
3101 int state = s->state;
3102 Error *local_error = NULL;
3104 if (state == MIGRATION_STATUS_CANCELLING ||
3105 state == MIGRATION_STATUS_CANCELLED) {
3106 /* End the migration, but don't set the state to failed */
3107 return MIG_THR_ERR_FATAL;
3110 /* Try to detect any file errors */
3111 ret = qemu_file_get_error_obj(s->to_dst_file, &local_error);
3112 if (!ret) {
3113 /* Everything is fine */
3114 assert(!local_error);
3115 return MIG_THR_ERR_NONE;
3118 if (local_error) {
3119 migrate_set_error(s, local_error);
3120 error_free(local_error);
3123 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
3125 * For postcopy, we allow the network to be down for a
3126 * while. After that, it can be continued by a
3127 * recovery phase.
3129 return postcopy_pause(s);
3130 } else {
3132 * For precopy (or postcopy with error outside IO), we fail
3133 * with no time.
3135 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3136 trace_migration_thread_file_err();
3138 /* Time to stop the migration, now. */
3139 return MIG_THR_ERR_FATAL;
3143 /* How many bytes have we transferred since the beginning of the migration */
3144 static uint64_t migration_total_bytes(MigrationState *s)
3146 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
3149 static void migration_calculate_complete(MigrationState *s)
3151 uint64_t bytes = migration_total_bytes(s);
3152 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3153 int64_t transfer_time;
3155 s->total_time = end_time - s->start_time;
3156 if (!s->downtime) {
3158 * It's still not set, so we are precopy migration. For
3159 * postcopy, downtime is calculated during postcopy_start().
3161 s->downtime = end_time - s->downtime_start;
3164 transfer_time = s->total_time - s->setup_time;
3165 if (transfer_time) {
3166 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3170 static void update_iteration_initial_status(MigrationState *s)
3173 * Update these three fields at the same time to avoid mismatch info lead
3174 * wrong speed calculation.
3176 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3177 s->iteration_initial_bytes = migration_total_bytes(s);
3178 s->iteration_initial_pages = ram_get_total_transferred_pages();
3181 static void migration_update_counters(MigrationState *s,
3182 int64_t current_time)
3184 uint64_t transferred, transferred_pages, time_spent;
3185 uint64_t current_bytes; /* bytes transferred since the beginning */
3186 double bandwidth;
3188 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3189 return;
3192 current_bytes = migration_total_bytes(s);
3193 transferred = current_bytes - s->iteration_initial_bytes;
3194 time_spent = current_time - s->iteration_start_time;
3195 bandwidth = (double)transferred / time_spent;
3196 s->threshold_size = bandwidth * s->parameters.downtime_limit;
3198 s->mbps = (((double) transferred * 8.0) /
3199 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3201 transferred_pages = ram_get_total_transferred_pages() -
3202 s->iteration_initial_pages;
3203 s->pages_per_second = (double) transferred_pages /
3204 (((double) time_spent / 1000.0));
3207 * if we haven't sent anything, we don't want to
3208 * recalculate. 10000 is a small enough number for our purposes
3210 if (ram_counters.dirty_pages_rate && transferred > 10000) {
3211 s->expected_downtime = ram_counters.remaining / bandwidth;
3214 qemu_file_reset_rate_limit(s->to_dst_file);
3216 update_iteration_initial_status(s);
3218 trace_migrate_transferred(transferred, time_spent,
3219 bandwidth, s->threshold_size);
3222 /* Migration thread iteration status */
3223 typedef enum {
3224 MIG_ITERATE_RESUME, /* Resume current iteration */
3225 MIG_ITERATE_SKIP, /* Skip current iteration */
3226 MIG_ITERATE_BREAK, /* Break the loop */
3227 } MigIterateState;
3230 * Return true if continue to the next iteration directly, false
3231 * otherwise.
3233 static MigIterateState migration_iteration_run(MigrationState *s)
3235 uint64_t pending_size, pend_pre, pend_compat, pend_post;
3236 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3238 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
3239 &pend_compat, &pend_post);
3240 pending_size = pend_pre + pend_compat + pend_post;
3242 trace_migrate_pending(pending_size, s->threshold_size,
3243 pend_pre, pend_compat, pend_post);
3245 if (pending_size && pending_size >= s->threshold_size) {
3246 /* Still a significant amount to transfer */
3247 if (!in_postcopy && pend_pre <= s->threshold_size &&
3248 atomic_read(&s->start_postcopy)) {
3249 if (postcopy_start(s)) {
3250 error_report("%s: postcopy failed to start", __func__);
3252 return MIG_ITERATE_SKIP;
3254 /* Just another iteration step */
3255 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3256 } else {
3257 trace_migration_thread_low_pending(pending_size);
3258 migration_completion(s);
3259 return MIG_ITERATE_BREAK;
3262 return MIG_ITERATE_RESUME;
3265 static void migration_iteration_finish(MigrationState *s)
3267 /* If we enabled cpu throttling for auto-converge, turn it off. */
3268 cpu_throttle_stop();
3270 qemu_mutex_lock_iothread();
3271 switch (s->state) {
3272 case MIGRATION_STATUS_COMPLETED:
3273 migration_calculate_complete(s);
3274 runstate_set(RUN_STATE_POSTMIGRATE);
3275 break;
3277 case MIGRATION_STATUS_ACTIVE:
3279 * We should really assert here, but since it's during
3280 * migration, let's try to reduce the usage of assertions.
3282 if (!migrate_colo_enabled()) {
3283 error_report("%s: critical error: calling COLO code without "
3284 "COLO enabled", __func__);
3286 migrate_start_colo_process(s);
3288 * Fixme: we will run VM in COLO no matter its old running state.
3289 * After exited COLO, we will keep running.
3291 s->vm_was_running = true;
3292 /* Fallthrough */
3293 case MIGRATION_STATUS_FAILED:
3294 case MIGRATION_STATUS_CANCELLED:
3295 case MIGRATION_STATUS_CANCELLING:
3296 if (s->vm_was_running) {
3297 vm_start();
3298 } else {
3299 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3300 runstate_set(RUN_STATE_POSTMIGRATE);
3303 break;
3305 default:
3306 /* Should not reach here, but if so, forgive the VM. */
3307 error_report("%s: Unknown ending state %d", __func__, s->state);
3308 break;
3310 migrate_fd_cleanup_schedule(s);
3311 qemu_mutex_unlock_iothread();
3314 void migration_make_urgent_request(void)
3316 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3319 void migration_consume_urgent_request(void)
3321 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3324 /* Returns true if the rate limiting was broken by an urgent request */
3325 bool migration_rate_limit(void)
3327 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3328 MigrationState *s = migrate_get_current();
3330 bool urgent = false;
3331 migration_update_counters(s, now);
3332 if (qemu_file_rate_limit(s->to_dst_file)) {
3334 * Wait for a delay to do rate limiting OR
3335 * something urgent to post the semaphore.
3337 int ms = s->iteration_start_time + BUFFER_DELAY - now;
3338 trace_migration_rate_limit_pre(ms);
3339 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3341 * We were woken by one or more urgent things but
3342 * the timedwait will have consumed one of them.
3343 * The service routine for the urgent wake will dec
3344 * the semaphore itself for each item it consumes,
3345 * so add this one we just eat back.
3347 qemu_sem_post(&s->rate_limit_sem);
3348 urgent = true;
3350 trace_migration_rate_limit_post(urgent);
3352 return urgent;
3356 * Master migration thread on the source VM.
3357 * It drives the migration and pumps the data down the outgoing channel.
3359 static void *migration_thread(void *opaque)
3361 MigrationState *s = opaque;
3362 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3363 MigThrError thr_error;
3364 bool urgent = false;
3366 rcu_register_thread();
3368 object_ref(OBJECT(s));
3369 update_iteration_initial_status(s);
3371 qemu_savevm_state_header(s->to_dst_file);
3374 * If we opened the return path, we need to make sure dst has it
3375 * opened as well.
3377 if (s->rp_state.from_dst_file) {
3378 /* Now tell the dest that it should open its end so it can reply */
3379 qemu_savevm_send_open_return_path(s->to_dst_file);
3381 /* And do a ping that will make stuff easier to debug */
3382 qemu_savevm_send_ping(s->to_dst_file, 1);
3385 if (migrate_postcopy()) {
3387 * Tell the destination that we *might* want to do postcopy later;
3388 * if the other end can't do postcopy it should fail now, nice and
3389 * early.
3391 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3394 if (migrate_colo_enabled()) {
3395 /* Notify migration destination that we enable COLO */
3396 qemu_savevm_send_colo_enable(s->to_dst_file);
3399 qemu_savevm_state_setup(s->to_dst_file);
3401 if (qemu_savevm_state_guest_unplug_pending()) {
3402 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3403 MIGRATION_STATUS_WAIT_UNPLUG);
3405 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3406 qemu_savevm_state_guest_unplug_pending()) {
3407 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3410 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG,
3411 MIGRATION_STATUS_ACTIVE);
3414 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3415 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3416 MIGRATION_STATUS_ACTIVE);
3418 trace_migration_thread_setup_complete();
3420 while (migration_is_active(s)) {
3421 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3422 MigIterateState iter_state = migration_iteration_run(s);
3423 if (iter_state == MIG_ITERATE_SKIP) {
3424 continue;
3425 } else if (iter_state == MIG_ITERATE_BREAK) {
3426 break;
3431 * Try to detect any kind of failures, and see whether we
3432 * should stop the migration now.
3434 thr_error = migration_detect_error(s);
3435 if (thr_error == MIG_THR_ERR_FATAL) {
3436 /* Stop migration */
3437 break;
3438 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3440 * Just recovered from a e.g. network failure, reset all
3441 * the local variables. This is important to avoid
3442 * breaking transferred_bytes and bandwidth calculation
3444 update_iteration_initial_status(s);
3447 urgent = migration_rate_limit();
3450 trace_migration_thread_after_loop();
3451 migration_iteration_finish(s);
3452 object_unref(OBJECT(s));
3453 rcu_unregister_thread();
3454 return NULL;
3457 void migrate_fd_connect(MigrationState *s, Error *error_in)
3459 Error *local_err = NULL;
3460 int64_t rate_limit;
3461 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3463 s->expected_downtime = s->parameters.downtime_limit;
3464 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
3465 if (error_in) {
3466 migrate_fd_error(s, error_in);
3467 migrate_fd_cleanup(s);
3468 return;
3471 if (resume) {
3472 /* This is a resumed migration */
3473 rate_limit = s->parameters.max_postcopy_bandwidth /
3474 XFER_LIMIT_RATIO;
3475 } else {
3476 /* This is a fresh new migration */
3477 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3479 /* Notify before starting migration thread */
3480 notifier_list_notify(&migration_state_notifiers, s);
3483 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3484 qemu_file_set_blocking(s->to_dst_file, true);
3487 * Open the return path. For postcopy, it is used exclusively. For
3488 * precopy, only if user specified "return-path" capability would
3489 * QEMU uses the return path.
3491 if (migrate_postcopy_ram() || migrate_use_return_path()) {
3492 if (open_return_path_on_source(s, !resume)) {
3493 error_report("Unable to open return-path for postcopy");
3494 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3495 migrate_fd_cleanup(s);
3496 return;
3500 if (resume) {
3501 /* Wakeup the main migration thread to do the recovery */
3502 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3503 MIGRATION_STATUS_POSTCOPY_RECOVER);
3504 qemu_sem_post(&s->postcopy_pause_sem);
3505 return;
3508 if (multifd_save_setup(&local_err) != 0) {
3509 error_report_err(local_err);
3510 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3511 MIGRATION_STATUS_FAILED);
3512 migrate_fd_cleanup(s);
3513 return;
3515 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3516 QEMU_THREAD_JOINABLE);
3517 s->migration_thread_running = true;
3520 void migration_global_dump(Monitor *mon)
3522 MigrationState *ms = migrate_get_current();
3524 monitor_printf(mon, "globals:\n");
3525 monitor_printf(mon, "store-global-state: %s\n",
3526 ms->store_global_state ? "on" : "off");
3527 monitor_printf(mon, "only-migratable: %s\n",
3528 only_migratable ? "on" : "off");
3529 monitor_printf(mon, "send-configuration: %s\n",
3530 ms->send_configuration ? "on" : "off");
3531 monitor_printf(mon, "send-section-footer: %s\n",
3532 ms->send_section_footer ? "on" : "off");
3533 monitor_printf(mon, "decompress-error-check: %s\n",
3534 ms->decompress_error_check ? "on" : "off");
3535 monitor_printf(mon, "clear-bitmap-shift: %u\n",
3536 ms->clear_bitmap_shift);
3539 #define DEFINE_PROP_MIG_CAP(name, x) \
3540 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3542 static Property migration_properties[] = {
3543 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3544 store_global_state, true),
3545 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3546 send_configuration, true),
3547 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3548 send_section_footer, true),
3549 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3550 decompress_error_check, true),
3551 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
3552 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
3554 /* Migration parameters */
3555 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3556 parameters.compress_level,
3557 DEFAULT_MIGRATE_COMPRESS_LEVEL),
3558 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3559 parameters.compress_threads,
3560 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3561 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3562 parameters.compress_wait_thread, true),
3563 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3564 parameters.decompress_threads,
3565 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3566 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3567 parameters.cpu_throttle_initial,
3568 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3569 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3570 parameters.cpu_throttle_increment,
3571 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3572 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3573 parameters.max_bandwidth, MAX_THROTTLE),
3574 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3575 parameters.downtime_limit,
3576 DEFAULT_MIGRATE_SET_DOWNTIME),
3577 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3578 parameters.x_checkpoint_delay,
3579 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3580 DEFINE_PROP_UINT8("multifd-channels", MigrationState,
3581 parameters.multifd_channels,
3582 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3583 DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
3584 parameters.multifd_compression,
3585 DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
3586 DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
3587 parameters.multifd_zlib_level,
3588 DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
3589 DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
3590 parameters.multifd_zstd_level,
3591 DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
3592 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3593 parameters.xbzrle_cache_size,
3594 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3595 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3596 parameters.max_postcopy_bandwidth,
3597 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3598 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3599 parameters.max_cpu_throttle,
3600 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3601 DEFINE_PROP_SIZE("announce-initial", MigrationState,
3602 parameters.announce_initial,
3603 DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
3604 DEFINE_PROP_SIZE("announce-max", MigrationState,
3605 parameters.announce_max,
3606 DEFAULT_MIGRATE_ANNOUNCE_MAX),
3607 DEFINE_PROP_SIZE("announce-rounds", MigrationState,
3608 parameters.announce_rounds,
3609 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
3610 DEFINE_PROP_SIZE("announce-step", MigrationState,
3611 parameters.announce_step,
3612 DEFAULT_MIGRATE_ANNOUNCE_STEP),
3614 /* Migration capabilities */
3615 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3616 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3617 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3618 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3619 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3620 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3621 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3622 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3623 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3624 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3625 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3626 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
3628 DEFINE_PROP_END_OF_LIST(),
3631 static void migration_class_init(ObjectClass *klass, void *data)
3633 DeviceClass *dc = DEVICE_CLASS(klass);
3635 dc->user_creatable = false;
3636 device_class_set_props(dc, migration_properties);
3639 static void migration_instance_finalize(Object *obj)
3641 MigrationState *ms = MIGRATION_OBJ(obj);
3642 MigrationParameters *params = &ms->parameters;
3644 qemu_mutex_destroy(&ms->error_mutex);
3645 qemu_mutex_destroy(&ms->qemu_file_lock);
3646 g_free(params->tls_hostname);
3647 g_free(params->tls_creds);
3648 qemu_sem_destroy(&ms->wait_unplug_sem);
3649 qemu_sem_destroy(&ms->rate_limit_sem);
3650 qemu_sem_destroy(&ms->pause_sem);
3651 qemu_sem_destroy(&ms->postcopy_pause_sem);
3652 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3653 qemu_sem_destroy(&ms->rp_state.rp_sem);
3654 error_free(ms->error);
3657 static void migration_instance_init(Object *obj)
3659 MigrationState *ms = MIGRATION_OBJ(obj);
3660 MigrationParameters *params = &ms->parameters;
3662 ms->state = MIGRATION_STATUS_NONE;
3663 ms->mbps = -1;
3664 ms->pages_per_second = -1;
3665 qemu_sem_init(&ms->pause_sem, 0);
3666 qemu_mutex_init(&ms->error_mutex);
3668 params->tls_hostname = g_strdup("");
3669 params->tls_creds = g_strdup("");
3671 /* Set has_* up only for parameter checks */
3672 params->has_compress_level = true;
3673 params->has_compress_threads = true;
3674 params->has_decompress_threads = true;
3675 params->has_cpu_throttle_initial = true;
3676 params->has_cpu_throttle_increment = true;
3677 params->has_max_bandwidth = true;
3678 params->has_downtime_limit = true;
3679 params->has_x_checkpoint_delay = true;
3680 params->has_block_incremental = true;
3681 params->has_multifd_channels = true;
3682 params->has_multifd_compression = true;
3683 params->has_multifd_zlib_level = true;
3684 params->has_multifd_zstd_level = true;
3685 params->has_xbzrle_cache_size = true;
3686 params->has_max_postcopy_bandwidth = true;
3687 params->has_max_cpu_throttle = true;
3688 params->has_announce_initial = true;
3689 params->has_announce_max = true;
3690 params->has_announce_rounds = true;
3691 params->has_announce_step = true;
3693 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3694 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3695 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3696 qemu_sem_init(&ms->rate_limit_sem, 0);
3697 qemu_sem_init(&ms->wait_unplug_sem, 0);
3698 qemu_mutex_init(&ms->qemu_file_lock);
3702 * Return true if check pass, false otherwise. Error will be put
3703 * inside errp if provided.
3705 static bool migration_object_check(MigrationState *ms, Error **errp)
3707 MigrationCapabilityStatusList *head = NULL;
3708 /* Assuming all off */
3709 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3710 int i;
3712 if (!migrate_params_check(&ms->parameters, errp)) {
3713 return false;
3716 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3717 if (ms->enabled_capabilities[i]) {
3718 head = migrate_cap_add(head, i, true);
3722 ret = migrate_caps_check(cap_list, head, errp);
3724 /* It works with head == NULL */
3725 qapi_free_MigrationCapabilityStatusList(head);
3727 return ret;
3730 static const TypeInfo migration_type = {
3731 .name = TYPE_MIGRATION,
3733 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3734 * not created using qdev_create(), it is not attached to the qdev
3735 * device tree, and it is never realized.
3737 * TODO: Make this TYPE_OBJECT once QOM provides something like
3738 * TYPE_DEVICE's "-global" properties.
3740 .parent = TYPE_DEVICE,
3741 .class_init = migration_class_init,
3742 .class_size = sizeof(MigrationClass),
3743 .instance_size = sizeof(MigrationState),
3744 .instance_init = migration_instance_init,
3745 .instance_finalize = migration_instance_finalize,
3748 static void register_migration_types(void)
3750 type_register_static(&migration_type);
3753 type_init(register_migration_types);