]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
migration: migrate 'inc' command option is deprecated.
[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"
2a9e2e59 23#include "file.h"
61e8b148 24#include "socket.h"
54d31236 25#include "sysemu/runstate.h"
46517dd4 26#include "sysemu/sysemu.h"
b0c3cf94 27#include "sysemu/cpu-throttle.h"
e1a3ecee 28#include "rdma.h"
7b1e1a22 29#include "ram.h"
c323518a 30#include "ram-compress.h"
84a899de 31#include "migration/global_state.h"
c4b63b7c 32#include "migration/misc.h"
6666c96a 33#include "migration.h"
947701cc 34#include "migration-stats.h"
20a519a0 35#include "savevm.h"
08a0aee1 36#include "qemu-file.h"
6720c2b3 37#include "channel.h"
987772d9 38#include "migration/vmstate.h"
737e150e 39#include "block/block.h"
e688df6b 40#include "qapi/error.h"
9aca82ba 41#include "qapi/clone-visitor.h"
31e4c354 42#include "qapi/qapi-visit-migration.h"
9aca82ba 43#include "qapi/qapi-visit-sockets.h"
9af23989
MA
44#include "qapi/qapi-commands-migration.h"
45#include "qapi/qapi-events-migration.h"
cc7a8ea7 46#include "qapi/qmp/qerror.h"
15280c36 47#include "qapi/qmp/qnull.h"
ab28bd23 48#include "qemu/rcu.h"
2c9e6fec 49#include "block.h"
be07b0ac 50#include "postcopy-ram.h"
766bd176 51#include "qemu/thread.h"
c09e5bb1 52#include "trace.h"
51180423 53#include "exec/target_page.h"
61b67d47 54#include "io/channel-buffer.h"
85a8578e 55#include "io/channel-tls.h"
35a6ed4f 56#include "migration/colo.h"
4ffdb337 57#include "hw/boards.h"
9d18af93 58#include "monitor/monitor.h"
50510ea2 59#include "net/announce.h"
c7e0acd5 60#include "qemu/queue.h"
d32ca5ad 61#include "multifd.h"
1b1f4ab6 62#include "threadinfo.h"
b5eea99e 63#include "qemu/yank.h"
6e8c25b4 64#include "sysemu/cpus.h"
39675fff 65#include "yank_functions.h"
1b529d90 66#include "sysemu/qtest.h"
1f0776f1 67#include "options.h"
15699cf5 68#include "sysemu/dirtylimit.h"
065e2813 69
99a0db9b
GH
70static NotifierList migration_state_notifiers =
71 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
72
da6f1790
JQ
73/* Messages sent on the return path from destination to source */
74enum mig_rp_message_type {
75 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
76 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
77 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
78
79 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
80 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
a335debb 81 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
13955b89 82 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
1b4adb10 83 MIG_RP_MSG_SWITCHOVER_ACK, /* Tell source it's OK to do switchover */
da6f1790
JQ
84
85 MIG_RP_MSG_MAX
86};
87
17549e84
JQ
88/* When we add fault tolerance, we could have several
89 migrations at once. For now we don't need to add
90 dynamic creation of migration */
91
e5cb7e76 92static MigrationState *current_migration;
e1b1b1bc 93static MigrationIncomingState *current_incoming;
e5cb7e76 94
3af8554b
DDAG
95static GSList *migration_blockers;
96
8b0b29dc 97static bool migration_object_check(MigrationState *ms, Error **errp);
0331c8ca
DDAG
98static int migration_maybe_pause(MigrationState *s,
99 int *current_active_state,
100 int new_state);
892ae715 101static void migrate_fd_cancel(MigrationState *s);
d7f5a043 102static int close_return_path_on_source(MigrationState *s);
8b0b29dc 103
d6f74fd1
PX
104static bool migration_needs_multiple_sockets(void)
105{
51b07548 106 return migrate_multifd() || migrate_postcopy_preempt();
d6f74fd1 107}
f444eeda 108
d6f74fd1 109static bool uri_supports_multi_channels(const char *uri)
f444eeda 110{
d6f74fd1
PX
111 return strstart(uri, "tcp:", NULL) || strstart(uri, "unix:", NULL) ||
112 strstart(uri, "vsock:", NULL);
f444eeda
PX
113}
114
d6f74fd1
PX
115static bool
116migration_channels_and_uri_compatible(const char *uri, Error **errp)
f444eeda 117{
d6f74fd1
PX
118 if (migration_needs_multiple_sockets() &&
119 !uri_supports_multi_channels(uri)) {
120 error_setg(errp, "Migration requires multi-channel URIs (e.g. tcp)");
121 return false;
122 }
123
124 return true;
f444eeda
PX
125}
126
8f8bfffc
PX
127static gint page_request_addr_cmp(gconstpointer ap, gconstpointer bp)
128{
129 uintptr_t a = (uintptr_t) ap, b = (uintptr_t) bp;
130
131 return (a > b) - (a < b);
132}
133
e5cb7e76
PX
134void migration_object_init(void)
135{
136 /* This can only be called once. */
137 assert(!current_migration);
138 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
4ffdb337 139
e1b1b1bc
PX
140 /*
141 * Init the migrate incoming object as well no matter whether
142 * we'll use it or not.
143 */
144 assert(!current_incoming);
145 current_incoming = g_new0(MigrationIncomingState, 1);
146 current_incoming->state = MIGRATION_STATUS_NONE;
147 current_incoming->postcopy_remote_fds =
148 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
149 qemu_mutex_init(&current_incoming->rp_mutex);
60bb3c58 150 qemu_mutex_init(&current_incoming->postcopy_prio_thread_mutex);
e1b1b1bc
PX
151 qemu_event_init(&current_incoming->main_thread_load_event, false);
152 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
153 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
60bb3c58 154 qemu_sem_init(&current_incoming->postcopy_pause_sem_fast_load, 0);
5655aab0
PX
155 qemu_sem_init(&current_incoming->postcopy_qemufile_dst_done, 0);
156
8f8bfffc 157 qemu_mutex_init(&current_incoming->page_request_mutex);
cf02f29e 158 qemu_cond_init(&current_incoming->page_request_cond);
8f8bfffc 159 current_incoming->page_requested = g_tree_new(page_request_addr_cmp);
e1b1b1bc 160
f9734d5d 161 migration_object_check(current_migration, &error_fatal);
e0d17dfd
PB
162
163 blk_mig_init();
164 ram_mig_init();
165 dirty_bitmap_mig_init();
e5cb7e76
PX
166}
167
458fecca 168void migration_cancel(const Error *error)
c7c0e724 169{
458fecca
LV
170 if (error) {
171 migrate_set_error(current_migration, error);
172 }
acac51ba
HH
173 if (migrate_dirty_limit()) {
174 qmp_cancel_vcpu_dirty_limit(false, -1, NULL);
175 }
c7c0e724
DH
176 migrate_fd_cancel(current_migration);
177}
178
892ae715 179void migration_shutdown(void)
1f895604 180{
795969ab
RL
181 /*
182 * When the QEMU main thread exit, the COLO thread
183 * may wait a semaphore. So, we should wakeup the
184 * COLO thread before migration shutdown.
185 */
186 colo_shutdown();
892ae715
DDAG
187 /*
188 * Cancel the current migration - that will (eventually)
189 * stop the migration using this structure
190 */
458fecca 191 migration_cancel(NULL);
1f895604 192 object_unref(OBJECT(current_migration));
1499ab09
VSO
193
194 /*
195 * Cancel outgoing migration of dirty bitmaps. It should
196 * at least unref used block nodes.
197 */
198 dirty_bitmap_mig_cancel_outgoing();
199
200 /*
201 * Cancel incoming migration of dirty bitmaps. Dirty bitmaps
202 * are non-critical data, and their loss never considered as
203 * something serious.
204 */
205 dirty_bitmap_mig_cancel_incoming();
1f895604
VSO
206}
207
bca7856a 208/* For outgoing */
859bc756 209MigrationState *migrate_get_current(void)
17549e84 210{
e5cb7e76
PX
211 /* This can only be called after the object created. */
212 assert(current_migration);
213 return current_migration;
17549e84
JQ
214}
215
bca7856a
DDAG
216MigrationIncomingState *migration_incoming_get_current(void)
217{
e1b1b1bc
PX
218 assert(current_incoming);
219 return current_incoming;
bca7856a
DDAG
220}
221
e031149c
PX
222void migration_incoming_transport_cleanup(MigrationIncomingState *mis)
223{
224 if (mis->socket_address_list) {
225 qapi_free_SocketAddressList(mis->socket_address_list);
226 mis->socket_address_list = NULL;
227 }
228
229 if (mis->transport_cleanup) {
230 mis->transport_cleanup(mis->transport_data);
231 mis->transport_data = mis->transport_cleanup = NULL;
232 }
233}
234
bca7856a
DDAG
235void migration_incoming_state_destroy(void)
236{
b4b076da
JQ
237 struct MigrationIncomingState *mis = migration_incoming_get_current();
238
cfc3bcf3 239 multifd_load_cleanup();
c323518a 240 compress_threads_load_cleanup();
cfc3bcf3 241
3482655b 242 if (mis->to_src_file) {
660819b1
PX
243 /* Tell source that we are done */
244 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
3482655b
PX
245 qemu_fclose(mis->to_src_file);
246 mis->to_src_file = NULL;
247 }
248
660819b1 249 if (mis->from_src_file) {
39675fff 250 migration_ioc_unregister_yank_from_file(mis->from_src_file);
660819b1
PX
251 qemu_fclose(mis->from_src_file);
252 mis->from_src_file = NULL;
253 }
00fa4fc8
DDAG
254 if (mis->postcopy_remote_fds) {
255 g_array_free(mis->postcopy_remote_fds, TRUE);
256 mis->postcopy_remote_fds = NULL;
257 }
660819b1 258
e031149c 259 migration_incoming_transport_cleanup(mis);
1783c00f
DDAG
260 qemu_event_reset(&mis->main_thread_load_event);
261
8f8bfffc
PX
262 if (mis->page_requested) {
263 g_tree_destroy(mis->page_requested);
264 mis->page_requested = NULL;
265 }
266
36f62f11
PX
267 if (mis->postcopy_qemufile_dst) {
268 migration_ioc_unregister_yank_from_file(mis->postcopy_qemufile_dst);
269 qemu_fclose(mis->postcopy_qemufile_dst);
270 mis->postcopy_qemufile_dst = NULL;
271 }
272
b5eea99e 273 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
bca7856a
DDAG
274}
275
b05dc723
JQ
276static void migrate_generate_event(int new_state)
277{
b890902c 278 if (migrate_events()) {
3ab72385 279 qapi_event_send_migration(new_state);
b05dc723
JQ
280 }
281}
282
da6f1790
JQ
283/*
284 * Send a message on the return channel back to the source
285 * of the migration.
286 */
d6208e35
PX
287static int migrate_send_rp_message(MigrationIncomingState *mis,
288 enum mig_rp_message_type message_type,
289 uint16_t len, void *data)
da6f1790 290{
d6208e35
PX
291 int ret = 0;
292
da6f1790 293 trace_migrate_send_rp_message((int)message_type, len);
37396950 294 QEMU_LOCK_GUARD(&mis->rp_mutex);
d6208e35
PX
295
296 /*
297 * It's possible that the file handle got lost due to network
298 * failures.
299 */
300 if (!mis->to_src_file) {
301 ret = -EIO;
37396950 302 return ret;
d6208e35
PX
303 }
304
da6f1790
JQ
305 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
306 qemu_put_be16(mis->to_src_file, len);
307 qemu_put_buffer(mis->to_src_file, data, len);
308 qemu_fflush(mis->to_src_file);
d6208e35
PX
309
310 /* It's possible that qemu file got error during sending */
311 ret = qemu_file_get_error(mis->to_src_file);
312
d6208e35 313 return ret;
da6f1790
JQ
314}
315
2e2bce16
PX
316/* Request one page from the source VM at the given start address.
317 * rb: the RAMBlock to request the page in
1e2d90eb
DDAG
318 * Start: Address offset within the RB
319 * Len: Length in bytes required - must be a multiple of pagesize
320 */
7a267fc4
PX
321int migrate_send_rp_message_req_pages(MigrationIncomingState *mis,
322 RAMBlock *rb, ram_addr_t start)
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 */
2e2bce16 326 size_t len = qemu_ram_pagesize(rb);
d6208e35 327 enum mig_rp_message_type msg_type;
2e2bce16
PX
328 const char *rbname;
329 int rbname_len;
1e2d90eb
DDAG
330
331 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
332 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
333
2e2bce16
PX
334 /*
335 * We maintain the last ramblock that we requested for page. Note that we
336 * don't need locking because this function will only be called within the
337 * postcopy ram fault thread.
338 */
339 if (rb != mis->last_rb) {
340 mis->last_rb = rb;
341
342 rbname = qemu_ram_get_idstr(rb);
343 rbname_len = strlen(rbname);
344
1e2d90eb
DDAG
345 assert(rbname_len < 256);
346
347 bufc[msglen++] = rbname_len;
348 memcpy(bufc + msglen, rbname, rbname_len);
349 msglen += rbname_len;
d6208e35 350 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
1e2d90eb 351 } else {
d6208e35 352 msg_type = MIG_RP_MSG_REQ_PAGES;
1e2d90eb 353 }
d6208e35
PX
354
355 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
1e2d90eb
DDAG
356}
357
7a267fc4 358int migrate_send_rp_req_pages(MigrationIncomingState *mis,
8f8bfffc 359 RAMBlock *rb, ram_addr_t start, uint64_t haddr)
7a267fc4 360{
7648297d 361 void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
a2429283 362 bool received = false;
8f8bfffc
PX
363
364 WITH_QEMU_LOCK_GUARD(&mis->page_request_mutex) {
365 received = ramblock_recv_bitmap_test_byte_offset(rb, start);
366 if (!received && !g_tree_lookup(mis->page_requested, aligned)) {
367 /*
368 * The page has not been received, and it's not yet in the page
369 * request list. Queue it. Set the value of element to 1, so that
370 * things like g_tree_lookup() will return TRUE (1) when found.
371 */
372 g_tree_insert(mis->page_requested, aligned, (gpointer)1);
cf02f29e 373 qatomic_inc(&mis->page_requested_count);
8f8bfffc
PX
374 trace_postcopy_page_req_add(aligned, mis->page_requested_count);
375 }
376 }
377
378 /*
379 * If the page is there, skip sending the message. We don't even need the
380 * lock because as long as the page arrived, it'll be there forever.
381 */
382 if (received) {
383 return 0;
384 }
385
7a267fc4
PX
386 return migrate_send_rp_message_req_pages(mis, rb, start);
387}
388
aad555c2
ZC
389static bool migration_colo_enabled;
390bool migration_incoming_colo_enabled(void)
391{
392 return migration_colo_enabled;
393}
394
395void migration_incoming_disable_colo(void)
396{
18b1d3c9 397 ram_block_discard_disable(false);
aad555c2
ZC
398 migration_colo_enabled = false;
399}
400
18b1d3c9 401int migration_incoming_enable_colo(void)
aad555c2 402{
51e47cf8
VSO
403#ifndef CONFIG_REPLICATION
404 error_report("ENABLE_COLO command come in migration stream, but COLO "
405 "module is not built in");
406 return -ENOTSUP;
407#endif
408
121ccedc
VSO
409 if (!migrate_colo()) {
410 error_report("ENABLE_COLO command come in migration stream, but c-colo "
411 "capability is not set");
412 return -EINVAL;
413 }
414
18b1d3c9
DH
415 if (ram_block_discard_disable(true)) {
416 error_report("COLO: cannot disable RAM discard");
417 return -EBUSY;
418 }
aad555c2 419 migration_colo_enabled = true;
18b1d3c9 420 return 0;
aad555c2
ZC
421}
422
9aca82ba
JQ
423void migrate_add_address(SocketAddress *address)
424{
425 MigrationIncomingState *mis = migration_incoming_get_current();
9aca82ba 426
54aa3de7
EB
427 QAPI_LIST_PREPEND(mis->socket_address_list,
428 QAPI_CLONE(SocketAddress, address));
9aca82ba
JQ
429}
430
e69d50d6 431static void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 432{
d658f65c 433 const char *p = NULL;
4111a732 434 MigrationIncomingState *mis = migration_incoming_get_current();
34c9dd8e 435
d6f74fd1
PX
436 /* URI is not suitable for migration? */
437 if (!migration_channels_and_uri_compatible(uri, errp)) {
438 return;
439 }
440
4111a732
FR
441 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
442 MIGRATION_STATUS_SETUP);
443
e69d50d6
PB
444 if (strstart(uri, "tcp:", &p) ||
445 strstart(uri, "unix:", NULL) ||
446 strstart(uri, "vsock:", NULL)) {
d658f65c 447 socket_start_incoming_migration(p ? p : uri, errp);
2da776db 448#ifdef CONFIG_RDMA
adde220a 449 } else if (strstart(uri, "rdma:", &p)) {
b88a3306
JQ
450 if (migrate_compress()) {
451 error_setg(errp, "RDMA and compression can't be used together");
452 return;
453 }
454 if (migrate_xbzrle()) {
455 error_setg(errp, "RDMA and XBZRLE can't be used together");
456 return;
457 }
458 if (migrate_multifd()) {
459 error_setg(errp, "RDMA and multifd can't be used together");
460 return;
461 }
2da776db
MH
462 rdma_start_incoming_migration(p, errp);
463#endif
adde220a 464 } else if (strstart(uri, "exec:", &p)) {
43eaae28 465 exec_start_incoming_migration(p, errp);
adde220a 466 } else if (strstart(uri, "fd:", &p)) {
43eaae28 467 fd_start_incoming_migration(p, errp);
2a9e2e59
SS
468 } else if (strstart(uri, "file:", &p)) {
469 file_start_incoming_migration(p, errp);
adde220a 470 } else {
312fd5f2 471 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 472 }
5bb7910a
AL
473}
474
0aa6aefc
DL
475static void process_incoming_migration_bh(void *opaque)
476{
477 Error *local_err = NULL;
478 MigrationIncomingState *mis = opaque;
479
0f073f44
DDAG
480 /* If capability late_block_activate is set:
481 * Only fire up the block code now if we're going to restart the
482 * VM, else 'cont' will do it.
483 * This causes file locking to happen; so we don't want it to happen
484 * unless we really are starting the VM.
485 */
486 if (!migrate_late_block_activate() ||
487 (autostart && (!global_state_received() ||
488 global_state_get_runstate() == RUN_STATE_RUNNING))) {
3b717194 489 /* Make sure all file formats throw away their mutable metadata.
0f073f44 490 * If we get an error here, just don't restart the VM yet. */
3b717194 491 bdrv_activate_all(&local_err);
0f073f44
DDAG
492 if (local_err) {
493 error_report_err(local_err);
494 local_err = NULL;
495 autostart = false;
496 }
d35ff5e6
KW
497 }
498
0aa6aefc
DL
499 /*
500 * This must happen after all error conditions are dealt with and
501 * we're sure the VM is going to be running on this host.
502 */
7659505c 503 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
0aa6aefc 504
cfc3bcf3 505 multifd_load_shutdown();
0aa6aefc 506
b35ebdf0
VSO
507 dirty_bitmap_mig_before_vm_start();
508
0aa6aefc
DL
509 if (!global_state_received() ||
510 global_state_get_runstate() == RUN_STATE_RUNNING) {
511 if (autostart) {
512 vm_start();
513 } else {
514 runstate_set(RUN_STATE_PAUSED);
515 }
db009729
ZC
516 } else if (migration_incoming_colo_enabled()) {
517 migration_incoming_disable_colo();
518 vm_start();
0aa6aefc
DL
519 } else {
520 runstate_set(global_state_get_runstate());
521 }
0aa6aefc
DL
522 /*
523 * This must happen after any state changes since as soon as an external
524 * observer sees this event they might start to prod at the VM assuming
525 * it's ready to use.
526 */
527 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
528 MIGRATION_STATUS_COMPLETED);
529 qemu_bh_delete(mis->bh);
530 migration_incoming_state_destroy();
531}
532
38e8f9af
MAL
533static void coroutine_fn
534process_incoming_migration_co(void *opaque)
511c0231 535{
b4b076da 536 MigrationIncomingState *mis = migration_incoming_get_current();
e9bef235 537 PostcopyState ps;
1c12e1f5
PB
538 int ret;
539
4f0fae7f 540 assert(mis->from_src_file);
c323518a
LS
541
542 if (compress_threads_load_setup(mis->from_src_file)) {
543 error_report("Failed to setup decompress threads");
544 goto fail;
545 }
546
67f11b5c 547 mis->largest_page_size = qemu_ram_pagesize_largest();
093e3c42 548 postcopy_state_set(POSTCOPY_INCOMING_NONE);
4111a732 549 migrate_set_state(&mis->state, MIGRATION_STATUS_SETUP,
93d7af6f 550 MIGRATION_STATUS_ACTIVE);
dd42ce24
VSO
551
552 mis->loadvm_co = qemu_coroutine_self();
4f0fae7f 553 ret = qemu_loadvm_state(mis->from_src_file);
dd42ce24 554 mis->loadvm_co = NULL;
bca7856a 555
e9bef235
DDAG
556 ps = postcopy_state_get();
557 trace_process_incoming_migration_co_end(ret, ps);
558 if (ps != POSTCOPY_INCOMING_NONE) {
559 if (ps == POSTCOPY_INCOMING_ADVISE) {
560 /*
561 * Where a migration had postcopy enabled (and thus went to advise)
562 * but managed to complete within the precopy period, we can use
563 * the normal exit.
564 */
565 postcopy_ram_incoming_cleanup(mis);
566 } else if (ret >= 0) {
567 /*
568 * Postcopy was started, cleanup should happen at the end of the
569 * postcopy thread.
570 */
571 trace_process_incoming_migration_co_postcopy_end_main();
572 return;
573 }
574 /* Else if something went wrong then just fall out of the normal exit */
575 }
576
ecbfec6d
VSO
577 if (ret < 0) {
578 error_report("load of migration failed: %s", strerror(-ret));
579 goto fail;
580 }
581
d0a14a2b
VSO
582 if (colo_incoming_co() < 0) {
583 goto fail;
25d0c16f
HZ
584 }
585
0aa6aefc
DL
586 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
587 qemu_bh_schedule(mis->bh);
6d99c2d4
FL
588 return;
589fail:
6d99c2d4
FL
590 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
591 MIGRATION_STATUS_FAILED);
592 qemu_fclose(mis->from_src_file);
e5bac1f5
LB
593
594 multifd_load_cleanup();
c323518a 595 compress_threads_load_cleanup();
e5bac1f5 596
6d99c2d4 597 exit(EXIT_FAILURE);
511c0231
JQ
598}
599
b673eab4 600/**
7d6f6933 601 * migration_incoming_setup: Setup incoming migration
b673eab4
JQ
602 * @f: file for main migration channel
603 * @errp: where to put errors
7d6f6933
MA
604 *
605 * Returns: %true on success, %false on error.
b673eab4 606 */
7d6f6933 607static bool migration_incoming_setup(QEMUFile *f, Error **errp)
82a4da79 608{
4f0fae7f 609 MigrationIncomingState *mis = migration_incoming_get_current();
82a4da79 610
4f0fae7f
JQ
611 if (!mis->from_src_file) {
612 mis->from_src_file = f;
613 }
06ad5135 614 qemu_file_set_blocking(f, false);
7d6f6933 615 return true;
e595a01a
JQ
616}
617
36c2f8be 618void migration_incoming_process(void)
e595a01a
JQ
619{
620 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
0b8b8753 621 qemu_coroutine_enter(co);
82a4da79
PB
622}
623
884835fa 624/* Returns true if recovered from a paused migration, otherwise false */
a39e9339 625static bool postcopy_try_recover(void)
e595a01a 626{
d96c9e8d
PX
627 MigrationIncomingState *mis = migration_incoming_get_current();
628
629 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
630 /* Resumed from a paused postcopy migration */
631
a39e9339
PX
632 /* This should be set already in migration_incoming_setup() */
633 assert(mis->from_src_file);
d96c9e8d 634 /* Postcopy has standalone thread to do vm load */
a39e9339 635 qemu_file_set_blocking(mis->from_src_file, true);
d96c9e8d
PX
636
637 /* Re-configure the return path */
a39e9339 638 mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);
d96c9e8d
PX
639
640 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
641 MIGRATION_STATUS_POSTCOPY_RECOVER);
642
643 /*
644 * Here, we only wake up the main loading thread (while the
60bb3c58 645 * rest threads will still be waiting), so that we can receive
d96c9e8d 646 * commands from source now, and answer it if needed. The
60bb3c58 647 * rest threads will be woken up afterwards until we are sure
d96c9e8d
PX
648 * that source is ready to reply to page requests.
649 */
650 qemu_sem_post(&mis->postcopy_pause_sem_dst);
884835fa
PX
651 return true;
652 }
653
654 return false;
655}
656
b673eab4 657void migration_fd_process_incoming(QEMUFile *f, Error **errp)
884835fa 658{
a39e9339 659 if (!migration_incoming_setup(f, errp)) {
884835fa 660 return;
d96c9e8d 661 }
a39e9339 662 if (postcopy_try_recover()) {
b673eab4
JQ
663 return;
664 }
884835fa 665 migration_incoming_process();
e595a01a
JQ
666}
667
5655aab0
PX
668/*
669 * Returns true when we want to start a new incoming migration process,
670 * false otherwise.
671 */
672static bool migration_should_start_incoming(bool main_channel)
673{
674 /* Multifd doesn't start unless all channels are established */
51b07548 675 if (migrate_multifd()) {
5655aab0
PX
676 return migration_has_all_channels();
677 }
678
679 /* Preempt channel only starts when the main channel is created */
680 if (migrate_postcopy_preempt()) {
681 return main_channel;
682 }
683
684 /*
685 * For all the rest types of migration, we should only reach here when
686 * it's the main channel that's being created, and we should always
687 * proceed with this channel.
688 */
689 assert(main_channel);
690 return true;
691}
692
49ed0d24 693void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
4f0fae7f
JQ
694{
695 MigrationIncomingState *mis = migration_incoming_get_current();
b673eab4 696 Error *local_err = NULL;
36f62f11 697 QEMUFile *f;
6720c2b3 698 bool default_channel = true;
699 uint32_t channel_magic = 0;
700 int ret = 0;
4f0fae7f 701
51b07548 702 if (migrate_multifd() && !migrate_postcopy_ram() &&
6720c2b3 703 qio_channel_has_feature(ioc, QIO_CHANNEL_FEATURE_READ_MSG_PEEK)) {
704 /*
705 * With multiple channels, it is possible that we receive channels
706 * out of order on destination side, causing incorrect mapping of
707 * source channels on destination side. Check channel MAGIC to
708 * decide type of channel. Please note this is best effort, postcopy
709 * preempt channel does not send any magic number so avoid it for
710 * postcopy live migration. Also tls live migration already does
711 * tls handshake while initializing main channel so with tls this
712 * issue is not possible.
713 */
714 ret = migration_channel_read_peek(ioc, (void *)&channel_magic,
715 sizeof(channel_magic), &local_err);
716
717 if (ret != 0) {
718 error_propagate(errp, local_err);
719 return;
720 }
721
722 default_channel = (channel_magic == cpu_to_be32(QEMU_VM_FILE_MAGIC));
723 } else {
724 default_channel = !mis->from_src_file;
725 }
726
727 if (multifd_load_setup(errp) != 0) {
728 error_setg(errp, "Failed to setup multifd channels");
729 return;
730 }
731
732 if (default_channel) {
36f62f11 733 f = qemu_file_new_input(ioc);
a429e7f4 734
7d6f6933 735 if (!migration_incoming_setup(f, errp)) {
b673eab4
JQ
736 return;
737 }
a429e7f4
PX
738 } else {
739 /* Multiple connections */
36f62f11 740 assert(migration_needs_multiple_sockets());
51b07548 741 if (migrate_multifd()) {
6720c2b3 742 multifd_recv_new_channel(ioc, &local_err);
36f62f11
PX
743 } else {
744 assert(migrate_postcopy_preempt());
745 f = qemu_file_new_input(ioc);
6720c2b3 746 postcopy_preempt_new_channel(mis, f);
36f62f11 747 }
49ed0d24
FL
748 if (local_err) {
749 error_propagate(errp, local_err);
750 return;
751 }
4f0fae7f 752 }
81e62053 753
5655aab0 754 if (migration_should_start_incoming(default_channel)) {
a39e9339
PX
755 /* If it's a recovery, we're done */
756 if (postcopy_try_recover()) {
757 return;
758 }
81e62053
PX
759 migration_incoming_process();
760 }
4f0fae7f
JQ
761}
762
428d8908
JQ
763/**
764 * @migration_has_all_channels: We have received all channels that we need
765 *
766 * Returns true when we have got connections to all the channels that
767 * we need for migration.
768 */
769bool migration_has_all_channels(void)
770{
ca273df3 771 MigrationIncomingState *mis = migration_incoming_get_current();
62c1e0ca 772
36f62f11
PX
773 if (!mis->from_src_file) {
774 return false;
775 }
62c1e0ca 776
51b07548 777 if (migrate_multifd()) {
36f62f11
PX
778 return multifd_recv_all_channels_created();
779 }
780
781 if (migrate_postcopy_preempt()) {
782 return mis->postcopy_qemufile_dst != NULL;
783 }
784
785 return true;
428d8908
JQ
786}
787
1b4adb10
AH
788int migrate_send_rp_switchover_ack(MigrationIncomingState *mis)
789{
790 return migrate_send_rp_message(mis, MIG_RP_MSG_SWITCHOVER_ACK, 0, NULL);
791}
792
6decec93
DDAG
793/*
794 * Send a 'SHUT' message on the return channel with the given value
795 * to indicate that we've finished with the RP. Non-0 value indicates
796 * error.
797 */
798void migrate_send_rp_shut(MigrationIncomingState *mis,
799 uint32_t value)
800{
801 uint32_t buf;
802
803 buf = cpu_to_be32(value);
804 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
805}
806
807/*
808 * Send a 'PONG' message on the return channel with the given value
809 * (normally in response to a 'PING')
810 */
811void migrate_send_rp_pong(MigrationIncomingState *mis,
812 uint32_t value)
813{
814 uint32_t buf;
815
816 buf = cpu_to_be32(value);
817 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
818}
819
a335debb
PX
820void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
821 char *block_name)
822{
823 char buf[512];
824 int len;
825 int64_t res;
826
827 /*
828 * First, we send the header part. It contains only the len of
829 * idstr, and the idstr itself.
830 */
831 len = strlen(block_name);
832 buf[0] = len;
833 memcpy(buf + 1, block_name, len);
834
835 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
836 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
837 __func__);
838 return;
839 }
840
841 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
842
843 /*
844 * Next, we dump the received bitmap to the stream.
845 *
846 * TODO: currently we are safe since we are the only one that is
847 * using the to_src_file handle (fault thread is still paused),
848 * and it's ok even not taking the mutex. However the best way is
849 * to take the lock before sending the message header, and release
850 * the lock after sending the bitmap.
851 */
852 qemu_mutex_lock(&mis->rp_mutex);
853 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
854 qemu_mutex_unlock(&mis->rp_mutex);
855
856 trace_migrate_send_rp_recv_bitmap(block_name, res);
857}
858
13955b89
PX
859void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
860{
861 uint32_t buf;
862
863 buf = cpu_to_be32(value);
864 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
865}
866
f6844b99
DDAG
867/*
868 * Return true if we're already in the middle of a migration
869 * (i.e. any of the active or setup states)
870 */
3d63da16 871bool migration_is_setup_or_active(int state)
f6844b99
DDAG
872{
873 switch (state) {
874 case MIGRATION_STATUS_ACTIVE:
9ec055ae 875 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
a688d2c1 876 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 877 case MIGRATION_STATUS_POSTCOPY_RECOVER:
f6844b99 878 case MIGRATION_STATUS_SETUP:
31e06077
DDAG
879 case MIGRATION_STATUS_PRE_SWITCHOVER:
880 case MIGRATION_STATUS_DEVICE:
c7e0acd5 881 case MIGRATION_STATUS_WAIT_UNPLUG:
19dd408a 882 case MIGRATION_STATUS_COLO:
f6844b99
DDAG
883 return true;
884
885 default:
886 return false;
887
888 }
889}
890
392d87e2
JQ
891bool migration_is_running(int state)
892{
893 switch (state) {
894 case MIGRATION_STATUS_ACTIVE:
895 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
896 case MIGRATION_STATUS_POSTCOPY_PAUSED:
897 case MIGRATION_STATUS_POSTCOPY_RECOVER:
898 case MIGRATION_STATUS_SETUP:
899 case MIGRATION_STATUS_PRE_SWITCHOVER:
900 case MIGRATION_STATUS_DEVICE:
901 case MIGRATION_STATUS_WAIT_UNPLUG:
902 case MIGRATION_STATUS_CANCELLING:
392d87e2
JQ
903 return true;
904
905 default:
906 return false;
907
908 }
909}
910
db18dee7
PX
911static bool migrate_show_downtime(MigrationState *s)
912{
913 return (s->state == MIGRATION_STATUS_COMPLETED) || migration_in_postcopy();
914}
915
640dfb14
WY
916static void populate_time_info(MigrationInfo *info, MigrationState *s)
917{
918 info->has_status = true;
919 info->has_setup_time = true;
920 info->setup_time = s->setup_time;
db18dee7 921
640dfb14
WY
922 if (s->state == MIGRATION_STATUS_COMPLETED) {
923 info->has_total_time = true;
924 info->total_time = s->total_time;
640dfb14
WY
925 } else {
926 info->has_total_time = true;
927 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
928 s->start_time;
db18dee7
PX
929 }
930
931 if (migrate_show_downtime(s)) {
932 info->has_downtime = true;
933 info->downtime = s->downtime;
934 } else {
640dfb14
WY
935 info->has_expected_downtime = true;
936 info->expected_downtime = s->expected_downtime;
937 }
938}
939
a22463a5
DDAG
940static void populate_ram_info(MigrationInfo *info, MigrationState *s)
941{
144fa06b
JQ
942 size_t page_size = qemu_target_page_size();
943
a22463a5 944 info->ram = g_malloc0(sizeof(*info->ram));
aff3f660 945 info->ram->transferred = stat64_get(&mig_stats.transferred);
a22463a5 946 info->ram->total = ram_bytes_total();
aff3f660 947 info->ram->duplicate = stat64_get(&mig_stats.zero_pages);
bedf53c1
JQ
948 /* legacy value. It is not used anymore */
949 info->ram->skipped = 0;
aff3f660 950 info->ram->normal = stat64_get(&mig_stats.normal_pages);
23b7576d 951 info->ram->normal_bytes = info->ram->normal * page_size;
a22463a5 952 info->ram->mbps = s->mbps;
536b5a4e 953 info->ram->dirty_sync_count =
aff3f660 954 stat64_get(&mig_stats.dirty_sync_count);
cf20c897 955 info->ram->dirty_sync_missed_zero_copy =
aff3f660 956 stat64_get(&mig_stats.dirty_sync_missed_zero_copy);
3c764f9b 957 info->ram->postcopy_requests =
aff3f660 958 stat64_get(&mig_stats.postcopy_requests);
144fa06b 959 info->ram->page_size = page_size;
aff3f660 960 info->ram->multifd_bytes = stat64_get(&mig_stats.multifd_bytes);
aecbfe9c 961 info->ram->pages_per_second = s->pages_per_second;
aff3f660
JQ
962 info->ram->precopy_bytes = stat64_get(&mig_stats.precopy_bytes);
963 info->ram->downtime_bytes = stat64_get(&mig_stats.downtime_bytes);
964 info->ram->postcopy_bytes = stat64_get(&mig_stats.postcopy_bytes);
a22463a5 965
87dca0c9 966 if (migrate_xbzrle()) {
114f5aee
JQ
967 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
968 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
9360447d
JQ
969 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
970 info->xbzrle_cache->pages = xbzrle_counters.pages;
971 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
972 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
e460a4b1 973 info->xbzrle_cache->encoding_rate = xbzrle_counters.encoding_rate;
9360447d 974 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
114f5aee
JQ
975 }
976
6f609005 977 populate_compress(info);
76e03000 978
338182c8
JQ
979 if (cpu_throttle_active()) {
980 info->has_cpu_throttle_percentage = true;
981 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
982 }
983
a22463a5
DDAG
984 if (s->state != MIGRATION_STATUS_COMPLETED) {
985 info->ram->remaining = ram_bytes_remaining();
72f8e587 986 info->ram->dirty_pages_rate =
aff3f660 987 stat64_get(&mig_stats.dirty_pages_rate);
a22463a5 988 }
15699cf5
HH
989
990 if (migrate_dirty_limit() && dirtylimit_in_service()) {
991 info->has_dirty_limit_throttle_time_per_round = true;
992 info->dirty_limit_throttle_time_per_round =
993 dirtylimit_throttle_time_per_round();
994
995 info->has_dirty_limit_ring_full_time = true;
996 info->dirty_limit_ring_full_time = dirtylimit_ring_full_time();
997 }
a22463a5
DDAG
998}
999
930ac04c
JQ
1000static void populate_disk_info(MigrationInfo *info)
1001{
1002 if (blk_mig_active()) {
930ac04c
JQ
1003 info->disk = g_malloc0(sizeof(*info->disk));
1004 info->disk->transferred = blk_mig_bytes_transferred();
1005 info->disk->remaining = blk_mig_bytes_remaining();
1006 info->disk->total = blk_mig_bytes_total();
1007 }
1008}
1009
65ace060 1010static void fill_source_migration_info(MigrationInfo *info)
5bb7910a 1011{
17549e84 1012 MigrationState *s = migrate_get_current();
552de79b 1013 int state = qatomic_read(&s->state);
372043f3 1014 GSList *cur_blocker = migration_blockers;
17549e84 1015
3af8554b 1016 info->blocked_reasons = NULL;
3af8554b 1017
372043f3
MA
1018 /*
1019 * There are two types of reasons a migration might be blocked;
1020 * a) devices marked in VMState as non-migratable, and
1021 * b) Explicit migration blockers
1022 * We need to add both of them here.
1023 */
1024 qemu_savevm_non_migratable_list(&info->blocked_reasons);
3af8554b 1025
372043f3
MA
1026 while (cur_blocker) {
1027 QAPI_LIST_PREPEND(info->blocked_reasons,
1028 g_strdup(error_get_pretty(cur_blocker->data)));
1029 cur_blocker = g_slist_next(cur_blocker);
3af8554b 1030 }
372043f3 1031 info->has_blocked_reasons = info->blocked_reasons != NULL;
3af8554b 1032
552de79b 1033 switch (state) {
31194731 1034 case MIGRATION_STATUS_NONE:
17549e84 1035 /* no migration has happened ever */
65ace060
AP
1036 /* do not overwrite destination migration status */
1037 return;
31194731 1038 case MIGRATION_STATUS_SETUP:
29ae8a41 1039 info->has_status = true;
ed4fbd10 1040 info->has_total_time = false;
29ae8a41 1041 break;
31194731
HZ
1042 case MIGRATION_STATUS_ACTIVE:
1043 case MIGRATION_STATUS_CANCELLING:
9ec055ae 1044 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
31e06077
DDAG
1045 case MIGRATION_STATUS_PRE_SWITCHOVER:
1046 case MIGRATION_STATUS_DEVICE:
a688d2c1 1047 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 1048 case MIGRATION_STATUS_POSTCOPY_RECOVER:
640dfb14
WY
1049 /* TODO add some postcopy stats */
1050 populate_time_info(info, s);
a22463a5 1051 populate_ram_info(info, s);
930ac04c 1052 populate_disk_info(info);
38c482b4 1053 migration_populate_vfio_info(info);
17549e84 1054 break;
0b827d5e
HZ
1055 case MIGRATION_STATUS_COLO:
1056 info->has_status = true;
1057 /* TODO: display COLO specific information (checkpoint info etc.) */
1058 break;
31194731 1059 case MIGRATION_STATUS_COMPLETED:
640dfb14 1060 populate_time_info(info, s);
a22463a5 1061 populate_ram_info(info, s);
38c482b4 1062 migration_populate_vfio_info(info);
17549e84 1063 break;
31194731 1064 case MIGRATION_STATUS_FAILED:
791e7c82 1065 info->has_status = true;
17549e84 1066 break;
31194731 1067 case MIGRATION_STATUS_CANCELLED:
791e7c82 1068 info->has_status = true;
17549e84 1069 break;
c7e0acd5
JF
1070 case MIGRATION_STATUS_WAIT_UNPLUG:
1071 info->has_status = true;
1072 break;
5bb7910a 1073 }
552de79b 1074 info->status = state;
c94143e5
PX
1075
1076 QEMU_LOCK_GUARD(&s->error_mutex);
1077 if (s->error) {
1078 info->error_desc = g_strdup(error_get_pretty(s->error));
1079 }
5bb7910a
AL
1080}
1081
65ace060
AP
1082static void fill_destination_migration_info(MigrationInfo *info)
1083{
1084 MigrationIncomingState *mis = migration_incoming_get_current();
1085
9aca82ba
JQ
1086 if (mis->socket_address_list) {
1087 info->has_socket_address = true;
1088 info->socket_address =
1089 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1090 }
1091
65ace060
AP
1092 switch (mis->state) {
1093 case MIGRATION_STATUS_NONE:
1094 return;
65ace060
AP
1095 case MIGRATION_STATUS_SETUP:
1096 case MIGRATION_STATUS_CANCELLING:
1097 case MIGRATION_STATUS_CANCELLED:
1098 case MIGRATION_STATUS_ACTIVE:
1099 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
3c9928d9
PX
1100 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1101 case MIGRATION_STATUS_POSTCOPY_RECOVER:
65ace060
AP
1102 case MIGRATION_STATUS_FAILED:
1103 case MIGRATION_STATUS_COLO:
1104 info->has_status = true;
1105 break;
1106 case MIGRATION_STATUS_COMPLETED:
1107 info->has_status = true;
1108 fill_destination_postcopy_migration_info(info);
1109 break;
1110 }
1111 info->status = mis->state;
1112}
1113
1114MigrationInfo *qmp_query_migrate(Error **errp)
1115{
1116 MigrationInfo *info = g_malloc0(sizeof(*info));
1117
1118 fill_destination_migration_info(info);
1119 fill_source_migration_info(info);
1120
1121 return info;
1122}
1123
4886a1bc
DDAG
1124void qmp_migrate_start_postcopy(Error **errp)
1125{
1126 MigrationState *s = migrate_get_current();
1127
16b0fd32 1128 if (!migrate_postcopy()) {
a54d340b 1129 error_setg(errp, "Enable postcopy with migrate_set_capability before"
4886a1bc
DDAG
1130 " the start of migration");
1131 return;
1132 }
1133
1134 if (s->state == MIGRATION_STATUS_NONE) {
1135 error_setg(errp, "Postcopy must be started after migration has been"
1136 " started");
1137 return;
1138 }
1139 /*
1140 * we don't error if migration has finished since that would be racy
1141 * with issuing this command.
1142 */
d73415a3 1143 qatomic_set(&s->start_postcopy, true);
4886a1bc
DDAG
1144}
1145
065e2813
AL
1146/* shared migration helpers */
1147
48781e5b 1148void migrate_set_state(int *state, int old_state, int new_state)
51cf4c1a 1149{
a31fedee 1150 assert(new_state < MIGRATION_STATUS__MAX);
d73415a3 1151 if (qatomic_cmpxchg(state, old_state, new_state) == old_state) {
a31fedee 1152 trace_migrate_set_state(MigrationStatus_str(new_state));
b05dc723 1153 migrate_generate_event(new_state);
51cf4c1a
Z
1154 }
1155}
1156
fd392cfa 1157static void migrate_fd_cleanup(MigrationState *s)
065e2813 1158{
bb1fadc4
PB
1159 qemu_bh_delete(s->cleanup_bh);
1160 s->cleanup_bh = NULL;
1161
83174765
PX
1162 g_free(s->hostname);
1163 s->hostname = NULL;
e3bf5e68
DH
1164 json_writer_free(s->vmdesc);
1165 s->vmdesc = NULL;
83174765 1166
0ceccd85
PX
1167 qemu_savevm_state_cleanup();
1168
89a02a9f 1169 if (s->to_dst_file) {
62df066f 1170 QEMUFile *tmp;
f986c3d2 1171
9013dca5 1172 trace_migrate_fd_cleanup();
404a7c05 1173 qemu_mutex_unlock_iothread();
1d34e4bf
DDAG
1174 if (s->migration_thread_running) {
1175 qemu_thread_join(&s->thread);
1176 s->migration_thread_running = false;
1177 }
404a7c05
PB
1178 qemu_mutex_lock_iothread();
1179
1398b2e3 1180 multifd_save_cleanup();
62df066f
PX
1181 qemu_mutex_lock(&s->qemu_file_lock);
1182 tmp = s->to_dst_file;
89a02a9f 1183 s->to_dst_file = NULL;
62df066f
PX
1184 qemu_mutex_unlock(&s->qemu_file_lock);
1185 /*
1186 * Close the file handle without the lock to make sure the
1187 * critical section won't block for long.
1188 */
39675fff 1189 migration_ioc_unregister_yank_from_file(tmp);
62df066f 1190 qemu_fclose(tmp);
065e2813
AL
1191 }
1192
36e9aab3
FR
1193 /*
1194 * We already cleaned up to_dst_file, so errors from the return
1195 * path might be due to that, ignore them.
1196 */
d7f5a043 1197 close_return_path_on_source(s);
36e9aab3 1198
8f8d528e 1199 assert(!migration_is_active(s));
7a2c1721 1200
94f5a437 1201 if (s->state == MIGRATION_STATUS_CANCELLING) {
48781e5b 1202 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
94f5a437 1203 MIGRATION_STATUS_CANCELLED);
7a2c1721 1204 }
a3fa1d78 1205
87db1a7d
JQ
1206 if (s->error) {
1207 /* It is used on info migrate. We can't free it */
1208 error_report_err(error_copy(s->error));
1209 }
d9cda213 1210 migration_call_notifiers(s);
b1a87956 1211 block_cleanup_parameters();
b5eea99e 1212 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
065e2813
AL
1213}
1214
fd392cfa
YK
1215static void migrate_fd_cleanup_schedule(MigrationState *s)
1216{
1217 /*
1218 * Ref the state for bh, because it may be called when
1219 * there're already no other refs
1220 */
1221 object_ref(OBJECT(s));
1222 qemu_bh_schedule(s->cleanup_bh);
1223}
1224
1225static void migrate_fd_cleanup_bh(void *opaque)
1226{
1227 MigrationState *s = opaque;
1228 migrate_fd_cleanup(s);
1229 object_unref(OBJECT(s));
1230}
1231
87db1a7d
JQ
1232void migrate_set_error(MigrationState *s, const Error *error)
1233{
6e8a355d 1234 QEMU_LOCK_GUARD(&s->error_mutex);
87db1a7d
JQ
1235 if (!s->error) {
1236 s->error = error_copy(error);
1237 }
87db1a7d
JQ
1238}
1239
2b2f6f41
PX
1240bool migrate_has_error(MigrationState *s)
1241{
1242 /* The lock is not helpful here, but still follow the rule */
1243 QEMU_LOCK_GUARD(&s->error_mutex);
1244 return qatomic_read(&s->error);
1245}
1246
ca7bd082
PX
1247static void migrate_error_free(MigrationState *s)
1248{
1249 QEMU_LOCK_GUARD(&s->error_mutex);
1250 if (s->error) {
1251 error_free(s->error);
1252 s->error = NULL;
1253 }
1254}
1255
aaf26bd3 1256static void migrate_fd_error(MigrationState *s, const Error *error)
065e2813 1257{
25174055 1258 trace_migrate_fd_error(error_get_pretty(error));
89a02a9f 1259 assert(s->to_dst_file == NULL);
48781e5b
HZ
1260 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1261 MIGRATION_STATUS_FAILED);
87db1a7d 1262 migrate_set_error(s, error);
458cf28e
JQ
1263}
1264
0edda1c4 1265static void migrate_fd_cancel(MigrationState *s)
065e2813 1266{
6f2b811a 1267 int old_state ;
7478fb0d 1268
9013dca5 1269 trace_migrate_fd_cancel();
065e2813 1270
43044ac0
PX
1271 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1272 if (s->rp_state.from_dst_file) {
1273 /* shutdown the rp socket, so causing the rp thread to shutdown */
1274 qemu_file_shutdown(s->rp_state.from_dst_file);
1275 }
70b20477
DDAG
1276 }
1277
6f2b811a
Z
1278 do {
1279 old_state = s->state;
392d87e2 1280 if (!migration_is_running(old_state)) {
6f2b811a
Z
1281 break;
1282 }
a7b36b48
DDAG
1283 /* If the migration is paused, kick it out of the pause */
1284 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1285 qemu_sem_post(&s->pause_sem);
1286 }
48781e5b 1287 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
31194731 1288 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
1289
1290 /*
1291 * If we're unlucky the migration code might be stuck somewhere in a
1292 * send/write while the network has failed and is waiting to timeout;
1293 * if we've got shutdown(2) available then we can force it to quit.
a26ba26e 1294 */
7478fb0d
FR
1295 if (s->state == MIGRATION_STATUS_CANCELLING) {
1296 WITH_QEMU_LOCK_GUARD(&s->qemu_file_lock) {
1297 if (s->to_dst_file) {
1298 qemu_file_shutdown(s->to_dst_file);
1299 }
1300 }
a26ba26e 1301 }
1d2acc31
HZ
1302 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1303 Error *local_err = NULL;
1304
3b717194 1305 bdrv_activate_all(&local_err);
1d2acc31
HZ
1306 if (local_err) {
1307 error_report_err(local_err);
1308 } else {
1309 s->block_inactive = false;
1310 }
1311 }
065e2813
AL
1312}
1313
d9cda213
SS
1314void migration_add_notifier(Notifier *notify,
1315 void (*func)(Notifier *notifier, void *data))
99a0db9b 1316{
d9cda213 1317 notify->notify = func;
99a0db9b
GH
1318 notifier_list_add(&migration_state_notifiers, notify);
1319}
1320
d9cda213
SS
1321void migration_remove_notifier(Notifier *notify)
1322{
1323 if (notify->notify) {
1324 notifier_remove(notify);
1325 notify->notify = NULL;
1326 }
1327}
1328
1329void migration_call_notifiers(MigrationState *s)
99a0db9b 1330{
d9cda213 1331 notifier_list_notify(&migration_state_notifiers, s);
99a0db9b
GH
1332}
1333
02edd2e7 1334bool migration_in_setup(MigrationState *s)
afe2df69 1335{
31194731 1336 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
1337}
1338
7073693b 1339bool migration_has_finished(MigrationState *s)
99a0db9b 1340{
31194731 1341 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 1342}
0edda1c4 1343
afe2df69
GH
1344bool migration_has_failed(MigrationState *s)
1345{
31194731
HZ
1346 return (s->state == MIGRATION_STATUS_CANCELLED ||
1347 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
1348}
1349
5727309d 1350bool migration_in_postcopy(void)
9ec055ae 1351{
5727309d
JQ
1352 MigrationState *s = migrate_get_current();
1353
3748fef9
DDAG
1354 switch (s->state) {
1355 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1356 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1357 case MIGRATION_STATUS_POSTCOPY_RECOVER:
1358 return true;
1359 default:
1360 return false;
1361 }
9ec055ae
DDAG
1362}
1363
b82fc321
DDAG
1364bool migration_in_postcopy_after_devices(MigrationState *s)
1365{
5727309d 1366 return migration_in_postcopy() && s->postcopy_after_devices;
b82fc321
DDAG
1367}
1368
06df2e69
DH
1369bool migration_in_incoming_postcopy(void)
1370{
1371 PostcopyState ps = postcopy_state_get();
1372
1373 return ps >= POSTCOPY_INCOMING_DISCARD && ps < POSTCOPY_INCOMING_END;
1374}
1375
80fe315c
DH
1376bool migration_incoming_postcopy_advised(void)
1377{
1378 PostcopyState ps = postcopy_state_get();
1379
1380 return ps >= POSTCOPY_INCOMING_ADVISE && ps < POSTCOPY_INCOMING_END;
1381}
1382
1a8e44a8
AG
1383bool migration_in_bg_snapshot(void)
1384{
1385 MigrationState *s = migrate_get_current();
1386
1387 return migrate_background_snapshot() &&
1388 migration_is_setup_or_active(s->state);
1389}
1390
fab35005 1391bool migration_is_idle(void)
fe44dc91 1392{
daff7f0b
MA
1393 MigrationState *s = current_migration;
1394
1395 if (!s) {
1396 return true;
1397 }
fe44dc91
AA
1398
1399 switch (s->state) {
1400 case MIGRATION_STATUS_NONE:
1401 case MIGRATION_STATUS_CANCELLED:
1402 case MIGRATION_STATUS_COMPLETED:
1403 case MIGRATION_STATUS_FAILED:
1404 return true;
1405 case MIGRATION_STATUS_SETUP:
1406 case MIGRATION_STATUS_CANCELLING:
1407 case MIGRATION_STATUS_ACTIVE:
1408 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1409 case MIGRATION_STATUS_COLO:
31e06077
DDAG
1410 case MIGRATION_STATUS_PRE_SWITCHOVER:
1411 case MIGRATION_STATUS_DEVICE:
c7e0acd5 1412 case MIGRATION_STATUS_WAIT_UNPLUG:
fe44dc91
AA
1413 return false;
1414 case MIGRATION_STATUS__MAX:
1415 g_assert_not_reached();
1416 }
1417
1418 return false;
1419}
1420
8f8d528e
WY
1421bool migration_is_active(MigrationState *s)
1422{
1423 return (s->state == MIGRATION_STATUS_ACTIVE ||
1424 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1425}
1426
08fc4cb5 1427int migrate_init(MigrationState *s, Error **errp)
0edda1c4 1428{
08fc4cb5
AH
1429 int ret;
1430
1431 ret = qemu_savevm_state_prepare(errp);
1432 if (ret) {
1433 return ret;
1434 }
1435
389775d1
DDAG
1436 /*
1437 * Reinitialise all migration state, except
1438 * parameters/capabilities that the user set, and
1439 * locks.
1440 */
389775d1 1441 s->cleanup_bh = 0;
8518278a 1442 s->vm_start_bh = 0;
89a02a9f 1443 s->to_dst_file = NULL;
389775d1 1444 s->state = MIGRATION_STATUS_NONE;
389775d1
DDAG
1445 s->rp_state.from_dst_file = NULL;
1446 s->rp_state.error = false;
1447 s->mbps = 0.0;
aecbfe9c 1448 s->pages_per_second = 0.0;
389775d1
DDAG
1449 s->downtime = 0;
1450 s->expected_downtime = 0;
389775d1 1451 s->setup_time = 0;
389775d1 1452 s->start_postcopy = false;
b82fc321 1453 s->postcopy_after_devices = false;
389775d1 1454 s->migration_thread_running = false;
d59ce6f3
DB
1455 error_free(s->error);
1456 s->error = NULL;
d8053e73 1457 s->hostname = NULL;
2aae1eb8 1458 s->vmdesc = NULL;
389775d1 1459
48781e5b 1460 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 1461
4af246a3
PX
1462 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1463 s->total_time = 0;
f4584076 1464 s->vm_old_state = -1;
b15df1ae
PX
1465 s->iteration_initial_bytes = 0;
1466 s->threshold_size = 0;
1b4adb10 1467 s->switchover_acked = false;
27fd25b0 1468 s->rdma_migration = false;
f543aa22 1469 /*
809f188a 1470 * set mig_stats memory to zero for a new migration
f543aa22
AH
1471 */
1472 memset(&mig_stats, 0, sizeof(mig_stats));
f543aa22 1473 migration_reset_vfio_bytes_transferred();
08fc4cb5
AH
1474
1475 return 0;
0edda1c4 1476}
cab30143 1477
c8a7fc51 1478int migrate_add_blocker_internal(Error **reasonp, Error **errp)
fa2756b7 1479{
4c170330
PX
1480 /* Snapshots are similar to migrations, so check RUN_STATE_SAVE_VM too. */
1481 if (runstate_check(RUN_STATE_SAVE_VM) || !migration_is_idle()) {
c8a7fc51 1482 error_propagate_prepend(errp, *reasonp,
4c170330
PX
1483 "disallowing migration blocker "
1484 "(migration/snapshot in progress) for: ");
c8a7fc51 1485 *reasonp = NULL;
4c170330 1486 return -EBUSY;
fe44dc91
AA
1487 }
1488
c8a7fc51 1489 migration_blockers = g_slist_prepend(migration_blockers, *reasonp);
4c170330 1490 return 0;
fa2756b7
AL
1491}
1492
c8a7fc51 1493int migrate_add_blocker(Error **reasonp, Error **errp)
60fd6801
PX
1494{
1495 if (only_migratable) {
c8a7fc51 1496 error_propagate_prepend(errp, *reasonp,
60fd6801
PX
1497 "disallowing migration blocker "
1498 "(--only-migratable) for: ");
c8a7fc51 1499 *reasonp = NULL;
60fd6801
PX
1500 return -EACCES;
1501 }
1502
c8a7fc51 1503 return migrate_add_blocker_internal(reasonp, errp);
60fd6801
PX
1504}
1505
c8a7fc51 1506void migrate_del_blocker(Error **reasonp)
fa2756b7 1507{
c8a7fc51
SS
1508 if (*reasonp) {
1509 migration_blockers = g_slist_remove(migration_blockers, *reasonp);
1510 error_free(*reasonp);
1511 *reasonp = NULL;
1512 }
fa2756b7
AL
1513}
1514
bf1ae1f4
DDAG
1515void qmp_migrate_incoming(const char *uri, Error **errp)
1516{
1517 Error *local_err = NULL;
4debb5f5 1518 static bool once = true;
bf1ae1f4 1519
4debb5f5
DDAG
1520 if (!once) {
1521 error_setg(errp, "The incoming migration has already been started");
603d5a42 1522 return;
4debb5f5 1523 }
e69d50d6
PB
1524 if (!runstate_check(RUN_STATE_INMIGRATE)) {
1525 error_setg(errp, "'-incoming' was not specified on the command line");
1526 return;
1527 }
bf1ae1f4 1528
cc48c587
PX
1529 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1530 return;
1531 }
1532
bf1ae1f4
DDAG
1533 qemu_start_incoming_migration(uri, &local_err);
1534
1535 if (local_err) {
cc48c587 1536 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
bf1ae1f4
DDAG
1537 error_propagate(errp, local_err);
1538 return;
1539 }
1540
4debb5f5 1541 once = false;
bf1ae1f4
DDAG
1542}
1543
02affd41
PX
1544void qmp_migrate_recover(const char *uri, Error **errp)
1545{
1546 MigrationIncomingState *mis = migration_incoming_get_current();
1547
b7f9afd4
PX
1548 /*
1549 * Don't even bother to use ERRP_GUARD() as it _must_ always be set by
1550 * callers (no one should ignore a recover failure); if there is, it's a
1551 * programming error.
1552 */
1553 assert(errp);
1554
02affd41
PX
1555 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1556 error_setg(errp, "Migrate recover can only be run "
1557 "when postcopy is paused.");
1558 return;
1559 }
1560
08401c04
PX
1561 /* If there's an existing transport, release it */
1562 migration_incoming_transport_cleanup(mis);
02affd41
PX
1563
1564 /*
1565 * Note that this call will never start a real migration; it will
1566 * only re-setup the migration stream and poke existing migration
1567 * to continue using that newly established channel.
1568 */
1569 qemu_start_incoming_migration(uri, errp);
1570}
1571
bfbf89c2
PX
1572void qmp_migrate_pause(Error **errp)
1573{
1574 MigrationState *ms = migrate_get_current();
1575 MigrationIncomingState *mis = migration_incoming_get_current();
7478fb0d 1576 int ret = 0;
bfbf89c2
PX
1577
1578 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1579 /* Source side, during postcopy */
1580 qemu_mutex_lock(&ms->qemu_file_lock);
7478fb0d
FR
1581 if (ms->to_dst_file) {
1582 ret = qemu_file_shutdown(ms->to_dst_file);
1583 }
bfbf89c2
PX
1584 qemu_mutex_unlock(&ms->qemu_file_lock);
1585 if (ret) {
1586 error_setg(errp, "Failed to pause source migration");
1587 }
1588 return;
1589 }
1590
1591 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1592 ret = qemu_file_shutdown(mis->from_src_file);
1593 if (ret) {
1594 error_setg(errp, "Failed to pause destination migration");
1595 }
1596 return;
1597 }
1598
1599 error_setg(errp, "migrate-pause is currently only supported "
1600 "during postcopy-active state");
1601}
1602
24f3902b
GK
1603bool migration_is_blocked(Error **errp)
1604{
1605 if (qemu_savevm_state_blocked(errp)) {
1606 return true;
1607 }
1608
1609 if (migration_blockers) {
250561e1 1610 error_propagate(errp, error_copy(migration_blockers->data));
24f3902b
GK
1611 return true;
1612 }
1613
1614 return false;
1615}
1616
d3e35b8f
PX
1617/* Returns true if continue to migrate, or false if error detected */
1618static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1619 bool resume, Error **errp)
cab30143 1620{
be7059cd 1621 Error *local_err = NULL;
d3e35b8f 1622
40101f32
JQ
1623 if (blk_inc) {
1624 warn_report("parameter 'inc' is deprecated;"
1625 " use blockdev-mirror with NBD instead");
1626 }
1627
d3e35b8f
PX
1628 if (resume) {
1629 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1630 error_setg(errp, "Cannot resume if there is no "
1631 "paused migration");
1632 return false;
1633 }
97ca211c
PX
1634
1635 /*
1636 * Postcopy recovery won't work well with release-ram
1637 * capability since release-ram will drop the page buffer as
1638 * long as the page is put into the send buffer. So if there
1639 * is a network failure happened, any page buffers that have
1640 * not yet reached the destination VM but have already been
1641 * sent from the source VM will be lost forever. Let's refuse
1642 * the client from resuming such a postcopy migration.
1643 * Luckily release-ram was designed to only be used when src
1644 * and destination VMs are on the same host, so it should be
1645 * fine.
1646 */
1647 if (migrate_release_ram()) {
1648 error_setg(errp, "Postcopy recovery cannot work "
1649 "when release-ram capability is set");
1650 return false;
1651 }
1652
d3e35b8f
PX
1653 /* This is a resume, skip init status */
1654 return true;
1655 }
cab30143 1656
392d87e2 1657 if (migration_is_running(s->state)) {
c6bd8c70 1658 error_setg(errp, QERR_MIGRATION_ACTIVE);
d3e35b8f 1659 return false;
cab30143 1660 }
d3e35b8f 1661
ca99993a
DDAG
1662 if (runstate_check(RUN_STATE_INMIGRATE)) {
1663 error_setg(errp, "Guest is waiting for an incoming migration");
d3e35b8f 1664 return false;
ca99993a
DDAG
1665 }
1666
36d0fe65
T
1667 if (runstate_check(RUN_STATE_POSTMIGRATE)) {
1668 error_setg(errp, "Can't migrate the vm that was paused due to "
1669 "previous migration");
1670 return false;
1671 }
1672
24f3902b 1673 if (migration_is_blocked(errp)) {
d3e35b8f 1674 return false;
fa2756b7
AL
1675 }
1676
d3e35b8f 1677 if (blk || blk_inc) {
5e804644 1678 if (migrate_colo()) {
3ba02445
RL
1679 error_setg(errp, "No disk migration is required in COLO mode");
1680 return false;
1681 }
6f8be708 1682 if (migrate_block() || migrate_block_incremental()) {
2833c59b
JQ
1683 error_setg(errp, "Command options are incompatible with "
1684 "current migration capabilities");
d3e35b8f 1685 return false;
2833c59b 1686 }
9eb1109c 1687 if (!migrate_cap_set(MIGRATION_CAPABILITY_BLOCK, true, &local_err)) {
2833c59b 1688 error_propagate(errp, local_err);
d3e35b8f 1689 return false;
2833c59b
JQ
1690 }
1691 s->must_remove_block_options = true;
1692 }
1693
d3e35b8f 1694 if (blk_inc) {
87c22901 1695 migrate_set_block_incremental(true);
2833c59b
JQ
1696 }
1697
08fc4cb5
AH
1698 if (migrate_init(s, errp)) {
1699 return false;
1700 }
cab30143 1701
d3e35b8f
PX
1702 return true;
1703}
1704
1705void qmp_migrate(const char *uri, bool has_blk, bool blk,
1706 bool has_inc, bool inc, bool has_detach, bool detach,
1707 bool has_resume, bool resume, Error **errp)
1708{
8c69ae9e 1709 bool resume_requested;
d3e35b8f
PX
1710 Error *local_err = NULL;
1711 MigrationState *s = migrate_get_current();
d658f65c 1712 const char *p = NULL;
d3e35b8f 1713
d6f74fd1
PX
1714 /* URI is not suitable for migration? */
1715 if (!migration_channels_and_uri_compatible(uri, errp)) {
1716 return;
1717 }
1718
8c69ae9e 1719 resume_requested = has_resume && resume;
d3e35b8f 1720 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
8c69ae9e 1721 resume_requested, errp)) {
d3e35b8f
PX
1722 /* Error detected, put into errp */
1723 return;
1724 }
1725
8c69ae9e 1726 if (!resume_requested) {
b5eea99e
LS
1727 if (!yank_register_instance(MIGRATION_YANK_INSTANCE, errp)) {
1728 return;
1729 }
1730 }
1731
d658f65c 1732 if (strstart(uri, "tcp:", &p) ||
9ba3b2ba
LM
1733 strstart(uri, "unix:", NULL) ||
1734 strstart(uri, "vsock:", NULL)) {
d658f65c 1735 socket_start_outgoing_migration(s, p ? p : uri, &local_err);
2da776db 1736#ifdef CONFIG_RDMA
41310c68 1737 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
1738 rdma_start_outgoing_migration(s, p, &local_err);
1739#endif
cab30143 1740 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 1741 exec_start_outgoing_migration(s, p, &local_err);
cab30143 1742 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 1743 fd_start_outgoing_migration(s, p, &local_err);
2a9e2e59
SS
1744 } else if (strstart(uri, "file:", &p)) {
1745 file_start_outgoing_migration(s, p, &local_err);
99a0db9b 1746 } else {
908927db 1747 error_setg(&local_err, QERR_INVALID_PARAMETER_VALUE, "uri",
c6bd8c70 1748 "a valid migration protocol");
48781e5b
HZ
1749 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1750 MIGRATION_STATUS_FAILED);
b1a87956 1751 block_cleanup_parameters();
cab30143
JQ
1752 }
1753
f37afb5a 1754 if (local_err) {
8c69ae9e 1755 if (!resume_requested) {
b5eea99e
LS
1756 yank_unregister_instance(MIGRATION_YANK_INSTANCE);
1757 }
d59ce6f3 1758 migrate_fd_error(s, local_err);
f37afb5a 1759 error_propagate(errp, local_err);
e1c37d0e 1760 return;
1299c631 1761 }
cab30143
JQ
1762}
1763
6cdedb07 1764void qmp_migrate_cancel(Error **errp)
cab30143 1765{
458fecca 1766 migration_cancel(NULL);
cab30143
JQ
1767}
1768
89cfc02c
DDAG
1769void qmp_migrate_continue(MigrationStatus state, Error **errp)
1770{
1771 MigrationState *s = migrate_get_current();
1772 if (s->state != state) {
1773 error_setg(errp, "Migration not in expected state: %s",
1774 MigrationStatus_str(s->state));
1775 return;
1776 }
1777 qemu_sem_post(&s->pause_sem);
1778}
1779
70b20477
DDAG
1780/* migration thread support */
1781/*
1782 * Something bad happened to the RP stream, mark an error
1783 * The caller shall print or trace something to indicate why
1784 */
1785static void mark_source_rp_bad(MigrationState *s)
1786{
1787 s->rp_state.error = true;
1788}
1789
5e79a4bf
PX
1790void migration_rp_wait(MigrationState *s)
1791{
1792 qemu_sem_wait(&s->rp_state.rp_sem);
1793}
1794
1795void migration_rp_kick(MigrationState *s)
1796{
1797 qemu_sem_post(&s->rp_state.rp_sem);
1798}
1799
70b20477
DDAG
1800static struct rp_cmd_args {
1801 ssize_t len; /* -1 = variable */
1802 const char *name;
1803} rp_cmd_args[] = {
1804 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1805 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1806 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1e2d90eb
DDAG
1807 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1808 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
a335debb 1809 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
13955b89 1810 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
1b4adb10 1811 [MIG_RP_MSG_SWITCHOVER_ACK] = { .len = 0, .name = "SWITCHOVER_ACK" },
70b20477
DDAG
1812 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1813};
1814
1e2d90eb
DDAG
1815/*
1816 * Process a request for pages received on the return path,
1817 * We're allowed to send more than requested (e.g. to round to our page size)
1818 * and we don't need to send pages that have already been sent.
1819 */
1820static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1821 ram_addr_t start, size_t len)
1822{
8e3b0cbb 1823 long our_host_ps = qemu_real_host_page_size();
6c595cde 1824
1e2d90eb 1825 trace_migrate_handle_rp_req_pages(rbname, start, len);
6c595cde
DDAG
1826
1827 /*
1828 * Since we currently insist on matching page sizes, just sanity check
1829 * we're being asked for whole host pages.
1830 */
7648297d
DH
1831 if (!QEMU_IS_ALIGNED(start, our_host_ps) ||
1832 !QEMU_IS_ALIGNED(len, our_host_ps)) {
6c595cde
DDAG
1833 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1834 " len: %zd", __func__, start, len);
1835 mark_source_rp_bad(ms);
1836 return;
1837 }
1838
96506894 1839 if (ram_save_queue_pages(rbname, start, len)) {
6c595cde
DDAG
1840 mark_source_rp_bad(ms);
1841 }
1e2d90eb
DDAG
1842}
1843
a335debb
PX
1844static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
1845{
1846 RAMBlock *block = qemu_ram_block_by_name(block_name);
1847
1848 if (!block) {
1849 error_report("%s: invalid block name '%s'", __func__, block_name);
1850 return -EINVAL;
1851 }
1852
1853 /* Fetch the received bitmap and refresh the dirty bitmap */
1854 return ram_dirty_bitmap_reload(s, block);
1855}
1856
13955b89
PX
1857static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
1858{
1859 trace_source_return_path_thread_resume_ack(value);
1860
1861 if (value != MIGRATION_RESUME_ACK_VALUE) {
1862 error_report("%s: illegal resume_ack value %"PRIu32,
1863 __func__, value);
1864 return -1;
1865 }
1866
1867 /* Now both sides are active. */
1868 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1869 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1870
94190696 1871 /* Notify send thread that time to continue send pages */
5e79a4bf 1872 migration_rp_kick(s);
13955b89
PX
1873
1874 return 0;
1875}
1876
93589827
PX
1877/*
1878 * Release ms->rp_state.from_dst_file (and postcopy_qemufile_src if
1879 * existed) in a safe way.
1880 */
1881static void migration_release_dst_files(MigrationState *ms)
43044ac0
PX
1882{
1883 QEMUFile *file;
1884
1885 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
1886 /*
1887 * Reset the from_dst_file pointer first before releasing it, as we
1888 * can't block within lock section
1889 */
1890 file = ms->rp_state.from_dst_file;
1891 ms->rp_state.from_dst_file = NULL;
1892 }
1893
93589827
PX
1894 /*
1895 * Do the same to postcopy fast path socket too if there is. No
1896 * locking needed because this qemufile should only be managed by
1897 * return path thread.
1898 */
1899 if (ms->postcopy_qemufile_src) {
1900 migration_ioc_unregister_yank_from_file(ms->postcopy_qemufile_src);
1901 qemu_file_shutdown(ms->postcopy_qemufile_src);
1902 qemu_fclose(ms->postcopy_qemufile_src);
1903 ms->postcopy_qemufile_src = NULL;
1904 }
1905
43044ac0
PX
1906 qemu_fclose(file);
1907}
1908
70b20477
DDAG
1909/*
1910 * Handles messages sent on the return path towards the source VM
1911 *
1912 */
1913static void *source_return_path_thread(void *opaque)
1914{
1915 MigrationState *ms = opaque;
1916 QEMUFile *rp = ms->rp_state.from_dst_file;
1917 uint16_t header_len, header_type;
568b01ca 1918 uint8_t buf[512];
70b20477 1919 uint32_t tmp32, sibling_error;
1e2d90eb
DDAG
1920 ram_addr_t start = 0; /* =0 to silence warning */
1921 size_t len = 0, expected_len;
70b20477
DDAG
1922 int res;
1923
1924 trace_source_return_path_thread_entry();
74637e6f 1925 rcu_register_thread();
14b1742e 1926
70b20477
DDAG
1927 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1928 migration_is_setup_or_active(ms->state)) {
1929 trace_source_return_path_thread_loop_top();
1930 header_type = qemu_get_be16(rp);
1931 header_len = qemu_get_be16(rp);
1932
7a9ddfbf
PX
1933 if (qemu_file_get_error(rp)) {
1934 mark_source_rp_bad(ms);
1935 goto out;
1936 }
1937
70b20477
DDAG
1938 if (header_type >= MIG_RP_MSG_MAX ||
1939 header_type == MIG_RP_MSG_INVALID) {
1940 error_report("RP: Received invalid message 0x%04x length 0x%04x",
ed8b2828 1941 header_type, header_len);
70b20477
DDAG
1942 mark_source_rp_bad(ms);
1943 goto out;
1944 }
1945
1946 if ((rp_cmd_args[header_type].len != -1 &&
1947 header_len != rp_cmd_args[header_type].len) ||
568b01ca 1948 header_len > sizeof(buf)) {
70b20477 1949 error_report("RP: Received '%s' message (0x%04x) with"
ed8b2828
MZ
1950 "incorrect length %d expecting %zu",
1951 rp_cmd_args[header_type].name, header_type, header_len,
1952 (size_t)rp_cmd_args[header_type].len);
70b20477
DDAG
1953 mark_source_rp_bad(ms);
1954 goto out;
1955 }
1956
1957 /* We know we've got a valid header by this point */
1958 res = qemu_get_buffer(rp, buf, header_len);
1959 if (res != header_len) {
1960 error_report("RP: Failed reading data for message 0x%04x"
1961 " read %d expected %d",
1962 header_type, res, header_len);
1963 mark_source_rp_bad(ms);
1964 goto out;
1965 }
1966
1967 /* OK, we have the message and the data */
1968 switch (header_type) {
1969 case MIG_RP_MSG_SHUT:
4d885131 1970 sibling_error = ldl_be_p(buf);
70b20477
DDAG
1971 trace_source_return_path_thread_shut(sibling_error);
1972 if (sibling_error) {
1973 error_report("RP: Sibling indicated error %d", sibling_error);
1974 mark_source_rp_bad(ms);
1975 }
1976 /*
1977 * We'll let the main thread deal with closing the RP
1978 * we could do a shutdown(2) on it, but we're the only user
1979 * anyway, so there's nothing gained.
1980 */
1981 goto out;
1982
1983 case MIG_RP_MSG_PONG:
4d885131 1984 tmp32 = ldl_be_p(buf);
70b20477 1985 trace_source_return_path_thread_pong(tmp32);
b28fb582 1986 qemu_sem_post(&ms->rp_state.rp_pong_acks);
70b20477
DDAG
1987 break;
1988
1e2d90eb 1989 case MIG_RP_MSG_REQ_PAGES:
4d885131
PM
1990 start = ldq_be_p(buf);
1991 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
1992 migrate_handle_rp_req_pages(ms, NULL, start, len);
1993 break;
1994
1995 case MIG_RP_MSG_REQ_PAGES_ID:
1996 expected_len = 12 + 1; /* header + termination */
1997
1998 if (header_len >= expected_len) {
4d885131
PM
1999 start = ldq_be_p(buf);
2000 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2001 /* Now we expect an idstr */
2002 tmp32 = buf[12]; /* Length of the following idstr */
2003 buf[13 + tmp32] = '\0';
2004 expected_len += tmp32;
2005 }
2006 if (header_len != expected_len) {
2007 error_report("RP: Req_Page_id with length %d expecting %zd",
ed8b2828 2008 header_len, expected_len);
1e2d90eb
DDAG
2009 mark_source_rp_bad(ms);
2010 goto out;
2011 }
2012 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2013 break;
2014
a335debb
PX
2015 case MIG_RP_MSG_RECV_BITMAP:
2016 if (header_len < 1) {
2017 error_report("%s: missing block name", __func__);
2018 mark_source_rp_bad(ms);
2019 goto out;
2020 }
2021 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2022 buf[buf[0] + 1] = '\0';
2023 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2024 mark_source_rp_bad(ms);
2025 goto out;
2026 }
2027 break;
2028
13955b89
PX
2029 case MIG_RP_MSG_RESUME_ACK:
2030 tmp32 = ldl_be_p(buf);
2031 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2032 mark_source_rp_bad(ms);
2033 goto out;
2034 }
2035 break;
2036
1b4adb10
AH
2037 case MIG_RP_MSG_SWITCHOVER_ACK:
2038 ms->switchover_acked = true;
2039 trace_source_return_path_thread_switchover_acked();
2040 break;
2041
70b20477
DDAG
2042 default:
2043 break;
2044 }
2045 }
14b1742e
PX
2046
2047out:
ef796ee9 2048 if (qemu_file_get_error(rp)) {
70b20477
DDAG
2049 trace_source_return_path_thread_bad_end();
2050 mark_source_rp_bad(ms);
2051 }
2052
2053 trace_source_return_path_thread_end();
74637e6f 2054 rcu_unregister_thread();
70b20477
DDAG
2055 return NULL;
2056}
2057
ef796ee9 2058static int open_return_path_on_source(MigrationState *ms)
70b20477 2059{
89a02a9f 2060 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
70b20477
DDAG
2061 if (!ms->rp_state.from_dst_file) {
2062 return -1;
2063 }
2064
2065 trace_open_return_path_on_source();
d3e35b8f 2066
70b20477
DDAG
2067 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2068 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
53021ea1 2069 ms->rp_state.rp_thread_created = true;
70b20477
DDAG
2070
2071 trace_open_return_path_on_source_continue();
2072
2073 return 0;
2074}
2075
d7f5a043 2076static int close_return_path_on_source(MigrationState *ms)
70b20477 2077{
d50f5dc0
FR
2078 int ret;
2079
2080 if (!ms->rp_state.rp_thread_created) {
2081 return 0;
2082 }
2083
2084 trace_migration_return_path_end_before();
2085
70b20477 2086 /*
639decf5
FR
2087 * If this is a normal exit then the destination will send a SHUT
2088 * and the rp_thread will exit, however if there's an error we
2089 * need to cause it to exit. shutdown(2), if we have it, will
2090 * cause it to unblock if it's stuck waiting for the destination.
70b20477 2091 */
639decf5
FR
2092 WITH_QEMU_LOCK_GUARD(&ms->qemu_file_lock) {
2093 if (ms->to_dst_file && ms->rp_state.from_dst_file &&
2094 qemu_file_get_error(ms->to_dst_file)) {
2095 qemu_file_shutdown(ms->rp_state.from_dst_file);
2096 }
70b20477 2097 }
639decf5 2098
70b20477
DDAG
2099 trace_await_return_path_close_on_source_joining();
2100 qemu_thread_join(&ms->rp_state.rp_thread);
53021ea1 2101 ms->rp_state.rp_thread_created = false;
70b20477 2102 trace_await_return_path_close_on_source_close();
d50f5dc0
FR
2103
2104 ret = ms->rp_state.error;
ef796ee9 2105 ms->rp_state.error = false;
36e9aab3
FR
2106
2107 migration_release_dst_files(ms);
2108
d50f5dc0
FR
2109 trace_migration_return_path_end_after(ret);
2110 return ret;
70b20477
DDAG
2111}
2112
5655aab0
PX
2113static inline void
2114migration_wait_main_channel(MigrationState *ms)
2115{
2116 /* Wait until one PONG message received */
2117 qemu_sem_wait(&ms->rp_state.rp_pong_acks);
2118}
2119
1d34e4bf
DDAG
2120/*
2121 * Switch from normal iteration to postcopy
2122 * Returns non-0 on error
2123 */
908927db 2124static int postcopy_start(MigrationState *ms, Error **errp)
1d34e4bf
DDAG
2125{
2126 int ret;
61b67d47
DB
2127 QIOChannelBuffer *bioc;
2128 QEMUFile *fb;
1d34e4bf 2129 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
52033349 2130 uint64_t bandwidth = migrate_max_postcopy_bandwidth();
ef8d6488 2131 bool restart_block = false;
0331c8ca 2132 int cur_state = MIGRATION_STATUS_ACTIVE;
d0edb8a1 2133
5655aab0
PX
2134 if (migrate_postcopy_preempt()) {
2135 migration_wait_main_channel(ms);
2136 if (postcopy_preempt_establish_channel(ms)) {
2137 migrate_set_state(&ms->state, ms->state, MIGRATION_STATUS_FAILED);
2138 return -1;
2139 }
d0edb8a1
PX
2140 }
2141
0331c8ca
DDAG
2142 if (!migrate_pause_before_switchover()) {
2143 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2144 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2145 }
1d34e4bf
DDAG
2146
2147 trace_postcopy_start();
2148 qemu_mutex_lock_iothread();
2149 trace_postcopy_start_set_run();
2150
fb064112 2151 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
1d34e4bf
DDAG
2152 global_state_store();
2153 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
76b1c7fe
KW
2154 if (ret < 0) {
2155 goto fail;
2156 }
1d34e4bf 2157
0331c8ca
DDAG
2158 ret = migration_maybe_pause(ms, &cur_state,
2159 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2160 if (ret < 0) {
2161 goto fail;
2162 }
2163
76b1c7fe 2164 ret = bdrv_inactivate_all();
1d34e4bf
DDAG
2165 if (ret < 0) {
2166 goto fail;
2167 }
ef8d6488 2168 restart_block = true;
1d34e4bf 2169
1c0d249d
DDAG
2170 /*
2171 * Cause any non-postcopiable, but iterative devices to
2172 * send out their final data.
2173 */
a1fbe750 2174 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1c0d249d 2175
1d34e4bf
DDAG
2176 /*
2177 * in Finish migrate and with the io-lock held everything should
2178 * be quiet, but we've potentially still got dirty pages and we
2179 * need to tell the destination to throw any pages it's already received
2180 * that are dirty
2181 */
58110f0a 2182 if (migrate_postcopy_ram()) {
739fcc1b 2183 ram_postcopy_send_discard_bitmap(ms);
1d34e4bf
DDAG
2184 }
2185
2186 /*
2187 * send rest of state - note things that are doing postcopy
2188 * will notice we're in POSTCOPY_ACTIVE and not actually
2189 * wrap their state up here
2190 */
e1fde0e0 2191 migration_rate_set(bandwidth);
58110f0a
VSO
2192 if (migrate_postcopy_ram()) {
2193 /* Ping just for debugging, helps line traces up */
2194 qemu_savevm_send_ping(ms->to_dst_file, 2);
2195 }
1d34e4bf
DDAG
2196
2197 /*
2198 * While loading the device state we may trigger page transfer
2199 * requests and the fd must be free to process those, and thus
2200 * the destination must read the whole device state off the fd before
2201 * it starts processing it. Unfortunately the ad-hoc migration format
2202 * doesn't allow the destination to know the size to read without fully
2203 * parsing it through each devices load-state code (especially the open
2204 * coded devices that use get/put).
2205 * So we wrap the device state up in a package with a length at the start;
2206 * to do this we use a qemu_buf to hold the whole of the device state.
2207 */
61b67d47 2208 bioc = qio_channel_buffer_new(4096);
6f01f136 2209 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
77ef2dc1 2210 fb = qemu_file_new_output(QIO_CHANNEL(bioc));
61b67d47 2211 object_unref(OBJECT(bioc));
1d34e4bf 2212
c76201ab
DDAG
2213 /*
2214 * Make sure the receiver can get incoming pages before we send the rest
2215 * of the state
2216 */
2217 qemu_savevm_send_postcopy_listen(fb);
2218
a1fbe750 2219 qemu_savevm_state_complete_precopy(fb, false, false);
58110f0a
VSO
2220 if (migrate_postcopy_ram()) {
2221 qemu_savevm_send_ping(fb, 3);
2222 }
1d34e4bf
DDAG
2223
2224 qemu_savevm_send_postcopy_run(fb);
2225
2226 /* <><> end of stuff going into the package */
1d34e4bf 2227
ef8d6488
DDAG
2228 /* Last point of recovery; as soon as we send the package the destination
2229 * can open devices and potentially start running.
2230 * Lets just check again we've not got any errors.
2231 */
2232 ret = qemu_file_get_error(ms->to_dst_file);
2233 if (ret) {
908927db 2234 error_setg(errp, "postcopy_start: Migration stream errored (pre package)");
ef8d6488
DDAG
2235 goto fail_closefb;
2236 }
2237
2238 restart_block = false;
2239
1d34e4bf 2240 /* Now send that blob */
61b67d47 2241 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1d34e4bf
DDAG
2242 goto fail_closefb;
2243 }
2244 qemu_fclose(fb);
b82fc321
DDAG
2245
2246 /* Send a notify to give a chance for anything that needs to happen
2247 * at the transition to postcopy and after the device state; in particular
2248 * spice needs to trigger a transition now
2249 */
2250 ms->postcopy_after_devices = true;
d9cda213 2251 migration_call_notifiers(ms);
b82fc321 2252
1d34e4bf
DDAG
2253 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2254
2255 qemu_mutex_unlock_iothread();
2256
58110f0a
VSO
2257 if (migrate_postcopy_ram()) {
2258 /*
2259 * Although this ping is just for debug, it could potentially be
2260 * used for getting a better measurement of downtime at the source.
2261 */
2262 qemu_savevm_send_ping(ms->to_dst_file, 4);
2263 }
1d34e4bf 2264
ced1c616
PB
2265 if (migrate_release_ram()) {
2266 ram_postcopy_migrated_memory_release(ms);
2267 }
2268
89a02a9f 2269 ret = qemu_file_get_error(ms->to_dst_file);
1d34e4bf 2270 if (ret) {
908927db 2271 error_setg(errp, "postcopy_start: Migration stream errored");
48781e5b 2272 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf
DDAG
2273 MIGRATION_STATUS_FAILED);
2274 }
2275
c01b16ed
PX
2276 trace_postcopy_preempt_enabled(migrate_postcopy_preempt());
2277
1d34e4bf
DDAG
2278 return ret;
2279
2280fail_closefb:
2281 qemu_fclose(fb);
2282fail:
48781e5b 2283 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf 2284 MIGRATION_STATUS_FAILED);
ef8d6488
DDAG
2285 if (restart_block) {
2286 /* A failure happened early enough that we know the destination hasn't
2287 * accessed block devices, so we're safe to recover.
2288 */
2289 Error *local_err = NULL;
2290
3b717194 2291 bdrv_activate_all(&local_err);
ef8d6488
DDAG
2292 if (local_err) {
2293 error_report_err(local_err);
2294 }
2295 }
1d34e4bf
DDAG
2296 qemu_mutex_unlock_iothread();
2297 return -1;
2298}
2299
e91d8951
DDAG
2300/**
2301 * migration_maybe_pause: Pause if required to by
2302 * migrate_pause_before_switchover called with the iothread locked
2303 * Returns: 0 on success
2304 */
0331c8ca
DDAG
2305static int migration_maybe_pause(MigrationState *s,
2306 int *current_active_state,
2307 int new_state)
e91d8951
DDAG
2308{
2309 if (!migrate_pause_before_switchover()) {
2310 return 0;
2311 }
2312
2313 /* Since leaving this state is not atomic with posting the semaphore
2314 * it's possible that someone could have issued multiple migrate_continue
2315 * and the semaphore is incorrectly positive at this point;
2316 * the docs say it's undefined to reinit a semaphore that's already
2317 * init'd, so use timedwait to eat up any existing posts.
2318 */
2319 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2320 /* This block intentionally left blank */
2321 }
2322
8958338b
ZF
2323 /*
2324 * If the migration is cancelled when it is in the completion phase,
2325 * the migration state is set to MIGRATION_STATUS_CANCELLING.
2326 * So we don't need to wait a semaphore, otherwise we would always
2327 * wait for the 'pause_sem' semaphore.
2328 */
2329 if (s->state != MIGRATION_STATUS_CANCELLING) {
2330 qemu_mutex_unlock_iothread();
2331 migrate_set_state(&s->state, *current_active_state,
2332 MIGRATION_STATUS_PRE_SWITCHOVER);
2333 qemu_sem_wait(&s->pause_sem);
2334 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2335 new_state);
2336 *current_active_state = new_state;
2337 qemu_mutex_lock_iothread();
2338 }
e91d8951 2339
0331c8ca 2340 return s->state == new_state ? 0 : -EINVAL;
e91d8951
DDAG
2341}
2342
d7f5a043
WW
2343static int migration_completion_precopy(MigrationState *s,
2344 int *current_active_state)
09f6c85e
DDAG
2345{
2346 int ret;
2347
d7f5a043
WW
2348 qemu_mutex_lock_iothread();
2349 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2350 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
f4584076 2351
d7f5a043
WW
2352 s->vm_old_state = runstate_get();
2353 global_state_store();
c33f1829 2354
d7f5a043
WW
2355 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2356 trace_migration_completion_vm_stop(ret);
2357 if (ret < 0) {
2358 goto out_unlock;
2359 }
c33f1829 2360
d7f5a043
WW
2361 ret = migration_maybe_pause(s, current_active_state,
2362 MIGRATION_STATUS_DEVICE);
2363 if (ret < 0) {
2364 goto out_unlock;
2365 }
09f6c85e 2366
d7f5a043
WW
2367 /*
2368 * Inactivate disks except in COLO, and track that we have done so in order
2369 * to remember to reactivate them if migration fails or is cancelled.
2370 */
2371 s->block_inactive = !migrate_colo();
2372 migration_rate_set(RATE_LIMIT_DISABLED);
2373 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2374 s->block_inactive);
2375out_unlock:
2376 qemu_mutex_unlock_iothread();
2377 return ret;
2378}
b10ac0c4 2379
d7f5a043
WW
2380static void migration_completion_postcopy(MigrationState *s)
2381{
2382 trace_migration_completion_postcopy_end();
2383
2384 qemu_mutex_lock_iothread();
2385 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2386 qemu_mutex_unlock_iothread();
2387
2388 /*
2389 * Shutdown the postcopy fast path thread. This is only needed when dest
2390 * QEMU binary is old (7.1/7.2). QEMU 8.0+ doesn't need this.
2391 */
2392 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
2393 postcopy_preempt_shutdown_file(s);
2394 }
68b88468 2395
d7f5a043
WW
2396 trace_migration_completion_postcopy_end_after_complete();
2397}
2398
2399static void migration_completion_failed(MigrationState *s,
2400 int current_active_state)
2401{
2402 if (s->block_inactive && (s->state == MIGRATION_STATUS_ACTIVE ||
2403 s->state == MIGRATION_STATUS_DEVICE)) {
6621883f 2404 /*
d7f5a043
WW
2405 * If not doing postcopy, vm_start() will be called: let's
2406 * regain control on images.
6621883f 2407 */
d7f5a043
WW
2408 Error *local_err = NULL;
2409
2410 qemu_mutex_lock_iothread();
2411 bdrv_activate_all(&local_err);
2412 if (local_err) {
2413 error_report_err(local_err);
2414 } else {
2415 s->block_inactive = false;
36f62f11 2416 }
d7f5a043
WW
2417 qemu_mutex_unlock_iothread();
2418 }
2419
2420 migrate_set_state(&s->state, current_active_state,
2421 MIGRATION_STATUS_FAILED);
2422}
36f62f11 2423
d7f5a043
WW
2424/**
2425 * migration_completion: Used by migration_thread when there's not much left.
2426 * The caller 'breaks' the loop when this returns.
2427 *
2428 * @s: Current migration state
2429 */
2430static void migration_completion(MigrationState *s)
2431{
2432 int ret = 0;
2433 int current_active_state = s->state;
2434
2435 if (s->state == MIGRATION_STATUS_ACTIVE) {
2436 ret = migration_completion_precopy(s, &current_active_state);
2437 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2438 migration_completion_postcopy(s);
444252b9 2439 } else {
d7f5a043
WW
2440 ret = -1;
2441 }
2442
2443 if (ret < 0) {
6ba11211 2444 goto fail;
09f6c85e 2445 }
09f6c85e 2446
d7f5a043 2447 if (close_return_path_on_source(s)) {
d50f5dc0 2448 goto fail;
09f6c85e
DDAG
2449 }
2450
89a02a9f 2451 if (qemu_file_get_error(s->to_dst_file)) {
09f6c85e 2452 trace_migration_completion_file_err();
6dab4c93 2453 goto fail;
09f6c85e
DDAG
2454 }
2455
5e804644 2456 if (migrate_colo() && s->state == MIGRATION_STATUS_ACTIVE) {
eeeb48ee
ZC
2457 /* COLO does not support postcopy */
2458 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
2459 MIGRATION_STATUS_COLO);
2460 } else {
0b827d5e
HZ
2461 migrate_set_state(&s->state, current_active_state,
2462 MIGRATION_STATUS_COMPLETED);
2463 }
2464
09f6c85e
DDAG
2465 return;
2466
6dab4c93 2467fail:
d7f5a043 2468 migration_completion_failed(s, current_active_state);
09f6c85e
DDAG
2469}
2470
8518278a
AG
2471/**
2472 * bg_migration_completion: Used by bg_migration_thread when after all the
2473 * RAM has been saved. The caller 'breaks' the loop when this returns.
2474 *
2475 * @s: Current migration state
2476 */
2477static void bg_migration_completion(MigrationState *s)
2478{
2479 int current_active_state = s->state;
2480
8518278a
AG
2481 if (s->state == MIGRATION_STATUS_ACTIVE) {
2482 /*
2483 * By this moment we have RAM content saved into the migration stream.
2484 * The next step is to flush the non-RAM content (device state)
2485 * right after the ram content. The device state has been stored into
2486 * the temporary buffer before RAM saving started.
2487 */
2488 qemu_put_buffer(s->to_dst_file, s->bioc->data, s->bioc->usage);
2489 qemu_fflush(s->to_dst_file);
2490 } else if (s->state == MIGRATION_STATUS_CANCELLING) {
2491 goto fail;
2492 }
2493
2494 if (qemu_file_get_error(s->to_dst_file)) {
2495 trace_migration_completion_file_err();
2496 goto fail;
2497 }
2498
2499 migrate_set_state(&s->state, current_active_state,
2500 MIGRATION_STATUS_COMPLETED);
2501 return;
2502
2503fail:
2504 migrate_set_state(&s->state, current_active_state,
2505 MIGRATION_STATUS_FAILED);
2506}
2507
b23c2ade
PX
2508typedef enum MigThrError {
2509 /* No error detected */
2510 MIG_THR_ERR_NONE = 0,
2511 /* Detected error, but resumed successfully */
2512 MIG_THR_ERR_RECOVERED = 1,
2513 /* Detected fatal error, need to exit */
2514 MIG_THR_ERR_FATAL = 2,
2515} MigThrError;
2516
94190696
PX
2517static int postcopy_resume_handshake(MigrationState *s)
2518{
2519 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2520
2521 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
5e79a4bf 2522 migration_rp_wait(s);
94190696
PX
2523 }
2524
2525 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2526 return 0;
2527 }
2528
2529 return -1;
2530}
2531
135b87b4
PX
2532/* Return zero if success, or <0 for error */
2533static int postcopy_do_resume(MigrationState *s)
2534{
d1b8eadb
PX
2535 int ret;
2536
2537 /*
2538 * Call all the resume_prepare() hooks, so that modules can be
2539 * ready for the migration resume.
2540 */
2541 ret = qemu_savevm_state_resume_prepare(s);
2542 if (ret) {
2543 error_report("%s: resume_prepare() failure detected: %d",
2544 __func__, ret);
2545 return ret;
2546 }
2547
5655aab0
PX
2548 /*
2549 * If preempt is enabled, re-establish the preempt channel. Note that
2550 * we do it after resume prepare to make sure the main channel will be
2551 * created before the preempt channel. E.g. with weak network, the
2552 * dest QEMU may get messed up with the preempt and main channels on
2553 * the order of connection setup. This guarantees the correct order.
2554 */
2555 ret = postcopy_preempt_establish_channel(s);
2556 if (ret) {
2557 error_report("%s: postcopy_preempt_establish_channel(): %d",
2558 __func__, ret);
2559 return ret;
2560 }
2561
d1b8eadb 2562 /*
94190696
PX
2563 * Last handshake with destination on the resume (destination will
2564 * switch to postcopy-active afterwards)
d1b8eadb 2565 */
94190696
PX
2566 ret = postcopy_resume_handshake(s);
2567 if (ret) {
2568 error_report("%s: handshake failed: %d", __func__, ret);
2569 return ret;
2570 }
d1b8eadb 2571
135b87b4
PX
2572 return 0;
2573}
2574
b23c2ade
PX
2575/*
2576 * We don't return until we are in a safe state to continue current
2577 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2578 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2579 */
2580static MigThrError postcopy_pause(MigrationState *s)
2581{
2582 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
b23c2ade 2583
135b87b4 2584 while (true) {
62df066f
PX
2585 QEMUFile *file;
2586
39675fff
PX
2587 /*
2588 * Current channel is possibly broken. Release it. Note that this is
2589 * guaranteed even without lock because to_dst_file should only be
2590 * modified by the migration thread. That also guarantees that the
2591 * unregister of yank is safe too without the lock. It should be safe
2592 * even to be within the qemu_file_lock, but we didn't do that to avoid
2593 * taking more mutex (yank_lock) within qemu_file_lock. TL;DR: we make
2594 * the qemu_file_lock critical section as small as possible.
2595 */
135b87b4 2596 assert(s->to_dst_file);
39675fff 2597 migration_ioc_unregister_yank_from_file(s->to_dst_file);
62df066f
PX
2598 qemu_mutex_lock(&s->qemu_file_lock);
2599 file = s->to_dst_file;
135b87b4 2600 s->to_dst_file = NULL;
62df066f
PX
2601 qemu_mutex_unlock(&s->qemu_file_lock);
2602
2603 qemu_file_shutdown(file);
2604 qemu_fclose(file);
b23c2ade 2605
ef796ee9
FR
2606 /*
2607 * We're already pausing, so ignore any errors on the return
2608 * path and just wait for the thread to finish. It will be
2609 * re-created when we resume.
2610 */
d7f5a043 2611 close_return_path_on_source(s);
ef796ee9 2612
d246ea50
PX
2613 migrate_set_state(&s->state, s->state,
2614 MIGRATION_STATUS_POSTCOPY_PAUSED);
2615
135b87b4
PX
2616 error_report("Detected IO failure for postcopy. "
2617 "Migration paused.");
b23c2ade 2618
135b87b4
PX
2619 /*
2620 * We wait until things fixed up. Then someone will setup the
2621 * status back for us.
2622 */
2623 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2624 qemu_sem_wait(&s->postcopy_pause_sem);
2625 }
2626
2627 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2628 /* Woken up by a recover procedure. Give it a shot */
b23c2ade 2629
135b87b4
PX
2630 /* Do the resume logic */
2631 if (postcopy_do_resume(s) == 0) {
2632 /* Let's continue! */
2633 trace_postcopy_pause_continued();
2634 return MIG_THR_ERR_RECOVERED;
2635 } else {
2636 /*
2637 * Something wrong happened during the recovery, let's
2638 * pause again. Pause is always better than throwing
2639 * data away.
2640 */
2641 continue;
2642 }
2643 } else {
2644 /* This is not right... Time to quit. */
2645 return MIG_THR_ERR_FATAL;
2646 }
2647 }
b23c2ade
PX
2648}
2649
2650static MigThrError migration_detect_error(MigrationState *s)
2651{
2652 int ret;
c3c5eae6 2653 int state = s->state;
3d661c8a 2654 Error *local_error = NULL;
c3c5eae6
DDAG
2655
2656 if (state == MIGRATION_STATUS_CANCELLING ||
2657 state == MIGRATION_STATUS_CANCELLED) {
2658 /* End the migration, but don't set the state to failed */
2659 return MIG_THR_ERR_FATAL;
2660 }
b23c2ade 2661
60bb3c58
PX
2662 /*
2663 * Try to detect any file errors. Note that postcopy_qemufile_src will
2664 * be NULL when postcopy preempt is not enabled.
2665 */
2666 ret = qemu_file_get_error_obj_any(s->to_dst_file,
2667 s->postcopy_qemufile_src,
2668 &local_error);
b23c2ade
PX
2669 if (!ret) {
2670 /* Everything is fine */
3d661c8a 2671 assert(!local_error);
b23c2ade
PX
2672 return MIG_THR_ERR_NONE;
2673 }
2674
3d661c8a
YK
2675 if (local_error) {
2676 migrate_set_error(s, local_error);
2677 error_free(local_error);
2678 }
2679
d5c8f2af 2680 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret) {
b23c2ade
PX
2681 /*
2682 * For postcopy, we allow the network to be down for a
2683 * while. After that, it can be continued by a
2684 * recovery phase.
2685 */
2686 return postcopy_pause(s);
2687 } else {
2688 /*
2689 * For precopy (or postcopy with error outside IO), we fail
2690 * with no time.
2691 */
c3c5eae6 2692 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
b23c2ade
PX
2693 trace_migration_thread_file_err();
2694
2695 /* Time to stop the migration, now. */
2696 return MIG_THR_ERR_FATAL;
2697 }
2698}
2699
cf011f08
PX
2700static void migration_calculate_complete(MigrationState *s)
2701{
99319e2d 2702 uint64_t bytes = migration_transferred_bytes(s->to_dst_file);
cf011f08 2703 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
6cde6fbe 2704 int64_t transfer_time;
cf011f08
PX
2705
2706 s->total_time = end_time - s->start_time;
2707 if (!s->downtime) {
2708 /*
2709 * It's still not set, so we are precopy migration. For
2710 * postcopy, downtime is calculated during postcopy_start().
2711 */
2712 s->downtime = end_time - s->downtime_start;
2713 }
2714
6cde6fbe
JQ
2715 transfer_time = s->total_time - s->setup_time;
2716 if (transfer_time) {
2717 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
cf011f08
PX
2718 }
2719}
2720
87f3bd87
IR
2721static void update_iteration_initial_status(MigrationState *s)
2722{
2723 /*
2724 * Update these three fields at the same time to avoid mismatch info lead
2725 * wrong speed calculation.
2726 */
2727 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
99319e2d 2728 s->iteration_initial_bytes = migration_transferred_bytes(s->to_dst_file);
87f3bd87
IR
2729 s->iteration_initial_pages = ram_get_total_transferred_pages();
2730}
2731
b15df1ae
PX
2732static void migration_update_counters(MigrationState *s,
2733 int64_t current_time)
2734{
aecbfe9c 2735 uint64_t transferred, transferred_pages, time_spent;
0c8f0efd 2736 uint64_t current_bytes; /* bytes transferred since the beginning */
8b239597
PX
2737 uint64_t switchover_bw;
2738 /* Expected bandwidth when switching over to destination QEMU */
2739 double expected_bw_per_ms;
b15df1ae
PX
2740 double bandwidth;
2741
2742 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2743 return;
2744 }
2745
8b239597 2746 switchover_bw = migrate_avail_switchover_bandwidth();
99319e2d 2747 current_bytes = migration_transferred_bytes(s->to_dst_file);
0c8f0efd 2748 transferred = current_bytes - s->iteration_initial_bytes;
b15df1ae
PX
2749 time_spent = current_time - s->iteration_start_time;
2750 bandwidth = (double)transferred / time_spent;
8b239597
PX
2751
2752 if (switchover_bw) {
2753 /*
2754 * If the user specified a switchover bandwidth, let's trust the
2755 * user so that can be more accurate than what we estimated.
2756 */
2757 expected_bw_per_ms = switchover_bw / 1000;
2758 } else {
2759 /* If the user doesn't specify bandwidth, we use the estimated */
2760 expected_bw_per_ms = bandwidth;
2761 }
2762
2763 s->threshold_size = expected_bw_per_ms * migrate_downtime_limit();
b15df1ae
PX
2764
2765 s->mbps = (((double) transferred * 8.0) /
2766 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2767
aecbfe9c
XG
2768 transferred_pages = ram_get_total_transferred_pages() -
2769 s->iteration_initial_pages;
2770 s->pages_per_second = (double) transferred_pages /
2771 (((double) time_spent / 1000.0));
2772
b15df1ae
PX
2773 /*
2774 * if we haven't sent anything, we don't want to
2775 * recalculate. 10000 is a small enough number for our purposes
2776 */
aff3f660 2777 if (stat64_get(&mig_stats.dirty_pages_rate) &&
72f8e587 2778 transferred > 10000) {
73208a33 2779 s->expected_downtime =
8b239597 2780 stat64_get(&mig_stats.dirty_bytes_last_sync) / expected_bw_per_ms;
b15df1ae
PX
2781 }
2782
813cd616 2783 migration_rate_reset(s->to_dst_file);
b15df1ae 2784
87f3bd87 2785 update_iteration_initial_status(s);
b15df1ae
PX
2786
2787 trace_migrate_transferred(transferred, time_spent,
8b239597
PX
2788 /* Both in unit bytes/ms */
2789 bandwidth, switchover_bw / 1000,
2790 s->threshold_size);
b15df1ae
PX
2791}
2792
1b4adb10
AH
2793static bool migration_can_switchover(MigrationState *s)
2794{
2795 if (!migrate_switchover_ack()) {
2796 return true;
2797 }
2798
2799 /* No reason to wait for switchover ACK if VM is stopped */
2800 if (!runstate_is_running()) {
2801 return true;
2802 }
2803
2804 return s->switchover_acked;
2805}
2806
2ad87305
PX
2807/* Migration thread iteration status */
2808typedef enum {
2809 MIG_ITERATE_RESUME, /* Resume current iteration */
2810 MIG_ITERATE_SKIP, /* Skip current iteration */
2811 MIG_ITERATE_BREAK, /* Break the loop */
2812} MigIterateState;
2813
2814/*
2815 * Return true if continue to the next iteration directly, false
2816 * otherwise.
2817 */
2818static MigIterateState migration_iteration_run(MigrationState *s)
2819{
24beea4e 2820 uint64_t must_precopy, can_postcopy;
908927db 2821 Error *local_err = NULL;
2ad87305 2822 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
1b4adb10 2823 bool can_switchover = migration_can_switchover(s);
2ad87305 2824
24beea4e
JQ
2825 qemu_savevm_state_pending_estimate(&must_precopy, &can_postcopy);
2826 uint64_t pending_size = must_precopy + can_postcopy;
2ad87305 2827
24beea4e 2828 trace_migrate_pending_estimate(pending_size, must_precopy, can_postcopy);
c8df4a7a 2829
24beea4e
JQ
2830 if (must_precopy <= s->threshold_size) {
2831 qemu_savevm_state_pending_exact(&must_precopy, &can_postcopy);
2832 pending_size = must_precopy + can_postcopy;
2833 trace_migrate_pending_exact(pending_size, must_precopy, can_postcopy);
c8df4a7a 2834 }
2ad87305 2835
1b4adb10 2836 if ((!pending_size || pending_size < s->threshold_size) && can_switchover) {
2ad87305
PX
2837 trace_migration_thread_low_pending(pending_size);
2838 migration_completion(s);
2839 return MIG_ITERATE_BREAK;
2840 }
2841
d9df9292 2842 /* Still a significant amount to transfer */
1b4adb10 2843 if (!in_postcopy && must_precopy <= s->threshold_size && can_switchover &&
d9df9292 2844 qatomic_read(&s->start_postcopy)) {
908927db
TG
2845 if (postcopy_start(s, &local_err)) {
2846 migrate_set_error(s, local_err);
2847 error_report_err(local_err);
d9df9292
JQ
2848 }
2849 return MIG_ITERATE_SKIP;
2850 }
2851
2852 /* Just another iteration step */
2853 qemu_savevm_state_iterate(s->to_dst_file, in_postcopy);
2ad87305
PX
2854 return MIG_ITERATE_RESUME;
2855}
2856
199aa6d4
PX
2857static void migration_iteration_finish(MigrationState *s)
2858{
2859 /* If we enabled cpu throttling for auto-converge, turn it off. */
2860 cpu_throttle_stop();
2861
2862 qemu_mutex_lock_iothread();
2863 switch (s->state) {
2864 case MIGRATION_STATUS_COMPLETED:
2865 migration_calculate_complete(s);
2866 runstate_set(RUN_STATE_POSTMIGRATE);
2867 break;
751fe4c6 2868 case MIGRATION_STATUS_COLO:
d70178a8 2869 assert(migrate_colo());
199aa6d4 2870 migrate_start_colo_process(s);
f4584076 2871 s->vm_old_state = RUN_STATE_RUNNING;
199aa6d4
PX
2872 /* Fallthrough */
2873 case MIGRATION_STATUS_FAILED:
2874 case MIGRATION_STATUS_CANCELLED:
57225e5f 2875 case MIGRATION_STATUS_CANCELLING:
f4584076 2876 if (s->vm_old_state == RUN_STATE_RUNNING) {
aa505f8e
RL
2877 if (!runstate_check(RUN_STATE_SHUTDOWN)) {
2878 vm_start();
2879 }
199aa6d4
PX
2880 } else {
2881 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
a4c6275a 2882 runstate_set(s->vm_old_state);
199aa6d4
PX
2883 }
2884 }
2885 break;
2886
2887 default:
2888 /* Should not reach here, but if so, forgive the VM. */
2889 error_report("%s: Unknown ending state %d", __func__, s->state);
2890 break;
2891 }
fd392cfa 2892 migrate_fd_cleanup_schedule(s);
199aa6d4
PX
2893 qemu_mutex_unlock_iothread();
2894}
2895
8518278a
AG
2896static void bg_migration_iteration_finish(MigrationState *s)
2897{
3a8b81f2
FE
2898 /*
2899 * Stop tracking RAM writes - un-protect memory, un-register UFFD
2900 * memory ranges, flush kernel wait queues and wake up threads
2901 * waiting for write fault to be resolved.
2902 */
2903 ram_write_tracking_stop();
2904
8518278a
AG
2905 qemu_mutex_lock_iothread();
2906 switch (s->state) {
2907 case MIGRATION_STATUS_COMPLETED:
2908 migration_calculate_complete(s);
2909 break;
2910
2911 case MIGRATION_STATUS_ACTIVE:
2912 case MIGRATION_STATUS_FAILED:
2913 case MIGRATION_STATUS_CANCELLED:
2914 case MIGRATION_STATUS_CANCELLING:
2915 break;
2916
2917 default:
2918 /* Should not reach here, but if so, forgive the VM. */
2919 error_report("%s: Unknown ending state %d", __func__, s->state);
2920 break;
2921 }
2922
2923 migrate_fd_cleanup_schedule(s);
2924 qemu_mutex_unlock_iothread();
2925}
2926
2927/*
2928 * Return true if continue to the next iteration directly, false
2929 * otherwise.
2930 */
2931static MigIterateState bg_migration_iteration_run(MigrationState *s)
2932{
2933 int res;
2934
2935 res = qemu_savevm_state_iterate(s->to_dst_file, false);
2936 if (res > 0) {
2937 bg_migration_completion(s);
2938 return MIG_ITERATE_BREAK;
2939 }
2940
2941 return MIG_ITERATE_RESUME;
2942}
2943
ad767bed
DDAG
2944void migration_make_urgent_request(void)
2945{
2946 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
2947}
2948
2949void migration_consume_urgent_request(void)
2950{
2951 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
2952}
2953
97e1e067
DDAG
2954/* Returns true if the rate limiting was broken by an urgent request */
2955bool migration_rate_limit(void)
2956{
2957 int64_t now = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2958 MigrationState *s = migrate_get_current();
2959
2960 bool urgent = false;
2961 migration_update_counters(s, now);
e1fde0e0 2962 if (migration_rate_exceeded(s->to_dst_file)) {
77386127
LS
2963
2964 if (qemu_file_get_error(s->to_dst_file)) {
2965 return false;
2966 }
97e1e067
DDAG
2967 /*
2968 * Wait for a delay to do rate limiting OR
2969 * something urgent to post the semaphore.
2970 */
2971 int ms = s->iteration_start_time + BUFFER_DELAY - now;
2972 trace_migration_rate_limit_pre(ms);
2973 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
2974 /*
2975 * We were woken by one or more urgent things but
2976 * the timedwait will have consumed one of them.
2977 * The service routine for the urgent wake will dec
2978 * the semaphore itself for each item it consumes,
2979 * so add this one we just eat back.
2980 */
2981 qemu_sem_post(&s->rate_limit_sem);
2982 urgent = true;
2983 }
2984 trace_migration_rate_limit_post(urgent);
2985 }
2986 return urgent;
2987}
2988
fde93d99
LV
2989/*
2990 * if failover devices are present, wait they are completely
2991 * unplugged
2992 */
2993
2994static void qemu_savevm_wait_unplug(MigrationState *s, int old_state,
2995 int new_state)
2996{
2997 if (qemu_savevm_state_guest_unplug_pending()) {
2998 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_WAIT_UNPLUG);
2999
3000 while (s->state == MIGRATION_STATUS_WAIT_UNPLUG &&
3001 qemu_savevm_state_guest_unplug_pending()) {
3002 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3003 }
944bc528
LV
3004 if (s->state != MIGRATION_STATUS_WAIT_UNPLUG) {
3005 int timeout = 120; /* 30 seconds */
3006 /*
3007 * migration has been canceled
3008 * but as we have started an unplug we must wait the end
3009 * to be able to plug back the card
3010 */
3011 while (timeout-- && qemu_savevm_state_guest_unplug_pending()) {
3012 qemu_sem_timedwait(&s->wait_unplug_sem, 250);
3013 }
1b529d90
LV
3014 if (qemu_savevm_state_guest_unplug_pending() &&
3015 !qtest_enabled()) {
a51dcef0
LV
3016 warn_report("migration: partially unplugged device on "
3017 "failure");
3018 }
944bc528 3019 }
fde93d99
LV
3020
3021 migrate_set_state(&s->state, MIGRATION_STATUS_WAIT_UNPLUG, new_state);
3022 } else {
3023 migrate_set_state(&s->state, old_state, new_state);
3024 }
3025}
3026
70b20477
DDAG
3027/*
3028 * Master migration thread on the source VM.
3029 * It drives the migration and pumps the data down the outgoing channel.
3030 */
5f496a1b 3031static void *migration_thread(void *opaque)
0d82d0e8 3032{
9848a404 3033 MigrationState *s = opaque;
1b1f4ab6 3034 MigrationThread *thread = NULL;
bc72ad67 3035 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
b23c2ade 3036 MigThrError thr_error;
ad767bed 3037 bool urgent = false;
76f5933a 3038
788fa680 3039 thread = migration_threads_add("live_migration", qemu_get_thread_id());
1b1f4ab6 3040
ab28bd23
PB
3041 rcu_register_thread();
3042
892ae715 3043 object_ref(OBJECT(s));
87f3bd87 3044 update_iteration_initial_status(s);
b15df1ae 3045
930e239d 3046 qemu_mutex_lock_iothread();
89a02a9f 3047 qemu_savevm_state_header(s->to_dst_file);
930e239d 3048 qemu_mutex_unlock_iothread();
1d34e4bf 3049
62a02658
PX
3050 /*
3051 * If we opened the return path, we need to make sure dst has it
3052 * opened as well.
3053 */
43044ac0 3054 if (s->rp_state.rp_thread_created) {
1d34e4bf 3055 /* Now tell the dest that it should open its end so it can reply */
89a02a9f 3056 qemu_savevm_send_open_return_path(s->to_dst_file);
1d34e4bf
DDAG
3057
3058 /* And do a ping that will make stuff easier to debug */
89a02a9f 3059 qemu_savevm_send_ping(s->to_dst_file, 1);
0425dc97 3060 }
1d34e4bf 3061
58110f0a 3062 if (migrate_postcopy()) {
1d34e4bf
DDAG
3063 /*
3064 * Tell the destination that we *might* want to do postcopy later;
3065 * if the other end can't do postcopy it should fail now, nice and
3066 * early.
3067 */
89a02a9f 3068 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1d34e4bf
DDAG
3069 }
3070
5e804644 3071 if (migrate_colo()) {
aad555c2
ZC
3072 /* Notify migration destination that we enable COLO */
3073 qemu_savevm_send_colo_enable(s->to_dst_file);
3074 }
3075
930e239d 3076 qemu_mutex_lock_iothread();
9907e842 3077 qemu_savevm_state_setup(s->to_dst_file);
930e239d 3078 qemu_mutex_unlock_iothread();
0d82d0e8 3079
fde93d99
LV
3080 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3081 MIGRATION_STATUS_ACTIVE);
c7e0acd5 3082
bc72ad67 3083 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
29ae8a41 3084
9ec055ae
DDAG
3085 trace_migration_thread_setup_complete();
3086
8f8d528e 3087 while (migration_is_active(s)) {
e1fde0e0 3088 if (urgent || !migration_rate_exceeded(s->to_dst_file)) {
2ad87305
PX
3089 MigIterateState iter_state = migration_iteration_run(s);
3090 if (iter_state == MIG_ITERATE_SKIP) {
3091 continue;
3092 } else if (iter_state == MIG_ITERATE_BREAK) {
09f6c85e 3093 break;
c369f40d
JQ
3094 }
3095 }
f4410a5d 3096
b23c2ade
PX
3097 /*
3098 * Try to detect any kind of failures, and see whether we
3099 * should stop the migration now.
3100 */
3101 thr_error = migration_detect_error(s);
3102 if (thr_error == MIG_THR_ERR_FATAL) {
3103 /* Stop migration */
fd45ee2c 3104 break;
b23c2ade
PX
3105 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3106 /*
3107 * Just recovered from a e.g. network failure, reset all
3108 * the local variables. This is important to avoid
3109 * breaking transferred_bytes and bandwidth calculation
3110 */
87f3bd87 3111 update_iteration_initial_status(s);
fd45ee2c 3112 }
b15df1ae 3113
97e1e067 3114 urgent = migration_rate_limit();
a3fa1d78
PB
3115 }
3116
1d34e4bf 3117 trace_migration_thread_after_loop();
199aa6d4 3118 migration_iteration_finish(s);
892ae715 3119 object_unref(OBJECT(s));
ab28bd23 3120 rcu_unregister_thread();
788fa680 3121 migration_threads_remove(thread);
0d82d0e8
JQ
3122 return NULL;
3123}
3124
8518278a
AG
3125static void bg_migration_vm_start_bh(void *opaque)
3126{
3127 MigrationState *s = opaque;
3128
3129 qemu_bh_delete(s->vm_start_bh);
3130 s->vm_start_bh = NULL;
3131
3132 vm_start();
3133 s->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - s->downtime_start;
3134}
3135
3136/**
3137 * Background snapshot thread, based on live migration code.
3138 * This is an alternative implementation of live migration mechanism
3139 * introduced specifically to support background snapshots.
3140 *
3141 * It takes advantage of userfault_fd write protection mechanism introduced
3142 * in v5.7 kernel. Compared to existing dirty page logging migration much
3143 * lesser stream traffic is produced resulting in smaller snapshot images,
3144 * simply cause of no page duplicates can get into the stream.
3145 *
3146 * Another key point is that generated vmstate stream reflects machine state
3147 * 'frozen' at the beginning of snapshot creation compared to dirty page logging
3148 * mechanism, which effectively results in that saved snapshot is the state of VM
3149 * at the end of the process.
3150 */
3151static void *bg_migration_thread(void *opaque)
3152{
3153 MigrationState *s = opaque;
3154 int64_t setup_start;
3155 MigThrError thr_error;
3156 QEMUFile *fb;
3157 bool early_fail = true;
3158
3159 rcu_register_thread();
3160 object_ref(OBJECT(s));
3161
e1fde0e0 3162 migration_rate_set(RATE_LIMIT_DISABLED);
8518278a
AG
3163
3164 setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
3165 /*
3166 * We want to save vmstate for the moment when migration has been
3167 * initiated but also we want to save RAM content while VM is running.
3168 * The RAM content should appear first in the vmstate. So, we first
3169 * stash the non-RAM part of the vmstate to the temporary buffer,
3170 * then write RAM part of the vmstate to the migration stream
3171 * with vCPUs running and, finally, write stashed non-RAM part of
3172 * the vmstate from the buffer to the migration stream.
3173 */
ecb23efe 3174 s->bioc = qio_channel_buffer_new(512 * 1024);
8518278a 3175 qio_channel_set_name(QIO_CHANNEL(s->bioc), "vmstate-buffer");
77ef2dc1 3176 fb = qemu_file_new_output(QIO_CHANNEL(s->bioc));
8518278a
AG
3177 object_unref(OBJECT(s->bioc));
3178
3179 update_iteration_initial_status(s);
3180
eeccb99c
AG
3181 /*
3182 * Prepare for tracking memory writes with UFFD-WP - populate
3183 * RAM pages before protecting.
3184 */
3185#ifdef __linux__
3186 ram_write_tracking_prepare();
3187#endif
3188
930e239d 3189 qemu_mutex_lock_iothread();
8518278a
AG
3190 qemu_savevm_state_header(s->to_dst_file);
3191 qemu_savevm_state_setup(s->to_dst_file);
930e239d 3192 qemu_mutex_unlock_iothread();
8518278a 3193
fde93d99
LV
3194 qemu_savevm_wait_unplug(s, MIGRATION_STATUS_SETUP,
3195 MIGRATION_STATUS_ACTIVE);
8518278a 3196
8518278a
AG
3197 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
3198
3199 trace_migration_thread_setup_complete();
3200 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3201
3202 qemu_mutex_lock_iothread();
3203
3204 /*
3205 * If VM is currently in suspended state, then, to make a valid runstate
3206 * transition in vm_stop_force_state() we need to wakeup it up.
3207 */
3208 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
f4584076 3209 s->vm_old_state = runstate_get();
8518278a 3210
c33f1829 3211 global_state_store();
8518278a
AG
3212 /* Forcibly stop VM before saving state of vCPUs and devices */
3213 if (vm_stop_force_state(RUN_STATE_PAUSED)) {
3214 goto fail;
3215 }
3216 /*
3217 * Put vCPUs in sync with shadow context structures, then
3218 * save their state to channel-buffer along with devices.
3219 */
3220 cpu_synchronize_all_states();
3221 if (qemu_savevm_state_complete_precopy_non_iterable(fb, false, false)) {
3222 goto fail;
3223 }
ecb23efe
AG
3224 /*
3225 * Since we are going to get non-iterable state data directly
3226 * from s->bioc->data, explicit flush is needed here.
3227 */
3228 qemu_fflush(fb);
3229
8518278a
AG
3230 /* Now initialize UFFD context and start tracking RAM writes */
3231 if (ram_write_tracking_start()) {
3232 goto fail;
3233 }
3234 early_fail = false;
3235
3236 /*
3237 * Start VM from BH handler to avoid write-fault lock here.
3238 * UFFD-WP protection for the whole RAM is already enabled so
3239 * calling VM state change notifiers from vm_start() would initiate
3240 * writes to virtio VQs memory which is in write-protected region.
3241 */
3242 s->vm_start_bh = qemu_bh_new(bg_migration_vm_start_bh, s);
3243 qemu_bh_schedule(s->vm_start_bh);
3244
3245 qemu_mutex_unlock_iothread();
3246
3247 while (migration_is_active(s)) {
3248 MigIterateState iter_state = bg_migration_iteration_run(s);
3249 if (iter_state == MIG_ITERATE_SKIP) {
3250 continue;
3251 } else if (iter_state == MIG_ITERATE_BREAK) {
3252 break;
3253 }
3254
3255 /*
3256 * Try to detect any kind of failures, and see whether we
3257 * should stop the migration now.
3258 */
3259 thr_error = migration_detect_error(s);
3260 if (thr_error == MIG_THR_ERR_FATAL) {
3261 /* Stop migration */
3262 break;
3263 }
3264
3265 migration_update_counters(s, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
3266 }
3267
3268 trace_migration_thread_after_loop();
3269
3270fail:
3271 if (early_fail) {
3272 migrate_set_state(&s->state, MIGRATION_STATUS_ACTIVE,
3273 MIGRATION_STATUS_FAILED);
3274 qemu_mutex_unlock_iothread();
3275 }
3276
3277 bg_migration_iteration_finish(s);
3278
3279 qemu_fclose(fb);
3280 object_unref(OBJECT(s));
3281 rcu_unregister_thread();
3282
3283 return NULL;
3284}
3285
cce8040b 3286void migrate_fd_connect(MigrationState *s, Error *error_in)
0d82d0e8 3287{
00f4b572 3288 Error *local_err = NULL;
52033349 3289 uint64_t rate_limit;
d3e35b8f
PX
3290 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3291
ca7bd082
PX
3292 /*
3293 * If there's a previous error, free it and prepare for another one.
3294 * Meanwhile if migration completes successfully, there won't have an error
3295 * dumped when calling migrate_fd_cleanup().
3296 */
3297 migrate_error_free(s);
3298
f5da8ba4 3299 s->expected_downtime = migrate_downtime_limit();
9cbc3649
MAL
3300 if (resume) {
3301 assert(s->cleanup_bh);
3302 } else {
3303 assert(!s->cleanup_bh);
3304 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
3305 }
cce8040b
DDAG
3306 if (error_in) {
3307 migrate_fd_error(s, error_in);
ca30f24d
PX
3308 if (resume) {
3309 /*
3310 * Don't do cleanup for resume if channel is invalid, but only dump
3311 * the error. We wait for another channel connect from the user.
3312 * The error_report still gives HMP user a hint on what failed.
3313 * It's normally done in migrate_fd_cleanup(), but call it here
3314 * explicitly.
3315 */
3316 error_report_err(error_copy(s->error));
3317 } else {
3318 migrate_fd_cleanup(s);
3319 }
cce8040b
DDAG
3320 return;
3321 }
0d82d0e8 3322
d3e35b8f
PX
3323 if (resume) {
3324 /* This is a resumed migration */
9d3ebbe2 3325 rate_limit = migrate_max_postcopy_bandwidth();
d3e35b8f
PX
3326 } else {
3327 /* This is a fresh new migration */
9d3ebbe2 3328 rate_limit = migrate_max_bandwidth();
442773ce 3329
d3e35b8f 3330 /* Notify before starting migration thread */
d9cda213 3331 migration_call_notifiers(s);
d3e35b8f
PX
3332 }
3333
e1fde0e0 3334 migration_rate_set(rate_limit);
d3e35b8f 3335 qemu_file_set_blocking(s->to_dst_file, true);
9287ac27 3336
1d34e4bf 3337 /*
c788ada8
PX
3338 * Open the return path. For postcopy, it is used exclusively. For
3339 * precopy, only if user specified "return-path" capability would
3340 * QEMU uses the return path.
1d34e4bf 3341 */
38ad1110 3342 if (migrate_postcopy_ram() || migrate_return_path()) {
ef796ee9 3343 if (open_return_path_on_source(s)) {
908927db 3344 error_setg(&local_err, "Unable to open return-path for postcopy");
d3e35b8f 3345 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
908927db
TG
3346 migrate_set_error(s, local_err);
3347 error_report_err(local_err);
1d34e4bf
DDAG
3348 migrate_fd_cleanup(s);
3349 return;
3350 }
3351 }
3352
06064a67
PX
3353 /*
3354 * This needs to be done before resuming a postcopy. Note: for newer
3355 * QEMUs we will delay the channel creation until postcopy_start(), to
3356 * avoid disorder of channel creations.
3357 */
3358 if (migrate_postcopy_preempt() && s->preempt_pre_7_2) {
3359 postcopy_preempt_setup(s);
3360 }
3361
d3e35b8f 3362 if (resume) {
135b87b4
PX
3363 /* Wakeup the main migration thread to do the recovery */
3364 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3365 MIGRATION_STATUS_POSTCOPY_RECOVER);
3366 qemu_sem_post(&s->postcopy_pause_sem);
d3e35b8f
PX
3367 return;
3368 }
3369
00f4b572 3370 if (multifd_save_setup(&local_err) != 0) {
908927db 3371 migrate_set_error(s, local_err);
00f4b572 3372 error_report_err(local_err);
f986c3d2
JQ
3373 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3374 MIGRATION_STATUS_FAILED);
3375 migrate_fd_cleanup(s);
3376 return;
3377 }
8518278a
AG
3378
3379 if (migrate_background_snapshot()) {
3380 qemu_thread_create(&s->thread, "bg_snapshot",
3381 bg_migration_thread, s, QEMU_THREAD_JOINABLE);
3382 } else {
3383 qemu_thread_create(&s->thread, "live_migration",
3384 migration_thread, s, QEMU_THREAD_JOINABLE);
3385 }
1d34e4bf 3386 s->migration_thread_running = true;
0d82d0e8 3387}
093e3c42 3388
e5cb7e76
PX
3389static void migration_class_init(ObjectClass *klass, void *data)
3390{
3391 DeviceClass *dc = DEVICE_CLASS(klass);
3392
3393 dc->user_creatable = false;
4f67d30b 3394 device_class_set_props(dc, migration_properties);
e5cb7e76
PX
3395}
3396
b91bf5e4
MAL
3397static void migration_instance_finalize(Object *obj)
3398{
3399 MigrationState *ms = MIGRATION_OBJ(obj);
b91bf5e4 3400
87db1a7d 3401 qemu_mutex_destroy(&ms->error_mutex);
62df066f 3402 qemu_mutex_destroy(&ms->qemu_file_lock);
c7e0acd5 3403 qemu_sem_destroy(&ms->wait_unplug_sem);
ad767bed 3404 qemu_sem_destroy(&ms->rate_limit_sem);
e91d8951 3405 qemu_sem_destroy(&ms->pause_sem);
b23c2ade 3406 qemu_sem_destroy(&ms->postcopy_pause_sem);
edd090c7 3407 qemu_sem_destroy(&ms->rp_state.rp_sem);
b28fb582 3408 qemu_sem_destroy(&ms->rp_state.rp_pong_acks);
d0edb8a1 3409 qemu_sem_destroy(&ms->postcopy_qemufile_src_sem);
ab105cc1 3410 error_free(ms->error);
b91bf5e4
MAL
3411}
3412
e5cb7e76
PX
3413static void migration_instance_init(Object *obj)
3414{
3415 MigrationState *ms = MIGRATION_OBJ(obj);
3416
3417 ms->state = MIGRATION_STATUS_NONE;
e5cb7e76 3418 ms->mbps = -1;
aecbfe9c 3419 ms->pages_per_second = -1;
e91d8951 3420 qemu_sem_init(&ms->pause_sem, 0);
87db1a7d 3421 qemu_mutex_init(&ms->error_mutex);
8b0b29dc 3422
61a174e2 3423 migrate_params_init(&ms->parameters);
b23c2ade
PX
3424
3425 qemu_sem_init(&ms->postcopy_pause_sem, 0);
edd090c7 3426 qemu_sem_init(&ms->rp_state.rp_sem, 0);
b28fb582 3427 qemu_sem_init(&ms->rp_state.rp_pong_acks, 0);
ad767bed 3428 qemu_sem_init(&ms->rate_limit_sem, 0);
c7e0acd5 3429 qemu_sem_init(&ms->wait_unplug_sem, 0);
d0edb8a1 3430 qemu_sem_init(&ms->postcopy_qemufile_src_sem, 0);
62df066f 3431 qemu_mutex_init(&ms->qemu_file_lock);
8b0b29dc
PX
3432}
3433
3434/*
3435 * Return true if check pass, false otherwise. Error will be put
3436 * inside errp if provided.
3437 */
3438static bool migration_object_check(MigrationState *ms, Error **errp)
3439{
6b19a7d9 3440 /* Assuming all off */
b02c7fc9 3441 bool old_caps[MIGRATION_CAPABILITY__MAX] = { 0 };
6b19a7d9 3442
8b0b29dc
PX
3443 if (!migrate_params_check(&ms->parameters, errp)) {
3444 return false;
3445 }
3446
b02c7fc9 3447 return migrate_caps_check(old_caps, ms->capabilities, errp);
e5cb7e76
PX
3448}
3449
3450static const TypeInfo migration_type = {
3451 .name = TYPE_MIGRATION,
01f6e14c 3452 /*
c8d3ff38 3453 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2194abd6 3454 * not created using qdev_new(), it is not attached to the qdev
c8d3ff38
PX
3455 * device tree, and it is never realized.
3456 *
3457 * TODO: Make this TYPE_OBJECT once QOM provides something like
3458 * TYPE_DEVICE's "-global" properties.
01f6e14c 3459 */
e5cb7e76
PX
3460 .parent = TYPE_DEVICE,
3461 .class_init = migration_class_init,
3462 .class_size = sizeof(MigrationClass),
3463 .instance_size = sizeof(MigrationState),
3464 .instance_init = migration_instance_init,
b91bf5e4 3465 .instance_finalize = migration_instance_finalize,
e5cb7e76
PX
3466};
3467
3468static void register_migration_types(void)
3469{
3470 type_register_static(&migration_type);
3471}
3472
3473type_init(register_migration_types);