]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
migration/vmstate: Introduce VMSTATE_WITH_TMP_TEST() and VMSTATE_BITMAP_TEST()
[mirror_qemu.git] / migration / migration.c
CommitLineData
5bb7910a
AL
1/*
2 * QEMU live migration
3 *
4 * Copyright IBM, Corp. 2008
5 *
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
6b620ca3
PB
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.
5bb7910a
AL
14 */
15
1393a485 16#include "qemu/osdep.h"
f348b6d1 17#include "qemu/cutils.h"
d49b6836 18#include "qemu/error-report.h"
db725815 19#include "qemu/main-loop.h"
795c40b8 20#include "migration/blocker.h"
f4dbe1bf 21#include "exec.h"
7fcac4a2 22#include "fd.h"
61e8b148 23#include "socket.h"
54d31236 24#include "sysemu/runstate.h"
46517dd4 25#include "sysemu/sysemu.h"
b0c3cf94 26#include "sysemu/cpu-throttle.h"
e1a3ecee 27#include "rdma.h"
7b1e1a22 28#include "ram.h"
84a899de 29#include "migration/global_state.h"
c4b63b7c 30#include "migration/misc.h"
6666c96a 31#include "migration.h"
20a519a0 32#include "savevm.h"
08a0aee1 33#include "qemu-file.h"
987772d9 34#include "migration/vmstate.h"
737e150e 35#include "block/block.h"
e688df6b 36#include "qapi/error.h"
9aca82ba 37#include "qapi/clone-visitor.h"
31e4c354 38#include "qapi/qapi-visit-migration.h"
9aca82ba 39#include "qapi/qapi-visit-sockets.h"
9af23989
MA
40#include "qapi/qapi-commands-migration.h"
41#include "qapi/qapi-events-migration.h"
cc7a8ea7 42#include "qapi/qmp/qerror.h"
15280c36 43#include "qapi/qmp/qnull.h"
ab28bd23 44#include "qemu/rcu.h"
2c9e6fec 45#include "block.h"
be07b0ac 46#include "postcopy-ram.h"
766bd176 47#include "qemu/thread.h"
c09e5bb1 48#include "trace.h"
51180423 49#include "exec/target_page.h"
61b67d47 50#include "io/channel-buffer.h"
85a8578e 51#include "io/channel-tls.h"
35a6ed4f 52#include "migration/colo.h"
4ffdb337 53#include "hw/boards.h"
a27bd6c7 54#include "hw/qdev-properties.h"
ce35e229 55#include "hw/qdev-properties-system.h"
9d18af93 56#include "monitor/monitor.h"
50510ea2 57#include "net/announce.h"
c7e0acd5 58#include "qemu/queue.h"
d32ca5ad 59#include "multifd.h"
b5eea99e 60#include "qemu/yank.h"
6e8c25b4 61#include "sysemu/cpus.h"
39675fff 62#include "yank_functions.h"
1b529d90 63#include "sysemu/qtest.h"
27be8635 64#include "ui/qemu-spice.h"
065e2813 65
7590a2ae 66#define MAX_THROTTLE (128 << 20) /* Migration transfer speed throttling */
5bb7910a 67
5b4e1eb7
JQ
68/* Amount of time to allocate to each "chunk" of bandwidth-throttled
69 * data. */
70#define BUFFER_DELAY 100
71#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
72
2ff30257
AA
73/* Time in milliseconds we are allowed to stop the source,
74 * for sending the last part */
75#define DEFAULT_MIGRATE_SET_DOWNTIME 300
76
87c9cc1c
DHB
77/* Maximum migrate downtime set to 2000 seconds */
78#define MAX_MIGRATE_DOWNTIME_SECONDS 2000
79#define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
80
8706d2d5
LL
81/* Default compression thread count */
82#define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
3fcb38c2
LL
83/* Default decompression thread count, usually decompression is at
84 * least 4 times as fast as compression.*/
85#define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
8706d2d5
LL
86/*0: means nocompress, 1: best speed, ... 9: best compress ratio */
87#define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
1626fee3 88/* Define default autoconverge cpu throttle migration parameters */
dc14a470 89#define DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD 50
d85a31d1
JH
90#define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
91#define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
4cbc9c7f 92#define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
8706d2d5 93
17ad9b35 94/* Migration XBZRLE default cache size */
73af8dd8 95#define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
17ad9b35 96
131b2153
ZC
97/* The delay time (in ms) between two COLO checkpoints */
98#define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
4075fb1c 99#define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
96eef042 100#define DEFAULT_MIGRATE_MULTIFD_COMPRESSION MULTIFD_COMPRESSION_NONE
9004db48
JQ
101/* 0: means nocompress, 1: best speed, ... 9: best compress ratio */
102#define DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL 1
6a9ad154
JQ
103/* 0: means nocompress, 1: best speed, ... 20: best compress ratio */
104#define DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL 1
68b53591 105
7e555c6c
DDAG
106/* Background transfer rate for postcopy, 0 means unlimited, note
107 * that page requests can still exceed this limit.
108 */
109#define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
110
ee3d96ba
DDAG
111/*
112 * Parameters for self_announce_delay giving a stream of RARP/ARP
113 * packets after migration.
114 */
115#define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50
116#define DEFAULT_MIGRATE_ANNOUNCE_MAX 550
117#define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5
118#define DEFAULT_MIGRATE_ANNOUNCE_STEP 100
119
99a0db9b
GH
120static NotifierList migration_state_notifiers =
121 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
122
da6f1790
JQ
123/* Messages sent on the return path from destination to source */
124enum mig_rp_message_type {
125 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
126 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
127 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
128
129 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
130 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
a335debb 131 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
13955b89 132 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
da6f1790
JQ
133
134 MIG_RP_MSG_MAX
135};
136
6e8c25b4
AG
137/* Migration capabilities set */
138struct MigrateCapsSet {
139 int size; /* Capability set size */
140 MigrationCapability caps[]; /* Variadic array of capabilities */
141};
142typedef struct MigrateCapsSet MigrateCapsSet;
143
144/* Define and initialize MigrateCapsSet */
145#define INITIALIZE_MIGRATE_CAPS_SET(_name, ...) \
146 MigrateCapsSet _name = { \
147 .size = sizeof((int []) { __VA_ARGS__ }) / sizeof(int), \
148 .caps = { __VA_ARGS__ } \
149 }
150
151/* Background-snapshot compatibility check list */
152static const
153INITIALIZE_MIGRATE_CAPS_SET(check_caps_background_snapshot,
154 MIGRATION_CAPABILITY_POSTCOPY_RAM,
155 MIGRATION_CAPABILITY_DIRTY_BITMAPS,
156 MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME,
157 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE,
158 MIGRATION_CAPABILITY_RETURN_PATH,
159 MIGRATION_CAPABILITY_MULTIFD,
160 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER,
161 MIGRATION_CAPABILITY_AUTO_CONVERGE,
162 MIGRATION_CAPABILITY_RELEASE_RAM,
163 MIGRATION_CAPABILITY_RDMA_PIN_ALL,
164 MIGRATION_CAPABILITY_COMPRESS,
165 MIGRATION_CAPABILITY_XBZRLE,
166 MIGRATION_CAPABILITY_X_COLO,
1abaec9a
LB
167 MIGRATION_CAPABILITY_VALIDATE_UUID,
168 MIGRATION_CAPABILITY_ZERO_COPY_SEND);
6e8c25b4 169
17549e84
JQ
170/* When we add fault tolerance, we could have several
171 migrations at once. For now we don't need to add
172 dynamic creation of migration */
173
e5cb7e76 174static MigrationState *current_migration;
e1b1b1bc 175static MigrationIncomingState *current_incoming;
e5cb7e76 176
3af8554b
DDAG
177static GSList *migration_blockers;
178
8b0b29dc 179static bool migration_object_check(MigrationState *ms, Error **errp);
0331c8ca
DDAG
180static int migration_maybe_pause(MigrationState *s,
181 int *current_active_state,
182 int new_state);
892ae715 183static void migrate_fd_cancel(MigrationState *s);
8b0b29dc 184
f444eeda
PX
185static bool migrate_allow_multi_channels = true;
186
187void migrate_protocol_allow_multi_channels(bool allow)
188{
189 migrate_allow_multi_channels = allow;
190}
191
192bool migrate_multi_channels_is_allowed(void)
193{
194 return migrate_allow_multi_channels;
195}
196
8f8bfffc
PX
197static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
198{
199 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
200
201 return (a > b) - (a < b);
202}
203
e5cb7e76
PX
204void migration_object_init(void)
205{
206 /* This can only be called once. */
207 assert(!current_migration);
208 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
4ffdb337 209
e1b1b1bc
PX
210 /*
211 * Init the migrate incoming object as well no matter whether
212 * we'll use it or not.
213 */
214 assert(!current_incoming);
215 current_incoming = g_new0(MigrationIncomingState, 1);
216 current_incoming->state = MIGRATION_STATUS_NONE;
217 current_incoming->postcopy_remote_fds =
218 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
219 qemu_mutex_init(&current_incoming->rp_mutex);
60bb3c58 220 qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
e1b1b1bc
PX
221 qemu_event_init(&current_incoming->main_thread_load_event, false);
222 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
223 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
60bb3c58 224 qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
8f8bfffc
PX
225 qemu_mutex_init(&current_incoming->page_request_mutex);
226 current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
e1b1b1bc 227
f9734d5d 228 migration_object_check(current_migration, &error_fatal);
e0d17dfd
PB
229
230 blk_mig_init();
231 ram_mig_init();
232 dirty_bitmap_mig_init();
e5cb7e76
PX
233}
234
458fecca 235void migration_cancel(const Error *error)
c7c0e724 236{
458fecca
LV
237 if (error) {
238 migrate_set_error(current_migration, error);
239 }
c7c0e724
DH
240 migrate_fd_cancel(current_migration);
241}
242
892ae715 243void migration_shutdown(void)
1f895604 244{
795969ab
RL
245 /*
246 * When the QEMU main thread exit, the COLO thread
247 * may wait a semaphore. So, we should wakeup the
248 * COLO thread before migration shutdown.
249 */
250 colo_shutdown();
892ae715
DDAG
251 /*
252 * Cancel the current migration - that will (eventually)
253 * stop the migration using this structure
254 */
458fecca 255 migration_cancel(NULL);
1f895604 256 object_unref(OBJECT(current_migration));
1499ab09
VSO
257
258 /*
259 * Cancel outgoing migration of dirty bitmaps. It should
260 * at least unref used block nodes.
261 */
262 dirty_bitmap_mig_cancel_outgoing();
263
264 /*
265 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
266 * are non-critical data, and their loss never considered as
267 * something serious.
268 */
269 dirty_bitmap_mig_cancel_incoming();
1f895604
VSO
270}
271
bca7856a 272/* For outgoing */
859bc756 273MigrationState *migrate_get_current(void)
17549e84 274{
e5cb7e76
PX
275 /* This can only be called after the object created. */
276 assert(current_migration);
277 return current_migration;
17549e84
JQ
278}
279
bca7856a
DDAG
280MigrationIncomingState *migration_incoming_get_current(void)
281{
e1b1b1bc
PX
282 assert(current_incoming);
283 return current_incoming;
bca7856a
DDAG
284}
285
e031149c
PX
286void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
287{
288 if (mis->socket_address_list) {
289 qapi_free_SocketAddressList(mis->socket_address_list);
290 mis->socket_address_list = NULL;
291 }
292
293 if (mis->transport_cleanup) {
294 mis->transport_cleanup(mis->transport_data);
295 mis->transport_data = mis->transport_cleanup = NULL;
296 }
297}
298
bca7856a
DDAG
299void migration_incoming_state_destroy(void)
300{
b4b076da
JQ
301 struct MigrationIncomingState *mis = migration_incoming_get_current();
302
3482655b 303 if (mis->to_src_file) {
660819b1
PX
304 /* Tell source that we are done */
305 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
3482655b
PX
306 qemu_fclose(mis->to_src_file);
307 mis->to_src_file = NULL;
308 }
309
660819b1 310 if (mis->from_src_file) {
39675fff 311 migration_ioc_unregister_yank_from_file(mis->from_src_file);
660819b1
PX
312 qemu_fclose(mis->from_src_file);
313 mis->from_src_file = NULL;
314 }
00fa4fc8
DDAG
315 if (mis->postcopy_remote_fds) {
316 g_array_free(mis->postcopy_remote_fds, TRUE);
317 mis->postcopy_remote_fds = NULL;
318 }
660819b1 319
e031149c 320 migration_incoming_transport_cleanup(mis);
1783c00f
DDAG
321 qemu_event_reset(&mis->main_thread_load_event);
322
8f8bfffc
PX
323 if (mis->page_requested) {
324 g_tree_destroy(mis->page_requested);
325 mis->page_requested = NULL;
326 }
327
36f62f11
PX
328 if (mis->postcopy_qemufile_dst) {
329 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
330 qemu_fclose(mis->postcopy_qemufile_dst);
331 mis->postcopy_qemufile_dst = NULL;
332 }
333
b5eea99e 334 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
bca7856a
DDAG
335}
336
b05dc723
JQ
337static void migrate_generate_event(int new_state)
338{
339 if (migrate_use_events()) {
3ab72385 340 qapi_event_send_migration(new_state);
b05dc723
JQ
341 }
342}
343
0f073f44
DDAG
344static bool migrate_late_block_activate(void)
345{
346 MigrationState *s;
347
348 s = migrate_get_current();
349
350 return s->enabled_capabilities[
351 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
352}
353
da6f1790
JQ
354/*
355 * Send a message on the return channel back to the source
356 * of the migration.
357 */
d6208e35
PX
358static int migrate_send_rp_message(MigrationIncomingState *mis,
359 enum mig_rp_message_type message_type,
360 uint16_t len, void *data)
da6f1790 361{
d6208e35
PX
362 int ret = 0;
363
da6f1790 364 trace_migrate_send_rp_message((int)message_type, len);
37396950 365 QEMU_LOCK_GUARD(&mis->rp_mutex);
d6208e35
PX
366
367 /*
368 * It's possible that the file handle got lost due to network
369 * failures.
370 */
371 if (!mis->to_src_file) {
372 ret = -EIO;
37396950 373 return ret;
d6208e35
PX
374 }
375
da6f1790
JQ
376 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
377 qemu_put_be16(mis->to_src_file, len);
378 qemu_put_buffer(mis->to_src_file, data, len);
379 qemu_fflush(mis->to_src_file);
d6208e35
PX
380
381 /* It's possible that qemu file got error during sending */
382 ret = qemu_file_get_error(mis->to_src_file);
383
d6208e35 384 return ret;
da6f1790
JQ
385}
386
2e2bce16
PX
387/* Request one page from the source VM at the given start address.
388 * rb: the RAMBlock to request the page in
1e2d90eb
DDAG
389 * Start: Address offset within the RB
390 * Len: Length in bytes required - must be a multiple of pagesize
391 */
7a267fc4
PX
392int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
393 RAMBlock *rb, ram_addr_t start)
1e2d90eb 394{
cb8d4c8f 395 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
1e2d90eb 396 size_t msglen = 12; /* start + len */
2e2bce16 397 size_t len = qemu_ram_pagesize(rb);
d6208e35 398 enum mig_rp_message_type msg_type;
2e2bce16
PX
399 const char *rbname;
400 int rbname_len;
1e2d90eb
DDAG
401
402 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
403 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
404
2e2bce16
PX
405 /*
406 * We maintain the last ramblock that we requested for page. Note that we
407 * don't need locking because this function will only be called within the
408 * postcopy ram fault thread.
409 */
410 if (rb != mis->last_rb) {
411 mis->last_rb = rb;
412
413 rbname = qemu_ram_get_idstr(rb);
414 rbname_len = strlen(rbname);
415
1e2d90eb
DDAG
416 assert(rbname_len < 256);
417
418 bufc[msglen++] = rbname_len;
419 memcpy(bufc + msglen, rbname, rbname_len);
420 msglen += rbname_len;
d6208e35 421 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
1e2d90eb 422 } else {
d6208e35 423 msg_type = MIG_RP_MSG_REQ_PAGES;
1e2d90eb 424 }
d6208e35
PX
425
426 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
1e2d90eb
DDAG
427}
428
7a267fc4 429int migrate_send_rp_req_pages(MigrationIncomingState *mis,
8f8bfffc 430 RAMBlock *rb, ram_addr_t start, uint64_t haddr)
7a267fc4 431{
7648297d 432 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
a2429283 433 bool received = false;
8f8bfffc
PX
434
435 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
436 received = ramblock_recv_bitmap_test_byte_offset(rb, start);
437 if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
438 /*
439 * The page has not been received, and it's not yet in the page
440 * request list. Queue it. Set the value of element to 1, so that
441 * things like g_tree_lookup() will return TRUE (1) when found.
442 */
443 g_tree_insert(mis->page_requested, aligned, (gpointer)1);
444 mis->page_requested_count++;
445 trace_postcopy_page_req_add(aligned, mis->page_requested_count);
446 }
447 }
448
449 /*
450 * If the page is there, skip sending the message. We don't even need the
451 * lock because as long as the page arrived, it'll be there forever.
452 */
453 if (received) {
454 return 0;
455 }
456
7a267fc4
PX
457 return migrate_send_rp_message_req_pages(mis, rb, start);
458}
459
aad555c2
ZC
460static bool migration_colo_enabled;
461bool migration_incoming_colo_enabled(void)
462{
463 return migration_colo_enabled;
464}
465
466void migration_incoming_disable_colo(void)
467{
18b1d3c9 468 ram_block_discard_disable(false);
aad555c2
ZC
469 migration_colo_enabled = false;
470}
471
18b1d3c9 472int migration_incoming_enable_colo(void)
aad555c2 473{
18b1d3c9
DH
474 if (ram_block_discard_disable(true)) {
475 error_report("COLO: cannot disable RAM discard");
476 return -EBUSY;
477 }
aad555c2 478 migration_colo_enabled = true;
18b1d3c9 479 return 0;
aad555c2
ZC
480}
481
9aca82ba
JQ
482void migrate_add_address(SocketAddress *address)
483{
484 MigrationIncomingState *mis = migration_incoming_get_current();
9aca82ba 485
54aa3de7
EB
486 QAPI_LIST_PREPEND(mis->socket_address_list,
487 QAPI_CLONE(SocketAddress, address));
9aca82ba
JQ
488}
489
e69d50d6 490static void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 491{
d658f65c 492 const char *p = NULL;
34c9dd8e 493
f444eeda 494 migrate_protocol_allow_multi_channels(false); /* reset it anyway */
3ab72385 495 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
e69d50d6
PB
496 if (strstart(uri, "tcp:", &p) ||
497 strstart(uri, "unix:", NULL) ||
498 strstart(uri, "vsock:", NULL)) {
f444eeda 499 migrate_protocol_allow_multi_channels(true);
d658f65c 500 socket_start_incoming_migration(p ? p : uri, errp);
2da776db 501#ifdef CONFIG_RDMA
adde220a 502 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
503 rdma_start_incoming_migration(p, errp);
504#endif
adde220a 505 } else if (strstart(uri, "exec:", &p)) {
43eaae28 506 exec_start_incoming_migration(p, errp);
adde220a 507 } else if (strstart(uri, "fd:", &p)) {
43eaae28 508 fd_start_incoming_migration(p, errp);
adde220a 509 } else {
312fd5f2 510 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 511 }
5bb7910a
AL
512}
513
0aa6aefc
DL
514static void process_incoming_migration_bh(void *opaque)
515{
516 Error *local_err = NULL;
517 MigrationIncomingState *mis = opaque;
518
0f073f44
DDAG
519 /* If capability late_block_activate is set:
520 * Only fire up the block code now if we're going to restart the
521 * VM, else 'cont' will do it.
522 * This causes file locking to happen; so we don't want it to happen
523 * unless we really are starting the VM.
524 */
525 if (!migrate_late_block_activate() ||
526 (autostart && (!global_state_received() ||
527 global_state_get_runstate() == RUN_STATE_RUNNING))) {
3b717194 528 /* Make sure all file formats throw away their mutable metadata.
0f073f44 529 * If we get an error here, just don't restart the VM yet. */
3b717194 530 bdrv_activate_all(&local_err);
0f073f44
DDAG
531 if (local_err) {
532 error_report_err(local_err);
533 local_err = NULL;
534 autostart = false;
535 }
d35ff5e6
KW
536 }
537
0aa6aefc
DL
538 /*
539 * This must happen after all error conditions are dealt with and
540 * we're sure the VM is going to be running on this host.
541 */
7659505c 542 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
0aa6aefc 543
f986c3d2
JQ
544 if (multifd_load_cleanup(&local_err) != 0) {
545 error_report_err(local_err);
546 autostart = false;
547 }
0aa6aefc
DL
548 /* If global state section was not received or we are in running
549 state, we need to obey autostart. Any other state is set with
550 runstate_set. */
551
b35ebdf0
VSO
552 dirty_bitmap_mig_before_vm_start();
553
0aa6aefc
DL
554 if (!global_state_received() ||
555 global_state_get_runstate() == RUN_STATE_RUNNING) {
556 if (autostart) {
557 vm_start();
558 } else {
559 runstate_set(RUN_STATE_PAUSED);
560 }
db009729
ZC
561 } else if (migration_incoming_colo_enabled()) {
562 migration_incoming_disable_colo();
563 vm_start();
0aa6aefc
DL
564 } else {
565 runstate_set(global_state_get_runstate());
566 }
0aa6aefc
DL
567 /*
568 * This must happen after any state changes since as soon as an external
569 * observer sees this event they might start to prod at the VM assuming
570 * it's ready to use.
571 */
572 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
573 MIGRATION_STATUS_COMPLETED);
574 qemu_bh_delete(mis->bh);
575 migration_incoming_state_destroy();
576}
577
38e8f9af
MAL
578static void coroutine_fn
579process_incoming_migration_co(void *opaque)
511c0231 580{
b4b076da 581 MigrationIncomingState *mis = migration_incoming_get_current();
e9bef235 582 PostcopyState ps;
1c12e1f5 583 int ret;
8e48ac95 584 Error *local_err = NULL;
1c12e1f5 585
4f0fae7f 586 assert(mis->from_src_file);
92370989 587 mis->migration_incoming_co = qemu_coroutine_self();
67f11b5c 588 mis->largest_page_size = qemu_ram_pagesize_largest();
093e3c42 589 postcopy_state_set(POSTCOPY_INCOMING_NONE);
93d7af6f
HZ
590 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
591 MIGRATION_STATUS_ACTIVE);
4f0fae7f 592 ret = qemu_loadvm_state(mis->from_src_file);
bca7856a 593
e9bef235
DDAG
594 ps = postcopy_state_get();
595 trace_process_incoming_migration_co_end(ret, ps);
596 if (ps != POSTCOPY_INCOMING_NONE) {
597 if (ps == POSTCOPY_INCOMING_ADVISE) {
598 /*
599 * Where a migration had postcopy enabled (and thus went to advise)
600 * but managed to complete within the precopy period, we can use
601 * the normal exit.
602 */
603 postcopy_ram_incoming_cleanup(mis);
604 } else if (ret >= 0) {
605 /*
606 * Postcopy was started, cleanup should happen at the end of the
607 * postcopy thread.
608 */
609 trace_process_incoming_migration_co_postcopy_end_main();
610 return;
611 }
612 /* Else if something went wrong then just fall out of the normal exit */
613 }
614
25d0c16f 615 /* we get COLO info, and know if we are in COLO mode */
aad555c2 616 if (!ret && migration_incoming_colo_enabled()) {
3b717194
EGE
617 /* Make sure all file formats throw away their mutable metadata */
618 bdrv_activate_all(&local_err);
8e48ac95 619 if (local_err) {
8e48ac95 620 error_report_err(local_err);
6d99c2d4 621 goto fail;
8e48ac95
ZC
622 }
623
25d0c16f
HZ
624 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
625 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
626 mis->have_colo_incoming_thread = true;
627 qemu_coroutine_yield();
628
684bfd18 629 qemu_mutex_unlock_iothread();
25d0c16f
HZ
630 /* Wait checkpoint incoming thread exit before free resource */
631 qemu_thread_join(&mis->colo_incoming_thread);
684bfd18 632 qemu_mutex_lock_iothread();
13af18f2
ZC
633 /* We hold the global iothread lock, so it is safe here */
634 colo_release_ram_cache();
25d0c16f
HZ
635 }
636
1c12e1f5 637 if (ret < 0) {
db80face 638 error_report("load of migration failed: %s", strerror(-ret));
6d99c2d4 639 goto fail;
511c0231 640 }
0aa6aefc
DL
641 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
642 qemu_bh_schedule(mis->bh);
92370989 643 mis->migration_incoming_co = NULL;
6d99c2d4
FL
644 return;
645fail:
646 local_err = NULL;
647 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
648 MIGRATION_STATUS_FAILED);
649 qemu_fclose(mis->from_src_file);
650 if (multifd_load_cleanup(&local_err) != 0) {
651 error_report_err(local_err);
652 }
653 exit(EXIT_FAILURE);
511c0231
JQ
654}
655
b673eab4 656/**
7d6f6933 657 * migration_incoming_setup: Setup incoming migration
b673eab4
JQ
658 * @f: file for main migration channel
659 * @errp: where to put errors
7d6f6933
MA
660 *
661 * Returns: %true on success, %false on error.
b673eab4 662 */
7d6f6933 663static bool migration_incoming_setup(QEMUFile *f, Error **errp)
82a4da79 664{
4f0fae7f 665 MigrationIncomingState *mis = migration_incoming_get_current();
82a4da79 666
7d6f6933
MA
667 if (multifd_load_setup(errp) != 0) {
668 return false;
f986c3d2
JQ
669 }
670
4f0fae7f
JQ
671 if (!mis->from_src_file) {
672 mis->from_src_file = f;
673 }
06ad5135 674 qemu_file_set_blocking(f, false);
7d6f6933 675 return true;
e595a01a
JQ
676}
677
36c2f8be 678void migration_incoming_process(void)
e595a01a
JQ
679{
680 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
0b8b8753 681 qemu_coroutine_enter(co);
82a4da79
PB
682}
683
884835fa 684/* Returns true if recovered from a paused migration, otherwise false */
a39e9339 685static bool postcopy_try_recover(void)
e595a01a 686{
d96c9e8d
PX
687 MigrationIncomingState *mis = migration_incoming_get_current();
688
689 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
690 /* Resumed from a paused postcopy migration */
691
a39e9339
PX
692 /* This should be set already in migration_incoming_setup() */
693 assert(mis->from_src_file);
d96c9e8d 694 /* Postcopy has standalone thread to do vm load */
a39e9339 695 qemu_file_set_blocking(mis->from_src_file, true);
d96c9e8d
PX
696
697 /* Re-configure the return path */
a39e9339 698 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
d96c9e8d
PX
699
700 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
701 MIGRATION_STATUS_POSTCOPY_RECOVER);
702
703 /*
704 * Here, we only wake up the main loading thread (while the
60bb3c58 705 * rest threads will still be waiting), so that we can receive
d96c9e8d 706 * commands from source now, and answer it if needed. The
60bb3c58 707 * rest threads will be woken up afterwards until we are sure
d96c9e8d
PX
708 * that source is ready to reply to page requests.
709 */
710 qemu_sem_post(&mis->postcopy_pause_sem_dst);
884835fa
PX
711 return true;
712 }
713
714 return false;
715}
716
b673eab4 717void migration_fd_process_incoming(QEMUFile *f, Error **errp)
884835fa 718{
a39e9339 719 if (!migration_incoming_setup(f, errp)) {
884835fa 720 return;
d96c9e8d 721 }
a39e9339 722 if (postcopy_try_recover()) {
b673eab4
JQ
723 return;
724 }
884835fa 725 migration_incoming_process();
e595a01a
JQ
726}
727
36f62f11
PX
728static bool migration_needs_multiple_sockets(void)
729{
730 return migrate_use_multifd() || migrate_postcopy_preempt();
731}
732
49ed0d24 733void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
4f0fae7f
JQ
734{
735 MigrationIncomingState *mis = migration_incoming_get_current();
b673eab4 736 Error *local_err = NULL;
a429e7f4 737 bool start_migration;
36f62f11 738 QEMUFile *f;
4f0fae7f
JQ
739
740 if (!mis->from_src_file) {
a429e7f4 741 /* The first connection (multifd may have multiple) */
36f62f11 742 f = qemu_file_new_input(ioc);
a429e7f4 743
7d6f6933 744 if (!migration_incoming_setup(f, errp)) {
b673eab4
JQ
745 return;
746 }
a429e7f4
PX
747
748 /*
749 * Common migration only needs one channel, so we can start
36f62f11 750 * right now. Some features need more than one channel, we wait.
a429e7f4 751 */
36f62f11 752 start_migration = !migration_needs_multiple_sockets();
a429e7f4
PX
753 } else {
754 /* Multiple connections */
36f62f11
PX
755 assert(migration_needs_multiple_sockets());
756 if (migrate_use_multifd()) {
757 start_migration = multifd_recv_new_channel(ioc, &local_err);
758 } else {
759 assert(migrate_postcopy_preempt());
760 f = qemu_file_new_input(ioc);
761 start_migration = postcopy_preempt_new_channel(mis, f);
762 }
49ed0d24
FL
763 if (local_err) {
764 error_propagate(errp, local_err);
765 return;
766 }
4f0fae7f 767 }
81e62053 768
a429e7f4 769 if (start_migration) {
a39e9339
PX
770 /* If it's a recovery, we're done */
771 if (postcopy_try_recover()) {
772 return;
773 }
81e62053
PX
774 migration_incoming_process();
775 }
4f0fae7f
JQ
776}
777
428d8908
JQ
778/**
779 * @migration_has_all_channels: We have received all channels that we need
780 *
781 * Returns true when we have got connections to all the channels that
782 * we need for migration.
783 */
784bool migration_has_all_channels(void)
785{
ca273df3 786 MigrationIncomingState *mis = migration_incoming_get_current();
62c1e0ca 787
36f62f11
PX
788 if (!mis->from_src_file) {
789 return false;
790 }
62c1e0ca 791
36f62f11
PX
792 if (migrate_use_multifd()) {
793 return multifd_recv_all_channels_created();
794 }
795
796 if (migrate_postcopy_preempt()) {
797 return mis->postcopy_qemufile_dst != NULL;
798 }
799
800 return true;
428d8908
JQ
801}
802
6decec93
DDAG
803/*
804 * Send a 'SHUT' message on the return channel with the given value
805 * to indicate that we've finished with the RP. Non-0 value indicates
806 * error.
807 */
808void migrate_send_rp_shut(MigrationIncomingState *mis,
809 uint32_t value)
810{
811 uint32_t buf;
812
813 buf = cpu_to_be32(value);
814 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
815}
816
817/*
818 * Send a 'PONG' message on the return channel with the given value
819 * (normally in response to a 'PING')
820 */
821void migrate_send_rp_pong(MigrationIncomingState *mis,
822 uint32_t value)
823{
824 uint32_t buf;
825
826 buf = cpu_to_be32(value);
827 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
828}
829
a335debb
PX
830void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
831 char *block_name)
832{
833 char buf[512];
834 int len;
835 int64_t res;
836
837 /*
838 * First, we send the header part. It contains only the len of
839 * idstr, and the idstr itself.
840 */
841 len = strlen(block_name);
842 buf[0] = len;
843 memcpy(buf + 1, block_name, len);
844
845 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
846 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
847 __func__);
848 return;
849 }
850
851 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
852
853 /*
854 * Next, we dump the received bitmap to the stream.
855 *
856 * TODO: currently we are safe since we are the only one that is
857 * using the to_src_file handle (fault thread is still paused),
858 * and it's ok even not taking the mutex. However the best way is
859 * to take the lock before sending the message header, and release
860 * the lock after sending the bitmap.
861 */
862 qemu_mutex_lock(&mis->rp_mutex);
863 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
864 qemu_mutex_unlock(&mis->rp_mutex);
865
866 trace_migrate_send_rp_recv_bitmap(block_name, res);
867}
868
13955b89
PX
869void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
870{
871 uint32_t buf;
872
873 buf = cpu_to_be32(value);
874 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
875}
876
bbf6da32
OW
877MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
878{
95b3a8c8
EB
879 MigrationCapabilityStatusList *head = NULL, **tail = &head;
880 MigrationCapabilityStatus *caps;
bbf6da32
OW
881 MigrationState *s = migrate_get_current();
882 int i;
883
7fb1cf16 884 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
ed1701c6
DDAG
885#ifndef CONFIG_LIVE_BLOCK_MIGRATION
886 if (i == MIGRATION_CAPABILITY_BLOCK) {
887 continue;
888 }
889#endif
95b3a8c8
EB
890 caps = g_malloc0(sizeof(*caps));
891 caps->capability = i;
892 caps->state = s->enabled_capabilities[i];
893 QAPI_LIST_APPEND(tail, caps);
bbf6da32
OW
894 }
895
896 return head;
897}
898
85de8323
LL
899MigrationParameters *qmp_query_migrate_parameters(Error **errp)
900{
901 MigrationParameters *params;
902 MigrationState *s = migrate_get_current();
903
e87fae4c 904 /* TODO use QAPI_CLONE() instead of duplicating it inline */
85de8323 905 params = g_malloc0(sizeof(*params));
de63ab61 906 params->has_compress_level = true;
2594f56d 907 params->compress_level = s->parameters.compress_level;
de63ab61 908 params->has_compress_threads = true;
2594f56d 909 params->compress_threads = s->parameters.compress_threads;
1d58872a
XG
910 params->has_compress_wait_thread = true;
911 params->compress_wait_thread = s->parameters.compress_wait_thread;
de63ab61 912 params->has_decompress_threads = true;
2594f56d 913 params->decompress_threads = s->parameters.decompress_threads;
dc14a470
KZ
914 params->has_throttle_trigger_threshold = true;
915 params->throttle_trigger_threshold = s->parameters.throttle_trigger_threshold;
de63ab61 916 params->has_cpu_throttle_initial = true;
2594f56d 917 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
de63ab61 918 params->has_cpu_throttle_increment = true;
2594f56d 919 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
cbbf8182
KZ
920 params->has_cpu_throttle_tailslow = true;
921 params->cpu_throttle_tailslow = s->parameters.cpu_throttle_tailslow;
69ef1f36
DB
922 params->tls_creds = g_strdup(s->parameters.tls_creds);
923 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
7cd75cbd
MZ
924 params->tls_authz = g_strdup(s->parameters.tls_authz ?
925 s->parameters.tls_authz : "");
2ff30257
AA
926 params->has_max_bandwidth = true;
927 params->max_bandwidth = s->parameters.max_bandwidth;
928 params->has_downtime_limit = true;
929 params->downtime_limit = s->parameters.downtime_limit;
fe39a4d4 930 params->has_x_checkpoint_delay = true;
68b53591 931 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
2833c59b
JQ
932 params->has_block_incremental = true;
933 params->block_incremental = s->parameters.block_incremental;
cbfd6c95
JQ
934 params->has_multifd_channels = true;
935 params->multifd_channels = s->parameters.multifd_channels;
96eef042
JQ
936 params->has_multifd_compression = true;
937 params->multifd_compression = s->parameters.multifd_compression;
9004db48
JQ
938 params->has_multifd_zlib_level = true;
939 params->multifd_zlib_level = s->parameters.multifd_zlib_level;
6a9ad154
JQ
940 params->has_multifd_zstd_level = true;
941 params->multifd_zstd_level = s->parameters.multifd_zstd_level;
73af8dd8
JQ
942 params->has_xbzrle_cache_size = true;
943 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
7e555c6c
DDAG
944 params->has_max_postcopy_bandwidth = true;
945 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
4cbc9c7f
LQ
946 params->has_max_cpu_throttle = true;
947 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
ee3d96ba
DDAG
948 params->has_announce_initial = true;
949 params->announce_initial = s->parameters.announce_initial;
950 params->has_announce_max = true;
951 params->announce_max = s->parameters.announce_max;
952 params->has_announce_rounds = true;
953 params->announce_rounds = s->parameters.announce_rounds;
954 params->has_announce_step = true;
955 params->announce_step = s->parameters.announce_step;
85de8323 956
31e4c354
HR
957 if (s->parameters.has_block_bitmap_mapping) {
958 params->has_block_bitmap_mapping = true;
959 params->block_bitmap_mapping =
960 QAPI_CLONE(BitmapMigrationNodeAliasList,
961 s->parameters.block_bitmap_mapping);
962 }
963
85de8323
LL
964 return params;
965}
966
27be8635
MA
967void qmp_client_migrate_info(const char *protocol, const char *hostname,
968 bool has_port, int64_t port,
969 bool has_tls_port, int64_t tls_port,
970 const char *cert_subject,
971 Error **errp)
972{
973 if (strcmp(protocol, "spice") == 0) {
974 if (!qemu_using_spice(errp)) {
975 return;
976 }
977
978 if (!has_port && !has_tls_port) {
979 error_setg(errp, QERR_MISSING_PARAMETER, "port/tls-port");
980 return;
981 }
982
983 if (qemu_spice.migrate_info(hostname,
984 has_port ? port : -1,
985 has_tls_port ? tls_port : -1,
986 cert_subject)) {
987 error_setg(errp, "Could not set up display for migration");
988 return;
989 }
990 return;
991 }
992
993 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "protocol", "'spice'");
994}
995
ee3d96ba
DDAG
996AnnounceParameters *migrate_announce_params(void)
997{
998 static AnnounceParameters ap;
999
1000 MigrationState *s = migrate_get_current();
1001
1002 ap.initial = s->parameters.announce_initial;
1003 ap.max = s->parameters.announce_max;
1004 ap.rounds = s->parameters.announce_rounds;
1005 ap.step = s->parameters.announce_step;
1006
1007 return &ap;
1008}
1009
f6844b99
DDAG
1010/*
1011 * Return true if we're already in the middle of a migration
1012 * (i.e. any of the active or setup states)
1013 */
3d63da16 1014bool migration_is_setup_or_active(int state)
f6844b99
DDAG
1015{
1016 switch (state) {
1017 case MIGRATION_STATUS_ACTIVE:
9ec055ae 1018 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
a688d2c1 1019 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 1020 case MIGRATION_STATUS_POSTCOPY_RECOVER:
f6844b99 1021 case MIGRATION_STATUS_SETUP:
31e06077
DDAG
1022 case MIGRATION_STATUS_PRE_SWITCHOVER:
1023 case MIGRATION_STATUS_DEVICE:
c7e0acd5 1024 case MIGRATION_STATUS_WAIT_UNPLUG:
19dd408a 1025 case MIGRATION_STATUS_COLO:
f6844b99
DDAG
1026 return true;
1027
1028 default:
1029 return false;
1030
1031 }
1032}
1033
392d87e2
JQ
1034bool migration_is_running(int state)
1035{
1036 switch (state) {
1037 case MIGRATION_STATUS_ACTIVE:
1038 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1039 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1040 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1041 case MIGRATION_STATUS_SETUP:
1042 case MIGRATION_STATUS_PRE_SWITCHOVER:
1043 case MIGRATION_STATUS_DEVICE:
1044 case MIGRATION_STATUS_WAIT_UNPLUG:
1045 case MIGRATION_STATUS_CANCELLING:
392d87e2
JQ
1046 return true;
1047
1048 default:
1049 return false;
1050
1051 }
1052}
1053
640dfb14
WY
1054static void populate_time_info(MigrationInfo *info, MigrationState *s)
1055{
1056 info->has_status = true;
1057 info->has_setup_time = true;
1058 info->setup_time = s->setup_time;
1059 if (s->state == MIGRATION_STATUS_COMPLETED) {
1060 info->has_total_time = true;
1061 info->total_time = s->total_time;
1062 info->has_downtime = true;
1063 info->downtime = s->downtime;
1064 } else {
1065 info->has_total_time = true;
1066 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
1067 s->start_time;
1068 info->has_expected_downtime = true;
1069 info->expected_downtime = s->expected_downtime;
1070 }
1071}
1072
a22463a5
DDAG
1073static void populate_ram_info(MigrationInfo *info, MigrationState *s)
1074{
144fa06b
JQ
1075 size_t page_size = qemu_target_page_size();
1076
a22463a5 1077 info->ram = g_malloc0(sizeof(*info->ram));
23b7576d 1078 info->ram->transferred = stat64_get(&ram_atomic_counters.transferred);
a22463a5 1079 info->ram->total = ram_bytes_total();
23b7576d 1080 info->ram->duplicate = stat64_get(&ram_atomic_counters.duplicate);
bedf53c1
JQ
1081 /* legacy value. It is not used anymore */
1082 info->ram->skipped = 0;
23b7576d
PX
1083 info->ram->normal = stat64_get(&ram_atomic_counters.normal);
1084 info->ram->normal_bytes = info->ram->normal * page_size;
a22463a5 1085 info->ram->mbps = s->mbps;
9360447d 1086 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
cf20c897
LB
1087 info->ram->dirty_sync_missed_zero_copy =
1088 ram_counters.dirty_sync_missed_zero_copy;
9360447d 1089 info->ram->postcopy_requests = ram_counters.postcopy_requests;
144fa06b 1090 info->ram->page_size = page_size;
a61c45bd 1091 info->ram->multifd_bytes = ram_counters.multifd_bytes;
aecbfe9c 1092 info->ram->pages_per_second = s->pages_per_second;
ae680668
DE
1093 info->ram->precopy_bytes = ram_counters.precopy_bytes;
1094 info->ram->downtime_bytes = ram_counters.downtime_bytes;
23b7576d 1095 info->ram->postcopy_bytes = stat64_get(&ram_atomic_counters.postcopy_bytes);
a22463a5 1096
114f5aee 1097 if (migrate_use_xbzrle()) {
114f5aee
JQ
1098 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
1099 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
9360447d
JQ
1100 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
1101 info->xbzrle_cache->pages = xbzrle_counters.pages;
1102 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
1103 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
e460a4b1 1104 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
9360447d 1105 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
114f5aee
JQ
1106 }
1107
76e03000 1108 if (migrate_use_compression()) {
76e03000
XG
1109 info->compression = g_malloc0(sizeof(*info->compression));
1110 info->compression->pages = compression_counters.pages;
1111 info->compression->busy = compression_counters.busy;
1112 info->compression->busy_rate = compression_counters.busy_rate;
1113 info->compression->compressed_size =
1114 compression_counters.compressed_size;
1115 info->compression->compression_rate =
1116 compression_counters.compression_rate;
1117 }
1118
338182c8
JQ
1119 if (cpu_throttle_active()) {
1120 info->has_cpu_throttle_percentage = true;
1121 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
1122 }
1123
a22463a5
DDAG
1124 if (s->state != MIGRATION_STATUS_COMPLETED) {
1125 info->ram->remaining = ram_bytes_remaining();
9360447d 1126 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
a22463a5
DDAG
1127 }
1128}
1129
930ac04c
JQ
1130static void populate_disk_info(MigrationInfo *info)
1131{
1132 if (blk_mig_active()) {
930ac04c
JQ
1133 info->disk = g_malloc0(sizeof(*info->disk));
1134 info->disk->transferred = blk_mig_bytes_transferred();
1135 info->disk->remaining = blk_mig_bytes_remaining();
1136 info->disk->total = blk_mig_bytes_total();
1137 }
1138}
1139
65ace060 1140static void fill_source_migration_info(MigrationInfo *info)
5bb7910a 1141{
17549e84 1142 MigrationState *s = migrate_get_current();
552de79b 1143 int state = qatomic_read(&s->state);
372043f3 1144 GSList *cur_blocker = migration_blockers;
17549e84 1145
3af8554b 1146 info->blocked_reasons = NULL;
3af8554b 1147
372043f3
MA
1148 /*
1149 * There are two types of reasons a migration might be blocked;
1150 * a) devices marked in VMState as non-migratable, and
1151 * b) Explicit migration blockers
1152 * We need to add both of them here.
1153 */
1154 qemu_savevm_non_migratable_list(&info->blocked_reasons);
3af8554b 1155
372043f3
MA
1156 while (cur_blocker) {
1157 QAPI_LIST_PREPEND(info->blocked_reasons,
1158 g_strdup(error_get_pretty(cur_blocker->data)));
1159 cur_blocker = g_slist_next(cur_blocker);
3af8554b 1160 }
372043f3 1161 info->has_blocked_reasons = info->blocked_reasons != NULL;
3af8554b 1162
552de79b 1163 switch (state) {
31194731 1164 case MIGRATION_STATUS_NONE:
17549e84 1165 /* no migration has happened ever */
65ace060
AP
1166 /* do not overwrite destination migration status */
1167 return;
31194731 1168 case MIGRATION_STATUS_SETUP:
29ae8a41 1169 info->has_status = true;
ed4fbd10 1170 info->has_total_time = false;
29ae8a41 1171 break;
31194731
HZ
1172 case MIGRATION_STATUS_ACTIVE:
1173 case MIGRATION_STATUS_CANCELLING:
9ec055ae 1174 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
31e06077
DDAG
1175 case MIGRATION_STATUS_PRE_SWITCHOVER:
1176 case MIGRATION_STATUS_DEVICE:
a688d2c1 1177 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 1178 case MIGRATION_STATUS_POSTCOPY_RECOVER:
640dfb14
WY
1179 /* TODO add some postcopy stats */
1180 populate_time_info(info, s);
a22463a5 1181 populate_ram_info(info, s);
930ac04c 1182 populate_disk_info(info);
3710586c 1183 populate_vfio_info(info);
17549e84 1184 break;
0b827d5e
HZ
1185 case MIGRATION_STATUS_COLO:
1186 info->has_status = true;
1187 /* TODO: display COLO specific information (checkpoint info etc.) */
1188 break;
31194731 1189 case MIGRATION_STATUS_COMPLETED:
640dfb14 1190 populate_time_info(info, s);
a22463a5 1191 populate_ram_info(info, s);
3710586c 1192 populate_vfio_info(info);
17549e84 1193 break;
31194731 1194 case MIGRATION_STATUS_FAILED:
791e7c82 1195 info->has_status = true;
d59ce6f3 1196 if (s->error) {
d59ce6f3
DB
1197 info->error_desc = g_strdup(error_get_pretty(s->error));
1198 }
17549e84 1199 break;
31194731 1200 case MIGRATION_STATUS_CANCELLED:
791e7c82 1201 info->has_status = true;
17549e84 1202 break;
c7e0acd5
JF
1203 case MIGRATION_STATUS_WAIT_UNPLUG:
1204 info->has_status = true;
1205 break;
5bb7910a 1206 }
552de79b 1207 info->status = state;
5bb7910a
AL
1208}
1209
6e8c25b4
AG
1210typedef enum WriteTrackingSupport {
1211 WT_SUPPORT_UNKNOWN = 0,
1212 WT_SUPPORT_ABSENT,
1213 WT_SUPPORT_AVAILABLE,
1214 WT_SUPPORT_COMPATIBLE
1215} WriteTrackingSupport;
1216
1217static
1218WriteTrackingSupport migrate_query_write_tracking(void)
1219{
1220 /* Check if kernel supports required UFFD features */
1221 if (!ram_write_tracking_available()) {
1222 return WT_SUPPORT_ABSENT;
1223 }
1224 /*
1225 * Check if current memory configuration is
1226 * compatible with required UFFD features.
1227 */
1228 if (!ram_write_tracking_compatible()) {
1229 return WT_SUPPORT_AVAILABLE;
1230 }
1231
1232 return WT_SUPPORT_COMPATIBLE;
1233}
1234
4a84214e
PX
1235/**
1236 * @migration_caps_check - check capability validity
1237 *
1238 * @cap_list: old capability list, array of bool
1239 * @params: new capabilities to be applied soon
1240 * @errp: set *errp if the check failed, with reason
1241 *
1242 * Returns true if check passed, otherwise false.
1243 */
1244static bool migrate_caps_check(bool *cap_list,
1245 MigrationCapabilityStatusList *params,
1246 Error **errp)
00458433 1247{
00458433 1248 MigrationCapabilityStatusList *cap;
4a84214e 1249 bool old_postcopy_cap;
d7651f15 1250 MigrationIncomingState *mis = migration_incoming_get_current();
00458433 1251
4a84214e 1252 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
00458433
OW
1253
1254 for (cap = params; cap; cap = cap->next) {
4a84214e
PX
1255 cap_list[cap->value->capability] = cap->value->state;
1256 }
1257
ed1701c6 1258#ifndef CONFIG_LIVE_BLOCK_MIGRATION
4a84214e
PX
1259 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
1260 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
1261 "block migration");
1262 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
1263 return false;
00458433 1264 }
4a84214e 1265#endif
53dd370c 1266
7e934f5b
ZC
1267#ifndef CONFIG_REPLICATION
1268 if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
1269 error_setg(errp, "QEMU compiled without replication module"
1270 " can't enable COLO");
1271 error_append_hint(errp, "Please enable replication before COLO.\n");
1272 return false;
1273 }
1274#endif
1275
4a84214e 1276 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
096631bd
DDAG
1277 /* This check is reasonably expensive, so only when it's being
1278 * set the first time, also it's only the destination that needs
1279 * special support.
1280 */
1281 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
d7651f15 1282 !postcopy_ram_supported_by_host(mis)) {
096631bd
DDAG
1283 /* postcopy_ram_supported_by_host will have emitted a more
1284 * detailed message
1285 */
4a84214e
PX
1286 error_setg(errp, "Postcopy is not supported");
1287 return false;
096631bd 1288 }
18269069
YK
1289
1290 if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1291 error_setg(errp, "Postcopy is not compatible with ignore-shared");
1292 return false;
1293 }
53dd370c 1294 }
4a84214e 1295
6e8c25b4
AG
1296 if (cap_list[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT]) {
1297 WriteTrackingSupport wt_support;
1298 int idx;
1299 /*
1300 * Check if 'background-snapshot' capability is supported by
1301 * host kernel and compatible with guest memory configuration.
1302 */
1303 wt_support = migrate_query_write_tracking();
1304 if (wt_support < WT_SUPPORT_AVAILABLE) {
1305 error_setg(errp, "Background-snapshot is not supported by host kernel");
1306 return false;
1307 }
1308 if (wt_support < WT_SUPPORT_COMPATIBLE) {
1309 error_setg(errp, "Background-snapshot is not compatible "
1310 "with guest memory configuration");
1311 return false;
1312 }
1313
1314 /*
1315 * Check if there are any migration capabilities
1316 * incompatible with 'background-snapshot'.
1317 */
1318 for (idx = 0; idx < check_caps_background_snapshot.size; idx++) {
1319 int incomp_cap = check_caps_background_snapshot.caps[idx];
1320 if (cap_list[incomp_cap]) {
1321 error_setg(errp,
1322 "Background-snapshot is not compatible with %s",
1323 MigrationCapability_str(incomp_cap));
1324 return false;
1325 }
1326 }
1327 }
1328
1abaec9a
LB
1329#ifdef CONFIG_LINUX
1330 if (cap_list[MIGRATION_CAPABILITY_ZERO_COPY_SEND] &&
1331 (!cap_list[MIGRATION_CAPABILITY_MULTIFD] ||
90eb69e4
LB
1332 cap_list[MIGRATION_CAPABILITY_COMPRESS] ||
1333 cap_list[MIGRATION_CAPABILITY_XBZRLE] ||
1334 migrate_multifd_compression() ||
1abaec9a
LB
1335 migrate_use_tls())) {
1336 error_setg(errp,
1337 "Zero copy only available for non-compressed non-TLS multifd migration");
1338 return false;
1339 }
1340#else
1341 if (cap_list[MIGRATION_CAPABILITY_ZERO_COPY_SEND]) {
1342 error_setg(errp,
1343 "Zero copy currently only available on Linux");
1344 return false;
1345 }
1346#endif
1347
1348
5ad15e86
LZ
1349 /* incoming side only */
1350 if (runstate_check(RUN_STATE_INMIGRATE) &&
f444eeda 1351 !migrate_multi_channels_is_allowed() &&
5ad15e86
LZ
1352 cap_list[MIGRATION_CAPABILITY_MULTIFD]) {
1353 error_setg(errp, "multifd is not supported by current protocol");
1354 return false;
1355 }
1356
ce5b0f4a
PX
1357 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT]) {
1358 if (!cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
1359 error_setg(errp, "Postcopy preempt requires postcopy-ram");
1360 return false;
1361 }
afed4273
PX
1362
1363 /*
1364 * Preempt mode requires urgent pages to be sent in separate
1365 * channel, OTOH compression logic will disorder all pages into
1366 * different compression channels, which is not compatible with the
1367 * preempt assumptions on channel assignments.
1368 */
1369 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
1370 error_setg(errp, "Postcopy preempt not compatible with compress");
1371 return false;
1372 }
ce5b0f4a
PX
1373 }
1374
6f39c90b
PX
1375 if (cap_list[MIGRATION_CAPABILITY_MULTIFD]) {
1376 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
1377 error_setg(errp, "Multifd is not compatible with compress");
1378 return false;
1379 }
1380 }
1381
4a84214e
PX
1382 return true;
1383}
1384
65ace060
AP
1385static void fill_destination_migration_info(MigrationInfo *info)
1386{
1387 MigrationIncomingState *mis = migration_incoming_get_current();
1388
9aca82ba
JQ
1389 if (mis->socket_address_list) {
1390 info->has_socket_address = true;
1391 info->socket_address =
1392 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1393 }
1394
65ace060
AP
1395 switch (mis->state) {
1396 case MIGRATION_STATUS_NONE:
1397 return;
65ace060
AP
1398 case MIGRATION_STATUS_SETUP:
1399 case MIGRATION_STATUS_CANCELLING:
1400 case MIGRATION_STATUS_CANCELLED:
1401 case MIGRATION_STATUS_ACTIVE:
1402 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
3c9928d9
PX
1403 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1404 case MIGRATION_STATUS_POSTCOPY_RECOVER:
65ace060
AP
1405 case MIGRATION_STATUS_FAILED:
1406 case MIGRATION_STATUS_COLO:
1407 info->has_status = true;
1408 break;
1409 case MIGRATION_STATUS_COMPLETED:
1410 info->has_status = true;
1411 fill_destination_postcopy_migration_info(info);
1412 break;
1413 }
1414 info->status = mis->state;
1415}
1416
1417MigrationInfo *qmp_query_migrate(Error **errp)
1418{
1419 MigrationInfo *info = g_malloc0(sizeof(*info));
1420
1421 fill_destination_migration_info(info);
1422 fill_source_migration_info(info);
1423
1424 return info;
1425}
1426
4a84214e
PX
1427void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1428 Error **errp)
1429{
1430 MigrationState *s = migrate_get_current();
1431 MigrationCapabilityStatusList *cap;
dd0ee30c 1432 bool cap_list[MIGRATION_CAPABILITY__MAX];
4a84214e 1433
392d87e2 1434 if (migration_is_running(s->state)) {
4a84214e
PX
1435 error_setg(errp, QERR_MIGRATION_ACTIVE);
1436 return;
1437 }
1438
dd0ee30c
PX
1439 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1440 if (!migrate_caps_check(cap_list, params, errp)) {
4a84214e
PX
1441 return;
1442 }
1443
1444 for (cap = params; cap; cap = cap->next) {
1445 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1446 }
00458433
OW
1447}
1448
16d063bc
PX
1449/*
1450 * Check whether the parameters are valid. Error will be put into errp
1451 * (if provided). Return true if valid, otherwise false.
1452 */
1453static bool migrate_params_check(MigrationParameters *params, Error **errp)
85de8323 1454{
7f375e04 1455 if (params->has_compress_level &&
741d4086 1456 (params->compress_level > 9)) {
c6bd8c70 1457 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
54270c45 1458 "a value between 0 and 9");
16d063bc 1459 return false;
85de8323 1460 }
16d063bc 1461
741d4086 1462 if (params->has_compress_threads && (params->compress_threads < 1)) {
c6bd8c70
MA
1463 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1464 "compress_threads",
54270c45 1465 "a value between 1 and 255");
16d063bc 1466 return false;
85de8323 1467 }
16d063bc 1468
741d4086 1469 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
c6bd8c70
MA
1470 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1471 "decompress_threads",
54270c45 1472 "a value between 1 and 255");
16d063bc 1473 return false;
85de8323 1474 }
16d063bc 1475
dc14a470
KZ
1476 if (params->has_throttle_trigger_threshold &&
1477 (params->throttle_trigger_threshold < 1 ||
1478 params->throttle_trigger_threshold > 100)) {
1479 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1480 "throttle_trigger_threshold",
1481 "an integer in the range of 1 to 100");
1482 return false;
1483 }
1484
7f375e04
EB
1485 if (params->has_cpu_throttle_initial &&
1486 (params->cpu_throttle_initial < 1 ||
1487 params->cpu_throttle_initial > 99)) {
1626fee3 1488 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 1489 "cpu_throttle_initial",
1626fee3 1490 "an integer in the range of 1 to 99");
16d063bc 1491 return false;
1626fee3 1492 }
16d063bc 1493
7f375e04
EB
1494 if (params->has_cpu_throttle_increment &&
1495 (params->cpu_throttle_increment < 1 ||
1496 params->cpu_throttle_increment > 99)) {
1626fee3 1497 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 1498 "cpu_throttle_increment",
1626fee3 1499 "an integer in the range of 1 to 99");
16d063bc 1500 return false;
1626fee3 1501 }
16d063bc 1502
741d4086 1503 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
2ee30cf0
MZ
1504 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1505 "max_bandwidth",
1506 "an integer in the range of 0 to "stringify(SIZE_MAX)
1507 " bytes/second");
16d063bc 1508 return false;
2ff30257 1509 }
16d063bc 1510
2ff30257 1511 if (params->has_downtime_limit &&
741d4086 1512 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
2ee30cf0
MZ
1513 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1514 "downtime_limit",
1515 "an integer in the range of 0 to "
7ac5529a 1516 stringify(MAX_MIGRATE_DOWNTIME)" ms");
16d063bc 1517 return false;
2ff30257 1518 }
16d063bc 1519
741d4086
JQ
1520 /* x_checkpoint_delay is now always positive */
1521
cbfd6c95 1522 if (params->has_multifd_channels && (params->multifd_channels < 1)) {
4075fb1c
JQ
1523 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1524 "multifd_channels",
54270c45 1525 "a value between 1 and 255");
4075fb1c
JQ
1526 return false;
1527 }
16d063bc 1528
9004db48
JQ
1529 if (params->has_multifd_zlib_level &&
1530 (params->multifd_zlib_level > 9)) {
1531 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zlib_level",
54270c45 1532 "a value between 0 and 9");
9004db48
JQ
1533 return false;
1534 }
1535
6a9ad154
JQ
1536 if (params->has_multifd_zstd_level &&
1537 (params->multifd_zstd_level > 20)) {
1538 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "multifd_zstd_level",
54270c45 1539 "a value between 0 and 20");
6a9ad154
JQ
1540 return false;
1541 }
1542
73af8dd8
JQ
1543 if (params->has_xbzrle_cache_size &&
1544 (params->xbzrle_cache_size < qemu_target_page_size() ||
1545 !is_power_of_2(params->xbzrle_cache_size))) {
1546 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1547 "xbzrle_cache_size",
54270c45 1548 "a power of two no less than the target page size");
73af8dd8
JQ
1549 return false;
1550 }
1551
4cbc9c7f
LQ
1552 if (params->has_max_cpu_throttle &&
1553 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1554 params->max_cpu_throttle > 99)) {
1555 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1556 "max_cpu_throttle",
1557 "an integer in the range of cpu_throttle_initial to 99");
1558 return false;
1559 }
1560
ee3d96ba
DDAG
1561 if (params->has_announce_initial &&
1562 params->announce_initial > 100000) {
1563 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1564 "announce_initial",
54270c45 1565 "a value between 0 and 100000");
ee3d96ba
DDAG
1566 return false;
1567 }
1568 if (params->has_announce_max &&
1569 params->announce_max > 100000) {
1570 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1571 "announce_max",
54270c45 1572 "a value between 0 and 100000");
ee3d96ba
DDAG
1573 return false;
1574 }
1575 if (params->has_announce_rounds &&
1576 params->announce_rounds > 1000) {
1577 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1578 "announce_rounds",
54270c45 1579 "a value between 0 and 1000");
ee3d96ba
DDAG
1580 return false;
1581 }
1582 if (params->has_announce_step &&
1583 (params->announce_step < 1 ||
1584 params->announce_step > 10000)) {
1585 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1586 "announce_step",
54270c45 1587 "a value between 0 and 10000");
ee3d96ba
DDAG
1588 return false;
1589 }
31e4c354
HR
1590
1591 if (params->has_block_bitmap_mapping &&
1592 !check_dirty_bitmap_mig_alias_map(params->block_bitmap_mapping, errp)) {
1593 error_prepend(errp, "Invalid mapping given for block-bitmap-mapping: ");
1594 return false;
1595 }
90eb69e4
LB
1596
1597#ifdef CONFIG_LINUX
1598 if (migrate_use_zero_copy_send() &&
1599 ((params->has_multifd_compression && params->multifd_compression) ||
720a252c 1600 (params->tls_creds && *params->tls_creds))) {
90eb69e4
LB
1601 error_setg(errp,
1602 "Zero copy only available for non-compressed non-TLS multifd migration");
1603 return false;
1604 }
1605#endif
1606
16d063bc
PX
1607 return true;
1608}
1609
1bda8b3c
MA
1610static void migrate_params_test_apply(MigrateSetParameters *params,
1611 MigrationParameters *dest)
1612{
1613 *dest = migrate_get_current()->parameters;
1614
1615 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1616
1617 if (params->has_compress_level) {
1618 dest->compress_level = params->compress_level;
1619 }
1620
1621 if (params->has_compress_threads) {
1622 dest->compress_threads = params->compress_threads;
1623 }
1624
1d58872a
XG
1625 if (params->has_compress_wait_thread) {
1626 dest->compress_wait_thread = params->compress_wait_thread;
1627 }
1628
1bda8b3c
MA
1629 if (params->has_decompress_threads) {
1630 dest->decompress_threads = params->decompress_threads;
1631 }
1632
dc14a470
KZ
1633 if (params->has_throttle_trigger_threshold) {
1634 dest->throttle_trigger_threshold = params->throttle_trigger_threshold;
1635 }
1636
1bda8b3c
MA
1637 if (params->has_cpu_throttle_initial) {
1638 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1639 }
1640
1641 if (params->has_cpu_throttle_increment) {
1642 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1643 }
1644
cbbf8182
KZ
1645 if (params->has_cpu_throttle_tailslow) {
1646 dest->cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1647 }
1648
720a252c 1649 if (params->tls_creds) {
01fa5598 1650 assert(params->tls_creds->type == QTYPE_QSTRING);
9728ebfb 1651 dest->tls_creds = params->tls_creds->u.s;
1bda8b3c
MA
1652 }
1653
720a252c 1654 if (params->tls_hostname) {
01fa5598 1655 assert(params->tls_hostname->type == QTYPE_QSTRING);
9728ebfb 1656 dest->tls_hostname = params->tls_hostname->u.s;
1bda8b3c
MA
1657 }
1658
1659 if (params->has_max_bandwidth) {
1660 dest->max_bandwidth = params->max_bandwidth;
1661 }
1662
1663 if (params->has_downtime_limit) {
1664 dest->downtime_limit = params->downtime_limit;
1665 }
1666
1667 if (params->has_x_checkpoint_delay) {
1668 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1669 }
1670
1671 if (params->has_block_incremental) {
1672 dest->block_incremental = params->block_incremental;
1673 }
cbfd6c95
JQ
1674 if (params->has_multifd_channels) {
1675 dest->multifd_channels = params->multifd_channels;
5e7577a1 1676 }
96eef042
JQ
1677 if (params->has_multifd_compression) {
1678 dest->multifd_compression = params->multifd_compression;
1679 }
73af8dd8
JQ
1680 if (params->has_xbzrle_cache_size) {
1681 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1682 }
7e555c6c
DDAG
1683 if (params->has_max_postcopy_bandwidth) {
1684 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1685 }
4cbc9c7f
LQ
1686 if (params->has_max_cpu_throttle) {
1687 dest->max_cpu_throttle = params->max_cpu_throttle;
1688 }
ee3d96ba
DDAG
1689 if (params->has_announce_initial) {
1690 dest->announce_initial = params->announce_initial;
1691 }
1692 if (params->has_announce_max) {
1693 dest->announce_max = params->announce_max;
1694 }
1695 if (params->has_announce_rounds) {
1696 dest->announce_rounds = params->announce_rounds;
1697 }
1698 if (params->has_announce_step) {
1699 dest->announce_step = params->announce_step;
1700 }
31e4c354
HR
1701
1702 if (params->has_block_bitmap_mapping) {
1703 dest->has_block_bitmap_mapping = true;
1704 dest->block_bitmap_mapping = params->block_bitmap_mapping;
1705 }
1bda8b3c
MA
1706}
1707
73af8dd8 1708static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
16d063bc
PX
1709{
1710 MigrationState *s = migrate_get_current();
1711
e87fae4c
MA
1712 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1713
7f375e04
EB
1714 if (params->has_compress_level) {
1715 s->parameters.compress_level = params->compress_level;
85de8323 1716 }
476c72aa 1717
7f375e04
EB
1718 if (params->has_compress_threads) {
1719 s->parameters.compress_threads = params->compress_threads;
85de8323 1720 }
476c72aa 1721
1d58872a
XG
1722 if (params->has_compress_wait_thread) {
1723 s->parameters.compress_wait_thread = params->compress_wait_thread;
1724 }
1725
7f375e04
EB
1726 if (params->has_decompress_threads) {
1727 s->parameters.decompress_threads = params->decompress_threads;
85de8323 1728 }
476c72aa 1729
dc14a470
KZ
1730 if (params->has_throttle_trigger_threshold) {
1731 s->parameters.throttle_trigger_threshold = params->throttle_trigger_threshold;
1732 }
1733
7f375e04
EB
1734 if (params->has_cpu_throttle_initial) {
1735 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1626fee3 1736 }
476c72aa 1737
7f375e04
EB
1738 if (params->has_cpu_throttle_increment) {
1739 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1626fee3 1740 }
476c72aa 1741
cbbf8182
KZ
1742 if (params->has_cpu_throttle_tailslow) {
1743 s->parameters.cpu_throttle_tailslow = params->cpu_throttle_tailslow;
1744 }
1745
720a252c 1746 if (params->tls_creds) {
69ef1f36 1747 g_free(s->parameters.tls_creds);
01fa5598
MA
1748 assert(params->tls_creds->type == QTYPE_QSTRING);
1749 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
69ef1f36 1750 }
476c72aa 1751
720a252c 1752 if (params->tls_hostname) {
69ef1f36 1753 g_free(s->parameters.tls_hostname);
01fa5598
MA
1754 assert(params->tls_hostname->type == QTYPE_QSTRING);
1755 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
69ef1f36 1756 }
476c72aa 1757
720a252c 1758 if (params->tls_authz) {
d2f1d29b
DB
1759 g_free(s->parameters.tls_authz);
1760 assert(params->tls_authz->type == QTYPE_QSTRING);
1761 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1762 }
1763
2ff30257
AA
1764 if (params->has_max_bandwidth) {
1765 s->parameters.max_bandwidth = params->max_bandwidth;
c38c1c14 1766 if (s->to_dst_file && !migration_in_postcopy()) {
2ff30257
AA
1767 qemu_file_set_rate_limit(s->to_dst_file,
1768 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1769 }
1770 }
476c72aa 1771
2ff30257
AA
1772 if (params->has_downtime_limit) {
1773 s->parameters.downtime_limit = params->downtime_limit;
1774 }
68b53591
HZ
1775
1776 if (params->has_x_checkpoint_delay) {
1777 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
479125d5
HZ
1778 if (migration_in_colo_state()) {
1779 colo_checkpoint_notify(s);
1780 }
68b53591 1781 }
476c72aa 1782
2833c59b
JQ
1783 if (params->has_block_incremental) {
1784 s->parameters.block_incremental = params->block_incremental;
1785 }
cbfd6c95
JQ
1786 if (params->has_multifd_channels) {
1787 s->parameters.multifd_channels = params->multifd_channels;
4075fb1c 1788 }
96eef042
JQ
1789 if (params->has_multifd_compression) {
1790 s->parameters.multifd_compression = params->multifd_compression;
1791 }
73af8dd8
JQ
1792 if (params->has_xbzrle_cache_size) {
1793 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1794 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1795 }
7e555c6c
DDAG
1796 if (params->has_max_postcopy_bandwidth) {
1797 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
c38c1c14
DDAG
1798 if (s->to_dst_file && migration_in_postcopy()) {
1799 qemu_file_set_rate_limit(s->to_dst_file,
1800 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1801 }
7e555c6c 1802 }
4cbc9c7f
LQ
1803 if (params->has_max_cpu_throttle) {
1804 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1805 }
ee3d96ba
DDAG
1806 if (params->has_announce_initial) {
1807 s->parameters.announce_initial = params->announce_initial;
1808 }
1809 if (params->has_announce_max) {
1810 s->parameters.announce_max = params->announce_max;
1811 }
1812 if (params->has_announce_rounds) {
1813 s->parameters.announce_rounds = params->announce_rounds;
1814 }
1815 if (params->has_announce_step) {
1816 s->parameters.announce_step = params->announce_step;
1817 }
31e4c354
HR
1818
1819 if (params->has_block_bitmap_mapping) {
1820 qapi_free_BitmapMigrationNodeAliasList(
1821 s->parameters.block_bitmap_mapping);
1822
1823 s->parameters.has_block_bitmap_mapping = true;
1824 s->parameters.block_bitmap_mapping =
1825 QAPI_CLONE(BitmapMigrationNodeAliasList,
1826 params->block_bitmap_mapping);
1827 }
85de8323
LL
1828}
1829
1bda8b3c 1830void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
476c72aa 1831{
1bda8b3c
MA
1832 MigrationParameters tmp;
1833
01fa5598 1834 /* TODO Rewrite "" to null instead */
720a252c 1835 if (params->tls_creds
01fa5598 1836 && params->tls_creds->type == QTYPE_QNULL) {
cb3e7f08 1837 qobject_unref(params->tls_creds->u.n);
01fa5598
MA
1838 params->tls_creds->type = QTYPE_QSTRING;
1839 params->tls_creds->u.s = strdup("");
1840 }
1841 /* TODO Rewrite "" to null instead */
720a252c 1842 if (params->tls_hostname
01fa5598 1843 && params->tls_hostname->type == QTYPE_QNULL) {
cb3e7f08 1844 qobject_unref(params->tls_hostname->u.n);
01fa5598
MA
1845 params->tls_hostname->type = QTYPE_QSTRING;
1846 params->tls_hostname->u.s = strdup("");
1847 }
1848
1bda8b3c
MA
1849 migrate_params_test_apply(params, &tmp);
1850
1851 if (!migrate_params_check(&tmp, errp)) {
476c72aa
PX
1852 /* Invalid parameter */
1853 return;
1854 }
1855
73af8dd8 1856 migrate_params_apply(params, errp);
476c72aa
PX
1857}
1858
2594f56d 1859
4886a1bc
DDAG
1860void qmp_migrate_start_postcopy(Error **errp)
1861{
1862 MigrationState *s = migrate_get_current();
1863
16b0fd32 1864 if (!migrate_postcopy()) {
a54d340b 1865 error_setg(errp, "Enable postcopy with migrate_set_capability before"
4886a1bc
DDAG
1866 " the start of migration");
1867 return;
1868 }
1869
1870 if (s->state == MIGRATION_STATUS_NONE) {
1871 error_setg(errp, "Postcopy must be started after migration has been"
1872 " started");
1873 return;
1874 }
1875 /*
1876 * we don't error if migration has finished since that would be racy
1877 * with issuing this command.
1878 */
d73415a3 1879 qatomic_set(&s->start_postcopy, true);
4886a1bc
DDAG
1880}
1881
065e2813
AL
1882/* shared migration helpers */
1883
48781e5b 1884void migrate_set_state(int *state, int old_state, int new_state)
51cf4c1a 1885{
a31fedee 1886 assert(new_state < MIGRATION_STATUS__MAX);
d73415a3 1887 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
a31fedee 1888 trace_migrate_set_state(MigrationStatus_str(new_state));
b05dc723 1889 migrate_generate_event(new_state);
51cf4c1a
Z
1890 }
1891}
1892
eaedde52
EB
1893static MigrationCapabilityStatus *migrate_cap_add(MigrationCapability index,
1894 bool state)
2833c59b 1895{
eaedde52 1896 MigrationCapabilityStatus *cap;
2833c59b 1897
eaedde52
EB
1898 cap = g_new0(MigrationCapabilityStatus, 1);
1899 cap->capability = index;
1900 cap->state = state;
4e4a3d3a
PX
1901
1902 return cap;
1903}
1904
1905void migrate_set_block_enabled(bool value, Error **errp)
1906{
eaedde52 1907 MigrationCapabilityStatusList *cap = NULL;
4e4a3d3a 1908
eaedde52 1909 QAPI_LIST_PREPEND(cap, migrate_cap_add(MIGRATION_CAPABILITY_BLOCK, value));
2833c59b
JQ
1910 qmp_migrate_set_capabilities(cap, errp);
1911 qapi_free_MigrationCapabilityStatusList(cap);
1912}
1913
1914static void migrate_set_block_incremental(MigrationState *s, bool value)
1915{
1916 s->parameters.block_incremental = value;
1917}
1918
1919static void block_cleanup_parameters(MigrationState *s)
1920{
1921 if (s->must_remove_block_options) {
1922 /* setting to false can never fail */
1923 migrate_set_block_enabled(false, &error_abort);
1924 migrate_set_block_incremental(s, false);
1925 s->must_remove_block_options = false;
1926 }
1927}
1928
fd392cfa 1929static void migrate_fd_cleanup(MigrationState *s)
065e2813 1930{
bb1fadc4
PB
1931 qemu_bh_delete(s->cleanup_bh);
1932 s->cleanup_bh = NULL;
1933
83174765
PX
1934 g_free(s->hostname);
1935 s->hostname = NULL;
e3bf5e68
DH
1936 json_writer_free(s->vmdesc);
1937 s->vmdesc = NULL;
83174765 1938
0ceccd85
PX
1939 qemu_savevm_state_cleanup();
1940
89a02a9f 1941 if (s->to_dst_file) {
62df066f 1942 QEMUFile *tmp;
f986c3d2 1943
9013dca5 1944 trace_migrate_fd_cleanup();
404a7c05 1945 qemu_mutex_unlock_iothread();
1d34e4bf
DDAG
1946 if (s->migration_thread_running) {
1947 qemu_thread_join(&s->thread);
1948 s->migration_thread_running = false;
1949 }
404a7c05
PB
1950 qemu_mutex_lock_iothread();
1951
1398b2e3 1952 multifd_save_cleanup();
62df066f
PX
1953 qemu_mutex_lock(&s->qemu_file_lock);
1954 tmp = s->to_dst_file;
89a02a9f 1955 s->to_dst_file = NULL;
62df066f
PX
1956 qemu_mutex_unlock(&s->qemu_file_lock);
1957 /*
1958 * Close the file handle without the lock to make sure the
1959 * critical section won't block for long.
1960 */
39675fff 1961 migration_ioc_unregister_yank_from_file(tmp);
62df066f 1962 qemu_fclose(tmp);
065e2813
AL
1963 }
1964
36f62f11
PX
1965 if (s->postcopy_qemufile_src) {
1966 migration_ioc_unregister_yank_from_file(s->postcopy_qemufile_src);
1967 qemu_fclose(s->postcopy_qemufile_src);
1968 s->postcopy_qemufile_src = NULL;
1969 }
1970
8f8d528e 1971 assert(!migration_is_active(s));
7a2c1721 1972
94f5a437 1973 if (s->state == MIGRATION_STATUS_CANCELLING) {
48781e5b 1974 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
94f5a437 1975 MIGRATION_STATUS_CANCELLED);
7a2c1721 1976 }
a3fa1d78 1977
87db1a7d
JQ
1978 if (s->error) {
1979 /* It is used on info migrate. We can't free it */
1980 error_report_err(error_copy(s->error));
1981 }
a3fa1d78 1982 notifier_list_notify(&migration_state_notifiers, s);
2833c59b 1983 block_cleanup_parameters(s);
b5eea99e 1984 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
065e2813
AL
1985}
1986
fd392cfa
YK
1987static void migrate_fd_cleanup_schedule(MigrationState *s)
1988{
1989 /*
1990 * Ref the state for bh, because it may be called when
1991 * there're already no other refs
1992 */
1993 object_ref(OBJECT(s));
1994 qemu_bh_schedule(s->cleanup_bh);
1995}
1996
1997static void migrate_fd_cleanup_bh(void *opaque)
1998{
1999 MigrationState *s = opaque;
2000 migrate_fd_cleanup(s);
2001 object_unref(OBJECT(s));
2002}
2003
87db1a7d
JQ
2004void migrate_set_error(MigrationState *s, const Error *error)
2005{
6e8a355d 2006 QEMU_LOCK_GUARD(&s->error_mutex);
87db1a7d
JQ
2007 if (!s->error) {
2008 s->error = error_copy(error);
2009 }
87db1a7d
JQ
2010}
2011
ca7bd082
PX
2012static void migrate_error_free(MigrationState *s)
2013{
2014 QEMU_LOCK_GUARD(&s->error_mutex);
2015 if (s->error) {
2016 error_free(s->error);
2017 s->error = NULL;
2018 }
2019}
2020
d59ce6f3 2021void migrate_fd_error(MigrationState *s, const Error *error)
065e2813 2022{
25174055 2023 trace_migrate_fd_error(error_get_pretty(error));
89a02a9f 2024 assert(s->to_dst_file == NULL);
48781e5b
HZ
2025 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2026 MIGRATION_STATUS_FAILED);
87db1a7d 2027 migrate_set_error(s, error);
458cf28e
JQ
2028}
2029
0edda1c4 2030static void migrate_fd_cancel(MigrationState *s)
065e2813 2031{
6f2b811a 2032 int old_state ;
89a02a9f 2033 QEMUFile *f = migrate_get_current()->to_dst_file;
9013dca5 2034 trace_migrate_fd_cancel();
065e2813 2035
43044ac0
PX
2036 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
2037 if (s->rp_state.from_dst_file) {
2038 /* shutdown the rp socket, so causing the rp thread to shutdown */
2039 qemu_file_shutdown(s->rp_state.from_dst_file);
2040 }
70b20477
DDAG
2041 }
2042
6f2b811a
Z
2043 do {
2044 old_state = s->state;
392d87e2 2045 if (!migration_is_running(old_state)) {
6f2b811a
Z
2046 break;
2047 }
a7b36b48
DDAG
2048 /* If the migration is paused, kick it out of the pause */
2049 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
2050 qemu_sem_post(&s->pause_sem);
2051 }
48781e5b 2052 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
31194731 2053 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
2054
2055 /*
2056 * If we're unlucky the migration code might be stuck somewhere in a
2057 * send/write while the network has failed and is waiting to timeout;
2058 * if we've got shutdown(2) available then we can force it to quit.
2059 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
2060 * called in a bh, so there is no race against this cancel.
2061 */
31194731 2062 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
a26ba26e
DDAG
2063 qemu_file_shutdown(f);
2064 }
1d2acc31
HZ
2065 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
2066 Error *local_err = NULL;
2067
3b717194 2068 bdrv_activate_all(&local_err);
1d2acc31
HZ
2069 if (local_err) {
2070 error_report_err(local_err);
2071 } else {
2072 s->block_inactive = false;
2073 }
2074 }
065e2813
AL
2075}
2076
99a0db9b
GH
2077void add_migration_state_change_notifier(Notifier *notify)
2078{
2079 notifier_list_add(&migration_state_notifiers, notify);
2080}
2081
2082void remove_migration_state_change_notifier(Notifier *notify)
2083{
31552529 2084 notifier_remove(notify);
99a0db9b
GH
2085}
2086
02edd2e7 2087bool migration_in_setup(MigrationState *s)
afe2df69 2088{
31194731 2089 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
2090}
2091
7073693b 2092bool migration_has_finished(MigrationState *s)
99a0db9b 2093{
31194731 2094 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 2095}
0edda1c4 2096
afe2df69
GH
2097bool migration_has_failed(MigrationState *s)
2098{
31194731
HZ
2099 return (s->state == MIGRATION_STATUS_CANCELLED ||
2100 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
2101}
2102
5727309d 2103bool migration_in_postcopy(void)
9ec055ae 2104{
5727309d
JQ
2105 MigrationState *s = migrate_get_current();
2106
3748fef9
DDAG
2107 switch (s->state) {
2108 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2109 case MIGRATION_STATUS_POSTCOPY_PAUSED:
2110 case MIGRATION_STATUS_POSTCOPY_RECOVER:
2111 return true;
2112 default:
2113 return false;
2114 }
9ec055ae
DDAG
2115}
2116
b82fc321
DDAG
2117bool migration_in_postcopy_after_devices(MigrationState *s)
2118{
5727309d 2119 return migration_in_postcopy() && s->postcopy_after_devices;
b82fc321
DDAG
2120}
2121
06df2e69
DH
2122bool migration_in_incoming_postcopy(void)
2123{
2124 PostcopyState ps = postcopy_state_get();
2125
2126 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
2127}
2128
1a8e44a8
AG
2129bool migration_in_bg_snapshot(void)
2130{
2131 MigrationState *s = migrate_get_current();
2132
2133 return migrate_background_snapshot() &&
2134 migration_is_setup_or_active(s->state);
2135}
2136
fab35005 2137bool migration_is_idle(void)
fe44dc91 2138{
daff7f0b
MA
2139 MigrationState *s = current_migration;
2140
2141 if (!s) {
2142 return true;
2143 }
fe44dc91
AA
2144
2145 switch (s->state) {
2146 case MIGRATION_STATUS_NONE:
2147 case MIGRATION_STATUS_CANCELLED:
2148 case MIGRATION_STATUS_COMPLETED:
2149 case MIGRATION_STATUS_FAILED:
2150 return true;
2151 case MIGRATION_STATUS_SETUP:
2152 case MIGRATION_STATUS_CANCELLING:
2153 case MIGRATION_STATUS_ACTIVE:
2154 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
2155 case MIGRATION_STATUS_COLO:
31e06077
DDAG
2156 case MIGRATION_STATUS_PRE_SWITCHOVER:
2157 case MIGRATION_STATUS_DEVICE:
c7e0acd5 2158 case MIGRATION_STATUS_WAIT_UNPLUG:
fe44dc91
AA
2159 return false;
2160 case MIGRATION_STATUS__MAX:
2161 g_assert_not_reached();
2162 }
2163
2164 return false;
2165}
2166
8f8d528e
WY
2167bool migration_is_active(MigrationState *s)
2168{
2169 return (s->state == MIGRATION_STATUS_ACTIVE ||
2170 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2171}
2172
3e0c8050 2173void migrate_init(MigrationState *s)
0edda1c4 2174{
389775d1
DDAG
2175 /*
2176 * Reinitialise all migration state, except
2177 * parameters/capabilities that the user set, and
2178 * locks.
2179 */
389775d1 2180 s->cleanup_bh = 0;
8518278a 2181 s->vm_start_bh = 0;
89a02a9f 2182 s->to_dst_file = NULL;
389775d1 2183 s->state = MIGRATION_STATUS_NONE;
389775d1
DDAG
2184 s->rp_state.from_dst_file = NULL;
2185 s->rp_state.error = false;
2186 s->mbps = 0.0;
aecbfe9c 2187 s->pages_per_second = 0.0;
389775d1
DDAG
2188 s->downtime = 0;
2189 s->expected_downtime = 0;
389775d1 2190 s->setup_time = 0;
389775d1 2191 s->start_postcopy = false;
b82fc321 2192 s->postcopy_after_devices = false;
389775d1 2193 s->migration_thread_running = false;
d59ce6f3
DB
2194 error_free(s->error);
2195 s->error = NULL;
d8053e73 2196 s->hostname = NULL;
389775d1 2197
48781e5b 2198 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 2199
4af246a3
PX
2200 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2201 s->total_time = 0;
7287cbd4 2202 s->vm_was_running = false;
b15df1ae
PX
2203 s->iteration_initial_bytes = 0;
2204 s->threshold_size = 0;
0edda1c4 2205}
cab30143 2206
60fd6801 2207int migrate_add_blocker_internal(Error *reason, Error **errp)
fa2756b7 2208{
4c170330
PX
2209 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
2210 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
2211 error_propagate_prepend(errp, error_copy(reason),
2212 "disallowing migration blocker "
2213 "(migration/snapshot in progress) for: ");
2214 return -EBUSY;
fe44dc91
AA
2215 }
2216
4c170330
PX
2217 migration_blockers = g_slist_prepend(migration_blockers, reason);
2218 return 0;
fa2756b7
AL
2219}
2220
60fd6801
PX
2221int migrate_add_blocker(Error *reason, Error **errp)
2222{
2223 if (only_migratable) {
2224 error_propagate_prepend(errp, error_copy(reason),
2225 "disallowing migration blocker "
2226 "(--only-migratable) for: ");
2227 return -EACCES;
2228 }
2229
2230 return migrate_add_blocker_internal(reason, errp);
2231}
2232
fa2756b7
AL
2233void migrate_del_blocker(Error *reason)
2234{
2235 migration_blockers = g_slist_remove(migration_blockers, reason);
2236}
2237
bf1ae1f4
DDAG
2238void qmp_migrate_incoming(const char *uri, Error **errp)
2239{
2240 Error *local_err = NULL;
4debb5f5 2241 static bool once = true;
bf1ae1f4 2242
4debb5f5
DDAG
2243 if (!once) {
2244 error_setg(errp, "The incoming migration has already been started");
603d5a42 2245 return;
4debb5f5 2246 }
e69d50d6
PB
2247 if (!runstate_check(RUN_STATE_INMIGRATE)) {
2248 error_setg(errp, "'-incoming' was not specified on the command line");
2249 return;
2250 }
bf1ae1f4 2251
cc48c587
PX
2252 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2253 return;
2254 }
2255
bf1ae1f4
DDAG
2256 qemu_start_incoming_migration(uri, &local_err);
2257
2258 if (local_err) {
cc48c587 2259 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
bf1ae1f4
DDAG
2260 error_propagate(errp, local_err);
2261 return;
2262 }
2263
4debb5f5 2264 once = false;
bf1ae1f4
DDAG
2265}
2266
02affd41
PX
2267void qmp_migrate_recover(const char *uri, Error **errp)
2268{
2269 MigrationIncomingState *mis = migration_incoming_get_current();
2270
b7f9afd4
PX
2271 /*
2272 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
2273 * callers (no one should ignore a recover failure); if there is, it's a
2274 * programming error.
2275 */
2276 assert(errp);
2277
02affd41
PX
2278 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2279 error_setg(errp, "Migrate recover can only be run "
2280 "when postcopy is paused.");
2281 return;
2282 }
2283
08401c04
PX
2284 /* If there's an existing transport, release it */
2285 migration_incoming_transport_cleanup(mis);
02affd41
PX
2286
2287 /*
2288 * Note that this call will never start a real migration; it will
2289 * only re-setup the migration stream and poke existing migration
2290 * to continue using that newly established channel.
2291 */
2292 qemu_start_incoming_migration(uri, errp);
2293}
2294
bfbf89c2
PX
2295void qmp_migrate_pause(Error **errp)
2296{
2297 MigrationState *ms = migrate_get_current();
2298 MigrationIncomingState *mis = migration_incoming_get_current();
2299 int ret;
2300
2301 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2302 /* Source side, during postcopy */
2303 qemu_mutex_lock(&ms->qemu_file_lock);
2304 ret = qemu_file_shutdown(ms->to_dst_file);
2305 qemu_mutex_unlock(&ms->qemu_file_lock);
2306 if (ret) {
2307 error_setg(errp, "Failed to pause source migration");
2308 }
2309 return;
2310 }
2311
2312 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2313 ret = qemu_file_shutdown(mis->from_src_file);
2314 if (ret) {
2315 error_setg(errp, "Failed to pause destination migration");
2316 }
2317 return;
2318 }
2319
2320 error_setg(errp, "migrate-pause is currently only supported "
2321 "during postcopy-active state");
2322}
2323
24f3902b
GK
2324bool migration_is_blocked(Error **errp)
2325{
2326 if (qemu_savevm_state_blocked(errp)) {
2327 return true;
2328 }
2329
2330 if (migration_blockers) {
250561e1 2331 error_propagate(errp, error_copy(migration_blockers->data));
24f3902b
GK
2332 return true;
2333 }
2334
2335 return false;
2336}
2337
d3e35b8f
PX
2338/* Returns true if continue to migrate, or false if error detected */
2339static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
2340 bool resume, Error **errp)
cab30143 2341{
be7059cd 2342 Error *local_err = NULL;
d3e35b8f
PX
2343
2344 if (resume) {
2345 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
2346 error_setg(errp, "Cannot resume if there is no "
2347 "paused migration");
2348 return false;
2349 }
97ca211c
PX
2350
2351 /*
2352 * Postcopy recovery won't work well with release-ram
2353 * capability since release-ram will drop the page buffer as
2354 * long as the page is put into the send buffer. So if there
2355 * is a network failure happened, any page buffers that have
2356 * not yet reached the destination VM but have already been
2357 * sent from the source VM will be lost forever. Let's refuse
2358 * the client from resuming such a postcopy migration.
2359 * Luckily release-ram was designed to only be used when src
2360 * and destination VMs are on the same host, so it should be
2361 * fine.
2362 */
2363 if (migrate_release_ram()) {
2364 error_setg(errp, "Postcopy recovery cannot work "
2365 "when release-ram capability is set");
2366 return false;
2367 }
2368
d3e35b8f
PX
2369 /* This is a resume, skip init status */
2370 return true;
2371 }
cab30143 2372
392d87e2 2373 if (migration_is_running(s->state)) {
c6bd8c70 2374 error_setg(errp, QERR_MIGRATION_ACTIVE);
d3e35b8f 2375 return false;
cab30143 2376 }
d3e35b8f 2377
ca99993a
DDAG
2378 if (runstate_check(RUN_STATE_INMIGRATE)) {
2379 error_setg(errp, "Guest is waiting for an incoming migration");
d3e35b8f 2380 return false;
ca99993a
DDAG
2381 }
2382
36d0fe65
T
2383 if (runstate_check(RUN_STATE_POSTMIGRATE)) {
2384 error_setg(errp, "Can't migrate the vm that was paused due to "
2385 "previous migration");
2386 return false;
2387 }
2388
24f3902b 2389 if (migration_is_blocked(errp)) {
d3e35b8f 2390 return false;
fa2756b7
AL
2391 }
2392
d3e35b8f 2393 if (blk || blk_inc) {
3ba02445
RL
2394 if (migrate_colo_enabled()) {
2395 error_setg(errp, "No disk migration is required in COLO mode");
2396 return false;
2397 }
2833c59b
JQ
2398 if (migrate_use_block() || migrate_use_block_incremental()) {
2399 error_setg(errp, "Command options are incompatible with "
2400 "current migration capabilities");
d3e35b8f 2401 return false;
2833c59b
JQ
2402 }
2403 migrate_set_block_enabled(true, &local_err);
2404 if (local_err) {
2405 error_propagate(errp, local_err);
d3e35b8f 2406 return false;
2833c59b
JQ
2407 }
2408 s->must_remove_block_options = true;
2409 }
2410
d3e35b8f 2411 if (blk_inc) {
2833c59b
JQ
2412 migrate_set_block_incremental(s, true);
2413 }
2414
3e0c8050 2415 migrate_init(s);
87f3bd87 2416 /*
fa0b31d5 2417 * set ram_counters compression_counters memory to zero for a
87f3bd87
IR
2418 * new migration
2419 */
2420 memset(&ram_counters, 0, sizeof(ram_counters));
fa0b31d5 2421 memset(&compression_counters, 0, sizeof(compression_counters));
cab30143 2422
d3e35b8f
PX
2423 return true;
2424}
2425
2426void qmp_migrate(const char *uri, bool has_blk, bool blk,
2427 bool has_inc, bool inc, bool has_detach, bool detach,
2428 bool has_resume, bool resume, Error **errp)
2429{
2430 Error *local_err = NULL;
2431 MigrationState *s = migrate_get_current();
d658f65c 2432 const char *p = NULL;
d3e35b8f
PX
2433
2434 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
2435 has_resume && resume, errp)) {
2436 /* Error detected, put into errp */
2437 return;
2438 }
2439
b5eea99e
LS
2440 if (!(has_resume && resume)) {
2441 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
2442 return;
2443 }
2444 }
2445
f444eeda 2446 migrate_protocol_allow_multi_channels(false);
d658f65c 2447 if (strstart(uri, "tcp:", &p) ||
9ba3b2ba
LM
2448 strstart(uri, "unix:", NULL) ||
2449 strstart(uri, "vsock:", NULL)) {
f444eeda 2450 migrate_protocol_allow_multi_channels(true);
d658f65c 2451 socket_start_outgoing_migration(s, p ? p : uri, &local_err);
2da776db 2452#ifdef CONFIG_RDMA
41310c68 2453 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
2454 rdma_start_outgoing_migration(s, p, &local_err);
2455#endif
cab30143 2456 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 2457 exec_start_outgoing_migration(s, p, &local_err);
cab30143 2458 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 2459 fd_start_outgoing_migration(s, p, &local_err);
99a0db9b 2460 } else {
b5eea99e
LS
2461 if (!(has_resume && resume)) {
2462 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2463 }
c6bd8c70
MA
2464 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
2465 "a valid migration protocol");
48781e5b
HZ
2466 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2467 MIGRATION_STATUS_FAILED);
09576e74 2468 block_cleanup_parameters(s);
e1c37d0e 2469 return;
cab30143
JQ
2470 }
2471
f37afb5a 2472 if (local_err) {
b5eea99e
LS
2473 if (!(has_resume && resume)) {
2474 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
2475 }
d59ce6f3 2476 migrate_fd_error(s, local_err);
f37afb5a 2477 error_propagate(errp, local_err);
e1c37d0e 2478 return;
1299c631 2479 }
cab30143
JQ
2480}
2481
6cdedb07 2482void qmp_migrate_cancel(Error **errp)
cab30143 2483{
458fecca 2484 migration_cancel(NULL);
cab30143
JQ
2485}
2486
89cfc02c
DDAG
2487void qmp_migrate_continue(MigrationStatus state, Error **errp)
2488{
2489 MigrationState *s = migrate_get_current();
2490 if (s->state != state) {
2491 error_setg(errp, "Migration not in expected state: %s",
2492 MigrationStatus_str(s->state));
2493 return;
2494 }
2495 qemu_sem_post(&s->pause_sem);
2496}
2497
53f09a10
PB
2498bool migrate_release_ram(void)
2499{
2500 MigrationState *s;
2501
2502 s = migrate_get_current();
2503
2504 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2505}
2506
53dd370c
DDAG
2507bool migrate_postcopy_ram(void)
2508{
2509 MigrationState *s;
2510
2511 s = migrate_get_current();
2512
32c3db5b 2513 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
53dd370c
DDAG
2514}
2515
58110f0a
VSO
2516bool migrate_postcopy(void)
2517{
dd6bb914 2518 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
58110f0a
VSO
2519}
2520
bde1e2ec
CV
2521bool migrate_auto_converge(void)
2522{
2523 MigrationState *s;
2524
2525 s = migrate_get_current();
2526
2527 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2528}
2529
323004a3
PL
2530bool migrate_zero_blocks(void)
2531{
2532 MigrationState *s;
2533
2534 s = migrate_get_current();
2535
2536 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2537}
2538
f22f928e
AP
2539bool migrate_postcopy_blocktime(void)
2540{
2541 MigrationState *s;
2542
2543 s = migrate_get_current();
2544
2545 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2546}
2547
8706d2d5
LL
2548bool migrate_use_compression(void)
2549{
dde4e694
LL
2550 MigrationState *s;
2551
2552 s = migrate_get_current();
2553
2554 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
2555}
2556
2557int migrate_compress_level(void)
2558{
2559 MigrationState *s;
2560
2561 s = migrate_get_current();
2562
2594f56d 2563 return s->parameters.compress_level;
8706d2d5
LL
2564}
2565
2566int migrate_compress_threads(void)
2567{
2568 MigrationState *s;
2569
2570 s = migrate_get_current();
2571
2594f56d 2572 return s->parameters.compress_threads;
8706d2d5
LL
2573}
2574
1d58872a
XG
2575int migrate_compress_wait_thread(void)
2576{
2577 MigrationState *s;
2578
2579 s = migrate_get_current();
2580
2581 return s->parameters.compress_wait_thread;
2582}
2583
3fcb38c2
LL
2584int migrate_decompress_threads(void)
2585{
2586 MigrationState *s;
2587
2588 s = migrate_get_current();
2589
2594f56d 2590 return s->parameters.decompress_threads;
3fcb38c2
LL
2591}
2592
55efc8c2
VSO
2593bool migrate_dirty_bitmaps(void)
2594{
2595 MigrationState *s;
2596
2597 s = migrate_get_current();
2598
2599 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2600}
2601
18269069
YK
2602bool migrate_ignore_shared(void)
2603{
2604 MigrationState *s;
2605
2606 s = migrate_get_current();
2607
2608 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2609}
2610
b9d68df6
YK
2611bool migrate_validate_uuid(void)
2612{
2613 MigrationState *s;
2614
2615 s = migrate_get_current();
2616
2617 return s->enabled_capabilities[MIGRATION_CAPABILITY_VALIDATE_UUID];
2618}
2619
b05dc723
JQ
2620bool migrate_use_events(void)
2621{
2622 MigrationState *s;
2623
2624 s = migrate_get_current();
2625
2626 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2627}
2628
30126bbf
JQ
2629bool migrate_use_multifd(void)
2630{
2631 MigrationState *s;
2632
2633 s = migrate_get_current();
2634
cbfd6c95 2635 return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
30126bbf
JQ
2636}
2637
93fbd031
DDAG
2638bool migrate_pause_before_switchover(void)
2639{
2640 MigrationState *s;
2641
2642 s = migrate_get_current();
2643
2644 return s->enabled_capabilities[
2645 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2646}
2647
4075fb1c
JQ
2648int migrate_multifd_channels(void)
2649{
2650 MigrationState *s;
2651
2652 s = migrate_get_current();
2653
cbfd6c95 2654 return s->parameters.multifd_channels;
4075fb1c
JQ
2655}
2656
ab7cbb0b
JQ
2657MultiFDCompression migrate_multifd_compression(void)
2658{
2659 MigrationState *s;
2660
2661 s = migrate_get_current();
2662
ead34f64 2663 assert(s->parameters.multifd_compression < MULTIFD_COMPRESSION__MAX);
ab7cbb0b
JQ
2664 return s->parameters.multifd_compression;
2665}
2666
9004db48
JQ
2667int migrate_multifd_zlib_level(void)
2668{
2669 MigrationState *s;
2670
2671 s = migrate_get_current();
2672
2673 return s->parameters.multifd_zlib_level;
2674}
2675
6a9ad154
JQ
2676int migrate_multifd_zstd_level(void)
2677{
2678 MigrationState *s;
2679
2680 s = migrate_get_current();
2681
2682 return s->parameters.multifd_zstd_level;
2683}
2684
abb6295b
LB
2685#ifdef CONFIG_LINUX
2686bool migrate_use_zero_copy_send(void)
2687{
2688 MigrationState *s;
2689
2690 s = migrate_get_current();
2691
1abaec9a 2692 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_COPY_SEND];
abb6295b
LB
2693}
2694#endif
2695
d2fafb6a
LB
2696int migrate_use_tls(void)
2697{
2698 MigrationState *s;
2699
2700 s = migrate_get_current();
2701
2702 return s->parameters.tls_creds && *s->parameters.tls_creds;
2703}
2704
17ad9b35
OW
2705int migrate_use_xbzrle(void)
2706{
2707 MigrationState *s;
2708
2709 s = migrate_get_current();
2710
2711 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2712}
2713
8b9407a0 2714uint64_t migrate_xbzrle_cache_size(void)
17ad9b35
OW
2715{
2716 MigrationState *s;
2717
2718 s = migrate_get_current();
2719
73af8dd8 2720 return s->parameters.xbzrle_cache_size;
17ad9b35 2721}
0d82d0e8 2722
7e555c6c
DDAG
2723static int64_t migrate_max_postcopy_bandwidth(void)
2724{
2725 MigrationState *s;
2726
2727 s = migrate_get_current();
2728
2729 return s->parameters.max_postcopy_bandwidth;
2730}
2731
2833c59b
JQ
2732bool migrate_use_block(void)
2733{
2734 MigrationState *s;
2735
2736 s = migrate_get_current();
2737
2738 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2739}
2740
c788ada8
PX
2741bool migrate_use_return_path(void)
2742{
2743 MigrationState *s;
2744
2745 s = migrate_get_current();
2746
2747 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2748}
2749
2833c59b
JQ
2750bool migrate_use_block_incremental(void)
2751{
2752 MigrationState *s;
2753
2754 s = migrate_get_current();
2755
2756 return s->parameters.block_incremental;
2757}
2758
6e8c25b4
AG
2759bool migrate_background_snapshot(void)
2760{
2761 MigrationState *s;
2762
2763 s = migrate_get_current();
2764
2765 return s->enabled_capabilities[MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT];
2766}
2767
ce5b0f4a
PX
2768bool migrate_postcopy_preempt(void)
2769{
2770 MigrationState *s;
2771
2772 s = migrate_get_current();
2773
2774 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_PREEMPT];
2775}
2776
70b20477
DDAG
2777/* migration thread support */
2778/*
2779 * Something bad happened to the RP stream, mark an error
2780 * The caller shall print or trace something to indicate why
2781 */
2782static void mark_source_rp_bad(MigrationState *s)
2783{
2784 s->rp_state.error = true;
2785}
2786
2787static struct rp_cmd_args {
2788 ssize_t len; /* -1 = variable */
2789 const char *name;
2790} rp_cmd_args[] = {
2791 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2792 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2793 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1e2d90eb
DDAG
2794 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2795 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
a335debb 2796 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
13955b89 2797 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
70b20477
DDAG
2798 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2799};
2800
1e2d90eb
DDAG
2801/*
2802 * Process a request for pages received on the return path,
2803 * We're allowed to send more than requested (e.g. to round to our page size)
2804 * and we don't need to send pages that have already been sent.
2805 */
2806static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2807 ram_addr_t start, size_t len)
2808{
8e3b0cbb 2809 long our_host_ps = qemu_real_host_page_size();
6c595cde 2810
1e2d90eb 2811 trace_migrate_handle_rp_req_pages(rbname, start, len);
6c595cde
DDAG
2812
2813 /*
2814 * Since we currently insist on matching page sizes, just sanity check
2815 * we're being asked for whole host pages.
2816 */
7648297d
DH
2817 if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
2818 !QEMU_IS_ALIGNED(len, our_host_ps)) {
6c595cde
DDAG
2819 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2820 " len: %zd", __func__, start, len);
2821 mark_source_rp_bad(ms);
2822 return;
2823 }
2824
96506894 2825 if (ram_save_queue_pages(rbname, start, len)) {
6c595cde
DDAG
2826 mark_source_rp_bad(ms);
2827 }
1e2d90eb
DDAG
2828}
2829
14b1742e
PX
2830/* Return true to retry, false to quit */
2831static bool postcopy_pause_return_path_thread(MigrationState *s)
2832{
2833 trace_postcopy_pause_return_path();
2834
2835 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2836
2837 trace_postcopy_pause_return_path_continued();
2838
2839 return true;
2840}
2841
a335debb
PX
2842static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2843{
2844 RAMBlock *block = qemu_ram_block_by_name(block_name);
2845
2846 if (!block) {
2847 error_report("%s: invalid block name '%s'", __func__, block_name);
2848 return -EINVAL;
2849 }
2850
2851 /* Fetch the received bitmap and refresh the dirty bitmap */
2852 return ram_dirty_bitmap_reload(s, block);
2853}
2854
13955b89
PX
2855static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2856{
2857 trace_source_return_path_thread_resume_ack(value);
2858
2859 if (value != MIGRATION_RESUME_ACK_VALUE) {
2860 error_report("%s: illegal resume_ack value %"PRIu32,
2861 __func__, value);
2862 return -1;
2863 }
2864
2865 /* Now both sides are active. */
2866 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2867 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2868
94190696
PX
2869 /* Notify send thread that time to continue send pages */
2870 qemu_sem_post(&s->rp_state.rp_sem);
13955b89
PX
2871
2872 return 0;
2873}
2874
93589827
PX
2875/*
2876 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
2877 * existed) in a safe way.
2878 */
2879static void migration_release_dst_files(MigrationState *ms)
43044ac0
PX
2880{
2881 QEMUFile *file;
2882
2883 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2884 /*
2885 * Reset the from_dst_file pointer first before releasing it, as we
2886 * can't block within lock section
2887 */
2888 file = ms->rp_state.from_dst_file;
2889 ms->rp_state.from_dst_file = NULL;
2890 }
2891
93589827
PX
2892 /*
2893 * Do the same to postcopy fast path socket too if there is. No
2894 * locking needed because this qemufile should only be managed by
2895 * return path thread.
2896 */
2897 if (ms->postcopy_qemufile_src) {
2898 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
2899 qemu_file_shutdown(ms->postcopy_qemufile_src);
2900 qemu_fclose(ms->postcopy_qemufile_src);
2901 ms->postcopy_qemufile_src = NULL;
2902 }
2903
43044ac0
PX
2904 qemu_fclose(file);
2905}
2906
70b20477
DDAG
2907/*
2908 * Handles messages sent on the return path towards the source VM
2909 *
2910 */
2911static void *source_return_path_thread(void *opaque)
2912{
2913 MigrationState *ms = opaque;
2914 QEMUFile *rp = ms->rp_state.from_dst_file;
2915 uint16_t header_len, header_type;
568b01ca 2916 uint8_t buf[512];
70b20477 2917 uint32_t tmp32, sibling_error;
1e2d90eb
DDAG
2918 ram_addr_t start = 0; /* =0 to silence warning */
2919 size_t len = 0, expected_len;
70b20477
DDAG
2920 int res;
2921
2922 trace_source_return_path_thread_entry();
74637e6f 2923 rcu_register_thread();
14b1742e
PX
2924
2925retry:
70b20477
DDAG
2926 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2927 migration_is_setup_or_active(ms->state)) {
2928 trace_source_return_path_thread_loop_top();
2929 header_type = qemu_get_be16(rp);
2930 header_len = qemu_get_be16(rp);
2931
7a9ddfbf
PX
2932 if (qemu_file_get_error(rp)) {
2933 mark_source_rp_bad(ms);
2934 goto out;
2935 }
2936
70b20477
DDAG
2937 if (header_type >= MIG_RP_MSG_MAX ||
2938 header_type == MIG_RP_MSG_INVALID) {
2939 error_report("RP: Received invalid message 0x%04x length 0x%04x",
ed8b2828 2940 header_type, header_len);
70b20477
DDAG
2941 mark_source_rp_bad(ms);
2942 goto out;
2943 }
2944
2945 if ((rp_cmd_args[header_type].len != -1 &&
2946 header_len != rp_cmd_args[header_type].len) ||
568b01ca 2947 header_len > sizeof(buf)) {
70b20477 2948 error_report("RP: Received '%s' message (0x%04x) with"
ed8b2828
MZ
2949 "incorrect length %d expecting %zu",
2950 rp_cmd_args[header_type].name, header_type, header_len,
2951 (size_t)rp_cmd_args[header_type].len);
70b20477
DDAG
2952 mark_source_rp_bad(ms);
2953 goto out;
2954 }
2955
2956 /* We know we've got a valid header by this point */
2957 res = qemu_get_buffer(rp, buf, header_len);
2958 if (res != header_len) {
2959 error_report("RP: Failed reading data for message 0x%04x"
2960 " read %d expected %d",
2961 header_type, res, header_len);
2962 mark_source_rp_bad(ms);
2963 goto out;
2964 }
2965
2966 /* OK, we have the message and the data */
2967 switch (header_type) {
2968 case MIG_RP_MSG_SHUT:
4d885131 2969 sibling_error = ldl_be_p(buf);
70b20477
DDAG
2970 trace_source_return_path_thread_shut(sibling_error);
2971 if (sibling_error) {
2972 error_report("RP: Sibling indicated error %d", sibling_error);
2973 mark_source_rp_bad(ms);
2974 }
2975 /*
2976 * We'll let the main thread deal with closing the RP
2977 * we could do a shutdown(2) on it, but we're the only user
2978 * anyway, so there's nothing gained.
2979 */
2980 goto out;
2981
2982 case MIG_RP_MSG_PONG:
4d885131 2983 tmp32 = ldl_be_p(buf);
70b20477
DDAG
2984 trace_source_return_path_thread_pong(tmp32);
2985 break;
2986
1e2d90eb 2987 case MIG_RP_MSG_REQ_PAGES:
4d885131
PM
2988 start = ldq_be_p(buf);
2989 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2990 migrate_handle_rp_req_pages(ms, NULL, start, len);
2991 break;
2992
2993 case MIG_RP_MSG_REQ_PAGES_ID:
2994 expected_len = 12 + 1; /* header + termination */
2995
2996 if (header_len >= expected_len) {
4d885131
PM
2997 start = ldq_be_p(buf);
2998 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2999 /* Now we expect an idstr */
3000 tmp32 = buf[12]; /* Length of the following idstr */
3001 buf[13 + tmp32] = '\0';
3002 expected_len += tmp32;
3003 }
3004 if (header_len != expected_len) {
3005 error_report("RP: Req_Page_id with length %d expecting %zd",
ed8b2828 3006 header_len, expected_len);
1e2d90eb
DDAG
3007 mark_source_rp_bad(ms);
3008 goto out;
3009 }
3010 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
3011 break;
3012
a335debb
PX
3013 case MIG_RP_MSG_RECV_BITMAP:
3014 if (header_len < 1) {
3015 error_report("%s: missing block name", __func__);
3016 mark_source_rp_bad(ms);
3017 goto out;
3018 }
3019 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
3020 buf[buf[0] + 1] = '\0';
3021 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
3022 mark_source_rp_bad(ms);
3023 goto out;
3024 }
3025 break;
3026
13955b89
PX
3027 case MIG_RP_MSG_RESUME_ACK:
3028 tmp32 = ldl_be_p(buf);
3029 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
3030 mark_source_rp_bad(ms);
3031 goto out;
3032 }
3033 break;
3034
70b20477
DDAG
3035 default:
3036 break;
3037 }
3038 }
14b1742e
PX
3039
3040out:
3041 res = qemu_file_get_error(rp);
3042 if (res) {
d5c8f2af 3043 if (res && migration_in_postcopy()) {
14b1742e
PX
3044 /*
3045 * Maybe there is something we can do: it looks like a
3046 * network down issue, and we pause for a recovery.
3047 */
93589827 3048 migration_release_dst_files(ms);
2e3e3da3 3049 rp = NULL;
14b1742e 3050 if (postcopy_pause_return_path_thread(ms)) {
43044ac0
PX
3051 /*
3052 * Reload rp, reset the rest. Referencing it is safe since
3053 * it's reset only by us above, or when migration completes
3054 */
2e3e3da3 3055 rp = ms->rp_state.from_dst_file;
14b1742e
PX
3056 ms->rp_state.error = false;
3057 goto retry;
3058 }
3059 }
3060
70b20477
DDAG
3061 trace_source_return_path_thread_bad_end();
3062 mark_source_rp_bad(ms);
3063 }
3064
3065 trace_source_return_path_thread_end();
93589827 3066 migration_release_dst_files(ms);
74637e6f 3067 rcu_unregister_thread();
70b20477
DDAG
3068 return NULL;
3069}
3070
d3e35b8f
PX
3071static int open_return_path_on_source(MigrationState *ms,
3072 bool create_thread)
70b20477 3073{
89a02a9f 3074 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
70b20477
DDAG
3075 if (!ms->rp_state.from_dst_file) {
3076 return -1;
3077 }
3078
3079 trace_open_return_path_on_source();
d3e35b8f
PX
3080
3081 if (!create_thread) {
3082 /* We're done */
3083 return 0;
3084 }
3085
70b20477
DDAG
3086 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
3087 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
53021ea1 3088 ms->rp_state.rp_thread_created = true;
70b20477
DDAG
3089
3090 trace_open_return_path_on_source_continue();
3091
3092 return 0;
3093}
3094
70b20477
DDAG
3095/* Returns 0 if the RP was ok, otherwise there was an error on the RP */
3096static int await_return_path_close_on_source(MigrationState *ms)
3097{
3098 /*
3099 * If this is a normal exit then the destination will send a SHUT and the
3100 * rp_thread will exit, however if there's an error we need to cause
3101 * it to exit.
3102 */
89a02a9f 3103 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
70b20477
DDAG
3104 /*
3105 * shutdown(2), if we have it, will cause it to unblock if it's stuck
3106 * waiting for the destination.
3107 */
3108 qemu_file_shutdown(ms->rp_state.from_dst_file);
3109 mark_source_rp_bad(ms);
3110 }
3111 trace_await_return_path_close_on_source_joining();
3112 qemu_thread_join(&ms->rp_state.rp_thread);
53021ea1 3113 ms->rp_state.rp_thread_created = false;
70b20477
DDAG
3114 trace_await_return_path_close_on_source_close();
3115 return ms->rp_state.error;
3116}
3117
1d34e4bf
DDAG
3118/*
3119 * Switch from normal iteration to postcopy
3120 * Returns non-0 on error
3121 */
7287cbd4 3122static int postcopy_start(MigrationState *ms)
1d34e4bf
DDAG
3123{
3124 int ret;
61b67d47
DB
3125 QIOChannelBuffer *bioc;
3126 QEMUFile *fb;
1d34e4bf 3127 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
7e555c6c 3128 int64_t bandwidth = migrate_max_postcopy_bandwidth();
ef8d6488 3129 bool restart_block = false;
0331c8ca 3130 int cur_state = MIGRATION_STATUS_ACTIVE;
d0edb8a1
PX
3131
3132 if (postcopy_preempt_wait_channel(ms)) {
3133 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
3134 return -1;
3135 }
3136
0331c8ca
DDAG
3137 if (!migrate_pause_before_switchover()) {
3138 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
3139 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3140 }
1d34e4bf
DDAG
3141
3142 trace_postcopy_start();
3143 qemu_mutex_lock_iothread();
3144 trace_postcopy_start_set_run();
3145
fb064112 3146 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
1d34e4bf
DDAG
3147 global_state_store();
3148 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
76b1c7fe
KW
3149 if (ret < 0) {
3150 goto fail;
3151 }
1d34e4bf 3152
0331c8ca
DDAG
3153 ret = migration_maybe_pause(ms, &cur_state,
3154 MIGRATION_STATUS_POSTCOPY_ACTIVE);
3155 if (ret < 0) {
3156 goto fail;
3157 }
3158
76b1c7fe 3159 ret = bdrv_inactivate_all();
1d34e4bf
DDAG
3160 if (ret < 0) {
3161 goto fail;
3162 }
ef8d6488 3163 restart_block = true;
1d34e4bf 3164
1c0d249d
DDAG
3165 /*
3166 * Cause any non-postcopiable, but iterative devices to
3167 * send out their final data.
3168 */
a1fbe750 3169 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1c0d249d 3170
1d34e4bf
DDAG
3171 /*
3172 * in Finish migrate and with the io-lock held everything should
3173 * be quiet, but we've potentially still got dirty pages and we
3174 * need to tell the destination to throw any pages it's already received
3175 * that are dirty
3176 */
58110f0a 3177 if (migrate_postcopy_ram()) {
739fcc1b 3178 ram_postcopy_send_discard_bitmap(ms);
1d34e4bf
DDAG
3179 }
3180
3181 /*
3182 * send rest of state - note things that are doing postcopy
3183 * will notice we're in POSTCOPY_ACTIVE and not actually
3184 * wrap their state up here
3185 */
7e555c6c
DDAG
3186 /* 0 max-postcopy-bandwidth means unlimited */
3187 if (!bandwidth) {
3188 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
3189 } else {
3190 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
3191 }
58110f0a
VSO
3192 if (migrate_postcopy_ram()) {
3193 /* Ping just for debugging, helps line traces up */
3194 qemu_savevm_send_ping(ms->to_dst_file, 2);
3195 }
1d34e4bf
DDAG
3196
3197 /*
3198 * While loading the device state we may trigger page transfer
3199 * requests and the fd must be free to process those, and thus
3200 * the destination must read the whole device state off the fd before
3201 * it starts processing it. Unfortunately the ad-hoc migration format
3202 * doesn't allow the destination to know the size to read without fully
3203 * parsing it through each devices load-state code (especially the open
3204 * coded devices that use get/put).
3205 * So we wrap the device state up in a package with a length at the start;
3206 * to do this we use a qemu_buf to hold the whole of the device state.
3207 */
61b67d47 3208 bioc = qio_channel_buffer_new(4096);
6f01f136 3209 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
77ef2dc1 3210 fb = qemu_file_new_output(QIO_CHANNEL(bioc));
61b67d47 3211 object_unref(OBJECT(bioc));
1d34e4bf 3212
c76201ab
DDAG
3213 /*
3214 * Make sure the receiver can get incoming pages before we send the rest
3215 * of the state
3216 */
3217 qemu_savevm_send_postcopy_listen(fb);
3218
a1fbe750 3219 qemu_savevm_state_complete_precopy(fb, false, false);
58110f0a
VSO
3220 if (migrate_postcopy_ram()) {
3221 qemu_savevm_send_ping(fb, 3);
3222 }
1d34e4bf
DDAG
3223
3224 qemu_savevm_send_postcopy_run(fb);
3225
3226 /* <><> end of stuff going into the package */
1d34e4bf 3227
ef8d6488
DDAG
3228 /* Last point of recovery; as soon as we send the package the destination
3229 * can open devices and potentially start running.
3230 * Lets just check again we've not got any errors.
3231 */
3232 ret = qemu_file_get_error(ms->to_dst_file);
3233 if (ret) {
3234 error_report("postcopy_start: Migration stream errored (pre package)");
3235 goto fail_closefb;
3236 }
3237
3238 restart_block = false;
3239
1d34e4bf 3240 /* Now send that blob */
61b67d47 3241 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1d34e4bf
DDAG
3242 goto fail_closefb;
3243 }
3244 qemu_fclose(fb);
b82fc321
DDAG
3245
3246 /* Send a notify to give a chance for anything that needs to happen
3247 * at the transition to postcopy and after the device state; in particular
3248 * spice needs to trigger a transition now
3249 */
3250 ms->postcopy_after_devices = true;
3251 notifier_list_notify(&migration_state_notifiers, ms);
3252
1d34e4bf
DDAG
3253 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
3254
3255 qemu_mutex_unlock_iothread();
3256
58110f0a
VSO
3257 if (migrate_postcopy_ram()) {
3258 /*
3259 * Although this ping is just for debug, it could potentially be
3260 * used for getting a better measurement of downtime at the source.
3261 */
3262 qemu_savevm_send_ping(ms->to_dst_file, 4);
3263 }
1d34e4bf 3264
ced1c616
PB
3265 if (migrate_release_ram()) {
3266 ram_postcopy_migrated_memory_release(ms);
3267 }
3268
89a02a9f 3269 ret = qemu_file_get_error(ms->to_dst_file);
1d34e4bf
DDAG
3270 if (ret) {
3271 error_report("postcopy_start: Migration stream errored");
48781e5b 3272 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf
DDAG
3273 MIGRATION_STATUS_FAILED);
3274 }
3275
c01b16ed
PX
3276 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
3277
1d34e4bf
DDAG
3278 return ret;
3279
3280fail_closefb:
3281 qemu_fclose(fb);
3282fail:
48781e5b 3283 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf 3284 MIGRATION_STATUS_FAILED);
ef8d6488
DDAG
3285 if (restart_block) {
3286 /* A failure happened early enough that we know the destination hasn't
3287 * accessed block devices, so we're safe to recover.
3288 */
3289 Error *local_err = NULL;
3290
3b717194 3291 bdrv_activate_all(&local_err);
ef8d6488
DDAG
3292 if (local_err) {
3293 error_report_err(local_err);
3294 }
3295 }
1d34e4bf
DDAG
3296 qemu_mutex_unlock_iothread();
3297 return -1;
3298}
3299
e91d8951
DDAG
3300/**
3301 * migration_maybe_pause: Pause if required to by
3302 * migrate_pause_before_switchover called with the iothread locked
3303 * Returns: 0 on success
3304 */
0331c8ca
DDAG
3305static int migration_maybe_pause(MigrationState *s,
3306 int *current_active_state,
3307 int new_state)
e91d8951
DDAG
3308{
3309 if (!migrate_pause_before_switchover()) {
3310 return 0;
3311 }
3312
3313 /* Since leaving this state is not atomic with posting the semaphore
3314 * it's possible that someone could have issued multiple migrate_continue
3315 * and the semaphore is incorrectly positive at this point;
3316 * the docs say it's undefined to reinit a semaphore that's already
3317 * init'd, so use timedwait to eat up any existing posts.
3318 */
3319 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
3320 /* This block intentionally left blank */
3321 }
3322
8958338b
ZF
3323 /*
3324 * If the migration is cancelled when it is in the completion phase,
3325 * the migration state is set to MIGRATION_STATUS_CANCELLING.
3326 * So we don't need to wait a semaphore, otherwise we would always
3327 * wait for the 'pause_sem' semaphore.
3328 */
3329 if (s->state != MIGRATION_STATUS_CANCELLING) {
3330 qemu_mutex_unlock_iothread();
3331 migrate_set_state(&s->state, *current_active_state,
3332 MIGRATION_STATUS_PRE_SWITCHOVER);
3333 qemu_sem_wait(&s->pause_sem);
3334 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
3335 new_state);
3336 *current_active_state = new_state;
3337 qemu_mutex_lock_iothread();
3338 }
e91d8951 3339
0331c8ca 3340 return s->state == new_state ? 0 : -EINVAL;
e91d8951
DDAG
3341}
3342
09f6c85e
DDAG
3343/**
3344 * migration_completion: Used by migration_thread when there's not much left.
3345 * The caller 'breaks' the loop when this returns.
3346 *
3347 * @s: Current migration state
09f6c85e 3348 */
2ad87305 3349static void migration_completion(MigrationState *s)
09f6c85e
DDAG
3350{
3351 int ret;
2ad87305 3352 int current_active_state = s->state;
09f6c85e 3353
b10ac0c4
DDAG
3354 if (s->state == MIGRATION_STATUS_ACTIVE) {
3355 qemu_mutex_lock_iothread();
64909f97 3356 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
fb064112 3357 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
7287cbd4 3358 s->vm_was_running = runstate_is_running();
b10ac0c4
DDAG
3359 ret = global_state_store();
3360
3361 if (!ret) {
a1fbe750 3362 bool inactivate = !migrate_colo_enabled();
b10ac0c4 3363 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
626ff651 3364 trace_migration_completion_vm_stop(ret);
e91d8951 3365 if (ret >= 0) {
0331c8ca
DDAG
3366 ret = migration_maybe_pause(s, &current_active_state,
3367 MIGRATION_STATUS_DEVICE);
e91d8951 3368 }
f07fa4cb
KW
3369 if (ret >= 0) {
3370 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
a1fbe750
FZ
3371 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
3372 inactivate);
f07fa4cb 3373 }
a1fbe750
FZ
3374 if (inactivate && ret >= 0) {
3375 s->block_inactive = true;
b10ac0c4
DDAG
3376 }
3377 }
3378 qemu_mutex_unlock_iothread();
09f6c85e 3379
b10ac0c4
DDAG
3380 if (ret < 0) {
3381 goto fail;
09f6c85e 3382 }
b10ac0c4
DDAG
3383 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3384 trace_migration_completion_postcopy_end();
3385
68b88468 3386 qemu_mutex_lock_iothread();
89a02a9f 3387 qemu_savevm_state_complete_postcopy(s->to_dst_file);
68b88468
EGE
3388 qemu_mutex_unlock_iothread();
3389
36f62f11
PX
3390 /* Shutdown the postcopy fast path thread */
3391 if (migrate_postcopy_preempt()) {
3392 postcopy_preempt_shutdown_file(s);
3393 }
3394
b10ac0c4 3395 trace_migration_completion_postcopy_end_after_complete();
444252b9 3396 } else {
6ba11211 3397 goto fail;
09f6c85e 3398 }
09f6c85e 3399
b10ac0c4
DDAG
3400 /*
3401 * If rp was opened we must clean up the thread before
3402 * cleaning everything else up (since if there are no failures
3403 * it will wait for the destination to send it's status in
3404 * a SHUT command).
b10ac0c4 3405 */
53021ea1 3406 if (s->rp_state.rp_thread_created) {
b10ac0c4 3407 int rp_error;
0425dc97 3408 trace_migration_return_path_end_before();
b10ac0c4 3409 rp_error = await_return_path_close_on_source(s);
0425dc97 3410 trace_migration_return_path_end_after(rp_error);
b10ac0c4 3411 if (rp_error) {
fe904ea8 3412 goto fail_invalidate;
b10ac0c4 3413 }
09f6c85e
DDAG
3414 }
3415
89a02a9f 3416 if (qemu_file_get_error(s->to_dst_file)) {
09f6c85e 3417 trace_migration_completion_file_err();
fe904ea8 3418 goto fail_invalidate;
09f6c85e
DDAG
3419 }
3420
eeeb48ee
ZC
3421 if (migrate_colo_enabled() && s->state == MIGRATION_STATUS_ACTIVE) {
3422 /* COLO does not support postcopy */
3423 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3424 MIGRATION_STATUS_COLO);
3425 } else {
0b827d5e
HZ
3426 migrate_set_state(&s->state, current_active_state,
3427 MIGRATION_STATUS_COMPLETED);
3428 }
3429
09f6c85e
DDAG
3430 return;
3431
fe904ea8
GK
3432fail_invalidate:
3433 /* If not doing postcopy, vm_start() will be called: let's regain
3434 * control on images.
3435 */
6039dd5b
DDAG
3436 if (s->state == MIGRATION_STATUS_ACTIVE ||
3437 s->state == MIGRATION_STATUS_DEVICE) {
fe904ea8
GK
3438 Error *local_err = NULL;
3439
1d2acc31 3440 qemu_mutex_lock_iothread();
3b717194 3441 bdrv_activate_all(&local_err);
fe904ea8
GK
3442 if (local_err) {
3443 error_report_err(local_err);
1d2acc31
HZ
3444 } else {
3445 s->block_inactive = false;
fe904ea8 3446 }
1d2acc31 3447 qemu_mutex_unlock_iothread();
fe904ea8
GK
3448 }
3449
09f6c85e 3450fail:
48781e5b
HZ
3451 migrate_set_state(&s->state, current_active_state,
3452 MIGRATION_STATUS_FAILED);
09f6c85e
DDAG
3453}
3454
8518278a
AG
3455/**
3456 * bg_migration_completion: Used by bg_migration_thread when after all the
3457 * RAM has been saved. The caller 'breaks' the loop when this returns.
3458 *
3459 * @s: Current migration state
3460 */
3461static void bg_migration_completion(MigrationState *s)
3462{
3463 int current_active_state = s->state;
3464
3465 /*
3466 * Stop tracking RAM writes - un-protect memory, un-register UFFD
3467 * memory ranges, flush kernel wait queues and wake up threads
3468 * waiting for write fault to be resolved.
3469 */
3470 ram_write_tracking_stop();
3471
3472 if (s->state == MIGRATION_STATUS_ACTIVE) {
3473 /*
3474 * By this moment we have RAM content saved into the migration stream.
3475 * The next step is to flush the non-RAM content (device state)
3476 * right after the ram content. The device state has been stored into
3477 * the temporary buffer before RAM saving started.
3478 */
3479 qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
3480 qemu_fflush(s->to_dst_file);
3481 } else if (s->state == MIGRATION_STATUS_CANCELLING) {
3482 goto fail;
3483 }
3484
3485 if (qemu_file_get_error(s->to_dst_file)) {
3486 trace_migration_completion_file_err();
3487 goto fail;
3488 }
3489
3490 migrate_set_state(&s->state, current_active_state,
3491 MIGRATION_STATUS_COMPLETED);
3492 return;
3493
3494fail:
3495 migrate_set_state(&s->state, current_active_state,
3496 MIGRATION_STATUS_FAILED);
3497}
3498
35a6ed4f
HZ
3499bool migrate_colo_enabled(void)
3500{
3501 MigrationState *s = migrate_get_current();
3502 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
3503}
3504
b23c2ade
PX
3505typedef enum MigThrError {
3506 /* No error detected */
3507 MIG_THR_ERR_NONE = 0,
3508 /* Detected error, but resumed successfully */
3509 MIG_THR_ERR_RECOVERED = 1,
3510 /* Detected fatal error, need to exit */
3511 MIG_THR_ERR_FATAL = 2,
3512} MigThrError;
3513
94190696
PX
3514static int postcopy_resume_handshake(MigrationState *s)
3515{
3516 qemu_savevm_send_postcopy_resume(s->to_dst_file);
3517
3518 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3519 qemu_sem_wait(&s->rp_state.rp_sem);
3520 }
3521
3522 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
3523 return 0;
3524 }
3525
3526 return -1;
3527}
3528
135b87b4
PX
3529/* Return zero if success, or <0 for error */
3530static int postcopy_do_resume(MigrationState *s)
3531{
d1b8eadb
PX
3532 int ret;
3533
3534 /*
3535 * Call all the resume_prepare() hooks, so that modules can be
3536 * ready for the migration resume.
3537 */
3538 ret = qemu_savevm_state_resume_prepare(s);
3539 if (ret) {
3540 error_report("%s: resume_prepare() failure detected: %d",
3541 __func__, ret);
3542 return ret;
3543 }
3544
3545 /*
94190696
PX
3546 * Last handshake with destination on the resume (destination will
3547 * switch to postcopy-active afterwards)
d1b8eadb 3548 */
94190696
PX
3549 ret = postcopy_resume_handshake(s);
3550 if (ret) {
3551 error_report("%s: handshake failed: %d", __func__, ret);
3552 return ret;
3553 }
d1b8eadb 3554
135b87b4
PX
3555 return 0;
3556}
3557
b23c2ade
PX
3558/*
3559 * We don't return until we are in a safe state to continue current
3560 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
3561 * MIG_THR_ERR_FATAL if unrecovery failure happened.
3562 */
3563static MigThrError postcopy_pause(MigrationState *s)
3564{
3565 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
b23c2ade 3566
135b87b4 3567 while (true) {
62df066f
PX
3568 QEMUFile *file;
3569
39675fff
PX
3570 /*
3571 * Current channel is possibly broken. Release it. Note that this is
3572 * guaranteed even without lock because to_dst_file should only be
3573 * modified by the migration thread. That also guarantees that the
3574 * unregister of yank is safe too without the lock. It should be safe
3575 * even to be within the qemu_file_lock, but we didn't do that to avoid
3576 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
3577 * the qemu_file_lock critical section as small as possible.
3578 */
135b87b4 3579 assert(s->to_dst_file);
39675fff 3580 migration_ioc_unregister_yank_from_file(s->to_dst_file);
62df066f
PX
3581 qemu_mutex_lock(&s->qemu_file_lock);
3582 file = s->to_dst_file;
135b87b4 3583 s->to_dst_file = NULL;
62df066f
PX
3584 qemu_mutex_unlock(&s->qemu_file_lock);
3585
3586 qemu_file_shutdown(file);
3587 qemu_fclose(file);
b23c2ade 3588
d246ea50
PX
3589 migrate_set_state(&s->state, s->state,
3590 MIGRATION_STATUS_POSTCOPY_PAUSED);
3591
135b87b4
PX
3592 error_report("Detected IO failure for postcopy. "
3593 "Migration paused.");
b23c2ade 3594
135b87b4
PX
3595 /*
3596 * We wait until things fixed up. Then someone will setup the
3597 * status back for us.
3598 */
3599 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
3600 qemu_sem_wait(&s->postcopy_pause_sem);
3601 }
3602
3603 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
3604 /* Woken up by a recover procedure. Give it a shot */
b23c2ade 3605
d0edb8a1
PX
3606 if (postcopy_preempt_wait_channel(s)) {
3607 /*
3608 * Preempt enabled, and new channel create failed; loop
3609 * back to wait for another recovery.
3610 */
3611 continue;
3612 }
3613
135b87b4
PX
3614 /*
3615 * Firstly, let's wake up the return path now, with a new
3616 * return path channel.
3617 */
3618 qemu_sem_post(&s->postcopy_pause_rp_sem);
3619
3620 /* Do the resume logic */
3621 if (postcopy_do_resume(s) == 0) {
3622 /* Let's continue! */
3623 trace_postcopy_pause_continued();
3624 return MIG_THR_ERR_RECOVERED;
3625 } else {
3626 /*
3627 * Something wrong happened during the recovery, let's
3628 * pause again. Pause is always better than throwing
3629 * data away.
3630 */
3631 continue;
3632 }
3633 } else {
3634 /* This is not right... Time to quit. */
3635 return MIG_THR_ERR_FATAL;
3636 }
3637 }
b23c2ade
PX
3638}
3639
3640static MigThrError migration_detect_error(MigrationState *s)
3641{
3642 int ret;
c3c5eae6 3643 int state = s->state;
3d661c8a 3644 Error *local_error = NULL;
c3c5eae6
DDAG
3645
3646 if (state == MIGRATION_STATUS_CANCELLING ||
3647 state == MIGRATION_STATUS_CANCELLED) {
3648 /* End the migration, but don't set the state to failed */
3649 return MIG_THR_ERR_FATAL;
3650 }
b23c2ade 3651
60bb3c58
PX
3652 /*
3653 * Try to detect any file errors. Note that postcopy_qemufile_src will
3654 * be NULL when postcopy preempt is not enabled.
3655 */
3656 ret = qemu_file_get_error_obj_any(s->to_dst_file,
3657 s->postcopy_qemufile_src,
3658 &local_error);
b23c2ade
PX
3659 if (!ret) {
3660 /* Everything is fine */
3d661c8a 3661 assert(!local_error);
b23c2ade
PX
3662 return MIG_THR_ERR_NONE;
3663 }
3664
3d661c8a
YK
3665 if (local_error) {
3666 migrate_set_error(s, local_error);
3667 error_free(local_error);
3668 }
3669
d5c8f2af 3670 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
b23c2ade
PX
3671 /*
3672 * For postcopy, we allow the network to be down for a
3673 * while. After that, it can be continued by a
3674 * recovery phase.
3675 */
3676 return postcopy_pause(s);
3677 } else {
3678 /*
3679 * For precopy (or postcopy with error outside IO), we fail
3680 * with no time.
3681 */
c3c5eae6 3682 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
b23c2ade
PX
3683 trace_migration_thread_file_err();
3684
3685 /* Time to stop the migration, now. */
3686 return MIG_THR_ERR_FATAL;
3687 }
3688}
3689
268dcd46 3690/* How many bytes have we transferred since the beginning of the migration */
0c8f0efd
JQ
3691static uint64_t migration_total_bytes(MigrationState *s)
3692{
fbfa6404
DB
3693 return qemu_file_total_transferred(s->to_dst_file) +
3694 ram_counters.multifd_bytes;
0c8f0efd
JQ
3695}
3696
cf011f08
PX
3697static void migration_calculate_complete(MigrationState *s)
3698{
0c8f0efd 3699 uint64_t bytes = migration_total_bytes(s);
cf011f08 3700 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
6cde6fbe 3701 int64_t transfer_time;
cf011f08
PX
3702
3703 s->total_time = end_time - s->start_time;
3704 if (!s->downtime) {
3705 /*
3706 * It's still not set, so we are precopy migration. For
3707 * postcopy, downtime is calculated during postcopy_start().
3708 */
3709 s->downtime = end_time - s->downtime_start;
3710 }
3711
6cde6fbe
JQ
3712 transfer_time = s->total_time - s->setup_time;
3713 if (transfer_time) {
3714 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
cf011f08
PX
3715 }
3716}
3717
87f3bd87
IR
3718static void update_iteration_initial_status(MigrationState *s)
3719{
3720 /*
3721 * Update these three fields at the same time to avoid mismatch info lead
3722 * wrong speed calculation.
3723 */
3724 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3725 s->iteration_initial_bytes = migration_total_bytes(s);
3726 s->iteration_initial_pages = ram_get_total_transferred_pages();
3727}
3728
b15df1ae
PX
3729static void migration_update_counters(MigrationState *s,
3730 int64_t current_time)
3731{
aecbfe9c 3732 uint64_t transferred, transferred_pages, time_spent;
0c8f0efd 3733 uint64_t current_bytes; /* bytes transferred since the beginning */
b15df1ae
PX
3734 double bandwidth;
3735
3736 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3737 return;
3738 }
3739
0c8f0efd
JQ
3740 current_bytes = migration_total_bytes(s);
3741 transferred = current_bytes - s->iteration_initial_bytes;
b15df1ae
PX
3742 time_spent = current_time - s->iteration_start_time;
3743 bandwidth = (double)transferred / time_spent;
0781c1ed 3744 s->threshold_size = bandwidth * s->parameters.downtime_limit;
b15df1ae
PX
3745
3746 s->mbps = (((double) transferred * 8.0) /
3747 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3748
aecbfe9c
XG
3749 transferred_pages = ram_get_total_transferred_pages() -
3750 s->iteration_initial_pages;
3751 s->pages_per_second = (double) transferred_pages /
3752 (((double) time_spent / 1000.0));
3753
b15df1ae
PX
3754 /*
3755 * if we haven't sent anything, we don't want to
3756 * recalculate. 10000 is a small enough number for our purposes
3757 */
3758 if (ram_counters.dirty_pages_rate && transferred > 10000) {
650af890 3759 s->expected_downtime = ram_counters.remaining / bandwidth;
b15df1ae
PX
3760 }
3761
3762 qemu_file_reset_rate_limit(s->to_dst_file);
3763
87f3bd87 3764 update_iteration_initial_status(s);
b15df1ae
PX
3765
3766 trace_migrate_transferred(transferred, time_spent,
0781c1ed 3767 bandwidth, s->threshold_size);
b15df1ae
PX
3768}
3769
2ad87305
PX
3770/* Migration thread iteration status */
3771typedef enum {
3772 MIG_ITERATE_RESUME, /* Resume current iteration */
3773 MIG_ITERATE_SKIP, /* Skip current iteration */
3774 MIG_ITERATE_BREAK, /* Break the loop */
3775} MigIterateState;
3776
3777/*
3778 * Return true if continue to the next iteration directly, false
3779 * otherwise.
3780 */
3781static MigIterateState migration_iteration_run(MigrationState *s)
3782{
c8df4a7a 3783 uint64_t pend_pre, pend_compat, pend_post;
2ad87305
PX
3784 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3785
fd70385d 3786 qemu_savevm_state_pending_estimate(&pend_pre, &pend_compat, &pend_post);
c8df4a7a 3787 uint64_t pending_size = pend_pre + pend_compat + pend_post;
2ad87305 3788
fd70385d 3789 trace_migrate_pending_estimate(pending_size,
c8df4a7a
JQ
3790 pend_pre, pend_compat, pend_post);
3791
3792 if (pend_pre + pend_compat <= s->threshold_size) {
fd70385d 3793 qemu_savevm_state_pending_exact(&pend_pre, &pend_compat, &pend_post);
c8df4a7a 3794 pending_size = pend_pre + pend_compat + pend_post;
fd70385d 3795 trace_migrate_pending_exact(pending_size,
c8df4a7a
JQ
3796 pend_pre, pend_compat, pend_post);
3797 }
2ad87305 3798
d9df9292 3799 if (!pending_size || pending_size < s->threshold_size) {
2ad87305
PX
3800 trace_migration_thread_low_pending(pending_size);
3801 migration_completion(s);
3802 return MIG_ITERATE_BREAK;
3803 }
3804
d9df9292
JQ
3805 /* Still a significant amount to transfer */
3806 if (!in_postcopy && pend_pre <= s->threshold_size &&
3807 qatomic_read(&s->start_postcopy)) {
3808 if (postcopy_start(s)) {
3809 error_report("%s: postcopy failed to start", __func__);
3810 }
3811 return MIG_ITERATE_SKIP;
3812 }
3813
3814 /* Just another iteration step */
3815 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
2ad87305
PX
3816 return MIG_ITERATE_RESUME;
3817}
3818
199aa6d4
PX
3819static void migration_iteration_finish(MigrationState *s)
3820{
3821 /* If we enabled cpu throttling for auto-converge, turn it off. */
3822 cpu_throttle_stop();
3823
3824 qemu_mutex_lock_iothread();
3825 switch (s->state) {
3826 case MIGRATION_STATUS_COMPLETED:
3827 migration_calculate_complete(s);
3828 runstate_set(RUN_STATE_POSTMIGRATE);
3829 break;
751fe4c6 3830 case MIGRATION_STATUS_COLO:
199aa6d4
PX
3831 if (!migrate_colo_enabled()) {
3832 error_report("%s: critical error: calling COLO code without "
3833 "COLO enabled", __func__);
3834 }
3835 migrate_start_colo_process(s);
199aa6d4
PX
3836 s->vm_was_running = true;
3837 /* Fallthrough */
3838 case MIGRATION_STATUS_FAILED:
3839 case MIGRATION_STATUS_CANCELLED:
57225e5f 3840 case MIGRATION_STATUS_CANCELLING:
199aa6d4 3841 if (s->vm_was_running) {
aa505f8e
RL
3842 if (!runstate_check(RUN_STATE_SHUTDOWN)) {
3843 vm_start();
3844 }
199aa6d4
PX
3845 } else {
3846 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3847 runstate_set(RUN_STATE_POSTMIGRATE);
3848 }
3849 }
3850 break;
3851
3852 default:
3853 /* Should not reach here, but if so, forgive the VM. */
3854 error_report("%s: Unknown ending state %d", __func__, s->state);
3855 break;
3856 }
fd392cfa 3857 migrate_fd_cleanup_schedule(s);
199aa6d4
PX
3858 qemu_mutex_unlock_iothread();
3859}
3860
8518278a
AG
3861static void bg_migration_iteration_finish(MigrationState *s)
3862{
3863 qemu_mutex_lock_iothread();
3864 switch (s->state) {
3865 case MIGRATION_STATUS_COMPLETED:
3866 migration_calculate_complete(s);
3867 break;
3868
3869 case MIGRATION_STATUS_ACTIVE:
3870 case MIGRATION_STATUS_FAILED:
3871 case MIGRATION_STATUS_CANCELLED:
3872 case MIGRATION_STATUS_CANCELLING:
3873 break;
3874
3875 default:
3876 /* Should not reach here, but if so, forgive the VM. */
3877 error_report("%s: Unknown ending state %d", __func__, s->state);
3878 break;
3879 }
3880
3881 migrate_fd_cleanup_schedule(s);
3882 qemu_mutex_unlock_iothread();
3883}
3884
3885/*
3886 * Return true if continue to the next iteration directly, false
3887 * otherwise.
3888 */
3889static MigIterateState bg_migration_iteration_run(MigrationState *s)
3890{
3891 int res;
3892
3893 res = qemu_savevm_state_iterate(s->to_dst_file, false);
3894 if (res > 0) {
3895 bg_migration_completion(s);
3896 return MIG_ITERATE_BREAK;
3897 }
3898
3899 return MIG_ITERATE_RESUME;
3900}
3901
ad767bed
DDAG
3902void migration_make_urgent_request(void)
3903{
3904 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3905}
3906
3907void migration_consume_urgent_request(void)
3908{
3909 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3910}
3911
97e1e067
DDAG
3912/* Returns true if the rate limiting was broken by an urgent request */
3913bool migration_rate_limit(void)
3914{
3915 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3916 MigrationState *s = migrate_get_current();
3917
3918 bool urgent = false;
3919 migration_update_counters(s, now);
3920 if (qemu_file_rate_limit(s->to_dst_file)) {
77386127
LS
3921
3922 if (qemu_file_get_error(s->to_dst_file)) {
3923 return false;
3924 }
97e1e067
DDAG
3925 /*
3926 * Wait for a delay to do rate limiting OR
3927 * something urgent to post the semaphore.
3928 */
3929 int ms = s->iteration_start_time + BUFFER_DELAY - now;
3930 trace_migration_rate_limit_pre(ms);
3931 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3932 /*
3933 * We were woken by one or more urgent things but
3934 * the timedwait will have consumed one of them.
3935 * The service routine for the urgent wake will dec
3936 * the semaphore itself for each item it consumes,
3937 * so add this one we just eat back.
3938 */
3939 qemu_sem_post(&s->rate_limit_sem);
3940 urgent = true;
3941 }
3942 trace_migration_rate_limit_post(urgent);
3943 }
3944 return urgent;
3945}
3946
fde93d99
LV
3947/*
3948 * if failover devices are present, wait they are completely
3949 * unplugged
3950 */
3951
3952static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
3953 int new_state)
3954{
3955 if (qemu_savevm_state_guest_unplug_pending()) {
3956 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
3957
3958 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3959 qemu_savevm_state_guest_unplug_pending()) {
3960 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3961 }
944bc528
LV
3962 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3963 int timeout = 120; /* 30 seconds */
3964 /*
3965 * migration has been canceled
3966 * but as we have started an unplug we must wait the end
3967 * to be able to plug back the card
3968 */
3969 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3970 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3971 }
1b529d90
LV
3972 if (qemu_savevm_state_guest_unplug_pending() &&
3973 !qtest_enabled()) {
a51dcef0
LV
3974 warn_report("migration: partially unplugged device on "
3975 "failure");
3976 }
944bc528 3977 }
fde93d99
LV
3978
3979 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3980 } else {
3981 migrate_set_state(&s->state, old_state, new_state);
3982 }
3983}
3984
70b20477
DDAG
3985/*
3986 * Master migration thread on the source VM.
3987 * It drives the migration and pumps the data down the outgoing channel.
3988 */
5f496a1b 3989static void *migration_thread(void *opaque)
0d82d0e8 3990{
9848a404 3991 MigrationState *s = opaque;
bc72ad67 3992 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
b23c2ade 3993 MigThrError thr_error;
ad767bed 3994 bool urgent = false;
76f5933a 3995
ab28bd23
PB
3996 rcu_register_thread();
3997
892ae715 3998 object_ref(OBJECT(s));
87f3bd87 3999 update_iteration_initial_status(s);
b15df1ae 4000
89a02a9f 4001 qemu_savevm_state_header(s->to_dst_file);
1d34e4bf 4002
62a02658
PX
4003 /*
4004 * If we opened the return path, we need to make sure dst has it
4005 * opened as well.
4006 */
43044ac0 4007 if (s->rp_state.rp_thread_created) {
1d34e4bf 4008 /* Now tell the dest that it should open its end so it can reply */
89a02a9f 4009 qemu_savevm_send_open_return_path(s->to_dst_file);
1d34e4bf
DDAG
4010
4011 /* And do a ping that will make stuff easier to debug */
89a02a9f 4012 qemu_savevm_send_ping(s->to_dst_file, 1);
0425dc97 4013 }
1d34e4bf 4014
58110f0a 4015 if (migrate_postcopy()) {
1d34e4bf
DDAG
4016 /*
4017 * Tell the destination that we *might* want to do postcopy later;
4018 * if the other end can't do postcopy it should fail now, nice and
4019 * early.
4020 */
89a02a9f 4021 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1d34e4bf
DDAG
4022 }
4023
aad555c2
ZC
4024 if (migrate_colo_enabled()) {
4025 /* Notify migration destination that we enable COLO */
4026 qemu_savevm_send_colo_enable(s->to_dst_file);
4027 }
4028
9907e842 4029 qemu_savevm_state_setup(s->to_dst_file);
0d82d0e8 4030
fde93d99
LV
4031 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4032 MIGRATION_STATUS_ACTIVE);
c7e0acd5 4033
bc72ad67 4034 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
29ae8a41 4035
9ec055ae
DDAG
4036 trace_migration_thread_setup_complete();
4037
8f8d528e 4038 while (migration_is_active(s)) {
ad767bed 4039 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
2ad87305
PX
4040 MigIterateState iter_state = migration_iteration_run(s);
4041 if (iter_state == MIG_ITERATE_SKIP) {
4042 continue;
4043 } else if (iter_state == MIG_ITERATE_BREAK) {
09f6c85e 4044 break;
c369f40d
JQ
4045 }
4046 }
f4410a5d 4047
b23c2ade
PX
4048 /*
4049 * Try to detect any kind of failures, and see whether we
4050 * should stop the migration now.
4051 */
4052 thr_error = migration_detect_error(s);
4053 if (thr_error == MIG_THR_ERR_FATAL) {
4054 /* Stop migration */
fd45ee2c 4055 break;
b23c2ade
PX
4056 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
4057 /*
4058 * Just recovered from a e.g. network failure, reset all
4059 * the local variables. This is important to avoid
4060 * breaking transferred_bytes and bandwidth calculation
4061 */
87f3bd87 4062 update_iteration_initial_status(s);
fd45ee2c 4063 }
b15df1ae 4064
97e1e067 4065 urgent = migration_rate_limit();
a3fa1d78
PB
4066 }
4067
1d34e4bf 4068 trace_migration_thread_after_loop();
199aa6d4 4069 migration_iteration_finish(s);
892ae715 4070 object_unref(OBJECT(s));
ab28bd23 4071 rcu_unregister_thread();
0d82d0e8
JQ
4072 return NULL;
4073}
4074
8518278a
AG
4075static void bg_migration_vm_start_bh(void *opaque)
4076{
4077 MigrationState *s = opaque;
4078
4079 qemu_bh_delete(s->vm_start_bh);
4080 s->vm_start_bh = NULL;
4081
4082 vm_start();
4083 s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
4084}
4085
4086/**
4087 * Background snapshot thread, based on live migration code.
4088 * This is an alternative implementation of live migration mechanism
4089 * introduced specifically to support background snapshots.
4090 *
4091 * It takes advantage of userfault_fd write protection mechanism introduced
4092 * in v5.7 kernel. Compared to existing dirty page logging migration much
4093 * lesser stream traffic is produced resulting in smaller snapshot images,
4094 * simply cause of no page duplicates can get into the stream.
4095 *
4096 * Another key point is that generated vmstate stream reflects machine state
4097 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
4098 * mechanism, which effectively results in that saved snapshot is the state of VM
4099 * at the end of the process.
4100 */
4101static void *bg_migration_thread(void *opaque)
4102{
4103 MigrationState *s = opaque;
4104 int64_t setup_start;
4105 MigThrError thr_error;
4106 QEMUFile *fb;
4107 bool early_fail = true;
4108
4109 rcu_register_thread();
4110 object_ref(OBJECT(s));
4111
4112 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
4113
4114 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
4115 /*
4116 * We want to save vmstate for the moment when migration has been
4117 * initiated but also we want to save RAM content while VM is running.
4118 * The RAM content should appear first in the vmstate. So, we first
4119 * stash the non-RAM part of the vmstate to the temporary buffer,
4120 * then write RAM part of the vmstate to the migration stream
4121 * with vCPUs running and, finally, write stashed non-RAM part of
4122 * the vmstate from the buffer to the migration stream.
4123 */
ecb23efe 4124 s->bioc = qio_channel_buffer_new(512 * 1024);
8518278a 4125 qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
77ef2dc1 4126 fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
8518278a
AG
4127 object_unref(OBJECT(s->bioc));
4128
4129 update_iteration_initial_status(s);
4130
eeccb99c
AG
4131 /*
4132 * Prepare for tracking memory writes with UFFD-WP - populate
4133 * RAM pages before protecting.
4134 */
4135#ifdef __linux__
4136 ram_write_tracking_prepare();
4137#endif
4138
8518278a
AG
4139 qemu_savevm_state_header(s->to_dst_file);
4140 qemu_savevm_state_setup(s->to_dst_file);
4141
fde93d99
LV
4142 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
4143 MIGRATION_STATUS_ACTIVE);
8518278a 4144
8518278a
AG
4145 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
4146
4147 trace_migration_thread_setup_complete();
4148 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
4149
4150 qemu_mutex_lock_iothread();
4151
4152 /*
4153 * If VM is currently in suspended state, then, to make a valid runstate
4154 * transition in vm_stop_force_state() we need to wakeup it up.
4155 */
4156 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
4157 s->vm_was_running = runstate_is_running();
4158
4159 if (global_state_store()) {
4160 goto fail;
4161 }
4162 /* Forcibly stop VM before saving state of vCPUs and devices */
4163 if (vm_stop_force_state(RUN_STATE_PAUSED)) {
4164 goto fail;
4165 }
4166 /*
4167 * Put vCPUs in sync with shadow context structures, then
4168 * save their state to channel-buffer along with devices.
4169 */
4170 cpu_synchronize_all_states();
4171 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
4172 goto fail;
4173 }
ecb23efe
AG
4174 /*
4175 * Since we are going to get non-iterable state data directly
4176 * from s->bioc->data, explicit flush is needed here.
4177 */
4178 qemu_fflush(fb);
4179
8518278a
AG
4180 /* Now initialize UFFD context and start tracking RAM writes */
4181 if (ram_write_tracking_start()) {
4182 goto fail;
4183 }
4184 early_fail = false;
4185
4186 /*
4187 * Start VM from BH handler to avoid write-fault lock here.
4188 * UFFD-WP protection for the whole RAM is already enabled so
4189 * calling VM state change notifiers from vm_start() would initiate
4190 * writes to virtio VQs memory which is in write-protected region.
4191 */
4192 s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
4193 qemu_bh_schedule(s->vm_start_bh);
4194
4195 qemu_mutex_unlock_iothread();
4196
4197 while (migration_is_active(s)) {
4198 MigIterateState iter_state = bg_migration_iteration_run(s);
4199 if (iter_state == MIG_ITERATE_SKIP) {
4200 continue;
4201 } else if (iter_state == MIG_ITERATE_BREAK) {
4202 break;
4203 }
4204
4205 /*
4206 * Try to detect any kind of failures, and see whether we
4207 * should stop the migration now.
4208 */
4209 thr_error = migration_detect_error(s);
4210 if (thr_error == MIG_THR_ERR_FATAL) {
4211 /* Stop migration */
4212 break;
4213 }
4214
4215 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
4216 }
4217
4218 trace_migration_thread_after_loop();
4219
4220fail:
4221 if (early_fail) {
4222 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
4223 MIGRATION_STATUS_FAILED);
4224 qemu_mutex_unlock_iothread();
4225 }
4226
4227 bg_migration_iteration_finish(s);
4228
4229 qemu_fclose(fb);
4230 object_unref(OBJECT(s));
4231 rcu_unregister_thread();
4232
4233 return NULL;
4234}
4235
cce8040b 4236void migrate_fd_connect(MigrationState *s, Error *error_in)
0d82d0e8 4237{
00f4b572 4238 Error *local_err = NULL;
d3e35b8f
PX
4239 int64_t rate_limit;
4240 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
4241
ca7bd082
PX
4242 /*
4243 * If there's a previous error, free it and prepare for another one.
4244 * Meanwhile if migration completes successfully, there won't have an error
4245 * dumped when calling migrate_fd_cleanup().
4246 */
4247 migrate_error_free(s);
4248
2ff30257 4249 s->expected_downtime = s->parameters.downtime_limit;
9cbc3649
MAL
4250 if (resume) {
4251 assert(s->cleanup_bh);
4252 } else {
4253 assert(!s->cleanup_bh);
4254 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
4255 }
cce8040b
DDAG
4256 if (error_in) {
4257 migrate_fd_error(s, error_in);
ca30f24d
PX
4258 if (resume) {
4259 /*
4260 * Don't do cleanup for resume if channel is invalid, but only dump
4261 * the error. We wait for another channel connect from the user.
4262 * The error_report still gives HMP user a hint on what failed.
4263 * It's normally done in migrate_fd_cleanup(), but call it here
4264 * explicitly.
4265 */
4266 error_report_err(error_copy(s->error));
4267 } else {
4268 migrate_fd_cleanup(s);
4269 }
cce8040b
DDAG
4270 return;
4271 }
0d82d0e8 4272
d3e35b8f
PX
4273 if (resume) {
4274 /* This is a resumed migration */
8504ddec
PX
4275 rate_limit = s->parameters.max_postcopy_bandwidth /
4276 XFER_LIMIT_RATIO;
d3e35b8f
PX
4277 } else {
4278 /* This is a fresh new migration */
4279 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
442773ce 4280
d3e35b8f
PX
4281 /* Notify before starting migration thread */
4282 notifier_list_notify(&migration_state_notifiers, s);
4283 }
4284
4285 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
4286 qemu_file_set_blocking(s->to_dst_file, true);
9287ac27 4287
1d34e4bf 4288 /*
c788ada8
PX
4289 * Open the return path. For postcopy, it is used exclusively. For
4290 * precopy, only if user specified "return-path" capability would
4291 * QEMU uses the return path.
1d34e4bf 4292 */
c788ada8 4293 if (migrate_postcopy_ram() || migrate_use_return_path()) {
d3e35b8f 4294 if (open_return_path_on_source(s, !resume)) {
1d34e4bf 4295 error_report("Unable to open return-path for postcopy");
d3e35b8f 4296 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
1d34e4bf
DDAG
4297 migrate_fd_cleanup(s);
4298 return;
4299 }
4300 }
4301
36f62f11
PX
4302 /* This needs to be done before resuming a postcopy */
4303 if (postcopy_preempt_setup(s, &local_err)) {
4304 error_report_err(local_err);
4305 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4306 MIGRATION_STATUS_FAILED);
4307 migrate_fd_cleanup(s);
4308 return;
4309 }
4310
d3e35b8f 4311 if (resume) {
135b87b4
PX
4312 /* Wakeup the main migration thread to do the recovery */
4313 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
4314 MIGRATION_STATUS_POSTCOPY_RECOVER);
4315 qemu_sem_post(&s->postcopy_pause_sem);
d3e35b8f
PX
4316 return;
4317 }
4318
00f4b572
JQ
4319 if (multifd_save_setup(&local_err) != 0) {
4320 error_report_err(local_err);
f986c3d2
JQ
4321 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
4322 MIGRATION_STATUS_FAILED);
4323 migrate_fd_cleanup(s);
4324 return;
4325 }
8518278a
AG
4326
4327 if (migrate_background_snapshot()) {
4328 qemu_thread_create(&s->thread, "bg_snapshot",
4329 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
4330 } else {
4331 qemu_thread_create(&s->thread, "live_migration",
4332 migration_thread, s, QEMU_THREAD_JOINABLE);
4333 }
1d34e4bf 4334 s->migration_thread_running = true;
0d82d0e8 4335}
093e3c42 4336
9d18af93
PX
4337void migration_global_dump(Monitor *mon)
4338{
4339 MigrationState *ms = migrate_get_current();
4340
6f0f6428
JQ
4341 monitor_printf(mon, "globals:\n");
4342 monitor_printf(mon, "store-global-state: %s\n",
4343 ms->store_global_state ? "on" : "off");
4344 monitor_printf(mon, "only-migratable: %s\n",
811f8652 4345 only_migratable ? "on" : "off");
6f0f6428
JQ
4346 monitor_printf(mon, "send-configuration: %s\n",
4347 ms->send_configuration ? "on" : "off");
4348 monitor_printf(mon, "send-section-footer: %s\n",
4349 ms->send_section_footer ? "on" : "off");
f548222c
XG
4350 monitor_printf(mon, "decompress-error-check: %s\n",
4351 ms->decompress_error_check ? "on" : "off");
002cad6b
PX
4352 monitor_printf(mon, "clear-bitmap-shift: %u\n",
4353 ms->clear_bitmap_shift);
9d18af93
PX
4354}
4355
20814758
PX
4356#define DEFINE_PROP_MIG_CAP(name, x) \
4357 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
4358
5272298c
PX
4359static Property migration_properties[] = {
4360 DEFINE_PROP_BOOL("store-global-state", MigrationState,
4361 store_global_state, true),
71dd4c1a
PX
4362 DEFINE_PROP_BOOL("send-configuration", MigrationState,
4363 send_configuration, true),
15c38503
PX
4364 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
4365 send_section_footer, true),
f548222c
XG
4366 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
4367 decompress_error_check, true),
002cad6b
PX
4368 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
4369 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
89632faf
PX
4370
4371 /* Migration parameters */
741d4086 4372 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
89632faf
PX
4373 parameters.compress_level,
4374 DEFAULT_MIGRATE_COMPRESS_LEVEL),
741d4086 4375 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
89632faf
PX
4376 parameters.compress_threads,
4377 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
1d58872a
XG
4378 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
4379 parameters.compress_wait_thread, true),
741d4086 4380 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
89632faf
PX
4381 parameters.decompress_threads,
4382 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
dc14a470
KZ
4383 DEFINE_PROP_UINT8("x-throttle-trigger-threshold", MigrationState,
4384 parameters.throttle_trigger_threshold,
4385 DEFAULT_MIGRATE_THROTTLE_TRIGGER_THRESHOLD),
741d4086 4386 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
89632faf
PX
4387 parameters.cpu_throttle_initial,
4388 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
741d4086 4389 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
89632faf
PX
4390 parameters.cpu_throttle_increment,
4391 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
cbbf8182
KZ
4392 DEFINE_PROP_BOOL("x-cpu-throttle-tailslow", MigrationState,
4393 parameters.cpu_throttle_tailslow, false),
741d4086 4394 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
89632faf 4395 parameters.max_bandwidth, MAX_THROTTLE),
741d4086 4396 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
89632faf
PX
4397 parameters.downtime_limit,
4398 DEFAULT_MIGRATE_SET_DOWNTIME),
741d4086 4399 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
89632faf
PX
4400 parameters.x_checkpoint_delay,
4401 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
cbfd6c95
JQ
4402 DEFINE_PROP_UINT8("multifd-channels", MigrationState,
4403 parameters.multifd_channels,
4075fb1c 4404 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
96eef042
JQ
4405 DEFINE_PROP_MULTIFD_COMPRESSION("multifd-compression", MigrationState,
4406 parameters.multifd_compression,
4407 DEFAULT_MIGRATE_MULTIFD_COMPRESSION),
9004db48
JQ
4408 DEFINE_PROP_UINT8("multifd-zlib-level", MigrationState,
4409 parameters.multifd_zlib_level,
4410 DEFAULT_MIGRATE_MULTIFD_ZLIB_LEVEL),
6a9ad154
JQ
4411 DEFINE_PROP_UINT8("multifd-zstd-level", MigrationState,
4412 parameters.multifd_zstd_level,
4413 DEFAULT_MIGRATE_MULTIFD_ZSTD_LEVEL),
73af8dd8
JQ
4414 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
4415 parameters.xbzrle_cache_size,
4416 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
7e555c6c
DDAG
4417 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
4418 parameters.max_postcopy_bandwidth,
4419 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
4cbc9c7f
LQ
4420 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
4421 parameters.max_cpu_throttle,
4422 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
ee3d96ba
DDAG
4423 DEFINE_PROP_SIZE("announce-initial", MigrationState,
4424 parameters.announce_initial,
4425 DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
4426 DEFINE_PROP_SIZE("announce-max", MigrationState,
4427 parameters.announce_max,
4428 DEFAULT_MIGRATE_ANNOUNCE_MAX),
4429 DEFINE_PROP_SIZE("announce-rounds", MigrationState,
4430 parameters.announce_rounds,
4431 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
4432 DEFINE_PROP_SIZE("announce-step", MigrationState,
4433 parameters.announce_step,
4434 DEFAULT_MIGRATE_ANNOUNCE_STEP),
9a266627
PX
4435 DEFINE_PROP_STRING("tls-creds", MigrationState, parameters.tls_creds),
4436 DEFINE_PROP_STRING("tls-hostname", MigrationState, parameters.tls_hostname),
4437 DEFINE_PROP_STRING("tls-authz", MigrationState, parameters.tls_authz),
20814758
PX
4438
4439 /* Migration capabilities */
4440 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
4441 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
4442 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
4443 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
4444 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
4445 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
4446 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
ce5b0f4a
PX
4447 DEFINE_PROP_MIG_CAP("x-postcopy-preempt",
4448 MIGRATION_CAPABILITY_POSTCOPY_PREEMPT),
20814758
PX
4449 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
4450 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
4451 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
4452 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
cbfd6c95 4453 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
6e8c25b4
AG
4454 DEFINE_PROP_MIG_CAP("x-background-snapshot",
4455 MIGRATION_CAPABILITY_BACKGROUND_SNAPSHOT),
1abaec9a
LB
4456#ifdef CONFIG_LINUX
4457 DEFINE_PROP_MIG_CAP("x-zero-copy-send",
4458 MIGRATION_CAPABILITY_ZERO_COPY_SEND),
4459#endif
20814758 4460
5272298c
PX
4461 DEFINE_PROP_END_OF_LIST(),
4462};
4463
e5cb7e76
PX
4464static void migration_class_init(ObjectClass *klass, void *data)
4465{
4466 DeviceClass *dc = DEVICE_CLASS(klass);
4467
4468 dc->user_creatable = false;
4f67d30b 4469 device_class_set_props(dc, migration_properties);
e5cb7e76
PX
4470}
4471
b91bf5e4
MAL
4472static void migration_instance_finalize(Object *obj)
4473{
4474 MigrationState *ms = MIGRATION_OBJ(obj);
b91bf5e4 4475
87db1a7d 4476 qemu_mutex_destroy(&ms->error_mutex);
62df066f 4477 qemu_mutex_destroy(&ms->qemu_file_lock);
c7e0acd5 4478 qemu_sem_destroy(&ms->wait_unplug_sem);
ad767bed 4479 qemu_sem_destroy(&ms->rate_limit_sem);
e91d8951 4480 qemu_sem_destroy(&ms->pause_sem);
b23c2ade 4481 qemu_sem_destroy(&ms->postcopy_pause_sem);
14b1742e 4482 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
edd090c7 4483 qemu_sem_destroy(&ms->rp_state.rp_sem);
d0edb8a1 4484 qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
ab105cc1 4485 error_free(ms->error);
b91bf5e4
MAL
4486}
4487
e5cb7e76
PX
4488static void migration_instance_init(Object *obj)
4489{
4490 MigrationState *ms = MIGRATION_OBJ(obj);
8b0b29dc 4491 MigrationParameters *params = &ms->parameters;
e5cb7e76
PX
4492
4493 ms->state = MIGRATION_STATUS_NONE;
e5cb7e76 4494 ms->mbps = -1;
aecbfe9c 4495 ms->pages_per_second = -1;
e91d8951 4496 qemu_sem_init(&ms->pause_sem, 0);
87db1a7d 4497 qemu_mutex_init(&ms->error_mutex);
8b0b29dc
PX
4498
4499 params->tls_hostname = g_strdup("");
4500 params->tls_creds = g_strdup("");
4501
4502 /* Set has_* up only for parameter checks */
4503 params->has_compress_level = true;
4504 params->has_compress_threads = true;
df67aa3e 4505 params->has_compress_wait_thread = true;
8b0b29dc 4506 params->has_decompress_threads = true;
dc14a470 4507 params->has_throttle_trigger_threshold = true;
8b0b29dc
PX
4508 params->has_cpu_throttle_initial = true;
4509 params->has_cpu_throttle_increment = true;
cbbf8182 4510 params->has_cpu_throttle_tailslow = true;
8b0b29dc
PX
4511 params->has_max_bandwidth = true;
4512 params->has_downtime_limit = true;
4513 params->has_x_checkpoint_delay = true;
4514 params->has_block_incremental = true;
cbfd6c95 4515 params->has_multifd_channels = true;
96eef042 4516 params->has_multifd_compression = true;
9004db48 4517 params->has_multifd_zlib_level = true;
6a9ad154 4518 params->has_multifd_zstd_level = true;
73af8dd8 4519 params->has_xbzrle_cache_size = true;
7e555c6c 4520 params->has_max_postcopy_bandwidth = true;
4cbc9c7f 4521 params->has_max_cpu_throttle = true;
ee3d96ba
DDAG
4522 params->has_announce_initial = true;
4523 params->has_announce_max = true;
4524 params->has_announce_rounds = true;
4525 params->has_announce_step = true;
b23c2ade
PX
4526
4527 qemu_sem_init(&ms->postcopy_pause_sem, 0);
14b1742e 4528 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
edd090c7 4529 qemu_sem_init(&ms->rp_state.rp_sem, 0);
ad767bed 4530 qemu_sem_init(&ms->rate_limit_sem, 0);
c7e0acd5 4531 qemu_sem_init(&ms->wait_unplug_sem, 0);
d0edb8a1 4532 qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
62df066f 4533 qemu_mutex_init(&ms->qemu_file_lock);
8b0b29dc
PX
4534}
4535
4536/*
4537 * Return true if check pass, false otherwise. Error will be put
4538 * inside errp if provided.
4539 */
4540static bool migration_object_check(MigrationState *ms, Error **errp)
4541{
6b19a7d9
PX
4542 MigrationCapabilityStatusList *head = NULL;
4543 /* Assuming all off */
4544 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
4545 int i;
4546
8b0b29dc
PX
4547 if (!migrate_params_check(&ms->parameters, errp)) {
4548 return false;
4549 }
4550
6b19a7d9
PX
4551 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
4552 if (ms->enabled_capabilities[i]) {
eaedde52 4553 QAPI_LIST_PREPEND(head, migrate_cap_add(i, true));
6b19a7d9
PX
4554 }
4555 }
4556
4557 ret = migrate_caps_check(cap_list, head, errp);
4558
4559 /* It works with head == NULL */
4560 qapi_free_MigrationCapabilityStatusList(head);
4561
4562 return ret;
e5cb7e76
PX
4563}
4564
4565static const TypeInfo migration_type = {
4566 .name = TYPE_MIGRATION,
01f6e14c 4567 /*
c8d3ff38 4568 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2194abd6 4569 * not created using qdev_new(), it is not attached to the qdev
c8d3ff38
PX
4570 * device tree, and it is never realized.
4571 *
4572 * TODO: Make this TYPE_OBJECT once QOM provides something like
4573 * TYPE_DEVICE's "-global" properties.
01f6e14c 4574 */
e5cb7e76
PX
4575 .parent = TYPE_DEVICE,
4576 .class_init = migration_class_init,
4577 .class_size = sizeof(MigrationClass),
4578 .instance_size = sizeof(MigrationState),
4579 .instance_init = migration_instance_init,
b91bf5e4 4580 .instance_finalize = migration_instance_finalize,
e5cb7e76
PX
4581};
4582
4583static void register_migration_types(void)
4584{
4585 type_register_static(&migration_type);
4586}
4587
4588type_init(register_migration_types);