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