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