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