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