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