migration/dirtyrate: Add trace_calls to make it easier to debug
[qemu/ar7.git] / migration / migration.c
blob827f8be07d7c1f24cdea202477fc26177a06478f
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 "sysemu/cpu-throttle.h"
27 #include "rdma.h"
28 #include "ram.h"
29 #include "migration/global_state.h"
30 #include "migration/misc.h"
31 #include "migration.h"
32 #include "savevm.h"
33 #include "qemu-file-channel.h"
34 #include "qemu-file.h"
35 #include "migration/vmstate.h"
36 #include "block/block.h"
37 #include "qapi/error.h"
38 #include "qapi/clone-visitor.h"
39 #include "qapi/qapi-visit-migration.h"
40 #include "qapi/qapi-visit-sockets.h"
41 #include "qapi/qapi-commands-migration.h"
42 #include "qapi/qapi-events-migration.h"
43 #include "qapi/qmp/qerror.h"
44 #include "qapi/qmp/qnull.h"
45 #include "qemu/rcu.h"
46 #include "block.h"
47 #include "postcopy-ram.h"
48 #include "qemu/thread.h"
49 #include "trace.h"
50 #include "exec/target_page.h"
51 #include "io/channel-buffer.h"
52 #include "migration/colo.h"
53 #include "hw/boards.h"
54 #include "hw/qdev-properties.h"
55 #include "monitor/monitor.h"
56 #include "net/announce.h"
57 #include "qemu/queue.h"
58 #include "multifd.h"
60 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
62 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
63 * data. */
64 #define BUFFER_DELAY 100
65 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
67 /* Time in milliseconds we are allowed to stop the source,
68 * for sending the last part */
69 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
71 /* Maximum migrate downtime set to 2000 seconds */
72 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
73 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
75 /* Default compression thread count */
76 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
77 /* Default decompression thread count, usually decompression is at
78 * least 4 times as fast as compression.*/
79 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
80 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
81 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
82 /* Define default autoconverge cpu throttle migration parameters */
83 #define DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD 50
84 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
85 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
86 #define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
88 /* Migration XBZRLE default cache size */
89 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
91 /* The delay time (in ms) between two COLO checkpoints */
92 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
93 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
94 #define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE
95 /* 0: means nocompress, 1: best speed, ... 9: best compress ratio */
96 #define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1
97 /* 0: means nocompress, 1: best speed, ... 20: best compress ratio */
98 #define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1
100 /* Background transfer rate for postcopy, 0 means unlimited, note
101 * that page requests can still exceed this limit.
103 #define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
106 * Parameters for self_announce_delay giving a stream of RARP/ARP
107 * packets after migration.
109 #define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50
110 #define DEFAULT_MIGRATE_ANNOUNCE_MAX 550
111 #define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5
112 #define DEFAULT_MIGRATE_ANNOUNCE_STEP 100
114 static NotifierList migration_state_notifiers =
115 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
117 static bool deferred_incoming;
119 /* Messages sent on the return path from destination to source */
120 enum mig_rp_message_type {
121 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
122 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
123 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
125 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
126 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
127 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
128 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
130 MIG_RP_MSG_MAX
133 /* When we add fault tolerance, we could have several
134 migrations at once. For now we don't need to add
135 dynamic creation of migration */
137 static MigrationState *current_migration;
138 static MigrationIncomingState *current_incoming;
140 static bool migration_object_check(MigrationState *ms, Error **errp);
141 static int migration_maybe_pause(MigrationState *s,
142 int *current_active_state,
143 int new_state);
144 static void migrate_fd_cancel(MigrationState *s);
146 void migration_object_init(void)
148 MachineState *ms = MACHINE(qdev_get_machine());
149 Error *err = NULL;
151 /* This can only be called once. */
152 assert(!current_migration);
153 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
156 * Init the migrate incoming object as well no matter whether
157 * we'll use it or not.
159 assert(!current_incoming);
160 current_incoming = g_new0(MigrationIncomingState, 1);
161 current_incoming->state = MIGRATION_STATUS_NONE;
162 current_incoming->postcopy_remote_fds =
163 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
164 qemu_mutex_init(&current_incoming->rp_mutex);
165 qemu_event_init(&current_incoming->main_thread_load_event, false);
166 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
167 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
169 if (!migration_object_check(current_migration, &err)) {
170 error_report_err(err);
171 exit(1);
175 * We cannot really do this in migration_instance_init() since at
176 * that time global properties are not yet applied, then this
177 * value will be definitely replaced by something else.
179 if (ms->enforce_config_section) {
180 current_migration->send_configuration = true;
184 void migration_shutdown(void)
187 * Cancel the current migration - that will (eventually)
188 * stop the migration using this structure
190 migrate_fd_cancel(current_migration);
191 object_unref(OBJECT(current_migration));
194 * Cancel outgoing migration of dirty bitmaps. It should
195 * at least unref used block nodes.
197 dirty_bitmap_mig_cancel_outgoing();
200 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
201 * are non-critical data, and their loss never considered as
202 * something serious.
204 dirty_bitmap_mig_cancel_incoming();
207 /* For outgoing */
208 MigrationState *migrate_get_current(void)
210 /* This can only be called after the object created. */
211 assert(current_migration);
212 return current_migration;
215 MigrationIncomingState *migration_incoming_get_current(void)
217 assert(current_incoming);
218 return current_incoming;
221 void migration_incoming_state_destroy(void)
223 struct MigrationIncomingState *mis = migration_incoming_get_current();
225 if (mis->to_src_file) {
226 /* Tell source that we are done */
227 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
228 qemu_fclose(mis->to_src_file);
229 mis->to_src_file = NULL;
232 if (mis->from_src_file) {
233 qemu_fclose(mis->from_src_file);
234 mis->from_src_file = NULL;
236 if (mis->postcopy_remote_fds) {
237 g_array_free(mis->postcopy_remote_fds, TRUE);
238 mis->postcopy_remote_fds = NULL;
241 if (mis->socket_address_list) {
242 qapi_free_SocketAddressList(mis->socket_address_list);
243 mis->socket_address_list = NULL;
246 qemu_event_destroy(&mis->main_thread_load_event);
247 qemu_sem_destroy(&mis->postcopy_pause_sem_dst);
248 qemu_sem_destroy(&mis->postcopy_pause_sem_fault);
249 qemu_mutex_destroy(&mis->rp_mutex);
252 static void migrate_generate_event(int new_state)
254 if (migrate_use_events()) {
255 qapi_event_send_migration(new_state);
259 static bool migrate_late_block_activate(void)
261 MigrationState *s;
263 s = migrate_get_current();
265 return s->enabled_capabilities[
266 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
270 * Called on -incoming with a defer: uri.
271 * The migration can be started later after any parameters have been
272 * changed.
274 static void deferred_incoming_migration(Error **errp)
276 if (deferred_incoming) {
277 error_setg(errp, "Incoming migration already deferred");
279 deferred_incoming = true;
283 * Send a message on the return channel back to the source
284 * of the migration.
286 static int migrate_send_rp_message(MigrationIncomingState *mis,
287 enum mig_rp_message_type message_type,
288 uint16_t len, void *data)
290 int ret = 0;
292 trace_migrate_send_rp_message((int)message_type, len);
293 qemu_mutex_lock(&mis->rp_mutex);
296 * It's possible that the file handle got lost due to network
297 * failures.
299 if (!mis->to_src_file) {
300 ret = -EIO;
301 goto error;
304 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
305 qemu_put_be16(mis->to_src_file, len);
306 qemu_put_buffer(mis->to_src_file, data, len);
307 qemu_fflush(mis->to_src_file);
309 /* It's possible that qemu file got error during sending */
310 ret = qemu_file_get_error(mis->to_src_file);
312 error:
313 qemu_mutex_unlock(&mis->rp_mutex);
314 return ret;
317 /* Request one page from the source VM at the given start address.
318 * rb: the RAMBlock to request the page in
319 * Start: Address offset within the RB
320 * Len: Length in bytes required - must be a multiple of pagesize
322 int migrate_send_rp_req_pages(MigrationIncomingState *mis, RAMBlock *rb,
323 ram_addr_t start)
325 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
326 size_t msglen = 12; /* start + len */
327 size_t len = qemu_ram_pagesize(rb);
328 enum mig_rp_message_type msg_type;
329 const char *rbname;
330 int rbname_len;
332 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
333 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
336 * We maintain the last ramblock that we requested for page. Note that we
337 * don't need locking because this function will only be called within the
338 * postcopy ram fault thread.
340 if (rb != mis->last_rb) {
341 mis->last_rb = rb;
343 rbname = qemu_ram_get_idstr(rb);
344 rbname_len = strlen(rbname);
346 assert(rbname_len < 256);
348 bufc[msglen++] = rbname_len;
349 memcpy(bufc + msglen, rbname, rbname_len);
350 msglen += rbname_len;
351 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
352 } else {
353 msg_type = MIG_RP_MSG_REQ_PAGES;
356 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
359 static bool migration_colo_enabled;
360 bool migration_incoming_colo_enabled(void)
362 return migration_colo_enabled;
365 void migration_incoming_disable_colo(void)
367 ram_block_discard_disable(false);
368 migration_colo_enabled = false;
371 int migration_incoming_enable_colo(void)
373 if (ram_block_discard_disable(true)) {
374 error_report("COLO: cannot disable RAM discard");
375 return -EBUSY;
377 migration_colo_enabled = true;
378 return 0;
381 void migrate_add_address(SocketAddress *address)
383 MigrationIncomingState *mis = migration_incoming_get_current();
384 SocketAddressList *addrs;
386 addrs = g_new0(SocketAddressList, 1);
387 addrs->next = mis->socket_address_list;
388 mis->socket_address_list = addrs;
389 addrs->value = QAPI_CLONE(SocketAddress, address);
392 void qemu_start_incoming_migration(const char *uri, Error **errp)
394 const char *p = NULL;
396 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
397 if (!strcmp(uri, "defer")) {
398 deferred_incoming_migration(errp);
399 } else if (strstart(uri, "tcp:", &p) ||
400 strstart(uri, "unix:", NULL) ||
401 strstart(uri, "vsock:", NULL)) {
402 socket_start_incoming_migration(p ? p : uri, errp);
403 #ifdef CONFIG_RDMA
404 } else if (strstart(uri, "rdma:", &p)) {
405 rdma_start_incoming_migration(p, errp);
406 #endif
407 } else if (strstart(uri, "exec:", &p)) {
408 exec_start_incoming_migration(p, errp);
409 } else if (strstart(uri, "fd:", &p)) {
410 fd_start_incoming_migration(p, errp);
411 } else {
412 error_setg(errp, "unknown migration protocol: %s", uri);
416 static void process_incoming_migration_bh(void *opaque)
418 Error *local_err = NULL;
419 MigrationIncomingState *mis = opaque;
421 /* If capability late_block_activate is set:
422 * Only fire up the block code now if we're going to restart the
423 * VM, else 'cont' will do it.
424 * This causes file locking to happen; so we don't want it to happen
425 * unless we really are starting the VM.
427 if (!migrate_late_block_activate() ||
428 (autostart && (!global_state_received() ||
429 global_state_get_runstate() == RUN_STATE_RUNNING))) {
430 /* Make sure all file formats flush their mutable metadata.
431 * If we get an error here, just don't restart the VM yet. */
432 bdrv_invalidate_cache_all(&local_err);
433 if (local_err) {
434 error_report_err(local_err);
435 local_err = NULL;
436 autostart = false;
441 * This must happen after all error conditions are dealt with and
442 * we're sure the VM is going to be running on this host.
444 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
446 if (multifd_load_cleanup(&local_err) != 0) {
447 error_report_err(local_err);
448 autostart = false;
450 /* If global state section was not received or we are in running
451 state, we need to obey autostart. Any other state is set with
452 runstate_set. */
454 dirty_bitmap_mig_before_vm_start();
456 if (!global_state_received() ||
457 global_state_get_runstate() == RUN_STATE_RUNNING) {
458 if (autostart) {
459 vm_start();
460 } else {
461 runstate_set(RUN_STATE_PAUSED);
463 } else if (migration_incoming_colo_enabled()) {
464 migration_incoming_disable_colo();
465 vm_start();
466 } else {
467 runstate_set(global_state_get_runstate());
470 * This must happen after any state changes since as soon as an external
471 * observer sees this event they might start to prod at the VM assuming
472 * it's ready to use.
474 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
475 MIGRATION_STATUS_COMPLETED);
476 qemu_bh_delete(mis->bh);
477 migration_incoming_state_destroy();
480 static void process_incoming_migration_co(void *opaque)
482 MigrationIncomingState *mis = migration_incoming_get_current();
483 PostcopyState ps;
484 int ret;
485 Error *local_err = NULL;
487 assert(mis->from_src_file);
488 mis->migration_incoming_co = qemu_coroutine_self();
489 mis->largest_page_size = qemu_ram_pagesize_largest();
490 postcopy_state_set(POSTCOPY_INCOMING_NONE);
491 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
492 MIGRATION_STATUS_ACTIVE);
493 ret = qemu_loadvm_state(mis->from_src_file);
495 ps = postcopy_state_get();
496 trace_process_incoming_migration_co_end(ret, ps);
497 if (ps != POSTCOPY_INCOMING_NONE) {
498 if (ps == POSTCOPY_INCOMING_ADVISE) {
500 * Where a migration had postcopy enabled (and thus went to advise)
501 * but managed to complete within the precopy period, we can use
502 * the normal exit.
504 postcopy_ram_incoming_cleanup(mis);
505 } else if (ret >= 0) {
507 * Postcopy was started, cleanup should happen at the end of the
508 * postcopy thread.
510 trace_process_incoming_migration_co_postcopy_end_main();
511 return;
513 /* Else if something went wrong then just fall out of the normal exit */
516 /* we get COLO info, and know if we are in COLO mode */
517 if (!ret && migration_incoming_colo_enabled()) {
518 /* Make sure all file formats flush their mutable metadata */
519 bdrv_invalidate_cache_all(&local_err);
520 if (local_err) {
521 error_report_err(local_err);
522 goto fail;
525 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
526 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
527 mis->have_colo_incoming_thread = true;
528 qemu_coroutine_yield();
530 /* Wait checkpoint incoming thread exit before free resource */
531 qemu_thread_join(&mis->colo_incoming_thread);
532 /* We hold the global iothread lock, so it is safe here */
533 colo_release_ram_cache();
536 if (ret < 0) {
537 error_report("load of migration failed: %s", strerror(-ret));
538 goto fail;
540 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
541 qemu_bh_schedule(mis->bh);
542 mis->migration_incoming_co = NULL;
543 return;
544 fail:
545 local_err = NULL;
546 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
547 MIGRATION_STATUS_FAILED);
548 qemu_fclose(mis->from_src_file);
549 if (multifd_load_cleanup(&local_err) != 0) {
550 error_report_err(local_err);
552 exit(EXIT_FAILURE);
556 * @migration_incoming_setup: Setup incoming migration
558 * Returns 0 for no error or 1 for error
560 * @f: file for main migration channel
561 * @errp: where to put errors
563 static int migration_incoming_setup(QEMUFile *f, Error **errp)
565 MigrationIncomingState *mis = migration_incoming_get_current();
566 Error *local_err = NULL;
568 if (multifd_load_setup(&local_err) != 0) {
569 /* We haven't been able to create multifd threads
570 nothing better to do */
571 error_report_err(local_err);
572 exit(EXIT_FAILURE);
575 if (!mis->from_src_file) {
576 mis->from_src_file = f;
578 qemu_file_set_blocking(f, false);
579 return 0;
582 void migration_incoming_process(void)
584 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
585 qemu_coroutine_enter(co);
588 /* Returns true if recovered from a paused migration, otherwise false */
589 static bool postcopy_try_recover(QEMUFile *f)
591 MigrationIncomingState *mis = migration_incoming_get_current();
593 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
594 /* Resumed from a paused postcopy migration */
596 mis->from_src_file = f;
597 /* Postcopy has standalone thread to do vm load */
598 qemu_file_set_blocking(f, true);
600 /* Re-configure the return path */
601 mis->to_src_file = qemu_file_get_return_path(f);
603 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
604 MIGRATION_STATUS_POSTCOPY_RECOVER);
607 * Here, we only wake up the main loading thread (while the
608 * fault thread will still be waiting), so that we can receive
609 * commands from source now, and answer it if needed. The
610 * fault thread will be woken up afterwards until we are sure
611 * that source is ready to reply to page requests.
613 qemu_sem_post(&mis->postcopy_pause_sem_dst);
614 return true;
617 return false;
620 void migration_fd_process_incoming(QEMUFile *f, Error **errp)
622 Error *local_err = NULL;
624 if (postcopy_try_recover(f)) {
625 return;
628 if (migration_incoming_setup(f, &local_err)) {
629 if (local_err) {
630 error_propagate(errp, local_err);
632 return;
634 migration_incoming_process();
637 void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
639 MigrationIncomingState *mis = migration_incoming_get_current();
640 Error *local_err = NULL;
641 bool start_migration;
643 if (!mis->from_src_file) {
644 /* The first connection (multifd may have multiple) */
645 QEMUFile *f = qemu_fopen_channel_input(ioc);
647 /* If it's a recovery, we're done */
648 if (postcopy_try_recover(f)) {
649 return;
652 if (migration_incoming_setup(f, &local_err)) {
653 if (local_err) {
654 error_propagate(errp, local_err);
656 return;
660 * Common migration only needs one channel, so we can start
661 * right now. Multifd needs more than one channel, we wait.
663 start_migration = !migrate_use_multifd();
664 } else {
665 /* Multiple connections */
666 assert(migrate_use_multifd());
667 start_migration = multifd_recv_new_channel(ioc, &local_err);
668 if (local_err) {
669 error_propagate(errp, local_err);
670 return;
674 if (start_migration) {
675 migration_incoming_process();
680 * @migration_has_all_channels: We have received all channels that we need
682 * Returns true when we have got connections to all the channels that
683 * we need for migration.
685 bool migration_has_all_channels(void)
687 MigrationIncomingState *mis = migration_incoming_get_current();
688 bool all_channels;
690 all_channels = multifd_recv_all_channels_created();
692 return all_channels && mis->from_src_file != NULL;
696 * Send a 'SHUT' message on the return channel with the given value
697 * to indicate that we've finished with the RP. Non-0 value indicates
698 * error.
700 void migrate_send_rp_shut(MigrationIncomingState *mis,
701 uint32_t value)
703 uint32_t buf;
705 buf = cpu_to_be32(value);
706 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
710 * Send a 'PONG' message on the return channel with the given value
711 * (normally in response to a 'PING')
713 void migrate_send_rp_pong(MigrationIncomingState *mis,
714 uint32_t value)
716 uint32_t buf;
718 buf = cpu_to_be32(value);
719 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
722 void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
723 char *block_name)
725 char buf[512];
726 int len;
727 int64_t res;
730 * First, we send the header part. It contains only the len of
731 * idstr, and the idstr itself.
733 len = strlen(block_name);
734 buf[0] = len;
735 memcpy(buf + 1, block_name, len);
737 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
738 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
739 __func__);
740 return;
743 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
746 * Next, we dump the received bitmap to the stream.
748 * TODO: currently we are safe since we are the only one that is
749 * using the to_src_file handle (fault thread is still paused),
750 * and it's ok even not taking the mutex. However the best way is
751 * to take the lock before sending the message header, and release
752 * the lock after sending the bitmap.
754 qemu_mutex_lock(&mis->rp_mutex);
755 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
756 qemu_mutex_unlock(&mis->rp_mutex);
758 trace_migrate_send_rp_recv_bitmap(block_name, res);
761 void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
763 uint32_t buf;
765 buf = cpu_to_be32(value);
766 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
769 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
771 MigrationCapabilityStatusList *head = NULL;
772 MigrationCapabilityStatusList *caps;
773 MigrationState *s = migrate_get_current();
774 int i;
776 caps = NULL; /* silence compiler warning */
777 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
778 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
779 if (i == MIGRATION_CAPABILITY_BLOCK) {
780 continue;
782 #endif
783 if (head == NULL) {
784 head = g_malloc0(sizeof(*caps));
785 caps = head;
786 } else {
787 caps->next = g_malloc0(sizeof(*caps));
788 caps = caps->next;
790 caps->value =
791 g_malloc(sizeof(*caps->value));
792 caps->value->capability = i;
793 caps->value->state = s->enabled_capabilities[i];
796 return head;
799 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
801 MigrationParameters *params;
802 MigrationState *s = migrate_get_current();
804 /* TODO use QAPI_CLONE() instead of duplicating it inline */
805 params = g_malloc0(sizeof(*params));
806 params->has_compress_level = true;
807 params->compress_level = s->parameters.compress_level;
808 params->has_compress_threads = true;
809 params->compress_threads = s->parameters.compress_threads;
810 params->has_compress_wait_thread = true;
811 params->compress_wait_thread = s->parameters.compress_wait_thread;
812 params->has_decompress_threads = true;
813 params->decompress_threads = s->parameters.decompress_threads;
814 params->has_throttle_trigger_threshold = true;
815 params->throttle_trigger_threshold = s->parameters.throttle_trigger_threshold;
816 params->has_cpu_throttle_initial = true;
817 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
818 params->has_cpu_throttle_increment = true;
819 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
820 params->has_cpu_throttle_tailslow = true;
821 params->cpu_throttle_tailslow = s->parameters.cpu_throttle_tailslow;
822 params->has_tls_creds = true;
823 params->tls_creds = g_strdup(s->parameters.tls_creds);
824 params->has_tls_hostname = true;
825 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
826 params->has_tls_authz = true;
827 params->tls_authz = g_strdup(s->parameters.tls_authz ?
828 s->parameters.tls_authz : "");
829 params->has_max_bandwidth = true;
830 params->max_bandwidth = s->parameters.max_bandwidth;
831 params->has_downtime_limit = true;
832 params->downtime_limit = s->parameters.downtime_limit;
833 params->has_x_checkpoint_delay = true;
834 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
835 params->has_block_incremental = true;
836 params->block_incremental = s->parameters.block_incremental;
837 params->has_multifd_channels = true;
838 params->multifd_channels = s->parameters.multifd_channels;
839 params->has_multifd_compression = true;
840 params->multifd_compression = s->parameters.multifd_compression;
841 params->has_multifd_zlib_level = true;
842 params->multifd_zlib_level = s->parameters.multifd_zlib_level;
843 params->has_multifd_zstd_level = true;
844 params->multifd_zstd_level = s->parameters.multifd_zstd_level;
845 params->has_xbzrle_cache_size = true;
846 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
847 params->has_max_postcopy_bandwidth = true;
848 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
849 params->has_max_cpu_throttle = true;
850 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
851 params->has_announce_initial = true;
852 params->announce_initial = s->parameters.announce_initial;
853 params->has_announce_max = true;
854 params->announce_max = s->parameters.announce_max;
855 params->has_announce_rounds = true;
856 params->announce_rounds = s->parameters.announce_rounds;
857 params->has_announce_step = true;
858 params->announce_step = s->parameters.announce_step;
860 if (s->parameters.has_block_bitmap_mapping) {
861 params->has_block_bitmap_mapping = true;
862 params->block_bitmap_mapping =
863 QAPI_CLONE(BitmapMigrationNodeAliasList,
864 s->parameters.block_bitmap_mapping);
867 return params;
870 AnnounceParameters *migrate_announce_params(void)
872 static AnnounceParameters ap;
874 MigrationState *s = migrate_get_current();
876 ap.initial = s->parameters.announce_initial;
877 ap.max = s->parameters.announce_max;
878 ap.rounds = s->parameters.announce_rounds;
879 ap.step = s->parameters.announce_step;
881 return &ap;
885 * Return true if we're already in the middle of a migration
886 * (i.e. any of the active or setup states)
888 bool migration_is_setup_or_active(int state)
890 switch (state) {
891 case MIGRATION_STATUS_ACTIVE:
892 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
893 case MIGRATION_STATUS_POSTCOPY_PAUSED:
894 case MIGRATION_STATUS_POSTCOPY_RECOVER:
895 case MIGRATION_STATUS_SETUP:
896 case MIGRATION_STATUS_PRE_SWITCHOVER:
897 case MIGRATION_STATUS_DEVICE:
898 case MIGRATION_STATUS_WAIT_UNPLUG:
899 case MIGRATION_STATUS_COLO:
900 return true;
902 default:
903 return false;
908 bool migration_is_running(int state)
910 switch (state) {
911 case MIGRATION_STATUS_ACTIVE:
912 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
913 case MIGRATION_STATUS_POSTCOPY_PAUSED:
914 case MIGRATION_STATUS_POSTCOPY_RECOVER:
915 case MIGRATION_STATUS_SETUP:
916 case MIGRATION_STATUS_PRE_SWITCHOVER:
917 case MIGRATION_STATUS_DEVICE:
918 case MIGRATION_STATUS_WAIT_UNPLUG:
919 case MIGRATION_STATUS_CANCELLING:
920 return true;
922 default:
923 return false;
928 static void populate_time_info(MigrationInfo *info, MigrationState *s)
930 info->has_status = true;
931 info->has_setup_time = true;
932 info->setup_time = s->setup_time;
933 if (s->state == MIGRATION_STATUS_COMPLETED) {
934 info->has_total_time = true;
935 info->total_time = s->total_time;
936 info->has_downtime = true;
937 info->downtime = s->downtime;
938 } else {
939 info->has_total_time = true;
940 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
941 s->start_time;
942 info->has_expected_downtime = true;
943 info->expected_downtime = s->expected_downtime;
947 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
949 info->has_ram = true;
950 info->ram = g_malloc0(sizeof(*info->ram));
951 info->ram->transferred = ram_counters.transferred;
952 info->ram->total = ram_bytes_total();
953 info->ram->duplicate = ram_counters.duplicate;
954 /* legacy value. It is not used anymore */
955 info->ram->skipped = 0;
956 info->ram->normal = ram_counters.normal;
957 info->ram->normal_bytes = ram_counters.normal *
958 qemu_target_page_size();
959 info->ram->mbps = s->mbps;
960 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
961 info->ram->postcopy_requests = ram_counters.postcopy_requests;
962 info->ram->page_size = qemu_target_page_size();
963 info->ram->multifd_bytes = ram_counters.multifd_bytes;
964 info->ram->pages_per_second = s->pages_per_second;
966 if (migrate_use_xbzrle()) {
967 info->has_xbzrle_cache = true;
968 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
969 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
970 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
971 info->xbzrle_cache->pages = xbzrle_counters.pages;
972 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
973 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
974 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
975 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
978 if (migrate_use_compression()) {
979 info->has_compression = true;
980 info->compression = g_malloc0(sizeof(*info->compression));
981 info->compression->pages = compression_counters.pages;
982 info->compression->busy = compression_counters.busy;
983 info->compression->busy_rate = compression_counters.busy_rate;
984 info->compression->compressed_size =
985 compression_counters.compressed_size;
986 info->compression->compression_rate =
987 compression_counters.compression_rate;
990 if (cpu_throttle_active()) {
991 info->has_cpu_throttle_percentage = true;
992 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
995 if (s->state != MIGRATION_STATUS_COMPLETED) {
996 info->ram->remaining = ram_bytes_remaining();
997 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
1001 static void populate_disk_info(MigrationInfo *info)
1003 if (blk_mig_active()) {
1004 info->has_disk = true;
1005 info->disk = g_malloc0(sizeof(*info->disk));
1006 info->disk->transferred = blk_mig_bytes_transferred();
1007 info->disk->remaining = blk_mig_bytes_remaining();
1008 info->disk->total = blk_mig_bytes_total();
1012 static void fill_source_migration_info(MigrationInfo *info)
1014 MigrationState *s = migrate_get_current();
1016 switch (s->state) {
1017 case MIGRATION_STATUS_NONE:
1018 /* no migration has happened ever */
1019 /* do not overwrite destination migration status */
1020 return;
1021 case MIGRATION_STATUS_SETUP:
1022 info->has_status = true;
1023 info->has_total_time = false;
1024 break;
1025 case MIGRATION_STATUS_ACTIVE:
1026 case MIGRATION_STATUS_CANCELLING:
1027 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1028 case MIGRATION_STATUS_PRE_SWITCHOVER:
1029 case MIGRATION_STATUS_DEVICE:
1030 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1031 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1032 /* TODO add some postcopy stats */
1033 populate_time_info(info, s);
1034 populate_ram_info(info, s);
1035 populate_disk_info(info);
1036 break;
1037 case MIGRATION_STATUS_COLO:
1038 info->has_status = true;
1039 /* TODO: display COLO specific information (checkpoint info etc.) */
1040 break;
1041 case MIGRATION_STATUS_COMPLETED:
1042 populate_time_info(info, s);
1043 populate_ram_info(info, s);
1044 break;
1045 case MIGRATION_STATUS_FAILED:
1046 info->has_status = true;
1047 if (s->error) {
1048 info->has_error_desc = true;
1049 info->error_desc = g_strdup(error_get_pretty(s->error));
1051 break;
1052 case MIGRATION_STATUS_CANCELLED:
1053 info->has_status = true;
1054 break;
1055 case MIGRATION_STATUS_WAIT_UNPLUG:
1056 info->has_status = true;
1057 break;
1059 info->status = s->state;
1063 * @migration_caps_check - check capability validity
1065 * @cap_list: old capability list, array of bool
1066 * @params: new capabilities to be applied soon
1067 * @errp: set *errp if the check failed, with reason
1069 * Returns true if check passed, otherwise false.
1071 static bool migrate_caps_check(bool *cap_list,
1072 MigrationCapabilityStatusList *params,
1073 Error **errp)
1075 MigrationCapabilityStatusList *cap;
1076 bool old_postcopy_cap;
1077 MigrationIncomingState *mis = migration_incoming_get_current();
1079 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1081 for (cap = params; cap; cap = cap->next) {
1082 cap_list[cap->value->capability] = cap->value->state;
1085 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
1086 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
1087 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
1088 "block migration");
1089 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
1090 return false;
1092 #endif
1094 #ifndef CONFIG_REPLICATION
1095 if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
1096 error_setg(errp, "QEMU compiled without replication module"
1097 " can't enable COLO");
1098 error_append_hint(errp, "Please enable replication before COLO.\n");
1099 return false;
1101 #endif
1103 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1104 /* This check is reasonably expensive, so only when it's being
1105 * set the first time, also it's only the destination that needs
1106 * special support.
1108 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
1109 !postcopy_ram_supported_by_host(mis)) {
1110 /* postcopy_ram_supported_by_host will have emitted a more
1111 * detailed message
1113 error_setg(errp, "Postcopy is not supported");
1114 return false;
1117 if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1118 error_setg(errp, "Postcopy is not compatible with ignore-shared");
1119 return false;
1123 return true;
1126 static void fill_destination_migration_info(MigrationInfo *info)
1128 MigrationIncomingState *mis = migration_incoming_get_current();
1130 if (mis->socket_address_list) {
1131 info->has_socket_address = true;
1132 info->socket_address =
1133 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1136 switch (mis->state) {
1137 case MIGRATION_STATUS_NONE:
1138 return;
1139 case MIGRATION_STATUS_SETUP:
1140 case MIGRATION_STATUS_CANCELLING:
1141 case MIGRATION_STATUS_CANCELLED:
1142 case MIGRATION_STATUS_ACTIVE:
1143 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1144 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1145 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1146 case MIGRATION_STATUS_FAILED:
1147 case MIGRATION_STATUS_COLO:
1148 info->has_status = true;
1149 break;
1150 case MIGRATION_STATUS_COMPLETED:
1151 info->has_status = true;
1152 fill_destination_postcopy_migration_info(info);
1153 break;
1155 info->status = mis->state;
1158 MigrationInfo *qmp_query_migrate(Error **errp)
1160 MigrationInfo *info = g_malloc0(sizeof(*info));
1162 fill_destination_migration_info(info);
1163 fill_source_migration_info(info);
1165 return info;
1168 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1169 Error **errp)
1171 MigrationState *s = migrate_get_current();
1172 MigrationCapabilityStatusList *cap;
1173 bool cap_list[MIGRATION_CAPABILITY__MAX];
1175 if (migration_is_running(s->state)) {
1176 error_setg(errp, QERR_MIGRATION_ACTIVE);
1177 return;
1180 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1181 if (!migrate_caps_check(cap_list, params, errp)) {
1182 return;
1185 for (cap = params; cap; cap = cap->next) {
1186 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1191 * Check whether the parameters are valid. Error will be put into errp
1192 * (if provided). Return true if valid, otherwise false.
1194 static bool migrate_params_check(MigrationParameters *params, Error **errp)
1196 if (params->has_compress_level &&
1197 (params->compress_level > 9)) {
1198 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1199 "is invalid, it should be in the range of 0 to 9");
1200 return false;
1203 if (params->has_compress_threads && (params->compress_threads < 1)) {
1204 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1205 "compress_threads",
1206 "is invalid, it should be in the range of 1 to 255");
1207 return false;
1210 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
1211 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1212 "decompress_threads",
1213 "is invalid, it should be in the range of 1 to 255");
1214 return false;
1217 if (params->has_throttle_trigger_threshold &&
1218 (params->throttle_trigger_threshold < 1 ||
1219 params->throttle_trigger_threshold > 100)) {
1220 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1221 "throttle_trigger_threshold",
1222 "an integer in the range of 1 to 100");
1223 return false;
1226 if (params->has_cpu_throttle_initial &&
1227 (params->cpu_throttle_initial < 1 ||
1228 params->cpu_throttle_initial > 99)) {
1229 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1230 "cpu_throttle_initial",
1231 "an integer in the range of 1 to 99");
1232 return false;
1235 if (params->has_cpu_throttle_increment &&
1236 (params->cpu_throttle_increment < 1 ||
1237 params->cpu_throttle_increment > 99)) {
1238 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1239 "cpu_throttle_increment",
1240 "an integer in the range of 1 to 99");
1241 return false;
1244 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
1245 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1246 "max_bandwidth",
1247 "an integer in the range of 0 to "stringify(SIZE_MAX)
1248 " bytes/second");
1249 return false;
1252 if (params->has_downtime_limit &&
1253 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
1254 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1255 "downtime_limit",
1256 "an integer in the range of 0 to "
1257 stringify(MAX_MIGRATE_DOWNTIME)" ms");
1258 return false;
1261 /* x_checkpoint_delay is now always positive */
1263 if (params->has_multifd_channels && (params->multifd_channels < 1)) {
1264 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1265 "multifd_channels",
1266 "is invalid, it should be in the range of 1 to 255");
1267 return false;
1270 if (params->has_multifd_zlib_level &&
1271 (params->multifd_zlib_level > 9)) {
1272 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level",
1273 "is invalid, it should be in the range of 0 to 9");
1274 return false;
1277 if (params->has_multifd_zstd_level &&
1278 (params->multifd_zstd_level > 20)) {
1279 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level",
1280 "is invalid, it should be in the range of 0 to 20");
1281 return false;
1284 if (params->has_xbzrle_cache_size &&
1285 (params->xbzrle_cache_size < qemu_target_page_size() ||
1286 !is_power_of_2(params->xbzrle_cache_size))) {
1287 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1288 "xbzrle_cache_size",
1289 "is invalid, it should be bigger than target page size"
1290 " and a power of 2");
1291 return false;
1294 if (params->has_max_cpu_throttle &&
1295 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1296 params->max_cpu_throttle > 99)) {
1297 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1298 "max_cpu_throttle",
1299 "an integer in the range of cpu_throttle_initial to 99");
1300 return false;
1303 if (params->has_announce_initial &&
1304 params->announce_initial > 100000) {
1305 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1306 "announce_initial",
1307 "is invalid, it must be less than 100000 ms");
1308 return false;
1310 if (params->has_announce_max &&
1311 params->announce_max > 100000) {
1312 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1313 "announce_max",
1314 "is invalid, it must be less than 100000 ms");
1315 return false;
1317 if (params->has_announce_rounds &&
1318 params->announce_rounds > 1000) {
1319 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1320 "announce_rounds",
1321 "is invalid, it must be in the range of 0 to 1000");
1322 return false;
1324 if (params->has_announce_step &&
1325 (params->announce_step < 1 ||
1326 params->announce_step > 10000)) {
1327 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1328 "announce_step",
1329 "is invalid, it must be in the range of 1 to 10000 ms");
1330 return false;
1333 if (params->has_block_bitmap_mapping &&
1334 !check_dirty_bitmap_mig_alias_map(params->block_bitmap_mapping, errp)) {
1335 error_prepend(errp, "Invalid mapping given for block-bitmap-mapping: ");
1336 return false;
1339 return true;
1342 static void migrate_params_test_apply(MigrateSetParameters *params,
1343 MigrationParameters *dest)
1345 *dest = migrate_get_current()->parameters;
1347 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1349 if (params->has_compress_level) {
1350 dest->compress_level = params->compress_level;
1353 if (params->has_compress_threads) {
1354 dest->compress_threads = params->compress_threads;
1357 if (params->has_compress_wait_thread) {
1358 dest->compress_wait_thread = params->compress_wait_thread;
1361 if (params->has_decompress_threads) {
1362 dest->decompress_threads = params->decompress_threads;
1365 if (params->has_throttle_trigger_threshold) {
1366 dest->throttle_trigger_threshold = params->throttle_trigger_threshold;
1369 if (params->has_cpu_throttle_initial) {
1370 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1373 if (params->has_cpu_throttle_increment) {
1374 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1377 if (params->has_cpu_throttle_tailslow) {
1378 dest->cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1381 if (params->has_tls_creds) {
1382 assert(params->tls_creds->type == QTYPE_QSTRING);
1383 dest->tls_creds = params->tls_creds->u.s;
1386 if (params->has_tls_hostname) {
1387 assert(params->tls_hostname->type == QTYPE_QSTRING);
1388 dest->tls_hostname = params->tls_hostname->u.s;
1391 if (params->has_max_bandwidth) {
1392 dest->max_bandwidth = params->max_bandwidth;
1395 if (params->has_downtime_limit) {
1396 dest->downtime_limit = params->downtime_limit;
1399 if (params->has_x_checkpoint_delay) {
1400 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1403 if (params->has_block_incremental) {
1404 dest->block_incremental = params->block_incremental;
1406 if (params->has_multifd_channels) {
1407 dest->multifd_channels = params->multifd_channels;
1409 if (params->has_multifd_compression) {
1410 dest->multifd_compression = params->multifd_compression;
1412 if (params->has_xbzrle_cache_size) {
1413 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1415 if (params->has_max_postcopy_bandwidth) {
1416 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1418 if (params->has_max_cpu_throttle) {
1419 dest->max_cpu_throttle = params->max_cpu_throttle;
1421 if (params->has_announce_initial) {
1422 dest->announce_initial = params->announce_initial;
1424 if (params->has_announce_max) {
1425 dest->announce_max = params->announce_max;
1427 if (params->has_announce_rounds) {
1428 dest->announce_rounds = params->announce_rounds;
1430 if (params->has_announce_step) {
1431 dest->announce_step = params->announce_step;
1434 if (params->has_block_bitmap_mapping) {
1435 dest->has_block_bitmap_mapping = true;
1436 dest->block_bitmap_mapping = params->block_bitmap_mapping;
1440 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
1442 MigrationState *s = migrate_get_current();
1444 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1446 if (params->has_compress_level) {
1447 s->parameters.compress_level = params->compress_level;
1450 if (params->has_compress_threads) {
1451 s->parameters.compress_threads = params->compress_threads;
1454 if (params->has_compress_wait_thread) {
1455 s->parameters.compress_wait_thread = params->compress_wait_thread;
1458 if (params->has_decompress_threads) {
1459 s->parameters.decompress_threads = params->decompress_threads;
1462 if (params->has_throttle_trigger_threshold) {
1463 s->parameters.throttle_trigger_threshold = params->throttle_trigger_threshold;
1466 if (params->has_cpu_throttle_initial) {
1467 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1470 if (params->has_cpu_throttle_increment) {
1471 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1474 if (params->has_cpu_throttle_tailslow) {
1475 s->parameters.cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1478 if (params->has_tls_creds) {
1479 g_free(s->parameters.tls_creds);
1480 assert(params->tls_creds->type == QTYPE_QSTRING);
1481 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
1484 if (params->has_tls_hostname) {
1485 g_free(s->parameters.tls_hostname);
1486 assert(params->tls_hostname->type == QTYPE_QSTRING);
1487 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1490 if (params->has_tls_authz) {
1491 g_free(s->parameters.tls_authz);
1492 assert(params->tls_authz->type == QTYPE_QSTRING);
1493 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1496 if (params->has_max_bandwidth) {
1497 s->parameters.max_bandwidth = params->max_bandwidth;
1498 if (s->to_dst_file && !migration_in_postcopy()) {
1499 qemu_file_set_rate_limit(s->to_dst_file,
1500 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1504 if (params->has_downtime_limit) {
1505 s->parameters.downtime_limit = params->downtime_limit;
1508 if (params->has_x_checkpoint_delay) {
1509 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1510 if (migration_in_colo_state()) {
1511 colo_checkpoint_notify(s);
1515 if (params->has_block_incremental) {
1516 s->parameters.block_incremental = params->block_incremental;
1518 if (params->has_multifd_channels) {
1519 s->parameters.multifd_channels = params->multifd_channels;
1521 if (params->has_multifd_compression) {
1522 s->parameters.multifd_compression = params->multifd_compression;
1524 if (params->has_xbzrle_cache_size) {
1525 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1526 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1528 if (params->has_max_postcopy_bandwidth) {
1529 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1530 if (s->to_dst_file && migration_in_postcopy()) {
1531 qemu_file_set_rate_limit(s->to_dst_file,
1532 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1535 if (params->has_max_cpu_throttle) {
1536 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1538 if (params->has_announce_initial) {
1539 s->parameters.announce_initial = params->announce_initial;
1541 if (params->has_announce_max) {
1542 s->parameters.announce_max = params->announce_max;
1544 if (params->has_announce_rounds) {
1545 s->parameters.announce_rounds = params->announce_rounds;
1547 if (params->has_announce_step) {
1548 s->parameters.announce_step = params->announce_step;
1551 if (params->has_block_bitmap_mapping) {
1552 qapi_free_BitmapMigrationNodeAliasList(
1553 s->parameters.block_bitmap_mapping);
1555 s->parameters.has_block_bitmap_mapping = true;
1556 s->parameters.block_bitmap_mapping =
1557 QAPI_CLONE(BitmapMigrationNodeAliasList,
1558 params->block_bitmap_mapping);
1562 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1564 MigrationParameters tmp;
1566 /* TODO Rewrite "" to null instead */
1567 if (params->has_tls_creds
1568 && params->tls_creds->type == QTYPE_QNULL) {
1569 qobject_unref(params->tls_creds->u.n);
1570 params->tls_creds->type = QTYPE_QSTRING;
1571 params->tls_creds->u.s = strdup("");
1573 /* TODO Rewrite "" to null instead */
1574 if (params->has_tls_hostname
1575 && params->tls_hostname->type == QTYPE_QNULL) {
1576 qobject_unref(params->tls_hostname->u.n);
1577 params->tls_hostname->type = QTYPE_QSTRING;
1578 params->tls_hostname->u.s = strdup("");
1581 migrate_params_test_apply(params, &tmp);
1583 if (!migrate_params_check(&tmp, errp)) {
1584 /* Invalid parameter */
1585 return;
1588 migrate_params_apply(params, errp);
1592 void qmp_migrate_start_postcopy(Error **errp)
1594 MigrationState *s = migrate_get_current();
1596 if (!migrate_postcopy()) {
1597 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1598 " the start of migration");
1599 return;
1602 if (s->state == MIGRATION_STATUS_NONE) {
1603 error_setg(errp, "Postcopy must be started after migration has been"
1604 " started");
1605 return;
1608 * we don't error if migration has finished since that would be racy
1609 * with issuing this command.
1611 qatomic_set(&s->start_postcopy, true);
1614 /* shared migration helpers */
1616 void migrate_set_state(int *state, int old_state, int new_state)
1618 assert(new_state < MIGRATION_STATUS__MAX);
1619 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
1620 trace_migrate_set_state(MigrationStatus_str(new_state));
1621 migrate_generate_event(new_state);
1625 static MigrationCapabilityStatusList *migrate_cap_add(
1626 MigrationCapabilityStatusList *list,
1627 MigrationCapability index,
1628 bool state)
1630 MigrationCapabilityStatusList *cap;
1632 cap = g_new0(MigrationCapabilityStatusList, 1);
1633 cap->value = g_new0(MigrationCapabilityStatus, 1);
1634 cap->value->capability = index;
1635 cap->value->state = state;
1636 cap->next = list;
1638 return cap;
1641 void migrate_set_block_enabled(bool value, Error **errp)
1643 MigrationCapabilityStatusList *cap;
1645 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1646 qmp_migrate_set_capabilities(cap, errp);
1647 qapi_free_MigrationCapabilityStatusList(cap);
1650 static void migrate_set_block_incremental(MigrationState *s, bool value)
1652 s->parameters.block_incremental = value;
1655 static void block_cleanup_parameters(MigrationState *s)
1657 if (s->must_remove_block_options) {
1658 /* setting to false can never fail */
1659 migrate_set_block_enabled(false, &error_abort);
1660 migrate_set_block_incremental(s, false);
1661 s->must_remove_block_options = false;
1665 static void migrate_fd_cleanup(MigrationState *s)
1667 qemu_bh_delete(s->cleanup_bh);
1668 s->cleanup_bh = NULL;
1670 qemu_savevm_state_cleanup();
1672 if (s->to_dst_file) {
1673 QEMUFile *tmp;
1675 trace_migrate_fd_cleanup();
1676 qemu_mutex_unlock_iothread();
1677 if (s->migration_thread_running) {
1678 qemu_thread_join(&s->thread);
1679 s->migration_thread_running = false;
1681 qemu_mutex_lock_iothread();
1683 multifd_save_cleanup();
1684 qemu_mutex_lock(&s->qemu_file_lock);
1685 tmp = s->to_dst_file;
1686 s->to_dst_file = NULL;
1687 qemu_mutex_unlock(&s->qemu_file_lock);
1689 * Close the file handle without the lock to make sure the
1690 * critical section won't block for long.
1692 qemu_fclose(tmp);
1695 assert(!migration_is_active(s));
1697 if (s->state == MIGRATION_STATUS_CANCELLING) {
1698 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1699 MIGRATION_STATUS_CANCELLED);
1702 if (s->error) {
1703 /* It is used on info migrate. We can't free it */
1704 error_report_err(error_copy(s->error));
1706 notifier_list_notify(&migration_state_notifiers, s);
1707 block_cleanup_parameters(s);
1710 static void migrate_fd_cleanup_schedule(MigrationState *s)
1713 * Ref the state for bh, because it may be called when
1714 * there're already no other refs
1716 object_ref(OBJECT(s));
1717 qemu_bh_schedule(s->cleanup_bh);
1720 static void migrate_fd_cleanup_bh(void *opaque)
1722 MigrationState *s = opaque;
1723 migrate_fd_cleanup(s);
1724 object_unref(OBJECT(s));
1727 void migrate_set_error(MigrationState *s, const Error *error)
1729 QEMU_LOCK_GUARD(&s->error_mutex);
1730 if (!s->error) {
1731 s->error = error_copy(error);
1735 void migrate_fd_error(MigrationState *s, const Error *error)
1737 trace_migrate_fd_error(error_get_pretty(error));
1738 assert(s->to_dst_file == NULL);
1739 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1740 MIGRATION_STATUS_FAILED);
1741 migrate_set_error(s, error);
1744 static void migrate_fd_cancel(MigrationState *s)
1746 int old_state ;
1747 QEMUFile *f = migrate_get_current()->to_dst_file;
1748 trace_migrate_fd_cancel();
1750 if (s->rp_state.from_dst_file) {
1751 /* shutdown the rp socket, so causing the rp thread to shutdown */
1752 qemu_file_shutdown(s->rp_state.from_dst_file);
1755 do {
1756 old_state = s->state;
1757 if (!migration_is_running(old_state)) {
1758 break;
1760 /* If the migration is paused, kick it out of the pause */
1761 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1762 qemu_sem_post(&s->pause_sem);
1764 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1765 } while (s->state != MIGRATION_STATUS_CANCELLING);
1768 * If we're unlucky the migration code might be stuck somewhere in a
1769 * send/write while the network has failed and is waiting to timeout;
1770 * if we've got shutdown(2) available then we can force it to quit.
1771 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1772 * called in a bh, so there is no race against this cancel.
1774 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1775 qemu_file_shutdown(f);
1777 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1778 Error *local_err = NULL;
1780 bdrv_invalidate_cache_all(&local_err);
1781 if (local_err) {
1782 error_report_err(local_err);
1783 } else {
1784 s->block_inactive = false;
1789 void add_migration_state_change_notifier(Notifier *notify)
1791 notifier_list_add(&migration_state_notifiers, notify);
1794 void remove_migration_state_change_notifier(Notifier *notify)
1796 notifier_remove(notify);
1799 bool migration_in_setup(MigrationState *s)
1801 return s->state == MIGRATION_STATUS_SETUP;
1804 bool migration_has_finished(MigrationState *s)
1806 return s->state == MIGRATION_STATUS_COMPLETED;
1809 bool migration_has_failed(MigrationState *s)
1811 return (s->state == MIGRATION_STATUS_CANCELLED ||
1812 s->state == MIGRATION_STATUS_FAILED);
1815 bool migration_in_postcopy(void)
1817 MigrationState *s = migrate_get_current();
1819 switch (s->state) {
1820 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1821 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1822 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1823 return true;
1824 default:
1825 return false;
1829 bool migration_in_postcopy_after_devices(MigrationState *s)
1831 return migration_in_postcopy() && s->postcopy_after_devices;
1834 bool migration_in_incoming_postcopy(void)
1836 PostcopyState ps = postcopy_state_get();
1838 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
1841 bool migration_is_idle(void)
1843 MigrationState *s = current_migration;
1845 if (!s) {
1846 return true;
1849 switch (s->state) {
1850 case MIGRATION_STATUS_NONE:
1851 case MIGRATION_STATUS_CANCELLED:
1852 case MIGRATION_STATUS_COMPLETED:
1853 case MIGRATION_STATUS_FAILED:
1854 return true;
1855 case MIGRATION_STATUS_SETUP:
1856 case MIGRATION_STATUS_CANCELLING:
1857 case MIGRATION_STATUS_ACTIVE:
1858 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1859 case MIGRATION_STATUS_COLO:
1860 case MIGRATION_STATUS_PRE_SWITCHOVER:
1861 case MIGRATION_STATUS_DEVICE:
1862 case MIGRATION_STATUS_WAIT_UNPLUG:
1863 return false;
1864 case MIGRATION_STATUS__MAX:
1865 g_assert_not_reached();
1868 return false;
1871 bool migration_is_active(MigrationState *s)
1873 return (s->state == MIGRATION_STATUS_ACTIVE ||
1874 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1877 void migrate_init(MigrationState *s)
1880 * Reinitialise all migration state, except
1881 * parameters/capabilities that the user set, and
1882 * locks.
1884 s->cleanup_bh = 0;
1885 s->to_dst_file = NULL;
1886 s->state = MIGRATION_STATUS_NONE;
1887 s->rp_state.from_dst_file = NULL;
1888 s->rp_state.error = false;
1889 s->mbps = 0.0;
1890 s->pages_per_second = 0.0;
1891 s->downtime = 0;
1892 s->expected_downtime = 0;
1893 s->setup_time = 0;
1894 s->start_postcopy = false;
1895 s->postcopy_after_devices = false;
1896 s->migration_thread_running = false;
1897 error_free(s->error);
1898 s->error = NULL;
1900 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1902 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1903 s->total_time = 0;
1904 s->vm_was_running = false;
1905 s->iteration_initial_bytes = 0;
1906 s->threshold_size = 0;
1909 static GSList *migration_blockers;
1911 int migrate_add_blocker(Error *reason, Error **errp)
1913 if (only_migratable) {
1914 error_propagate_prepend(errp, error_copy(reason),
1915 "disallowing migration blocker "
1916 "(--only-migratable) for: ");
1917 return -EACCES;
1920 if (migration_is_idle()) {
1921 migration_blockers = g_slist_prepend(migration_blockers, reason);
1922 return 0;
1925 error_propagate_prepend(errp, error_copy(reason),
1926 "disallowing migration blocker "
1927 "(migration in progress) for: ");
1928 return -EBUSY;
1931 void migrate_del_blocker(Error *reason)
1933 migration_blockers = g_slist_remove(migration_blockers, reason);
1936 void qmp_migrate_incoming(const char *uri, Error **errp)
1938 Error *local_err = NULL;
1939 static bool once = true;
1941 if (!deferred_incoming) {
1942 error_setg(errp, "For use with '-incoming defer'");
1943 return;
1945 if (!once) {
1946 error_setg(errp, "The incoming migration has already been started");
1947 return;
1950 qemu_start_incoming_migration(uri, &local_err);
1952 if (local_err) {
1953 error_propagate(errp, local_err);
1954 return;
1957 once = false;
1960 void qmp_migrate_recover(const char *uri, Error **errp)
1962 MigrationIncomingState *mis = migration_incoming_get_current();
1964 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1965 error_setg(errp, "Migrate recover can only be run "
1966 "when postcopy is paused.");
1967 return;
1970 if (qatomic_cmpxchg(&mis->postcopy_recover_triggered,
1971 false, true) == true) {
1972 error_setg(errp, "Migrate recovery is triggered already");
1973 return;
1977 * Note that this call will never start a real migration; it will
1978 * only re-setup the migration stream and poke existing migration
1979 * to continue using that newly established channel.
1981 qemu_start_incoming_migration(uri, errp);
1984 void qmp_migrate_pause(Error **errp)
1986 MigrationState *ms = migrate_get_current();
1987 MigrationIncomingState *mis = migration_incoming_get_current();
1988 int ret;
1990 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1991 /* Source side, during postcopy */
1992 qemu_mutex_lock(&ms->qemu_file_lock);
1993 ret = qemu_file_shutdown(ms->to_dst_file);
1994 qemu_mutex_unlock(&ms->qemu_file_lock);
1995 if (ret) {
1996 error_setg(errp, "Failed to pause source migration");
1998 return;
2001 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2002 ret = qemu_file_shutdown(mis->from_src_file);
2003 if (ret) {
2004 error_setg(errp, "Failed to pause destination migration");
2006 return;
2009 error_setg(errp, "migrate-pause is currently only supported "
2010 "during postcopy-active state");
2013 bool migration_is_blocked(Error **errp)
2015 if (qemu_savevm_state_blocked(errp)) {
2016 return true;
2019 if (migration_blockers) {
2020 error_propagate(errp, error_copy(migration_blockers->data));
2021 return true;
2024 return false;
2027 /* Returns true if continue to migrate, or false if error detected */
2028 static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
2029 bool resume, Error **errp)
2031 Error *local_err = NULL;
2033 if (resume) {
2034 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2035 error_setg(errp, "Cannot resume if there is no "
2036 "paused migration");
2037 return false;
2041 * Postcopy recovery won't work well with release-ram
2042 * capability since release-ram will drop the page buffer as
2043 * long as the page is put into the send buffer. So if there
2044 * is a network failure happened, any page buffers that have
2045 * not yet reached the destination VM but have already been
2046 * sent from the source VM will be lost forever. Let's refuse
2047 * the client from resuming such a postcopy migration.
2048 * Luckily release-ram was designed to only be used when src
2049 * and destination VMs are on the same host, so it should be
2050 * fine.
2052 if (migrate_release_ram()) {
2053 error_setg(errp, "Postcopy recovery cannot work "
2054 "when release-ram capability is set");
2055 return false;
2058 /* This is a resume, skip init status */
2059 return true;
2062 if (migration_is_running(s->state)) {
2063 error_setg(errp, QERR_MIGRATION_ACTIVE);
2064 return false;
2067 if (runstate_check(RUN_STATE_INMIGRATE)) {
2068 error_setg(errp, "Guest is waiting for an incoming migration");
2069 return false;
2072 if (migration_is_blocked(errp)) {
2073 return false;
2076 if (blk || blk_inc) {
2077 if (migrate_use_block() || migrate_use_block_incremental()) {
2078 error_setg(errp, "Command options are incompatible with "
2079 "current migration capabilities");
2080 return false;
2082 migrate_set_block_enabled(true, &local_err);
2083 if (local_err) {
2084 error_propagate(errp, local_err);
2085 return false;
2087 s->must_remove_block_options = true;
2090 if (blk_inc) {
2091 migrate_set_block_incremental(s, true);
2094 migrate_init(s);
2096 * set ram_counters memory to zero for a
2097 * new migration
2099 memset(&ram_counters, 0, sizeof(ram_counters));
2101 return true;
2104 void qmp_migrate(const char *uri, bool has_blk, bool blk,
2105 bool has_inc, bool inc, bool has_detach, bool detach,
2106 bool has_resume, bool resume, Error **errp)
2108 Error *local_err = NULL;
2109 MigrationState *s = migrate_get_current();
2110 const char *p = NULL;
2112 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2113 has_resume && resume, errp)) {
2114 /* Error detected, put into errp */
2115 return;
2118 if (strstart(uri, "tcp:", &p) ||
2119 strstart(uri, "unix:", NULL) ||
2120 strstart(uri, "vsock:", NULL)) {
2121 socket_start_outgoing_migration(s, p ? p : uri, &local_err);
2122 #ifdef CONFIG_RDMA
2123 } else if (strstart(uri, "rdma:", &p)) {
2124 rdma_start_outgoing_migration(s, p, &local_err);
2125 #endif
2126 } else if (strstart(uri, "exec:", &p)) {
2127 exec_start_outgoing_migration(s, p, &local_err);
2128 } else if (strstart(uri, "fd:", &p)) {
2129 fd_start_outgoing_migration(s, p, &local_err);
2130 } else {
2131 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2132 "a valid migration protocol");
2133 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2134 MIGRATION_STATUS_FAILED);
2135 block_cleanup_parameters(s);
2136 return;
2139 if (local_err) {
2140 migrate_fd_error(s, local_err);
2141 error_propagate(errp, local_err);
2142 return;
2146 void qmp_migrate_cancel(Error **errp)
2148 migrate_fd_cancel(migrate_get_current());
2151 void qmp_migrate_continue(MigrationStatus state, Error **errp)
2153 MigrationState *s = migrate_get_current();
2154 if (s->state != state) {
2155 error_setg(errp, "Migration not in expected state: %s",
2156 MigrationStatus_str(s->state));
2157 return;
2159 qemu_sem_post(&s->pause_sem);
2162 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
2164 MigrateSetParameters p = {
2165 .has_xbzrle_cache_size = true,
2166 .xbzrle_cache_size = value,
2169 qmp_migrate_set_parameters(&p, errp);
2172 int64_t qmp_query_migrate_cache_size(Error **errp)
2174 return migrate_xbzrle_cache_size();
2177 void qmp_migrate_set_speed(int64_t value, Error **errp)
2179 MigrateSetParameters p = {
2180 .has_max_bandwidth = true,
2181 .max_bandwidth = value,
2184 qmp_migrate_set_parameters(&p, errp);
2187 void qmp_migrate_set_downtime(double value, Error **errp)
2189 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
2190 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
2191 "downtime_limit",
2192 "an integer in the range of 0 to "
2193 stringify(MAX_MIGRATE_DOWNTIME_SECONDS)" seconds");
2194 return;
2197 value *= 1000; /* Convert to milliseconds */
2199 MigrateSetParameters p = {
2200 .has_downtime_limit = true,
2201 .downtime_limit = (int64_t)value,
2204 qmp_migrate_set_parameters(&p, errp);
2207 bool migrate_release_ram(void)
2209 MigrationState *s;
2211 s = migrate_get_current();
2213 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2216 bool migrate_postcopy_ram(void)
2218 MigrationState *s;
2220 s = migrate_get_current();
2222 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
2225 bool migrate_postcopy(void)
2227 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
2230 bool migrate_auto_converge(void)
2232 MigrationState *s;
2234 s = migrate_get_current();
2236 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2239 bool migrate_zero_blocks(void)
2241 MigrationState *s;
2243 s = migrate_get_current();
2245 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2248 bool migrate_postcopy_blocktime(void)
2250 MigrationState *s;
2252 s = migrate_get_current();
2254 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2257 bool migrate_use_compression(void)
2259 MigrationState *s;
2261 s = migrate_get_current();
2263 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
2266 int migrate_compress_level(void)
2268 MigrationState *s;
2270 s = migrate_get_current();
2272 return s->parameters.compress_level;
2275 int migrate_compress_threads(void)
2277 MigrationState *s;
2279 s = migrate_get_current();
2281 return s->parameters.compress_threads;
2284 int migrate_compress_wait_thread(void)
2286 MigrationState *s;
2288 s = migrate_get_current();
2290 return s->parameters.compress_wait_thread;
2293 int migrate_decompress_threads(void)
2295 MigrationState *s;
2297 s = migrate_get_current();
2299 return s->parameters.decompress_threads;
2302 bool migrate_dirty_bitmaps(void)
2304 MigrationState *s;
2306 s = migrate_get_current();
2308 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2311 bool migrate_ignore_shared(void)
2313 MigrationState *s;
2315 s = migrate_get_current();
2317 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2320 bool migrate_validate_uuid(void)
2322 MigrationState *s;
2324 s = migrate_get_current();
2326 return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2329 bool migrate_use_events(void)
2331 MigrationState *s;
2333 s = migrate_get_current();
2335 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2338 bool migrate_use_multifd(void)
2340 MigrationState *s;
2342 s = migrate_get_current();
2344 return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
2347 bool migrate_pause_before_switchover(void)
2349 MigrationState *s;
2351 s = migrate_get_current();
2353 return s->enabled_capabilities[
2354 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2357 int migrate_multifd_channels(void)
2359 MigrationState *s;
2361 s = migrate_get_current();
2363 return s->parameters.multifd_channels;
2366 MultiFDCompression migrate_multifd_compression(void)
2368 MigrationState *s;
2370 s = migrate_get_current();
2372 return s->parameters.multifd_compression;
2375 int migrate_multifd_zlib_level(void)
2377 MigrationState *s;
2379 s = migrate_get_current();
2381 return s->parameters.multifd_zlib_level;
2384 int migrate_multifd_zstd_level(void)
2386 MigrationState *s;
2388 s = migrate_get_current();
2390 return s->parameters.multifd_zstd_level;
2393 int migrate_use_xbzrle(void)
2395 MigrationState *s;
2397 s = migrate_get_current();
2399 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2402 int64_t migrate_xbzrle_cache_size(void)
2404 MigrationState *s;
2406 s = migrate_get_current();
2408 return s->parameters.xbzrle_cache_size;
2411 static int64_t migrate_max_postcopy_bandwidth(void)
2413 MigrationState *s;
2415 s = migrate_get_current();
2417 return s->parameters.max_postcopy_bandwidth;
2420 bool migrate_use_block(void)
2422 MigrationState *s;
2424 s = migrate_get_current();
2426 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2429 bool migrate_use_return_path(void)
2431 MigrationState *s;
2433 s = migrate_get_current();
2435 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2438 bool migrate_use_block_incremental(void)
2440 MigrationState *s;
2442 s = migrate_get_current();
2444 return s->parameters.block_incremental;
2447 /* migration thread support */
2449 * Something bad happened to the RP stream, mark an error
2450 * The caller shall print or trace something to indicate why
2452 static void mark_source_rp_bad(MigrationState *s)
2454 s->rp_state.error = true;
2457 static struct rp_cmd_args {
2458 ssize_t len; /* -1 = variable */
2459 const char *name;
2460 } rp_cmd_args[] = {
2461 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2462 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2463 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
2464 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2465 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
2466 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
2467 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
2468 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2472 * Process a request for pages received on the return path,
2473 * We're allowed to send more than requested (e.g. to round to our page size)
2474 * and we don't need to send pages that have already been sent.
2476 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2477 ram_addr_t start, size_t len)
2479 long our_host_ps = qemu_real_host_page_size;
2481 trace_migrate_handle_rp_req_pages(rbname, start, len);
2484 * Since we currently insist on matching page sizes, just sanity check
2485 * we're being asked for whole host pages.
2487 if (start & (our_host_ps-1) ||
2488 (len & (our_host_ps-1))) {
2489 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2490 " len: %zd", __func__, start, len);
2491 mark_source_rp_bad(ms);
2492 return;
2495 if (ram_save_queue_pages(rbname, start, len)) {
2496 mark_source_rp_bad(ms);
2500 /* Return true to retry, false to quit */
2501 static bool postcopy_pause_return_path_thread(MigrationState *s)
2503 trace_postcopy_pause_return_path();
2505 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2507 trace_postcopy_pause_return_path_continued();
2509 return true;
2512 static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2514 RAMBlock *block = qemu_ram_block_by_name(block_name);
2516 if (!block) {
2517 error_report("%s: invalid block name '%s'", __func__, block_name);
2518 return -EINVAL;
2521 /* Fetch the received bitmap and refresh the dirty bitmap */
2522 return ram_dirty_bitmap_reload(s, block);
2525 static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2527 trace_source_return_path_thread_resume_ack(value);
2529 if (value != MIGRATION_RESUME_ACK_VALUE) {
2530 error_report("%s: illegal resume_ack value %"PRIu32,
2531 __func__, value);
2532 return -1;
2535 /* Now both sides are active. */
2536 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2537 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2539 /* Notify send thread that time to continue send pages */
2540 qemu_sem_post(&s->rp_state.rp_sem);
2542 return 0;
2546 * Handles messages sent on the return path towards the source VM
2549 static void *source_return_path_thread(void *opaque)
2551 MigrationState *ms = opaque;
2552 QEMUFile *rp = ms->rp_state.from_dst_file;
2553 uint16_t header_len, header_type;
2554 uint8_t buf[512];
2555 uint32_t tmp32, sibling_error;
2556 ram_addr_t start = 0; /* =0 to silence warning */
2557 size_t len = 0, expected_len;
2558 int res;
2560 trace_source_return_path_thread_entry();
2561 rcu_register_thread();
2563 retry:
2564 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2565 migration_is_setup_or_active(ms->state)) {
2566 trace_source_return_path_thread_loop_top();
2567 header_type = qemu_get_be16(rp);
2568 header_len = qemu_get_be16(rp);
2570 if (qemu_file_get_error(rp)) {
2571 mark_source_rp_bad(ms);
2572 goto out;
2575 if (header_type >= MIG_RP_MSG_MAX ||
2576 header_type == MIG_RP_MSG_INVALID) {
2577 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2578 header_type, header_len);
2579 mark_source_rp_bad(ms);
2580 goto out;
2583 if ((rp_cmd_args[header_type].len != -1 &&
2584 header_len != rp_cmd_args[header_type].len) ||
2585 header_len > sizeof(buf)) {
2586 error_report("RP: Received '%s' message (0x%04x) with"
2587 "incorrect length %d expecting %zu",
2588 rp_cmd_args[header_type].name, header_type, header_len,
2589 (size_t)rp_cmd_args[header_type].len);
2590 mark_source_rp_bad(ms);
2591 goto out;
2594 /* We know we've got a valid header by this point */
2595 res = qemu_get_buffer(rp, buf, header_len);
2596 if (res != header_len) {
2597 error_report("RP: Failed reading data for message 0x%04x"
2598 " read %d expected %d",
2599 header_type, res, header_len);
2600 mark_source_rp_bad(ms);
2601 goto out;
2604 /* OK, we have the message and the data */
2605 switch (header_type) {
2606 case MIG_RP_MSG_SHUT:
2607 sibling_error = ldl_be_p(buf);
2608 trace_source_return_path_thread_shut(sibling_error);
2609 if (sibling_error) {
2610 error_report("RP: Sibling indicated error %d", sibling_error);
2611 mark_source_rp_bad(ms);
2614 * We'll let the main thread deal with closing the RP
2615 * we could do a shutdown(2) on it, but we're the only user
2616 * anyway, so there's nothing gained.
2618 goto out;
2620 case MIG_RP_MSG_PONG:
2621 tmp32 = ldl_be_p(buf);
2622 trace_source_return_path_thread_pong(tmp32);
2623 break;
2625 case MIG_RP_MSG_REQ_PAGES:
2626 start = ldq_be_p(buf);
2627 len = ldl_be_p(buf + 8);
2628 migrate_handle_rp_req_pages(ms, NULL, start, len);
2629 break;
2631 case MIG_RP_MSG_REQ_PAGES_ID:
2632 expected_len = 12 + 1; /* header + termination */
2634 if (header_len >= expected_len) {
2635 start = ldq_be_p(buf);
2636 len = ldl_be_p(buf + 8);
2637 /* Now we expect an idstr */
2638 tmp32 = buf[12]; /* Length of the following idstr */
2639 buf[13 + tmp32] = '\0';
2640 expected_len += tmp32;
2642 if (header_len != expected_len) {
2643 error_report("RP: Req_Page_id with length %d expecting %zd",
2644 header_len, expected_len);
2645 mark_source_rp_bad(ms);
2646 goto out;
2648 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2649 break;
2651 case MIG_RP_MSG_RECV_BITMAP:
2652 if (header_len < 1) {
2653 error_report("%s: missing block name", __func__);
2654 mark_source_rp_bad(ms);
2655 goto out;
2657 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2658 buf[buf[0] + 1] = '\0';
2659 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2660 mark_source_rp_bad(ms);
2661 goto out;
2663 break;
2665 case MIG_RP_MSG_RESUME_ACK:
2666 tmp32 = ldl_be_p(buf);
2667 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2668 mark_source_rp_bad(ms);
2669 goto out;
2671 break;
2673 default:
2674 break;
2678 out:
2679 res = qemu_file_get_error(rp);
2680 if (res) {
2681 if (res == -EIO && migration_in_postcopy()) {
2683 * Maybe there is something we can do: it looks like a
2684 * network down issue, and we pause for a recovery.
2686 if (postcopy_pause_return_path_thread(ms)) {
2687 /* Reload rp, reset the rest */
2688 if (rp != ms->rp_state.from_dst_file) {
2689 qemu_fclose(rp);
2690 rp = ms->rp_state.from_dst_file;
2692 ms->rp_state.error = false;
2693 goto retry;
2697 trace_source_return_path_thread_bad_end();
2698 mark_source_rp_bad(ms);
2701 trace_source_return_path_thread_end();
2702 ms->rp_state.from_dst_file = NULL;
2703 qemu_fclose(rp);
2704 rcu_unregister_thread();
2705 return NULL;
2708 static int open_return_path_on_source(MigrationState *ms,
2709 bool create_thread)
2712 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
2713 if (!ms->rp_state.from_dst_file) {
2714 return -1;
2717 trace_open_return_path_on_source();
2719 if (!create_thread) {
2720 /* We're done */
2721 return 0;
2724 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2725 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2727 trace_open_return_path_on_source_continue();
2729 return 0;
2732 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2733 static int await_return_path_close_on_source(MigrationState *ms)
2736 * If this is a normal exit then the destination will send a SHUT and the
2737 * rp_thread will exit, however if there's an error we need to cause
2738 * it to exit.
2740 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
2742 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2743 * waiting for the destination.
2745 qemu_file_shutdown(ms->rp_state.from_dst_file);
2746 mark_source_rp_bad(ms);
2748 trace_await_return_path_close_on_source_joining();
2749 qemu_thread_join(&ms->rp_state.rp_thread);
2750 trace_await_return_path_close_on_source_close();
2751 return ms->rp_state.error;
2755 * Switch from normal iteration to postcopy
2756 * Returns non-0 on error
2758 static int postcopy_start(MigrationState *ms)
2760 int ret;
2761 QIOChannelBuffer *bioc;
2762 QEMUFile *fb;
2763 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2764 int64_t bandwidth = migrate_max_postcopy_bandwidth();
2765 bool restart_block = false;
2766 int cur_state = MIGRATION_STATUS_ACTIVE;
2767 if (!migrate_pause_before_switchover()) {
2768 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2769 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2772 trace_postcopy_start();
2773 qemu_mutex_lock_iothread();
2774 trace_postcopy_start_set_run();
2776 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2777 global_state_store();
2778 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2779 if (ret < 0) {
2780 goto fail;
2783 ret = migration_maybe_pause(ms, &cur_state,
2784 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2785 if (ret < 0) {
2786 goto fail;
2789 ret = bdrv_inactivate_all();
2790 if (ret < 0) {
2791 goto fail;
2793 restart_block = true;
2796 * Cause any non-postcopiable, but iterative devices to
2797 * send out their final data.
2799 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
2802 * in Finish migrate and with the io-lock held everything should
2803 * be quiet, but we've potentially still got dirty pages and we
2804 * need to tell the destination to throw any pages it's already received
2805 * that are dirty
2807 if (migrate_postcopy_ram()) {
2808 if (ram_postcopy_send_discard_bitmap(ms)) {
2809 error_report("postcopy send discard bitmap failed");
2810 goto fail;
2815 * send rest of state - note things that are doing postcopy
2816 * will notice we're in POSTCOPY_ACTIVE and not actually
2817 * wrap their state up here
2819 /* 0 max-postcopy-bandwidth means unlimited */
2820 if (!bandwidth) {
2821 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2822 } else {
2823 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2825 if (migrate_postcopy_ram()) {
2826 /* Ping just for debugging, helps line traces up */
2827 qemu_savevm_send_ping(ms->to_dst_file, 2);
2831 * While loading the device state we may trigger page transfer
2832 * requests and the fd must be free to process those, and thus
2833 * the destination must read the whole device state off the fd before
2834 * it starts processing it. Unfortunately the ad-hoc migration format
2835 * doesn't allow the destination to know the size to read without fully
2836 * parsing it through each devices load-state code (especially the open
2837 * coded devices that use get/put).
2838 * So we wrap the device state up in a package with a length at the start;
2839 * to do this we use a qemu_buf to hold the whole of the device state.
2841 bioc = qio_channel_buffer_new(4096);
2842 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2843 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2844 object_unref(OBJECT(bioc));
2847 * Make sure the receiver can get incoming pages before we send the rest
2848 * of the state
2850 qemu_savevm_send_postcopy_listen(fb);
2852 qemu_savevm_state_complete_precopy(fb, false, false);
2853 if (migrate_postcopy_ram()) {
2854 qemu_savevm_send_ping(fb, 3);
2857 qemu_savevm_send_postcopy_run(fb);
2859 /* <><> end of stuff going into the package */
2861 /* Last point of recovery; as soon as we send the package the destination
2862 * can open devices and potentially start running.
2863 * Lets just check again we've not got any errors.
2865 ret = qemu_file_get_error(ms->to_dst_file);
2866 if (ret) {
2867 error_report("postcopy_start: Migration stream errored (pre package)");
2868 goto fail_closefb;
2871 restart_block = false;
2873 /* Now send that blob */
2874 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2875 goto fail_closefb;
2877 qemu_fclose(fb);
2879 /* Send a notify to give a chance for anything that needs to happen
2880 * at the transition to postcopy and after the device state; in particular
2881 * spice needs to trigger a transition now
2883 ms->postcopy_after_devices = true;
2884 notifier_list_notify(&migration_state_notifiers, ms);
2886 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2888 qemu_mutex_unlock_iothread();
2890 if (migrate_postcopy_ram()) {
2892 * Although this ping is just for debug, it could potentially be
2893 * used for getting a better measurement of downtime at the source.
2895 qemu_savevm_send_ping(ms->to_dst_file, 4);
2898 if (migrate_release_ram()) {
2899 ram_postcopy_migrated_memory_release(ms);
2902 ret = qemu_file_get_error(ms->to_dst_file);
2903 if (ret) {
2904 error_report("postcopy_start: Migration stream errored");
2905 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2906 MIGRATION_STATUS_FAILED);
2909 return ret;
2911 fail_closefb:
2912 qemu_fclose(fb);
2913 fail:
2914 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2915 MIGRATION_STATUS_FAILED);
2916 if (restart_block) {
2917 /* A failure happened early enough that we know the destination hasn't
2918 * accessed block devices, so we're safe to recover.
2920 Error *local_err = NULL;
2922 bdrv_invalidate_cache_all(&local_err);
2923 if (local_err) {
2924 error_report_err(local_err);
2927 qemu_mutex_unlock_iothread();
2928 return -1;
2932 * migration_maybe_pause: Pause if required to by
2933 * migrate_pause_before_switchover called with the iothread locked
2934 * Returns: 0 on success
2936 static int migration_maybe_pause(MigrationState *s,
2937 int *current_active_state,
2938 int new_state)
2940 if (!migrate_pause_before_switchover()) {
2941 return 0;
2944 /* Since leaving this state is not atomic with posting the semaphore
2945 * it's possible that someone could have issued multiple migrate_continue
2946 * and the semaphore is incorrectly positive at this point;
2947 * the docs say it's undefined to reinit a semaphore that's already
2948 * init'd, so use timedwait to eat up any existing posts.
2950 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2951 /* This block intentionally left blank */
2955 * If the migration is cancelled when it is in the completion phase,
2956 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2957 * So we don't need to wait a semaphore, otherwise we would always
2958 * wait for the 'pause_sem' semaphore.
2960 if (s->state != MIGRATION_STATUS_CANCELLING) {
2961 qemu_mutex_unlock_iothread();
2962 migrate_set_state(&s->state, *current_active_state,
2963 MIGRATION_STATUS_PRE_SWITCHOVER);
2964 qemu_sem_wait(&s->pause_sem);
2965 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2966 new_state);
2967 *current_active_state = new_state;
2968 qemu_mutex_lock_iothread();
2971 return s->state == new_state ? 0 : -EINVAL;
2975 * migration_completion: Used by migration_thread when there's not much left.
2976 * The caller 'breaks' the loop when this returns.
2978 * @s: Current migration state
2980 static void migration_completion(MigrationState *s)
2982 int ret;
2983 int current_active_state = s->state;
2985 if (s->state == MIGRATION_STATUS_ACTIVE) {
2986 qemu_mutex_lock_iothread();
2987 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2988 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
2989 s->vm_was_running = runstate_is_running();
2990 ret = global_state_store();
2992 if (!ret) {
2993 bool inactivate = !migrate_colo_enabled();
2994 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2995 if (ret >= 0) {
2996 ret = migration_maybe_pause(s, &current_active_state,
2997 MIGRATION_STATUS_DEVICE);
2999 if (ret >= 0) {
3000 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
3001 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
3002 inactivate);
3004 if (inactivate && ret >= 0) {
3005 s->block_inactive = true;
3008 qemu_mutex_unlock_iothread();
3010 if (ret < 0) {
3011 goto fail;
3013 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3014 trace_migration_completion_postcopy_end();
3016 qemu_savevm_state_complete_postcopy(s->to_dst_file);
3017 trace_migration_completion_postcopy_end_after_complete();
3021 * If rp was opened we must clean up the thread before
3022 * cleaning everything else up (since if there are no failures
3023 * it will wait for the destination to send it's status in
3024 * a SHUT command).
3026 if (s->rp_state.from_dst_file) {
3027 int rp_error;
3028 trace_migration_return_path_end_before();
3029 rp_error = await_return_path_close_on_source(s);
3030 trace_migration_return_path_end_after(rp_error);
3031 if (rp_error) {
3032 goto fail_invalidate;
3036 if (qemu_file_get_error(s->to_dst_file)) {
3037 trace_migration_completion_file_err();
3038 goto fail_invalidate;
3041 if (!migrate_colo_enabled()) {
3042 migrate_set_state(&s->state, current_active_state,
3043 MIGRATION_STATUS_COMPLETED);
3046 return;
3048 fail_invalidate:
3049 /* If not doing postcopy, vm_start() will be called: let's regain
3050 * control on images.
3052 if (s->state == MIGRATION_STATUS_ACTIVE ||
3053 s->state == MIGRATION_STATUS_DEVICE) {
3054 Error *local_err = NULL;
3056 qemu_mutex_lock_iothread();
3057 bdrv_invalidate_cache_all(&local_err);
3058 if (local_err) {
3059 error_report_err(local_err);
3060 } else {
3061 s->block_inactive = false;
3063 qemu_mutex_unlock_iothread();
3066 fail:
3067 migrate_set_state(&s->state, current_active_state,
3068 MIGRATION_STATUS_FAILED);
3071 bool migrate_colo_enabled(void)
3073 MigrationState *s = migrate_get_current();
3074 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
3077 typedef enum MigThrError {
3078 /* No error detected */
3079 MIG_THR_ERR_NONE = 0,
3080 /* Detected error, but resumed successfully */
3081 MIG_THR_ERR_RECOVERED = 1,
3082 /* Detected fatal error, need to exit */
3083 MIG_THR_ERR_FATAL = 2,
3084 } MigThrError;
3086 static int postcopy_resume_handshake(MigrationState *s)
3088 qemu_savevm_send_postcopy_resume(s->to_dst_file);
3090 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3091 qemu_sem_wait(&s->rp_state.rp_sem);
3094 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3095 return 0;
3098 return -1;
3101 /* Return zero if success, or <0 for error */
3102 static int postcopy_do_resume(MigrationState *s)
3104 int ret;
3107 * Call all the resume_prepare() hooks, so that modules can be
3108 * ready for the migration resume.
3110 ret = qemu_savevm_state_resume_prepare(s);
3111 if (ret) {
3112 error_report("%s: resume_prepare() failure detected: %d",
3113 __func__, ret);
3114 return ret;
3118 * Last handshake with destination on the resume (destination will
3119 * switch to postcopy-active afterwards)
3121 ret = postcopy_resume_handshake(s);
3122 if (ret) {
3123 error_report("%s: handshake failed: %d", __func__, ret);
3124 return ret;
3127 return 0;
3131 * We don't return until we are in a safe state to continue current
3132 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
3133 * MIG_THR_ERR_FATAL if unrecovery failure happened.
3135 static MigThrError postcopy_pause(MigrationState *s)
3137 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3139 while (true) {
3140 QEMUFile *file;
3142 migrate_set_state(&s->state, s->state,
3143 MIGRATION_STATUS_POSTCOPY_PAUSED);
3145 /* Current channel is possibly broken. Release it. */
3146 assert(s->to_dst_file);
3147 qemu_mutex_lock(&s->qemu_file_lock);
3148 file = s->to_dst_file;
3149 s->to_dst_file = NULL;
3150 qemu_mutex_unlock(&s->qemu_file_lock);
3152 qemu_file_shutdown(file);
3153 qemu_fclose(file);
3155 error_report("Detected IO failure for postcopy. "
3156 "Migration paused.");
3159 * We wait until things fixed up. Then someone will setup the
3160 * status back for us.
3162 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3163 qemu_sem_wait(&s->postcopy_pause_sem);
3166 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3167 /* Woken up by a recover procedure. Give it a shot */
3170 * Firstly, let's wake up the return path now, with a new
3171 * return path channel.
3173 qemu_sem_post(&s->postcopy_pause_rp_sem);
3175 /* Do the resume logic */
3176 if (postcopy_do_resume(s) == 0) {
3177 /* Let's continue! */
3178 trace_postcopy_pause_continued();
3179 return MIG_THR_ERR_RECOVERED;
3180 } else {
3182 * Something wrong happened during the recovery, let's
3183 * pause again. Pause is always better than throwing
3184 * data away.
3186 continue;
3188 } else {
3189 /* This is not right... Time to quit. */
3190 return MIG_THR_ERR_FATAL;
3195 static MigThrError migration_detect_error(MigrationState *s)
3197 int ret;
3198 int state = s->state;
3199 Error *local_error = NULL;
3201 if (state == MIGRATION_STATUS_CANCELLING ||
3202 state == MIGRATION_STATUS_CANCELLED) {
3203 /* End the migration, but don't set the state to failed */
3204 return MIG_THR_ERR_FATAL;
3207 /* Try to detect any file errors */
3208 ret = qemu_file_get_error_obj(s->to_dst_file, &local_error);
3209 if (!ret) {
3210 /* Everything is fine */
3211 assert(!local_error);
3212 return MIG_THR_ERR_NONE;
3215 if (local_error) {
3216 migrate_set_error(s, local_error);
3217 error_free(local_error);
3220 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
3222 * For postcopy, we allow the network to be down for a
3223 * while. After that, it can be continued by a
3224 * recovery phase.
3226 return postcopy_pause(s);
3227 } else {
3229 * For precopy (or postcopy with error outside IO), we fail
3230 * with no time.
3232 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
3233 trace_migration_thread_file_err();
3235 /* Time to stop the migration, now. */
3236 return MIG_THR_ERR_FATAL;
3240 /* How many bytes have we transferred since the beginning of the migration */
3241 static uint64_t migration_total_bytes(MigrationState *s)
3243 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
3246 static void migration_calculate_complete(MigrationState *s)
3248 uint64_t bytes = migration_total_bytes(s);
3249 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3250 int64_t transfer_time;
3252 s->total_time = end_time - s->start_time;
3253 if (!s->downtime) {
3255 * It's still not set, so we are precopy migration. For
3256 * postcopy, downtime is calculated during postcopy_start().
3258 s->downtime = end_time - s->downtime_start;
3261 transfer_time = s->total_time - s->setup_time;
3262 if (transfer_time) {
3263 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
3267 static void update_iteration_initial_status(MigrationState *s)
3270 * Update these three fields at the same time to avoid mismatch info lead
3271 * wrong speed calculation.
3273 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3274 s->iteration_initial_bytes = migration_total_bytes(s);
3275 s->iteration_initial_pages = ram_get_total_transferred_pages();
3278 static void migration_update_counters(MigrationState *s,
3279 int64_t current_time)
3281 uint64_t transferred, transferred_pages, time_spent;
3282 uint64_t current_bytes; /* bytes transferred since the beginning */
3283 double bandwidth;
3285 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3286 return;
3289 current_bytes = migration_total_bytes(s);
3290 transferred = current_bytes - s->iteration_initial_bytes;
3291 time_spent = current_time - s->iteration_start_time;
3292 bandwidth = (double)transferred / time_spent;
3293 s->threshold_size = bandwidth * s->parameters.downtime_limit;
3295 s->mbps = (((double) transferred * 8.0) /
3296 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3298 transferred_pages = ram_get_total_transferred_pages() -
3299 s->iteration_initial_pages;
3300 s->pages_per_second = (double) transferred_pages /
3301 (((double) time_spent / 1000.0));
3304 * if we haven't sent anything, we don't want to
3305 * recalculate. 10000 is a small enough number for our purposes
3307 if (ram_counters.dirty_pages_rate && transferred > 10000) {
3308 s->expected_downtime = ram_counters.remaining / bandwidth;
3311 qemu_file_reset_rate_limit(s->to_dst_file);
3313 update_iteration_initial_status(s);
3315 trace_migrate_transferred(transferred, time_spent,
3316 bandwidth, s->threshold_size);
3319 /* Migration thread iteration status */
3320 typedef enum {
3321 MIG_ITERATE_RESUME, /* Resume current iteration */
3322 MIG_ITERATE_SKIP, /* Skip current iteration */
3323 MIG_ITERATE_BREAK, /* Break the loop */
3324 } MigIterateState;
3327 * Return true if continue to the next iteration directly, false
3328 * otherwise.
3330 static MigIterateState migration_iteration_run(MigrationState *s)
3332 uint64_t pending_size, pend_pre, pend_compat, pend_post;
3333 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3335 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
3336 &pend_compat, &pend_post);
3337 pending_size = pend_pre + pend_compat + pend_post;
3339 trace_migrate_pending(pending_size, s->threshold_size,
3340 pend_pre, pend_compat, pend_post);
3342 if (pending_size && pending_size >= s->threshold_size) {
3343 /* Still a significant amount to transfer */
3344 if (!in_postcopy && pend_pre <= s->threshold_size &&
3345 qatomic_read(&s->start_postcopy)) {
3346 if (postcopy_start(s)) {
3347 error_report("%s: postcopy failed to start", __func__);
3349 return MIG_ITERATE_SKIP;
3351 /* Just another iteration step */
3352 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
3353 } else {
3354 trace_migration_thread_low_pending(pending_size);
3355 migration_completion(s);
3356 return MIG_ITERATE_BREAK;
3359 return MIG_ITERATE_RESUME;
3362 static void migration_iteration_finish(MigrationState *s)
3364 /* If we enabled cpu throttling for auto-converge, turn it off. */
3365 cpu_throttle_stop();
3367 qemu_mutex_lock_iothread();
3368 switch (s->state) {
3369 case MIGRATION_STATUS_COMPLETED:
3370 migration_calculate_complete(s);
3371 runstate_set(RUN_STATE_POSTMIGRATE);
3372 break;
3374 case MIGRATION_STATUS_ACTIVE:
3376 * We should really assert here, but since it's during
3377 * migration, let's try to reduce the usage of assertions.
3379 if (!migrate_colo_enabled()) {
3380 error_report("%s: critical error: calling COLO code without "
3381 "COLO enabled", __func__);
3383 migrate_start_colo_process(s);
3385 * Fixme: we will run VM in COLO no matter its old running state.
3386 * After exited COLO, we will keep running.
3388 s->vm_was_running = true;
3389 /* Fallthrough */
3390 case MIGRATION_STATUS_FAILED:
3391 case MIGRATION_STATUS_CANCELLED:
3392 case MIGRATION_STATUS_CANCELLING:
3393 if (s->vm_was_running) {
3394 vm_start();
3395 } else {
3396 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3397 runstate_set(RUN_STATE_POSTMIGRATE);
3400 break;
3402 default:
3403 /* Should not reach here, but if so, forgive the VM. */
3404 error_report("%s: Unknown ending state %d", __func__, s->state);
3405 break;
3407 migrate_fd_cleanup_schedule(s);
3408 qemu_mutex_unlock_iothread();
3411 void migration_make_urgent_request(void)
3413 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3416 void migration_consume_urgent_request(void)
3418 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3421 /* Returns true if the rate limiting was broken by an urgent request */
3422 bool migration_rate_limit(void)
3424 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3425 MigrationState *s = migrate_get_current();
3427 bool urgent = false;
3428 migration_update_counters(s, now);
3429 if (qemu_file_rate_limit(s->to_dst_file)) {
3431 if (qemu_file_get_error(s->to_dst_file)) {
3432 return false;
3435 * Wait for a delay to do rate limiting OR
3436 * something urgent to post the semaphore.
3438 int ms = s->iteration_start_time + BUFFER_DELAY - now;
3439 trace_migration_rate_limit_pre(ms);
3440 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3442 * We were woken by one or more urgent things but
3443 * the timedwait will have consumed one of them.
3444 * The service routine for the urgent wake will dec
3445 * the semaphore itself for each item it consumes,
3446 * so add this one we just eat back.
3448 qemu_sem_post(&s->rate_limit_sem);
3449 urgent = true;
3451 trace_migration_rate_limit_post(urgent);
3453 return urgent;
3457 * Master migration thread on the source VM.
3458 * It drives the migration and pumps the data down the outgoing channel.
3460 static void *migration_thread(void *opaque)
3462 MigrationState *s = opaque;
3463 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3464 MigThrError thr_error;
3465 bool urgent = false;
3467 rcu_register_thread();
3469 object_ref(OBJECT(s));
3470 update_iteration_initial_status(s);
3472 qemu_savevm_state_header(s->to_dst_file);
3475 * If we opened the return path, we need to make sure dst has it
3476 * opened as well.
3478 if (s->rp_state.from_dst_file) {
3479 /* Now tell the dest that it should open its end so it can reply */
3480 qemu_savevm_send_open_return_path(s->to_dst_file);
3482 /* And do a ping that will make stuff easier to debug */
3483 qemu_savevm_send_ping(s->to_dst_file, 1);
3486 if (migrate_postcopy()) {
3488 * Tell the destination that we *might* want to do postcopy later;
3489 * if the other end can't do postcopy it should fail now, nice and
3490 * early.
3492 qemu_savevm_send_postcopy_advise(s->to_dst_file);
3495 if (migrate_colo_enabled()) {
3496 /* Notify migration destination that we enable COLO */
3497 qemu_savevm_send_colo_enable(s->to_dst_file);
3500 qemu_savevm_state_setup(s->to_dst_file);
3502 if (qemu_savevm_state_guest_unplug_pending()) {
3503 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3504 MIGRATION_STATUS_WAIT_UNPLUG);
3506 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3507 qemu_savevm_state_guest_unplug_pending()) {
3508 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3511 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG,
3512 MIGRATION_STATUS_ACTIVE);
3515 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3516 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3517 MIGRATION_STATUS_ACTIVE);
3519 trace_migration_thread_setup_complete();
3521 while (migration_is_active(s)) {
3522 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
3523 MigIterateState iter_state = migration_iteration_run(s);
3524 if (iter_state == MIG_ITERATE_SKIP) {
3525 continue;
3526 } else if (iter_state == MIG_ITERATE_BREAK) {
3527 break;
3532 * Try to detect any kind of failures, and see whether we
3533 * should stop the migration now.
3535 thr_error = migration_detect_error(s);
3536 if (thr_error == MIG_THR_ERR_FATAL) {
3537 /* Stop migration */
3538 break;
3539 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3541 * Just recovered from a e.g. network failure, reset all
3542 * the local variables. This is important to avoid
3543 * breaking transferred_bytes and bandwidth calculation
3545 update_iteration_initial_status(s);
3548 urgent = migration_rate_limit();
3551 trace_migration_thread_after_loop();
3552 migration_iteration_finish(s);
3553 object_unref(OBJECT(s));
3554 rcu_unregister_thread();
3555 return NULL;
3558 void migrate_fd_connect(MigrationState *s, Error *error_in)
3560 Error *local_err = NULL;
3561 int64_t rate_limit;
3562 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3564 s->expected_downtime = s->parameters.downtime_limit;
3565 if (resume) {
3566 assert(s->cleanup_bh);
3567 } else {
3568 assert(!s->cleanup_bh);
3569 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
3571 if (error_in) {
3572 migrate_fd_error(s, error_in);
3573 migrate_fd_cleanup(s);
3574 return;
3577 if (resume) {
3578 /* This is a resumed migration */
3579 rate_limit = s->parameters.max_postcopy_bandwidth /
3580 XFER_LIMIT_RATIO;
3581 } else {
3582 /* This is a fresh new migration */
3583 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
3585 /* Notify before starting migration thread */
3586 notifier_list_notify(&migration_state_notifiers, s);
3589 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3590 qemu_file_set_blocking(s->to_dst_file, true);
3593 * Open the return path. For postcopy, it is used exclusively. For
3594 * precopy, only if user specified "return-path" capability would
3595 * QEMU uses the return path.
3597 if (migrate_postcopy_ram() || migrate_use_return_path()) {
3598 if (open_return_path_on_source(s, !resume)) {
3599 error_report("Unable to open return-path for postcopy");
3600 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
3601 migrate_fd_cleanup(s);
3602 return;
3606 if (resume) {
3607 /* Wakeup the main migration thread to do the recovery */
3608 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3609 MIGRATION_STATUS_POSTCOPY_RECOVER);
3610 qemu_sem_post(&s->postcopy_pause_sem);
3611 return;
3614 if (multifd_save_setup(&local_err) != 0) {
3615 error_report_err(local_err);
3616 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3617 MIGRATION_STATUS_FAILED);
3618 migrate_fd_cleanup(s);
3619 return;
3621 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
3622 QEMU_THREAD_JOINABLE);
3623 s->migration_thread_running = true;
3626 void migration_global_dump(Monitor *mon)
3628 MigrationState *ms = migrate_get_current();
3630 monitor_printf(mon, "globals:\n");
3631 monitor_printf(mon, "store-global-state: %s\n",
3632 ms->store_global_state ? "on" : "off");
3633 monitor_printf(mon, "only-migratable: %s\n",
3634 only_migratable ? "on" : "off");
3635 monitor_printf(mon, "send-configuration: %s\n",
3636 ms->send_configuration ? "on" : "off");
3637 monitor_printf(mon, "send-section-footer: %s\n",
3638 ms->send_section_footer ? "on" : "off");
3639 monitor_printf(mon, "decompress-error-check: %s\n",
3640 ms->decompress_error_check ? "on" : "off");
3641 monitor_printf(mon, "clear-bitmap-shift: %u\n",
3642 ms->clear_bitmap_shift);
3645 #define DEFINE_PROP_MIG_CAP(name, x) \
3646 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3648 static Property migration_properties[] = {
3649 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3650 store_global_state, true),
3651 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3652 send_configuration, true),
3653 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3654 send_section_footer, true),
3655 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3656 decompress_error_check, true),
3657 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
3658 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
3660 /* Migration parameters */
3661 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
3662 parameters.compress_level,
3663 DEFAULT_MIGRATE_COMPRESS_LEVEL),
3664 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
3665 parameters.compress_threads,
3666 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
3667 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3668 parameters.compress_wait_thread, true),
3669 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
3670 parameters.decompress_threads,
3671 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
3672 DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
3673 parameters.throttle_trigger_threshold,
3674 DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
3675 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
3676 parameters.cpu_throttle_initial,
3677 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
3678 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
3679 parameters.cpu_throttle_increment,
3680 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
3681 DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState,
3682 parameters.cpu_throttle_tailslow, false),
3683 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
3684 parameters.max_bandwidth, MAX_THROTTLE),
3685 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
3686 parameters.downtime_limit,
3687 DEFAULT_MIGRATE_SET_DOWNTIME),
3688 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
3689 parameters.x_checkpoint_delay,
3690 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
3691 DEFINE_PROP_UINT8("multifd-channels", MigrationState,
3692 parameters.multifd_channels,
3693 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
3694 DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
3695 parameters.multifd_compression,
3696 DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
3697 DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
3698 parameters.multifd_zlib_level,
3699 DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
3700 DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
3701 parameters.multifd_zstd_level,
3702 DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
3703 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3704 parameters.xbzrle_cache_size,
3705 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
3706 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3707 parameters.max_postcopy_bandwidth,
3708 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
3709 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3710 parameters.max_cpu_throttle,
3711 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
3712 DEFINE_PROP_SIZE("announce-initial", MigrationState,
3713 parameters.announce_initial,
3714 DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
3715 DEFINE_PROP_SIZE("announce-max", MigrationState,
3716 parameters.announce_max,
3717 DEFAULT_MIGRATE_ANNOUNCE_MAX),
3718 DEFINE_PROP_SIZE("announce-rounds", MigrationState,
3719 parameters.announce_rounds,
3720 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
3721 DEFINE_PROP_SIZE("announce-step", MigrationState,
3722 parameters.announce_step,
3723 DEFAULT_MIGRATE_ANNOUNCE_STEP),
3725 /* Migration capabilities */
3726 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3727 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3728 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3729 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3730 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3731 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3732 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3733 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3734 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3735 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3736 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
3737 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
3739 DEFINE_PROP_END_OF_LIST(),
3742 static void migration_class_init(ObjectClass *klass, void *data)
3744 DeviceClass *dc = DEVICE_CLASS(klass);
3746 dc->user_creatable = false;
3747 device_class_set_props(dc, migration_properties);
3750 static void migration_instance_finalize(Object *obj)
3752 MigrationState *ms = MIGRATION_OBJ(obj);
3753 MigrationParameters *params = &ms->parameters;
3755 qemu_mutex_destroy(&ms->error_mutex);
3756 qemu_mutex_destroy(&ms->qemu_file_lock);
3757 g_free(params->tls_hostname);
3758 g_free(params->tls_creds);
3759 qemu_sem_destroy(&ms->wait_unplug_sem);
3760 qemu_sem_destroy(&ms->rate_limit_sem);
3761 qemu_sem_destroy(&ms->pause_sem);
3762 qemu_sem_destroy(&ms->postcopy_pause_sem);
3763 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
3764 qemu_sem_destroy(&ms->rp_state.rp_sem);
3765 error_free(ms->error);
3768 static void migration_instance_init(Object *obj)
3770 MigrationState *ms = MIGRATION_OBJ(obj);
3771 MigrationParameters *params = &ms->parameters;
3773 ms->state = MIGRATION_STATUS_NONE;
3774 ms->mbps = -1;
3775 ms->pages_per_second = -1;
3776 qemu_sem_init(&ms->pause_sem, 0);
3777 qemu_mutex_init(&ms->error_mutex);
3779 params->tls_hostname = g_strdup("");
3780 params->tls_creds = g_strdup("");
3782 /* Set has_* up only for parameter checks */
3783 params->has_compress_level = true;
3784 params->has_compress_threads = true;
3785 params->has_decompress_threads = true;
3786 params->has_throttle_trigger_threshold = true;
3787 params->has_cpu_throttle_initial = true;
3788 params->has_cpu_throttle_increment = true;
3789 params->has_cpu_throttle_tailslow = true;
3790 params->has_max_bandwidth = true;
3791 params->has_downtime_limit = true;
3792 params->has_x_checkpoint_delay = true;
3793 params->has_block_incremental = true;
3794 params->has_multifd_channels = true;
3795 params->has_multifd_compression = true;
3796 params->has_multifd_zlib_level = true;
3797 params->has_multifd_zstd_level = true;
3798 params->has_xbzrle_cache_size = true;
3799 params->has_max_postcopy_bandwidth = true;
3800 params->has_max_cpu_throttle = true;
3801 params->has_announce_initial = true;
3802 params->has_announce_max = true;
3803 params->has_announce_rounds = true;
3804 params->has_announce_step = true;
3806 qemu_sem_init(&ms->postcopy_pause_sem, 0);
3807 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
3808 qemu_sem_init(&ms->rp_state.rp_sem, 0);
3809 qemu_sem_init(&ms->rate_limit_sem, 0);
3810 qemu_sem_init(&ms->wait_unplug_sem, 0);
3811 qemu_mutex_init(&ms->qemu_file_lock);
3815 * Return true if check pass, false otherwise. Error will be put
3816 * inside errp if provided.
3818 static bool migration_object_check(MigrationState *ms, Error **errp)
3820 MigrationCapabilityStatusList *head = NULL;
3821 /* Assuming all off */
3822 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3823 int i;
3825 if (!migrate_params_check(&ms->parameters, errp)) {
3826 return false;
3829 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3830 if (ms->enabled_capabilities[i]) {
3831 head = migrate_cap_add(head, i, true);
3835 ret = migrate_caps_check(cap_list, head, errp);
3837 /* It works with head == NULL */
3838 qapi_free_MigrationCapabilityStatusList(head);
3840 return ret;
3843 static const TypeInfo migration_type = {
3844 .name = TYPE_MIGRATION,
3846 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3847 * not created using qdev_new(), it is not attached to the qdev
3848 * device tree, and it is never realized.
3850 * TODO: Make this TYPE_OBJECT once QOM provides something like
3851 * TYPE_DEVICE's "-global" properties.
3853 .parent = TYPE_DEVICE,
3854 .class_init = migration_class_init,
3855 .class_size = sizeof(MigrationClass),
3856 .instance_size = sizeof(MigrationState),
3857 .instance_init = migration_instance_init,
3858 .instance_finalize = migration_instance_finalize,
3861 static void register_migration_types(void)
3863 type_register_static(&migration_type);
3866 type_init(register_migration_types);