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