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