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