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