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