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