]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
hmp/migration: add migrate_recover command
[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"
795c40b8 19#include "migration/blocker.h"
f4dbe1bf 20#include "exec.h"
7fcac4a2 21#include "fd.h"
61e8b148 22#include "socket.h"
e1a3ecee 23#include "rdma.h"
7b1e1a22 24#include "ram.h"
84a899de 25#include "migration/global_state.h"
c4b63b7c 26#include "migration/misc.h"
6666c96a 27#include "migration.h"
20a519a0 28#include "savevm.h"
40014d81 29#include "qemu-file-channel.h"
08a0aee1 30#include "qemu-file.h"
987772d9 31#include "migration/vmstate.h"
737e150e 32#include "block/block.h"
e688df6b 33#include "qapi/error.h"
9af23989
MA
34#include "qapi/qapi-commands-migration.h"
35#include "qapi/qapi-events-migration.h"
cc7a8ea7 36#include "qapi/qmp/qerror.h"
15280c36 37#include "qapi/qmp/qnull.h"
ab28bd23 38#include "qemu/rcu.h"
2c9e6fec 39#include "block.h"
be07b0ac 40#include "postcopy-ram.h"
766bd176 41#include "qemu/thread.h"
c09e5bb1 42#include "trace.h"
51180423 43#include "exec/target_page.h"
61b67d47 44#include "io/channel-buffer.h"
35a6ed4f 45#include "migration/colo.h"
4ffdb337 46#include "hw/boards.h"
9d18af93 47#include "monitor/monitor.h"
065e2813 48
dc325627 49#define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
5bb7910a 50
5b4e1eb7
JQ
51/* Amount of time to allocate to each "chunk" of bandwidth-throttled
52 * data. */
53#define BUFFER_DELAY 100
54#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
55
2ff30257
AA
56/* Time in milliseconds we are allowed to stop the source,
57 * for sending the last part */
58#define DEFAULT_MIGRATE_SET_DOWNTIME 300
59
87c9cc1c
DHB
60/* Maximum migrate downtime set to 2000 seconds */
61#define MAX_MIGRATE_DOWNTIME_SECONDS 2000
62#define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
63
8706d2d5
LL
64/* Default compression thread count */
65#define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
3fcb38c2
LL
66/* Default decompression thread count, usually decompression is at
67 * least 4 times as fast as compression.*/
68#define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
8706d2d5
LL
69/*0: means nocompress, 1: best speed, ... 9: best compress ratio */
70#define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
1626fee3 71/* Define default autoconverge cpu throttle migration parameters */
d85a31d1
JH
72#define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
73#define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
8706d2d5 74
17ad9b35 75/* Migration XBZRLE default cache size */
73af8dd8 76#define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
17ad9b35 77
68b53591
HZ
78/* The delay time (in ms) between two COLO checkpoints
79 * Note: Please change this default value to 10000 when we support hybrid mode.
80 */
81#define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
4075fb1c 82#define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
0fb86605 83#define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
68b53591 84
99a0db9b
GH
85static NotifierList migration_state_notifiers =
86 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
87
adde220a
DDAG
88static bool deferred_incoming;
89
da6f1790
JQ
90/* Messages sent on the return path from destination to source */
91enum mig_rp_message_type {
92 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
93 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
94 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
95
96 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
97 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
a335debb 98 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
13955b89 99 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
da6f1790
JQ
100
101 MIG_RP_MSG_MAX
102};
103
17549e84
JQ
104/* When we add fault tolerance, we could have several
105 migrations at once. For now we don't need to add
106 dynamic creation of migration */
107
e5cb7e76 108static MigrationState *current_migration;
e1b1b1bc 109static MigrationIncomingState *current_incoming;
e5cb7e76 110
8b0b29dc 111static bool migration_object_check(MigrationState *ms, Error **errp);
0331c8ca
DDAG
112static int migration_maybe_pause(MigrationState *s,
113 int *current_active_state,
114 int new_state);
8b0b29dc 115
e5cb7e76
PX
116void migration_object_init(void)
117{
4ffdb337 118 MachineState *ms = MACHINE(qdev_get_machine());
8b0b29dc 119 Error *err = NULL;
4ffdb337 120
e5cb7e76
PX
121 /* This can only be called once. */
122 assert(!current_migration);
123 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
4ffdb337 124
e1b1b1bc
PX
125 /*
126 * Init the migrate incoming object as well no matter whether
127 * we'll use it or not.
128 */
129 assert(!current_incoming);
130 current_incoming = g_new0(MigrationIncomingState, 1);
131 current_incoming->state = MIGRATION_STATUS_NONE;
132 current_incoming->postcopy_remote_fds =
133 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
134 qemu_mutex_init(&current_incoming->rp_mutex);
135 qemu_event_init(&current_incoming->main_thread_load_event, false);
136 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
137 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
138
139 init_dirty_bitmap_incoming_migration();
140
8b0b29dc
PX
141 if (!migration_object_check(current_migration, &err)) {
142 error_report_err(err);
143 exit(1);
144 }
145
4ffdb337
PX
146 /*
147 * We cannot really do this in migration_instance_init() since at
148 * that time global properties are not yet applied, then this
149 * value will be definitely replaced by something else.
150 */
151 if (ms->enforce_config_section) {
152 current_migration->send_configuration = true;
153 }
e5cb7e76
PX
154}
155
1f895604
VSO
156void migration_object_finalize(void)
157{
158 object_unref(OBJECT(current_migration));
159}
160
bca7856a 161/* For outgoing */
859bc756 162MigrationState *migrate_get_current(void)
17549e84 163{
e5cb7e76
PX
164 /* This can only be called after the object created. */
165 assert(current_migration);
166 return current_migration;
17549e84
JQ
167}
168
bca7856a
DDAG
169MigrationIncomingState *migration_incoming_get_current(void)
170{
e1b1b1bc
PX
171 assert(current_incoming);
172 return current_incoming;
bca7856a
DDAG
173}
174
175void migration_incoming_state_destroy(void)
176{
b4b076da
JQ
177 struct MigrationIncomingState *mis = migration_incoming_get_current();
178
3482655b 179 if (mis->to_src_file) {
660819b1
PX
180 /* Tell source that we are done */
181 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
3482655b
PX
182 qemu_fclose(mis->to_src_file);
183 mis->to_src_file = NULL;
184 }
185
660819b1
PX
186 if (mis->from_src_file) {
187 qemu_fclose(mis->from_src_file);
188 mis->from_src_file = NULL;
189 }
00fa4fc8
DDAG
190 if (mis->postcopy_remote_fds) {
191 g_array_free(mis->postcopy_remote_fds, TRUE);
192 mis->postcopy_remote_fds = NULL;
193 }
660819b1 194
5089e186 195 qemu_event_reset(&mis->main_thread_load_event);
bca7856a
DDAG
196}
197
b05dc723
JQ
198static void migrate_generate_event(int new_state)
199{
200 if (migrate_use_events()) {
201 qapi_event_send_migration(new_state, &error_abort);
b05dc723
JQ
202 }
203}
204
adde220a
DDAG
205/*
206 * Called on -incoming with a defer: uri.
207 * The migration can be started later after any parameters have been
208 * changed.
209 */
210static void deferred_incoming_migration(Error **errp)
211{
212 if (deferred_incoming) {
213 error_setg(errp, "Incoming migration already deferred");
214 }
215 deferred_incoming = true;
216}
217
da6f1790
JQ
218/*
219 * Send a message on the return channel back to the source
220 * of the migration.
221 */
d6208e35
PX
222static int migrate_send_rp_message(MigrationIncomingState *mis,
223 enum mig_rp_message_type message_type,
224 uint16_t len, void *data)
da6f1790 225{
d6208e35
PX
226 int ret = 0;
227
da6f1790
JQ
228 trace_migrate_send_rp_message((int)message_type, len);
229 qemu_mutex_lock(&mis->rp_mutex);
d6208e35
PX
230
231 /*
232 * It's possible that the file handle got lost due to network
233 * failures.
234 */
235 if (!mis->to_src_file) {
236 ret = -EIO;
237 goto error;
238 }
239
da6f1790
JQ
240 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
241 qemu_put_be16(mis->to_src_file, len);
242 qemu_put_buffer(mis->to_src_file, data, len);
243 qemu_fflush(mis->to_src_file);
d6208e35
PX
244
245 /* It's possible that qemu file got error during sending */
246 ret = qemu_file_get_error(mis->to_src_file);
247
248error:
da6f1790 249 qemu_mutex_unlock(&mis->rp_mutex);
d6208e35 250 return ret;
da6f1790
JQ
251}
252
1e2d90eb
DDAG
253/* Request a range of pages from the source VM at the given
254 * start address.
255 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
256 * as the last request (a name must have been given previously)
257 * Start: Address offset within the RB
258 * Len: Length in bytes required - must be a multiple of pagesize
259 */
d6208e35
PX
260int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
261 ram_addr_t start, size_t len)
1e2d90eb 262{
cb8d4c8f 263 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
1e2d90eb 264 size_t msglen = 12; /* start + len */
d6208e35 265 enum mig_rp_message_type msg_type;
1e2d90eb
DDAG
266
267 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
268 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
269
270 if (rbname) {
271 int rbname_len = strlen(rbname);
272 assert(rbname_len < 256);
273
274 bufc[msglen++] = rbname_len;
275 memcpy(bufc + msglen, rbname, rbname_len);
276 msglen += rbname_len;
d6208e35 277 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
1e2d90eb 278 } else {
d6208e35 279 msg_type = MIG_RP_MSG_REQ_PAGES;
1e2d90eb 280 }
d6208e35
PX
281
282 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
1e2d90eb
DDAG
283}
284
43eaae28 285void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 286{
34c9dd8e
AL
287 const char *p;
288
7cf1fe6d 289 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
adde220a
DDAG
290 if (!strcmp(uri, "defer")) {
291 deferred_incoming_migration(errp);
292 } else if (strstart(uri, "tcp:", &p)) {
43eaae28 293 tcp_start_incoming_migration(p, errp);
2da776db 294#ifdef CONFIG_RDMA
adde220a 295 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
296 rdma_start_incoming_migration(p, errp);
297#endif
adde220a 298 } else if (strstart(uri, "exec:", &p)) {
43eaae28 299 exec_start_incoming_migration(p, errp);
adde220a 300 } else if (strstart(uri, "unix:", &p)) {
43eaae28 301 unix_start_incoming_migration(p, errp);
adde220a 302 } else if (strstart(uri, "fd:", &p)) {
43eaae28 303 fd_start_incoming_migration(p, errp);
adde220a 304 } else {
312fd5f2 305 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 306 }
5bb7910a
AL
307}
308
0aa6aefc
DL
309static void process_incoming_migration_bh(void *opaque)
310{
311 Error *local_err = NULL;
312 MigrationIncomingState *mis = opaque;
313
a18a73d7
DDAG
314 /* Make sure all file formats flush their mutable metadata.
315 * If we get an error here, just don't restart the VM yet. */
316 bdrv_invalidate_cache_all(&local_err);
317 if (local_err) {
318 error_report_err(local_err);
319 local_err = NULL;
320 autostart = false;
d35ff5e6
KW
321 }
322
0aa6aefc
DL
323 /*
324 * This must happen after all error conditions are dealt with and
325 * we're sure the VM is going to be running on this host.
326 */
327 qemu_announce_self();
328
f986c3d2
JQ
329 if (multifd_load_cleanup(&local_err) != 0) {
330 error_report_err(local_err);
331 autostart = false;
332 }
0aa6aefc
DL
333 /* If global state section was not received or we are in running
334 state, we need to obey autostart. Any other state is set with
335 runstate_set. */
336
b35ebdf0
VSO
337 dirty_bitmap_mig_before_vm_start();
338
0aa6aefc
DL
339 if (!global_state_received() ||
340 global_state_get_runstate() == RUN_STATE_RUNNING) {
341 if (autostart) {
342 vm_start();
343 } else {
344 runstate_set(RUN_STATE_PAUSED);
345 }
346 } else {
347 runstate_set(global_state_get_runstate());
348 }
0aa6aefc
DL
349 /*
350 * This must happen after any state changes since as soon as an external
351 * observer sees this event they might start to prod at the VM assuming
352 * it's ready to use.
353 */
354 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
355 MIGRATION_STATUS_COMPLETED);
356 qemu_bh_delete(mis->bh);
357 migration_incoming_state_destroy();
358}
359
82a4da79 360static void process_incoming_migration_co(void *opaque)
511c0231 361{
b4b076da 362 MigrationIncomingState *mis = migration_incoming_get_current();
e9bef235 363 PostcopyState ps;
1c12e1f5
PB
364 int ret;
365
4f0fae7f 366 assert(mis->from_src_file);
67f11b5c 367 mis->largest_page_size = qemu_ram_pagesize_largest();
093e3c42 368 postcopy_state_set(POSTCOPY_INCOMING_NONE);
93d7af6f
HZ
369 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
370 MIGRATION_STATUS_ACTIVE);
4f0fae7f 371 ret = qemu_loadvm_state(mis->from_src_file);
bca7856a 372
e9bef235
DDAG
373 ps = postcopy_state_get();
374 trace_process_incoming_migration_co_end(ret, ps);
375 if (ps != POSTCOPY_INCOMING_NONE) {
376 if (ps == POSTCOPY_INCOMING_ADVISE) {
377 /*
378 * Where a migration had postcopy enabled (and thus went to advise)
379 * but managed to complete within the precopy period, we can use
380 * the normal exit.
381 */
382 postcopy_ram_incoming_cleanup(mis);
383 } else if (ret >= 0) {
384 /*
385 * Postcopy was started, cleanup should happen at the end of the
386 * postcopy thread.
387 */
388 trace_process_incoming_migration_co_postcopy_end_main();
389 return;
390 }
391 /* Else if something went wrong then just fall out of the normal exit */
392 }
393
25d0c16f
HZ
394 /* we get COLO info, and know if we are in COLO mode */
395 if (!ret && migration_incoming_enable_colo()) {
396 mis->migration_incoming_co = qemu_coroutine_self();
397 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
398 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
399 mis->have_colo_incoming_thread = true;
400 qemu_coroutine_yield();
401
402 /* Wait checkpoint incoming thread exit before free resource */
403 qemu_thread_join(&mis->colo_incoming_thread);
404 }
405
1c12e1f5 406 if (ret < 0) {
f986c3d2
JQ
407 Error *local_err = NULL;
408
93d7af6f
HZ
409 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
410 MIGRATION_STATUS_FAILED);
db80face 411 error_report("load of migration failed: %s", strerror(-ret));
3a0f2cea 412 qemu_fclose(mis->from_src_file);
f986c3d2
JQ
413 if (multifd_load_cleanup(&local_err) != 0) {
414 error_report_err(local_err);
415 }
4aead692 416 exit(EXIT_FAILURE);
511c0231 417 }
0aa6aefc
DL
418 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
419 qemu_bh_schedule(mis->bh);
511c0231
JQ
420}
421
e595a01a 422static void migration_incoming_setup(QEMUFile *f)
82a4da79 423{
4f0fae7f 424 MigrationIncomingState *mis = migration_incoming_get_current();
82a4da79 425
f986c3d2
JQ
426 if (multifd_load_setup() != 0) {
427 /* We haven't been able to create multifd threads
428 nothing better to do */
429 exit(EXIT_FAILURE);
430 }
431
4f0fae7f
JQ
432 if (!mis->from_src_file) {
433 mis->from_src_file = f;
434 }
06ad5135 435 qemu_file_set_blocking(f, false);
e595a01a
JQ
436}
437
36c2f8be 438void migration_incoming_process(void)
e595a01a
JQ
439{
440 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
0b8b8753 441 qemu_coroutine_enter(co);
82a4da79
PB
442}
443
e595a01a
JQ
444void migration_fd_process_incoming(QEMUFile *f)
445{
d96c9e8d
PX
446 MigrationIncomingState *mis = migration_incoming_get_current();
447
448 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
449 /* Resumed from a paused postcopy migration */
450
451 mis->from_src_file = f;
452 /* Postcopy has standalone thread to do vm load */
453 qemu_file_set_blocking(f, true);
454
455 /* Re-configure the return path */
456 mis->to_src_file = qemu_file_get_return_path(f);
457
458 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
459 MIGRATION_STATUS_POSTCOPY_RECOVER);
460
461 /*
462 * Here, we only wake up the main loading thread (while the
463 * fault thread will still be waiting), so that we can receive
464 * commands from source now, and answer it if needed. The
465 * fault thread will be woken up afterwards until we are sure
466 * that source is ready to reply to page requests.
467 */
468 qemu_sem_post(&mis->postcopy_pause_sem_dst);
469 } else {
470 /* New incoming migration */
471 migration_incoming_setup(f);
472 migration_incoming_process();
473 }
e595a01a
JQ
474}
475
4f0fae7f
JQ
476void migration_ioc_process_incoming(QIOChannel *ioc)
477{
478 MigrationIncomingState *mis = migration_incoming_get_current();
479
480 if (!mis->from_src_file) {
481 QEMUFile *f = qemu_fopen_channel_input(ioc);
36c2f8be 482 migration_incoming_setup(f);
71bb07db 483 return;
4f0fae7f 484 }
71bb07db 485 multifd_recv_new_channel(ioc);
4f0fae7f
JQ
486}
487
428d8908
JQ
488/**
489 * @migration_has_all_channels: We have received all channels that we need
490 *
491 * Returns true when we have got connections to all the channels that
492 * we need for migration.
493 */
494bool migration_has_all_channels(void)
495{
62c1e0ca
JQ
496 bool all_channels;
497
498 all_channels = multifd_recv_all_channels_created();
499
500 return all_channels;
428d8908
JQ
501}
502
6decec93
DDAG
503/*
504 * Send a 'SHUT' message on the return channel with the given value
505 * to indicate that we've finished with the RP. Non-0 value indicates
506 * error.
507 */
508void migrate_send_rp_shut(MigrationIncomingState *mis,
509 uint32_t value)
510{
511 uint32_t buf;
512
513 buf = cpu_to_be32(value);
514 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
515}
516
517/*
518 * Send a 'PONG' message on the return channel with the given value
519 * (normally in response to a 'PING')
520 */
521void migrate_send_rp_pong(MigrationIncomingState *mis,
522 uint32_t value)
523{
524 uint32_t buf;
525
526 buf = cpu_to_be32(value);
527 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
528}
529
a335debb
PX
530void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
531 char *block_name)
532{
533 char buf[512];
534 int len;
535 int64_t res;
536
537 /*
538 * First, we send the header part. It contains only the len of
539 * idstr, and the idstr itself.
540 */
541 len = strlen(block_name);
542 buf[0] = len;
543 memcpy(buf + 1, block_name, len);
544
545 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
546 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
547 __func__);
548 return;
549 }
550
551 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
552
553 /*
554 * Next, we dump the received bitmap to the stream.
555 *
556 * TODO: currently we are safe since we are the only one that is
557 * using the to_src_file handle (fault thread is still paused),
558 * and it's ok even not taking the mutex. However the best way is
559 * to take the lock before sending the message header, and release
560 * the lock after sending the bitmap.
561 */
562 qemu_mutex_lock(&mis->rp_mutex);
563 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
564 qemu_mutex_unlock(&mis->rp_mutex);
565
566 trace_migrate_send_rp_recv_bitmap(block_name, res);
567}
568
13955b89
PX
569void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
570{
571 uint32_t buf;
572
573 buf = cpu_to_be32(value);
574 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
575}
576
bbf6da32
OW
577MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
578{
579 MigrationCapabilityStatusList *head = NULL;
580 MigrationCapabilityStatusList *caps;
581 MigrationState *s = migrate_get_current();
582 int i;
583
387eedeb 584 caps = NULL; /* silence compiler warning */
7fb1cf16 585 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
ed1701c6
DDAG
586#ifndef CONFIG_LIVE_BLOCK_MIGRATION
587 if (i == MIGRATION_CAPABILITY_BLOCK) {
588 continue;
589 }
590#endif
bbf6da32
OW
591 if (head == NULL) {
592 head = g_malloc0(sizeof(*caps));
593 caps = head;
594 } else {
595 caps->next = g_malloc0(sizeof(*caps));
596 caps = caps->next;
597 }
598 caps->value =
599 g_malloc(sizeof(*caps->value));
600 caps->value->capability = i;
601 caps->value->state = s->enabled_capabilities[i];
602 }
603
604 return head;
605}
606
85de8323
LL
607MigrationParameters *qmp_query_migrate_parameters(Error **errp)
608{
609 MigrationParameters *params;
610 MigrationState *s = migrate_get_current();
611
e87fae4c 612 /* TODO use QAPI_CLONE() instead of duplicating it inline */
85de8323 613 params = g_malloc0(sizeof(*params));
de63ab61 614 params->has_compress_level = true;
2594f56d 615 params->compress_level = s->parameters.compress_level;
de63ab61 616 params->has_compress_threads = true;
2594f56d 617 params->compress_threads = s->parameters.compress_threads;
de63ab61 618 params->has_decompress_threads = true;
2594f56d 619 params->decompress_threads = s->parameters.decompress_threads;
de63ab61 620 params->has_cpu_throttle_initial = true;
2594f56d 621 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
de63ab61 622 params->has_cpu_throttle_increment = true;
2594f56d 623 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
8cc99dcd 624 params->has_tls_creds = true;
69ef1f36 625 params->tls_creds = g_strdup(s->parameters.tls_creds);
8cc99dcd 626 params->has_tls_hostname = true;
69ef1f36 627 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
2ff30257
AA
628 params->has_max_bandwidth = true;
629 params->max_bandwidth = s->parameters.max_bandwidth;
630 params->has_downtime_limit = true;
631 params->downtime_limit = s->parameters.downtime_limit;
fe39a4d4 632 params->has_x_checkpoint_delay = true;
68b53591 633 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
2833c59b
JQ
634 params->has_block_incremental = true;
635 params->block_incremental = s->parameters.block_incremental;
4075fb1c
JQ
636 params->has_x_multifd_channels = true;
637 params->x_multifd_channels = s->parameters.x_multifd_channels;
0fb86605
JQ
638 params->has_x_multifd_page_count = true;
639 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
73af8dd8
JQ
640 params->has_xbzrle_cache_size = true;
641 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
85de8323
LL
642
643 return params;
644}
645
f6844b99
DDAG
646/*
647 * Return true if we're already in the middle of a migration
648 * (i.e. any of the active or setup states)
649 */
650static bool migration_is_setup_or_active(int state)
651{
652 switch (state) {
653 case MIGRATION_STATUS_ACTIVE:
9ec055ae 654 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
a688d2c1 655 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 656 case MIGRATION_STATUS_POSTCOPY_RECOVER:
f6844b99 657 case MIGRATION_STATUS_SETUP:
31e06077
DDAG
658 case MIGRATION_STATUS_PRE_SWITCHOVER:
659 case MIGRATION_STATUS_DEVICE:
f6844b99
DDAG
660 return true;
661
662 default:
663 return false;
664
665 }
666}
667
a22463a5
DDAG
668static void populate_ram_info(MigrationInfo *info, MigrationState *s)
669{
670 info->has_ram = true;
671 info->ram = g_malloc0(sizeof(*info->ram));
9360447d 672 info->ram->transferred = ram_counters.transferred;
a22463a5 673 info->ram->total = ram_bytes_total();
9360447d 674 info->ram->duplicate = ram_counters.duplicate;
bedf53c1
JQ
675 /* legacy value. It is not used anymore */
676 info->ram->skipped = 0;
9360447d
JQ
677 info->ram->normal = ram_counters.normal;
678 info->ram->normal_bytes = ram_counters.normal *
20afaed9 679 qemu_target_page_size();
a22463a5 680 info->ram->mbps = s->mbps;
9360447d
JQ
681 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
682 info->ram->postcopy_requests = ram_counters.postcopy_requests;
030ce1f8 683 info->ram->page_size = qemu_target_page_size();
a22463a5 684
114f5aee
JQ
685 if (migrate_use_xbzrle()) {
686 info->has_xbzrle_cache = true;
687 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
688 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
9360447d
JQ
689 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
690 info->xbzrle_cache->pages = xbzrle_counters.pages;
691 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
692 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
693 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
114f5aee
JQ
694 }
695
338182c8
JQ
696 if (cpu_throttle_active()) {
697 info->has_cpu_throttle_percentage = true;
698 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
699 }
700
a22463a5
DDAG
701 if (s->state != MIGRATION_STATUS_COMPLETED) {
702 info->ram->remaining = ram_bytes_remaining();
9360447d 703 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
a22463a5
DDAG
704 }
705}
706
930ac04c
JQ
707static void populate_disk_info(MigrationInfo *info)
708{
709 if (blk_mig_active()) {
710 info->has_disk = true;
711 info->disk = g_malloc0(sizeof(*info->disk));
712 info->disk->transferred = blk_mig_bytes_transferred();
713 info->disk->remaining = blk_mig_bytes_remaining();
714 info->disk->total = blk_mig_bytes_total();
715 }
716}
717
65ace060 718static void fill_source_migration_info(MigrationInfo *info)
5bb7910a 719{
17549e84
JQ
720 MigrationState *s = migrate_get_current();
721
722 switch (s->state) {
31194731 723 case MIGRATION_STATUS_NONE:
17549e84 724 /* no migration has happened ever */
65ace060
AP
725 /* do not overwrite destination migration status */
726 return;
17549e84 727 break;
31194731 728 case MIGRATION_STATUS_SETUP:
29ae8a41 729 info->has_status = true;
ed4fbd10 730 info->has_total_time = false;
29ae8a41 731 break;
31194731
HZ
732 case MIGRATION_STATUS_ACTIVE:
733 case MIGRATION_STATUS_CANCELLING:
9ec055ae 734 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
31e06077
DDAG
735 case MIGRATION_STATUS_PRE_SWITCHOVER:
736 case MIGRATION_STATUS_DEVICE:
a688d2c1 737 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 738 case MIGRATION_STATUS_POSTCOPY_RECOVER:
c8f9f4f4 739 /* TODO add some postcopy stats */
9ec055ae
DDAG
740 info->has_status = true;
741 info->has_total_time = true;
742 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
4af246a3 743 - s->start_time;
9ec055ae
DDAG
744 info->has_expected_downtime = true;
745 info->expected_downtime = s->expected_downtime;
746 info->has_setup_time = true;
747 info->setup_time = s->setup_time;
748
a22463a5 749 populate_ram_info(info, s);
930ac04c 750 populate_disk_info(info);
17549e84 751 break;
0b827d5e
HZ
752 case MIGRATION_STATUS_COLO:
753 info->has_status = true;
754 /* TODO: display COLO specific information (checkpoint info etc.) */
755 break;
31194731 756 case MIGRATION_STATUS_COMPLETED:
791e7c82 757 info->has_status = true;
00c14997 758 info->has_total_time = true;
7aa939af 759 info->total_time = s->total_time;
9c5a9fcf
JQ
760 info->has_downtime = true;
761 info->downtime = s->downtime;
ed4fbd10
MH
762 info->has_setup_time = true;
763 info->setup_time = s->setup_time;
d5f8a570 764
a22463a5 765 populate_ram_info(info, s);
17549e84 766 break;
31194731 767 case MIGRATION_STATUS_FAILED:
791e7c82 768 info->has_status = true;
d59ce6f3
DB
769 if (s->error) {
770 info->has_error_desc = true;
771 info->error_desc = g_strdup(error_get_pretty(s->error));
772 }
17549e84 773 break;
31194731 774 case MIGRATION_STATUS_CANCELLED:
791e7c82 775 info->has_status = true;
17549e84 776 break;
5bb7910a 777 }
cde63fbe 778 info->status = s->state;
5bb7910a
AL
779}
780
4a84214e
PX
781/**
782 * @migration_caps_check - check capability validity
783 *
784 * @cap_list: old capability list, array of bool
785 * @params: new capabilities to be applied soon
786 * @errp: set *errp if the check failed, with reason
787 *
788 * Returns true if check passed, otherwise false.
789 */
790static bool migrate_caps_check(bool *cap_list,
791 MigrationCapabilityStatusList *params,
792 Error **errp)
00458433 793{
00458433 794 MigrationCapabilityStatusList *cap;
4a84214e 795 bool old_postcopy_cap;
d7651f15 796 MigrationIncomingState *mis = migration_incoming_get_current();
00458433 797
4a84214e 798 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
00458433
OW
799
800 for (cap = params; cap; cap = cap->next) {
4a84214e
PX
801 cap_list[cap->value->capability] = cap->value->state;
802 }
803
ed1701c6 804#ifndef CONFIG_LIVE_BLOCK_MIGRATION
4a84214e
PX
805 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
806 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
807 "block migration");
808 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
809 return false;
00458433 810 }
4a84214e 811#endif
53dd370c 812
4a84214e
PX
813 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
814 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
53dd370c
DDAG
815 /* The decompression threads asynchronously write into RAM
816 * rather than use the atomic copies needed to avoid
817 * userfaulting. It should be possible to fix the decompression
818 * threads for compatibility in future.
819 */
4a84214e
PX
820 error_setg(errp, "Postcopy is not currently compatible "
821 "with compression");
822 return false;
53dd370c 823 }
4a84214e 824
096631bd
DDAG
825 /* This check is reasonably expensive, so only when it's being
826 * set the first time, also it's only the destination that needs
827 * special support.
828 */
829 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
d7651f15 830 !postcopy_ram_supported_by_host(mis)) {
096631bd
DDAG
831 /* postcopy_ram_supported_by_host will have emitted a more
832 * detailed message
833 */
4a84214e
PX
834 error_setg(errp, "Postcopy is not supported");
835 return false;
096631bd 836 }
53dd370c 837 }
4a84214e
PX
838
839 return true;
840}
841
65ace060
AP
842static void fill_destination_migration_info(MigrationInfo *info)
843{
844 MigrationIncomingState *mis = migration_incoming_get_current();
845
846 switch (mis->state) {
847 case MIGRATION_STATUS_NONE:
848 return;
849 break;
850 case MIGRATION_STATUS_SETUP:
851 case MIGRATION_STATUS_CANCELLING:
852 case MIGRATION_STATUS_CANCELLED:
853 case MIGRATION_STATUS_ACTIVE:
854 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
855 case MIGRATION_STATUS_FAILED:
856 case MIGRATION_STATUS_COLO:
857 info->has_status = true;
858 break;
859 case MIGRATION_STATUS_COMPLETED:
860 info->has_status = true;
861 fill_destination_postcopy_migration_info(info);
862 break;
863 }
864 info->status = mis->state;
865}
866
867MigrationInfo *qmp_query_migrate(Error **errp)
868{
869 MigrationInfo *info = g_malloc0(sizeof(*info));
870
871 fill_destination_migration_info(info);
872 fill_source_migration_info(info);
873
874 return info;
875}
876
4a84214e
PX
877void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
878 Error **errp)
879{
880 MigrationState *s = migrate_get_current();
881 MigrationCapabilityStatusList *cap;
dd0ee30c 882 bool cap_list[MIGRATION_CAPABILITY__MAX];
4a84214e
PX
883
884 if (migration_is_setup_or_active(s->state)) {
885 error_setg(errp, QERR_MIGRATION_ACTIVE);
886 return;
887 }
888
dd0ee30c
PX
889 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
890 if (!migrate_caps_check(cap_list, params, errp)) {
4a84214e
PX
891 return;
892 }
893
894 for (cap = params; cap; cap = cap->next) {
895 s->enabled_capabilities[cap->value->capability] = cap->value->state;
896 }
00458433
OW
897}
898
16d063bc
PX
899/*
900 * Check whether the parameters are valid. Error will be put into errp
901 * (if provided). Return true if valid, otherwise false.
902 */
903static bool migrate_params_check(MigrationParameters *params, Error **errp)
85de8323 904{
7f375e04 905 if (params->has_compress_level &&
741d4086 906 (params->compress_level > 9)) {
c6bd8c70
MA
907 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
908 "is invalid, it should be in the range of 0 to 9");
16d063bc 909 return false;
85de8323 910 }
16d063bc 911
741d4086 912 if (params->has_compress_threads && (params->compress_threads < 1)) {
c6bd8c70
MA
913 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
914 "compress_threads",
915 "is invalid, it should be in the range of 1 to 255");
16d063bc 916 return false;
85de8323 917 }
16d063bc 918
741d4086 919 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
c6bd8c70
MA
920 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
921 "decompress_threads",
922 "is invalid, it should be in the range of 1 to 255");
16d063bc 923 return false;
85de8323 924 }
16d063bc 925
7f375e04
EB
926 if (params->has_cpu_throttle_initial &&
927 (params->cpu_throttle_initial < 1 ||
928 params->cpu_throttle_initial > 99)) {
1626fee3 929 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 930 "cpu_throttle_initial",
1626fee3 931 "an integer in the range of 1 to 99");
16d063bc 932 return false;
1626fee3 933 }
16d063bc 934
7f375e04
EB
935 if (params->has_cpu_throttle_increment &&
936 (params->cpu_throttle_increment < 1 ||
937 params->cpu_throttle_increment > 99)) {
1626fee3 938 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 939 "cpu_throttle_increment",
1626fee3 940 "an integer in the range of 1 to 99");
16d063bc 941 return false;
1626fee3 942 }
16d063bc 943
741d4086 944 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
2ff30257
AA
945 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
946 " range of 0 to %zu bytes/second", SIZE_MAX);
16d063bc 947 return false;
2ff30257 948 }
16d063bc 949
2ff30257 950 if (params->has_downtime_limit &&
741d4086 951 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
87c9cc1c
DHB
952 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
953 "the range of 0 to %d milliseconds",
954 MAX_MIGRATE_DOWNTIME);
16d063bc 955 return false;
2ff30257 956 }
16d063bc 957
741d4086
JQ
958 /* x_checkpoint_delay is now always positive */
959
960 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
4075fb1c
JQ
961 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
962 "multifd_channels",
963 "is invalid, it should be in the range of 1 to 255");
964 return false;
965 }
0fb86605 966 if (params->has_x_multifd_page_count &&
741d4086
JQ
967 (params->x_multifd_page_count < 1 ||
968 params->x_multifd_page_count > 10000)) {
0fb86605
JQ
969 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
970 "multifd_page_count",
971 "is invalid, it should be in the range of 1 to 10000");
972 return false;
973 }
16d063bc 974
73af8dd8
JQ
975 if (params->has_xbzrle_cache_size &&
976 (params->xbzrle_cache_size < qemu_target_page_size() ||
977 !is_power_of_2(params->xbzrle_cache_size))) {
978 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
979 "xbzrle_cache_size",
980 "is invalid, it should be bigger than target page size"
981 " and a power of two");
982 return false;
983 }
984
16d063bc
PX
985 return true;
986}
987
1bda8b3c
MA
988static void migrate_params_test_apply(MigrateSetParameters *params,
989 MigrationParameters *dest)
990{
991 *dest = migrate_get_current()->parameters;
992
993 /* TODO use QAPI_CLONE() instead of duplicating it inline */
994
995 if (params->has_compress_level) {
996 dest->compress_level = params->compress_level;
997 }
998
999 if (params->has_compress_threads) {
1000 dest->compress_threads = params->compress_threads;
1001 }
1002
1003 if (params->has_decompress_threads) {
1004 dest->decompress_threads = params->decompress_threads;
1005 }
1006
1007 if (params->has_cpu_throttle_initial) {
1008 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1009 }
1010
1011 if (params->has_cpu_throttle_increment) {
1012 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1013 }
1014
1015 if (params->has_tls_creds) {
01fa5598
MA
1016 assert(params->tls_creds->type == QTYPE_QSTRING);
1017 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1bda8b3c
MA
1018 }
1019
1020 if (params->has_tls_hostname) {
01fa5598
MA
1021 assert(params->tls_hostname->type == QTYPE_QSTRING);
1022 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1bda8b3c
MA
1023 }
1024
1025 if (params->has_max_bandwidth) {
1026 dest->max_bandwidth = params->max_bandwidth;
1027 }
1028
1029 if (params->has_downtime_limit) {
1030 dest->downtime_limit = params->downtime_limit;
1031 }
1032
1033 if (params->has_x_checkpoint_delay) {
1034 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1035 }
1036
1037 if (params->has_block_incremental) {
1038 dest->block_incremental = params->block_incremental;
1039 }
5e7577a1
JQ
1040 if (params->has_x_multifd_channels) {
1041 dest->x_multifd_channels = params->x_multifd_channels;
1042 }
1043 if (params->has_x_multifd_page_count) {
1044 dest->x_multifd_page_count = params->x_multifd_page_count;
1045 }
73af8dd8
JQ
1046 if (params->has_xbzrle_cache_size) {
1047 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1048 }
1bda8b3c
MA
1049}
1050
73af8dd8 1051static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
16d063bc
PX
1052{
1053 MigrationState *s = migrate_get_current();
1054
e87fae4c
MA
1055 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1056
7f375e04
EB
1057 if (params->has_compress_level) {
1058 s->parameters.compress_level = params->compress_level;
85de8323 1059 }
476c72aa 1060
7f375e04
EB
1061 if (params->has_compress_threads) {
1062 s->parameters.compress_threads = params->compress_threads;
85de8323 1063 }
476c72aa 1064
7f375e04
EB
1065 if (params->has_decompress_threads) {
1066 s->parameters.decompress_threads = params->decompress_threads;
85de8323 1067 }
476c72aa 1068
7f375e04
EB
1069 if (params->has_cpu_throttle_initial) {
1070 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1626fee3 1071 }
476c72aa 1072
7f375e04
EB
1073 if (params->has_cpu_throttle_increment) {
1074 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1626fee3 1075 }
476c72aa 1076
7f375e04 1077 if (params->has_tls_creds) {
69ef1f36 1078 g_free(s->parameters.tls_creds);
01fa5598
MA
1079 assert(params->tls_creds->type == QTYPE_QSTRING);
1080 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
69ef1f36 1081 }
476c72aa 1082
7f375e04 1083 if (params->has_tls_hostname) {
69ef1f36 1084 g_free(s->parameters.tls_hostname);
01fa5598
MA
1085 assert(params->tls_hostname->type == QTYPE_QSTRING);
1086 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
69ef1f36 1087 }
476c72aa 1088
2ff30257
AA
1089 if (params->has_max_bandwidth) {
1090 s->parameters.max_bandwidth = params->max_bandwidth;
1091 if (s->to_dst_file) {
1092 qemu_file_set_rate_limit(s->to_dst_file,
1093 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1094 }
1095 }
476c72aa 1096
2ff30257
AA
1097 if (params->has_downtime_limit) {
1098 s->parameters.downtime_limit = params->downtime_limit;
1099 }
68b53591
HZ
1100
1101 if (params->has_x_checkpoint_delay) {
1102 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
479125d5
HZ
1103 if (migration_in_colo_state()) {
1104 colo_checkpoint_notify(s);
1105 }
68b53591 1106 }
476c72aa 1107
2833c59b
JQ
1108 if (params->has_block_incremental) {
1109 s->parameters.block_incremental = params->block_incremental;
1110 }
4075fb1c
JQ
1111 if (params->has_x_multifd_channels) {
1112 s->parameters.x_multifd_channels = params->x_multifd_channels;
1113 }
0fb86605
JQ
1114 if (params->has_x_multifd_page_count) {
1115 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
1116 }
73af8dd8
JQ
1117 if (params->has_xbzrle_cache_size) {
1118 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1119 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1120 }
85de8323
LL
1121}
1122
1bda8b3c 1123void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
476c72aa 1124{
1bda8b3c
MA
1125 MigrationParameters tmp;
1126
01fa5598
MA
1127 /* TODO Rewrite "" to null instead */
1128 if (params->has_tls_creds
1129 && params->tls_creds->type == QTYPE_QNULL) {
cb3e7f08 1130 qobject_unref(params->tls_creds->u.n);
01fa5598
MA
1131 params->tls_creds->type = QTYPE_QSTRING;
1132 params->tls_creds->u.s = strdup("");
1133 }
1134 /* TODO Rewrite "" to null instead */
1135 if (params->has_tls_hostname
1136 && params->tls_hostname->type == QTYPE_QNULL) {
cb3e7f08 1137 qobject_unref(params->tls_hostname->u.n);
01fa5598
MA
1138 params->tls_hostname->type = QTYPE_QSTRING;
1139 params->tls_hostname->u.s = strdup("");
1140 }
1141
1bda8b3c
MA
1142 migrate_params_test_apply(params, &tmp);
1143
1144 if (!migrate_params_check(&tmp, errp)) {
476c72aa
PX
1145 /* Invalid parameter */
1146 return;
1147 }
1148
73af8dd8 1149 migrate_params_apply(params, errp);
476c72aa
PX
1150}
1151
2594f56d 1152
4886a1bc
DDAG
1153void qmp_migrate_start_postcopy(Error **errp)
1154{
1155 MigrationState *s = migrate_get_current();
1156
16b0fd32 1157 if (!migrate_postcopy()) {
a54d340b 1158 error_setg(errp, "Enable postcopy with migrate_set_capability before"
4886a1bc
DDAG
1159 " the start of migration");
1160 return;
1161 }
1162
1163 if (s->state == MIGRATION_STATUS_NONE) {
1164 error_setg(errp, "Postcopy must be started after migration has been"
1165 " started");
1166 return;
1167 }
1168 /*
1169 * we don't error if migration has finished since that would be racy
1170 * with issuing this command.
1171 */
1172 atomic_set(&s->start_postcopy, true);
1173}
1174
065e2813
AL
1175/* shared migration helpers */
1176
48781e5b 1177void migrate_set_state(int *state, int old_state, int new_state)
51cf4c1a 1178{
a31fedee 1179 assert(new_state < MIGRATION_STATUS__MAX);
48781e5b 1180 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
a31fedee 1181 trace_migrate_set_state(MigrationStatus_str(new_state));
b05dc723 1182 migrate_generate_event(new_state);
51cf4c1a
Z
1183 }
1184}
1185
4e4a3d3a
PX
1186static MigrationCapabilityStatusList *migrate_cap_add(
1187 MigrationCapabilityStatusList *list,
1188 MigrationCapability index,
1189 bool state)
2833c59b
JQ
1190{
1191 MigrationCapabilityStatusList *cap;
1192
1193 cap = g_new0(MigrationCapabilityStatusList, 1);
1194 cap->value = g_new0(MigrationCapabilityStatus, 1);
4e4a3d3a
PX
1195 cap->value->capability = index;
1196 cap->value->state = state;
1197 cap->next = list;
1198
1199 return cap;
1200}
1201
1202void migrate_set_block_enabled(bool value, Error **errp)
1203{
1204 MigrationCapabilityStatusList *cap;
1205
1206 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
2833c59b
JQ
1207 qmp_migrate_set_capabilities(cap, errp);
1208 qapi_free_MigrationCapabilityStatusList(cap);
1209}
1210
1211static void migrate_set_block_incremental(MigrationState *s, bool value)
1212{
1213 s->parameters.block_incremental = value;
1214}
1215
1216static void block_cleanup_parameters(MigrationState *s)
1217{
1218 if (s->must_remove_block_options) {
1219 /* setting to false can never fail */
1220 migrate_set_block_enabled(false, &error_abort);
1221 migrate_set_block_incremental(s, false);
1222 s->must_remove_block_options = false;
1223 }
1224}
1225
bb1fadc4 1226static void migrate_fd_cleanup(void *opaque)
065e2813 1227{
bb1fadc4
PB
1228 MigrationState *s = opaque;
1229
1230 qemu_bh_delete(s->cleanup_bh);
1231 s->cleanup_bh = NULL;
1232
0ceccd85
PX
1233 qemu_savevm_state_cleanup();
1234
89a02a9f 1235 if (s->to_dst_file) {
f986c3d2
JQ
1236 Error *local_err = NULL;
1237
9013dca5 1238 trace_migrate_fd_cleanup();
404a7c05 1239 qemu_mutex_unlock_iothread();
1d34e4bf
DDAG
1240 if (s->migration_thread_running) {
1241 qemu_thread_join(&s->thread);
1242 s->migration_thread_running = false;
1243 }
404a7c05
PB
1244 qemu_mutex_lock_iothread();
1245
f986c3d2
JQ
1246 if (multifd_save_cleanup(&local_err) != 0) {
1247 error_report_err(local_err);
1248 }
89a02a9f
HZ
1249 qemu_fclose(s->to_dst_file);
1250 s->to_dst_file = NULL;
065e2813
AL
1251 }
1252
9ec055ae
DDAG
1253 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1254 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
7a2c1721 1255
94f5a437 1256 if (s->state == MIGRATION_STATUS_CANCELLING) {
48781e5b 1257 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
94f5a437 1258 MIGRATION_STATUS_CANCELLED);
7a2c1721 1259 }
a3fa1d78 1260
87db1a7d
JQ
1261 if (s->error) {
1262 /* It is used on info migrate. We can't free it */
1263 error_report_err(error_copy(s->error));
1264 }
a3fa1d78 1265 notifier_list_notify(&migration_state_notifiers, s);
2833c59b 1266 block_cleanup_parameters(s);
065e2813
AL
1267}
1268
87db1a7d
JQ
1269void migrate_set_error(MigrationState *s, const Error *error)
1270{
1271 qemu_mutex_lock(&s->error_mutex);
1272 if (!s->error) {
1273 s->error = error_copy(error);
1274 }
1275 qemu_mutex_unlock(&s->error_mutex);
1276}
1277
d59ce6f3 1278void migrate_fd_error(MigrationState *s, const Error *error)
065e2813 1279{
25174055 1280 trace_migrate_fd_error(error_get_pretty(error));
89a02a9f 1281 assert(s->to_dst_file == NULL);
48781e5b
HZ
1282 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1283 MIGRATION_STATUS_FAILED);
87db1a7d 1284 migrate_set_error(s, error);
458cf28e
JQ
1285}
1286
0edda1c4 1287static void migrate_fd_cancel(MigrationState *s)
065e2813 1288{
6f2b811a 1289 int old_state ;
89a02a9f 1290 QEMUFile *f = migrate_get_current()->to_dst_file;
9013dca5 1291 trace_migrate_fd_cancel();
065e2813 1292
70b20477
DDAG
1293 if (s->rp_state.from_dst_file) {
1294 /* shutdown the rp socket, so causing the rp thread to shutdown */
1295 qemu_file_shutdown(s->rp_state.from_dst_file);
1296 }
1297
6f2b811a
Z
1298 do {
1299 old_state = s->state;
f6844b99 1300 if (!migration_is_setup_or_active(old_state)) {
6f2b811a
Z
1301 break;
1302 }
a7b36b48
DDAG
1303 /* If the migration is paused, kick it out of the pause */
1304 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1305 qemu_sem_post(&s->pause_sem);
1306 }
48781e5b 1307 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
31194731 1308 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
1309
1310 /*
1311 * If we're unlucky the migration code might be stuck somewhere in a
1312 * send/write while the network has failed and is waiting to timeout;
1313 * if we've got shutdown(2) available then we can force it to quit.
1314 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1315 * called in a bh, so there is no race against this cancel.
1316 */
31194731 1317 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
a26ba26e
DDAG
1318 qemu_file_shutdown(f);
1319 }
1d2acc31
HZ
1320 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1321 Error *local_err = NULL;
1322
1323 bdrv_invalidate_cache_all(&local_err);
1324 if (local_err) {
1325 error_report_err(local_err);
1326 } else {
1327 s->block_inactive = false;
1328 }
1329 }
065e2813
AL
1330}
1331
99a0db9b
GH
1332void add_migration_state_change_notifier(Notifier *notify)
1333{
1334 notifier_list_add(&migration_state_notifiers, notify);
1335}
1336
1337void remove_migration_state_change_notifier(Notifier *notify)
1338{
31552529 1339 notifier_remove(notify);
99a0db9b
GH
1340}
1341
02edd2e7 1342bool migration_in_setup(MigrationState *s)
afe2df69 1343{
31194731 1344 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
1345}
1346
7073693b 1347bool migration_has_finished(MigrationState *s)
99a0db9b 1348{
31194731 1349 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 1350}
0edda1c4 1351
afe2df69
GH
1352bool migration_has_failed(MigrationState *s)
1353{
31194731
HZ
1354 return (s->state == MIGRATION_STATUS_CANCELLED ||
1355 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
1356}
1357
5727309d 1358bool migration_in_postcopy(void)
9ec055ae 1359{
5727309d
JQ
1360 MigrationState *s = migrate_get_current();
1361
9ec055ae
DDAG
1362 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1363}
1364
b82fc321
DDAG
1365bool migration_in_postcopy_after_devices(MigrationState *s)
1366{
5727309d 1367 return migration_in_postcopy() && s->postcopy_after_devices;
b82fc321
DDAG
1368}
1369
fab35005 1370bool migration_is_idle(void)
fe44dc91 1371{
fab35005 1372 MigrationState *s = migrate_get_current();
fe44dc91
AA
1373
1374 switch (s->state) {
1375 case MIGRATION_STATUS_NONE:
1376 case MIGRATION_STATUS_CANCELLED:
1377 case MIGRATION_STATUS_COMPLETED:
1378 case MIGRATION_STATUS_FAILED:
1379 return true;
1380 case MIGRATION_STATUS_SETUP:
1381 case MIGRATION_STATUS_CANCELLING:
1382 case MIGRATION_STATUS_ACTIVE:
1383 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1384 case MIGRATION_STATUS_COLO:
31e06077
DDAG
1385 case MIGRATION_STATUS_PRE_SWITCHOVER:
1386 case MIGRATION_STATUS_DEVICE:
fe44dc91
AA
1387 return false;
1388 case MIGRATION_STATUS__MAX:
1389 g_assert_not_reached();
1390 }
1391
1392 return false;
1393}
1394
3e0c8050 1395void migrate_init(MigrationState *s)
0edda1c4 1396{
389775d1
DDAG
1397 /*
1398 * Reinitialise all migration state, except
1399 * parameters/capabilities that the user set, and
1400 * locks.
1401 */
1402 s->bytes_xfer = 0;
1403 s->xfer_limit = 0;
1404 s->cleanup_bh = 0;
89a02a9f 1405 s->to_dst_file = NULL;
389775d1 1406 s->state = MIGRATION_STATUS_NONE;
389775d1
DDAG
1407 s->rp_state.from_dst_file = NULL;
1408 s->rp_state.error = false;
1409 s->mbps = 0.0;
1410 s->downtime = 0;
1411 s->expected_downtime = 0;
389775d1 1412 s->setup_time = 0;
389775d1 1413 s->start_postcopy = false;
b82fc321 1414 s->postcopy_after_devices = false;
389775d1 1415 s->migration_thread_running = false;
d59ce6f3
DB
1416 error_free(s->error);
1417 s->error = NULL;
389775d1 1418
48781e5b 1419 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 1420
4af246a3
PX
1421 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1422 s->total_time = 0;
7287cbd4 1423 s->vm_was_running = false;
b15df1ae
PX
1424 s->iteration_initial_bytes = 0;
1425 s->threshold_size = 0;
0edda1c4 1426}
cab30143 1427
fa2756b7
AL
1428static GSList *migration_blockers;
1429
fe44dc91 1430int migrate_add_blocker(Error *reason, Error **errp)
fa2756b7 1431{
3df663e5 1432 if (migrate_get_current()->only_migratable) {
b67b8c3a
AA
1433 error_propagate(errp, error_copy(reason));
1434 error_prepend(errp, "disallowing migration blocker "
1435 "(--only_migratable) for: ");
1436 return -EACCES;
1437 }
1438
fab35005 1439 if (migration_is_idle()) {
fe44dc91
AA
1440 migration_blockers = g_slist_prepend(migration_blockers, reason);
1441 return 0;
1442 }
1443
1444 error_propagate(errp, error_copy(reason));
1445 error_prepend(errp, "disallowing migration blocker (migration in "
1446 "progress) for: ");
1447 return -EBUSY;
fa2756b7
AL
1448}
1449
1450void migrate_del_blocker(Error *reason)
1451{
1452 migration_blockers = g_slist_remove(migration_blockers, reason);
1453}
1454
bf1ae1f4
DDAG
1455void qmp_migrate_incoming(const char *uri, Error **errp)
1456{
1457 Error *local_err = NULL;
4debb5f5 1458 static bool once = true;
bf1ae1f4
DDAG
1459
1460 if (!deferred_incoming) {
4debb5f5 1461 error_setg(errp, "For use with '-incoming defer'");
bf1ae1f4
DDAG
1462 return;
1463 }
4debb5f5
DDAG
1464 if (!once) {
1465 error_setg(errp, "The incoming migration has already been started");
1466 }
bf1ae1f4
DDAG
1467
1468 qemu_start_incoming_migration(uri, &local_err);
1469
1470 if (local_err) {
1471 error_propagate(errp, local_err);
1472 return;
1473 }
1474
4debb5f5 1475 once = false;
bf1ae1f4
DDAG
1476}
1477
02affd41
PX
1478void qmp_migrate_recover(const char *uri, Error **errp)
1479{
1480 MigrationIncomingState *mis = migration_incoming_get_current();
1481
1482 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1483 error_setg(errp, "Migrate recover can only be run "
1484 "when postcopy is paused.");
1485 return;
1486 }
1487
1488 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1489 false, true) == true) {
1490 error_setg(errp, "Migrate recovery is triggered already");
1491 return;
1492 }
1493
1494 /*
1495 * Note that this call will never start a real migration; it will
1496 * only re-setup the migration stream and poke existing migration
1497 * to continue using that newly established channel.
1498 */
1499 qemu_start_incoming_migration(uri, errp);
1500}
1501
24f3902b
GK
1502bool migration_is_blocked(Error **errp)
1503{
1504 if (qemu_savevm_state_blocked(errp)) {
1505 return true;
1506 }
1507
1508 if (migration_blockers) {
250561e1 1509 error_propagate(errp, error_copy(migration_blockers->data));
24f3902b
GK
1510 return true;
1511 }
1512
1513 return false;
1514}
1515
d3e35b8f
PX
1516/* Returns true if continue to migrate, or false if error detected */
1517static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1518 bool resume, Error **errp)
cab30143 1519{
be7059cd 1520 Error *local_err = NULL;
d3e35b8f
PX
1521
1522 if (resume) {
1523 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1524 error_setg(errp, "Cannot resume if there is no "
1525 "paused migration");
1526 return false;
1527 }
1528 /* This is a resume, skip init status */
1529 return true;
1530 }
cab30143 1531
f6844b99 1532 if (migration_is_setup_or_active(s->state) ||
0b827d5e
HZ
1533 s->state == MIGRATION_STATUS_CANCELLING ||
1534 s->state == MIGRATION_STATUS_COLO) {
c6bd8c70 1535 error_setg(errp, QERR_MIGRATION_ACTIVE);
d3e35b8f 1536 return false;
cab30143 1537 }
d3e35b8f 1538
ca99993a
DDAG
1539 if (runstate_check(RUN_STATE_INMIGRATE)) {
1540 error_setg(errp, "Guest is waiting for an incoming migration");
d3e35b8f 1541 return false;
ca99993a
DDAG
1542 }
1543
24f3902b 1544 if (migration_is_blocked(errp)) {
d3e35b8f 1545 return false;
fa2756b7
AL
1546 }
1547
d3e35b8f 1548 if (blk || blk_inc) {
2833c59b
JQ
1549 if (migrate_use_block() || migrate_use_block_incremental()) {
1550 error_setg(errp, "Command options are incompatible with "
1551 "current migration capabilities");
d3e35b8f 1552 return false;
2833c59b
JQ
1553 }
1554 migrate_set_block_enabled(true, &local_err);
1555 if (local_err) {
1556 error_propagate(errp, local_err);
d3e35b8f 1557 return false;
2833c59b
JQ
1558 }
1559 s->must_remove_block_options = true;
1560 }
1561
d3e35b8f 1562 if (blk_inc) {
2833c59b
JQ
1563 migrate_set_block_incremental(s, true);
1564 }
1565
3e0c8050 1566 migrate_init(s);
cab30143 1567
d3e35b8f
PX
1568 return true;
1569}
1570
1571void qmp_migrate(const char *uri, bool has_blk, bool blk,
1572 bool has_inc, bool inc, bool has_detach, bool detach,
1573 bool has_resume, bool resume, Error **errp)
1574{
1575 Error *local_err = NULL;
1576 MigrationState *s = migrate_get_current();
1577 const char *p;
1578
1579 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1580 has_resume && resume, errp)) {
1581 /* Error detected, put into errp */
1582 return;
1583 }
1584
cab30143 1585 if (strstart(uri, "tcp:", &p)) {
f37afb5a 1586 tcp_start_outgoing_migration(s, p, &local_err);
2da776db 1587#ifdef CONFIG_RDMA
41310c68 1588 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
1589 rdma_start_outgoing_migration(s, p, &local_err);
1590#endif
cab30143 1591 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 1592 exec_start_outgoing_migration(s, p, &local_err);
cab30143 1593 } else if (strstart(uri, "unix:", &p)) {
f37afb5a 1594 unix_start_outgoing_migration(s, p, &local_err);
cab30143 1595 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 1596 fd_start_outgoing_migration(s, p, &local_err);
99a0db9b 1597 } else {
c6bd8c70
MA
1598 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1599 "a valid migration protocol");
48781e5b
HZ
1600 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1601 MIGRATION_STATUS_FAILED);
09576e74 1602 block_cleanup_parameters(s);
e1c37d0e 1603 return;
cab30143
JQ
1604 }
1605
f37afb5a 1606 if (local_err) {
d59ce6f3 1607 migrate_fd_error(s, local_err);
f37afb5a 1608 error_propagate(errp, local_err);
e1c37d0e 1609 return;
1299c631 1610 }
cab30143
JQ
1611}
1612
6cdedb07 1613void qmp_migrate_cancel(Error **errp)
cab30143 1614{
17549e84 1615 migrate_fd_cancel(migrate_get_current());
cab30143
JQ
1616}
1617
89cfc02c
DDAG
1618void qmp_migrate_continue(MigrationStatus state, Error **errp)
1619{
1620 MigrationState *s = migrate_get_current();
1621 if (s->state != state) {
1622 error_setg(errp, "Migration not in expected state: %s",
1623 MigrationStatus_str(s->state));
1624 return;
1625 }
1626 qemu_sem_post(&s->pause_sem);
1627}
1628
9e1ba4cc
OW
1629void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1630{
73af8dd8
JQ
1631 MigrateSetParameters p = {
1632 .has_xbzrle_cache_size = true,
1633 .xbzrle_cache_size = value,
1634 };
c91e681a 1635
73af8dd8 1636 qmp_migrate_set_parameters(&p, errp);
9e1ba4cc
OW
1637}
1638
1639int64_t qmp_query_migrate_cache_size(Error **errp)
1640{
1641 return migrate_xbzrle_cache_size();
1642}
1643
3dc85383 1644void qmp_migrate_set_speed(int64_t value, Error **errp)
cab30143 1645{
1bda8b3c 1646 MigrateSetParameters p = {
2ff30257
AA
1647 .has_max_bandwidth = true,
1648 .max_bandwidth = value,
1649 };
cab30143 1650
2ff30257 1651 qmp_migrate_set_parameters(&p, errp);
cab30143
JQ
1652}
1653
4f0a993b 1654void qmp_migrate_set_downtime(double value, Error **errp)
cab30143 1655{
87c9cc1c
DHB
1656 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1657 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1658 "the range of 0 to %d seconds",
1659 MAX_MIGRATE_DOWNTIME_SECONDS);
1660 return;
1661 }
1662
2ff30257
AA
1663 value *= 1000; /* Convert to milliseconds */
1664 value = MAX(0, MIN(INT64_MAX, value));
1665
1bda8b3c 1666 MigrateSetParameters p = {
2ff30257
AA
1667 .has_downtime_limit = true,
1668 .downtime_limit = value,
1669 };
1670
1671 qmp_migrate_set_parameters(&p, errp);
99a0db9b 1672}
17ad9b35 1673
53f09a10
PB
1674bool migrate_release_ram(void)
1675{
1676 MigrationState *s;
1677
1678 s = migrate_get_current();
1679
1680 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1681}
1682
53dd370c
DDAG
1683bool migrate_postcopy_ram(void)
1684{
1685 MigrationState *s;
1686
1687 s = migrate_get_current();
1688
32c3db5b 1689 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
53dd370c
DDAG
1690}
1691
58110f0a
VSO
1692bool migrate_postcopy(void)
1693{
dd6bb914 1694 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
58110f0a
VSO
1695}
1696
bde1e2ec
CV
1697bool migrate_auto_converge(void)
1698{
1699 MigrationState *s;
1700
1701 s = migrate_get_current();
1702
1703 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1704}
1705
323004a3
PL
1706bool migrate_zero_blocks(void)
1707{
1708 MigrationState *s;
1709
1710 s = migrate_get_current();
1711
1712 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1713}
1714
f22f928e
AP
1715bool migrate_postcopy_blocktime(void)
1716{
1717 MigrationState *s;
1718
1719 s = migrate_get_current();
1720
1721 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
1722}
1723
8706d2d5
LL
1724bool migrate_use_compression(void)
1725{
dde4e694
LL
1726 MigrationState *s;
1727
1728 s = migrate_get_current();
1729
1730 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
1731}
1732
1733int migrate_compress_level(void)
1734{
1735 MigrationState *s;
1736
1737 s = migrate_get_current();
1738
2594f56d 1739 return s->parameters.compress_level;
8706d2d5
LL
1740}
1741
1742int migrate_compress_threads(void)
1743{
1744 MigrationState *s;
1745
1746 s = migrate_get_current();
1747
2594f56d 1748 return s->parameters.compress_threads;
8706d2d5
LL
1749}
1750
3fcb38c2
LL
1751int migrate_decompress_threads(void)
1752{
1753 MigrationState *s;
1754
1755 s = migrate_get_current();
1756
2594f56d 1757 return s->parameters.decompress_threads;
3fcb38c2
LL
1758}
1759
55efc8c2
VSO
1760bool migrate_dirty_bitmaps(void)
1761{
1762 MigrationState *s;
1763
1764 s = migrate_get_current();
1765
1766 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1767}
1768
b05dc723
JQ
1769bool migrate_use_events(void)
1770{
1771 MigrationState *s;
1772
1773 s = migrate_get_current();
1774
1775 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1776}
1777
30126bbf
JQ
1778bool migrate_use_multifd(void)
1779{
1780 MigrationState *s;
1781
1782 s = migrate_get_current();
1783
1784 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1785}
1786
93fbd031
DDAG
1787bool migrate_pause_before_switchover(void)
1788{
1789 MigrationState *s;
1790
1791 s = migrate_get_current();
1792
1793 return s->enabled_capabilities[
1794 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1795}
1796
4075fb1c
JQ
1797int migrate_multifd_channels(void)
1798{
1799 MigrationState *s;
1800
1801 s = migrate_get_current();
1802
1803 return s->parameters.x_multifd_channels;
1804}
1805
0fb86605
JQ
1806int migrate_multifd_page_count(void)
1807{
1808 MigrationState *s;
1809
1810 s = migrate_get_current();
1811
1812 return s->parameters.x_multifd_page_count;
1813}
1814
17ad9b35
OW
1815int migrate_use_xbzrle(void)
1816{
1817 MigrationState *s;
1818
1819 s = migrate_get_current();
1820
1821 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1822}
1823
1824int64_t migrate_xbzrle_cache_size(void)
1825{
1826 MigrationState *s;
1827
1828 s = migrate_get_current();
1829
73af8dd8 1830 return s->parameters.xbzrle_cache_size;
17ad9b35 1831}
0d82d0e8 1832
2833c59b
JQ
1833bool migrate_use_block(void)
1834{
1835 MigrationState *s;
1836
1837 s = migrate_get_current();
1838
1839 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1840}
1841
c788ada8
PX
1842bool migrate_use_return_path(void)
1843{
1844 MigrationState *s;
1845
1846 s = migrate_get_current();
1847
1848 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
1849}
1850
2833c59b
JQ
1851bool migrate_use_block_incremental(void)
1852{
1853 MigrationState *s;
1854
1855 s = migrate_get_current();
1856
1857 return s->parameters.block_incremental;
1858}
1859
70b20477
DDAG
1860/* migration thread support */
1861/*
1862 * Something bad happened to the RP stream, mark an error
1863 * The caller shall print or trace something to indicate why
1864 */
1865static void mark_source_rp_bad(MigrationState *s)
1866{
1867 s->rp_state.error = true;
1868}
1869
1870static struct rp_cmd_args {
1871 ssize_t len; /* -1 = variable */
1872 const char *name;
1873} rp_cmd_args[] = {
1874 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1875 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1876 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1e2d90eb
DDAG
1877 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1878 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
a335debb 1879 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
13955b89 1880 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
70b20477
DDAG
1881 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1882};
1883
1e2d90eb
DDAG
1884/*
1885 * Process a request for pages received on the return path,
1886 * We're allowed to send more than requested (e.g. to round to our page size)
1887 * and we don't need to send pages that have already been sent.
1888 */
1889static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1890 ram_addr_t start, size_t len)
1891{
6c595cde
DDAG
1892 long our_host_ps = getpagesize();
1893
1e2d90eb 1894 trace_migrate_handle_rp_req_pages(rbname, start, len);
6c595cde
DDAG
1895
1896 /*
1897 * Since we currently insist on matching page sizes, just sanity check
1898 * we're being asked for whole host pages.
1899 */
1900 if (start & (our_host_ps-1) ||
1901 (len & (our_host_ps-1))) {
1902 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1903 " len: %zd", __func__, start, len);
1904 mark_source_rp_bad(ms);
1905 return;
1906 }
1907
96506894 1908 if (ram_save_queue_pages(rbname, start, len)) {
6c595cde
DDAG
1909 mark_source_rp_bad(ms);
1910 }
1e2d90eb
DDAG
1911}
1912
14b1742e
PX
1913/* Return true to retry, false to quit */
1914static bool postcopy_pause_return_path_thread(MigrationState *s)
1915{
1916 trace_postcopy_pause_return_path();
1917
1918 qemu_sem_wait(&s->postcopy_pause_rp_sem);
1919
1920 trace_postcopy_pause_return_path_continued();
1921
1922 return true;
1923}
1924
a335debb
PX
1925static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
1926{
1927 RAMBlock *block = qemu_ram_block_by_name(block_name);
1928
1929 if (!block) {
1930 error_report("%s: invalid block name '%s'", __func__, block_name);
1931 return -EINVAL;
1932 }
1933
1934 /* Fetch the received bitmap and refresh the dirty bitmap */
1935 return ram_dirty_bitmap_reload(s, block);
1936}
1937
13955b89
PX
1938static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
1939{
1940 trace_source_return_path_thread_resume_ack(value);
1941
1942 if (value != MIGRATION_RESUME_ACK_VALUE) {
1943 error_report("%s: illegal resume_ack value %"PRIu32,
1944 __func__, value);
1945 return -1;
1946 }
1947
1948 /* Now both sides are active. */
1949 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1950 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1951
94190696
PX
1952 /* Notify send thread that time to continue send pages */
1953 qemu_sem_post(&s->rp_state.rp_sem);
13955b89
PX
1954
1955 return 0;
1956}
1957
70b20477
DDAG
1958/*
1959 * Handles messages sent on the return path towards the source VM
1960 *
1961 */
1962static void *source_return_path_thread(void *opaque)
1963{
1964 MigrationState *ms = opaque;
1965 QEMUFile *rp = ms->rp_state.from_dst_file;
1966 uint16_t header_len, header_type;
568b01ca 1967 uint8_t buf[512];
70b20477 1968 uint32_t tmp32, sibling_error;
1e2d90eb
DDAG
1969 ram_addr_t start = 0; /* =0 to silence warning */
1970 size_t len = 0, expected_len;
70b20477
DDAG
1971 int res;
1972
1973 trace_source_return_path_thread_entry();
14b1742e
PX
1974
1975retry:
70b20477
DDAG
1976 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1977 migration_is_setup_or_active(ms->state)) {
1978 trace_source_return_path_thread_loop_top();
1979 header_type = qemu_get_be16(rp);
1980 header_len = qemu_get_be16(rp);
1981
7a9ddfbf
PX
1982 if (qemu_file_get_error(rp)) {
1983 mark_source_rp_bad(ms);
1984 goto out;
1985 }
1986
70b20477
DDAG
1987 if (header_type >= MIG_RP_MSG_MAX ||
1988 header_type == MIG_RP_MSG_INVALID) {
1989 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1990 header_type, header_len);
1991 mark_source_rp_bad(ms);
1992 goto out;
1993 }
1994
1995 if ((rp_cmd_args[header_type].len != -1 &&
1996 header_len != rp_cmd_args[header_type].len) ||
568b01ca 1997 header_len > sizeof(buf)) {
70b20477
DDAG
1998 error_report("RP: Received '%s' message (0x%04x) with"
1999 "incorrect length %d expecting %zu",
2000 rp_cmd_args[header_type].name, header_type, header_len,
2001 (size_t)rp_cmd_args[header_type].len);
2002 mark_source_rp_bad(ms);
2003 goto out;
2004 }
2005
2006 /* We know we've got a valid header by this point */
2007 res = qemu_get_buffer(rp, buf, header_len);
2008 if (res != header_len) {
2009 error_report("RP: Failed reading data for message 0x%04x"
2010 " read %d expected %d",
2011 header_type, res, header_len);
2012 mark_source_rp_bad(ms);
2013 goto out;
2014 }
2015
2016 /* OK, we have the message and the data */
2017 switch (header_type) {
2018 case MIG_RP_MSG_SHUT:
4d885131 2019 sibling_error = ldl_be_p(buf);
70b20477
DDAG
2020 trace_source_return_path_thread_shut(sibling_error);
2021 if (sibling_error) {
2022 error_report("RP: Sibling indicated error %d", sibling_error);
2023 mark_source_rp_bad(ms);
2024 }
2025 /*
2026 * We'll let the main thread deal with closing the RP
2027 * we could do a shutdown(2) on it, but we're the only user
2028 * anyway, so there's nothing gained.
2029 */
2030 goto out;
2031
2032 case MIG_RP_MSG_PONG:
4d885131 2033 tmp32 = ldl_be_p(buf);
70b20477
DDAG
2034 trace_source_return_path_thread_pong(tmp32);
2035 break;
2036
1e2d90eb 2037 case MIG_RP_MSG_REQ_PAGES:
4d885131
PM
2038 start = ldq_be_p(buf);
2039 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2040 migrate_handle_rp_req_pages(ms, NULL, start, len);
2041 break;
2042
2043 case MIG_RP_MSG_REQ_PAGES_ID:
2044 expected_len = 12 + 1; /* header + termination */
2045
2046 if (header_len >= expected_len) {
4d885131
PM
2047 start = ldq_be_p(buf);
2048 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2049 /* Now we expect an idstr */
2050 tmp32 = buf[12]; /* Length of the following idstr */
2051 buf[13 + tmp32] = '\0';
2052 expected_len += tmp32;
2053 }
2054 if (header_len != expected_len) {
2055 error_report("RP: Req_Page_id with length %d expecting %zd",
2056 header_len, expected_len);
2057 mark_source_rp_bad(ms);
2058 goto out;
2059 }
2060 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2061 break;
2062
a335debb
PX
2063 case MIG_RP_MSG_RECV_BITMAP:
2064 if (header_len < 1) {
2065 error_report("%s: missing block name", __func__);
2066 mark_source_rp_bad(ms);
2067 goto out;
2068 }
2069 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2070 buf[buf[0] + 1] = '\0';
2071 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2072 mark_source_rp_bad(ms);
2073 goto out;
2074 }
2075 break;
2076
13955b89
PX
2077 case MIG_RP_MSG_RESUME_ACK:
2078 tmp32 = ldl_be_p(buf);
2079 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2080 mark_source_rp_bad(ms);
2081 goto out;
2082 }
2083 break;
2084
70b20477
DDAG
2085 default:
2086 break;
2087 }
2088 }
14b1742e
PX
2089
2090out:
2091 res = qemu_file_get_error(rp);
2092 if (res) {
2093 if (res == -EIO) {
2094 /*
2095 * Maybe there is something we can do: it looks like a
2096 * network down issue, and we pause for a recovery.
2097 */
2098 if (postcopy_pause_return_path_thread(ms)) {
2099 /* Reload rp, reset the rest */
2100 rp = ms->rp_state.from_dst_file;
2101 ms->rp_state.error = false;
2102 goto retry;
2103 }
2104 }
2105
70b20477
DDAG
2106 trace_source_return_path_thread_bad_end();
2107 mark_source_rp_bad(ms);
2108 }
2109
2110 trace_source_return_path_thread_end();
70b20477
DDAG
2111 ms->rp_state.from_dst_file = NULL;
2112 qemu_fclose(rp);
2113 return NULL;
2114}
2115
d3e35b8f
PX
2116static int open_return_path_on_source(MigrationState *ms,
2117 bool create_thread)
70b20477
DDAG
2118{
2119
89a02a9f 2120 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
70b20477
DDAG
2121 if (!ms->rp_state.from_dst_file) {
2122 return -1;
2123 }
2124
2125 trace_open_return_path_on_source();
d3e35b8f
PX
2126
2127 if (!create_thread) {
2128 /* We're done */
2129 return 0;
2130 }
2131
70b20477
DDAG
2132 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2133 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2134
2135 trace_open_return_path_on_source_continue();
2136
2137 return 0;
2138}
2139
70b20477
DDAG
2140/* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2141static int await_return_path_close_on_source(MigrationState *ms)
2142{
2143 /*
2144 * If this is a normal exit then the destination will send a SHUT and the
2145 * rp_thread will exit, however if there's an error we need to cause
2146 * it to exit.
2147 */
89a02a9f 2148 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
70b20477
DDAG
2149 /*
2150 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2151 * waiting for the destination.
2152 */
2153 qemu_file_shutdown(ms->rp_state.from_dst_file);
2154 mark_source_rp_bad(ms);
2155 }
2156 trace_await_return_path_close_on_source_joining();
2157 qemu_thread_join(&ms->rp_state.rp_thread);
2158 trace_await_return_path_close_on_source_close();
2159 return ms->rp_state.error;
2160}
2161
1d34e4bf
DDAG
2162/*
2163 * Switch from normal iteration to postcopy
2164 * Returns non-0 on error
2165 */
7287cbd4 2166static int postcopy_start(MigrationState *ms)
1d34e4bf
DDAG
2167{
2168 int ret;
61b67d47
DB
2169 QIOChannelBuffer *bioc;
2170 QEMUFile *fb;
1d34e4bf 2171 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
ef8d6488 2172 bool restart_block = false;
0331c8ca
DDAG
2173 int cur_state = MIGRATION_STATUS_ACTIVE;
2174 if (!migrate_pause_before_switchover()) {
2175 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2176 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2177 }
1d34e4bf
DDAG
2178
2179 trace_postcopy_start();
2180 qemu_mutex_lock_iothread();
2181 trace_postcopy_start_set_run();
2182
2183 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1d34e4bf
DDAG
2184 global_state_store();
2185 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
76b1c7fe
KW
2186 if (ret < 0) {
2187 goto fail;
2188 }
1d34e4bf 2189
0331c8ca
DDAG
2190 ret = migration_maybe_pause(ms, &cur_state,
2191 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2192 if (ret < 0) {
2193 goto fail;
2194 }
2195
76b1c7fe 2196 ret = bdrv_inactivate_all();
1d34e4bf
DDAG
2197 if (ret < 0) {
2198 goto fail;
2199 }
ef8d6488 2200 restart_block = true;
1d34e4bf 2201
1c0d249d
DDAG
2202 /*
2203 * Cause any non-postcopiable, but iterative devices to
2204 * send out their final data.
2205 */
a1fbe750 2206 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1c0d249d 2207
1d34e4bf
DDAG
2208 /*
2209 * in Finish migrate and with the io-lock held everything should
2210 * be quiet, but we've potentially still got dirty pages and we
2211 * need to tell the destination to throw any pages it's already received
2212 * that are dirty
2213 */
58110f0a
VSO
2214 if (migrate_postcopy_ram()) {
2215 if (ram_postcopy_send_discard_bitmap(ms)) {
2216 error_report("postcopy send discard bitmap failed");
2217 goto fail;
2218 }
1d34e4bf
DDAG
2219 }
2220
2221 /*
2222 * send rest of state - note things that are doing postcopy
2223 * will notice we're in POSTCOPY_ACTIVE and not actually
2224 * wrap their state up here
2225 */
89a02a9f 2226 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
58110f0a
VSO
2227 if (migrate_postcopy_ram()) {
2228 /* Ping just for debugging, helps line traces up */
2229 qemu_savevm_send_ping(ms->to_dst_file, 2);
2230 }
1d34e4bf
DDAG
2231
2232 /*
2233 * While loading the device state we may trigger page transfer
2234 * requests and the fd must be free to process those, and thus
2235 * the destination must read the whole device state off the fd before
2236 * it starts processing it. Unfortunately the ad-hoc migration format
2237 * doesn't allow the destination to know the size to read without fully
2238 * parsing it through each devices load-state code (especially the open
2239 * coded devices that use get/put).
2240 * So we wrap the device state up in a package with a length at the start;
2241 * to do this we use a qemu_buf to hold the whole of the device state.
2242 */
61b67d47 2243 bioc = qio_channel_buffer_new(4096);
6f01f136 2244 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
61b67d47
DB
2245 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2246 object_unref(OBJECT(bioc));
1d34e4bf 2247
c76201ab
DDAG
2248 /*
2249 * Make sure the receiver can get incoming pages before we send the rest
2250 * of the state
2251 */
2252 qemu_savevm_send_postcopy_listen(fb);
2253
a1fbe750 2254 qemu_savevm_state_complete_precopy(fb, false, false);
58110f0a
VSO
2255 if (migrate_postcopy_ram()) {
2256 qemu_savevm_send_ping(fb, 3);
2257 }
1d34e4bf
DDAG
2258
2259 qemu_savevm_send_postcopy_run(fb);
2260
2261 /* <><> end of stuff going into the package */
1d34e4bf 2262
ef8d6488
DDAG
2263 /* Last point of recovery; as soon as we send the package the destination
2264 * can open devices and potentially start running.
2265 * Lets just check again we've not got any errors.
2266 */
2267 ret = qemu_file_get_error(ms->to_dst_file);
2268 if (ret) {
2269 error_report("postcopy_start: Migration stream errored (pre package)");
2270 goto fail_closefb;
2271 }
2272
2273 restart_block = false;
2274
1d34e4bf 2275 /* Now send that blob */
61b67d47 2276 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1d34e4bf
DDAG
2277 goto fail_closefb;
2278 }
2279 qemu_fclose(fb);
b82fc321
DDAG
2280
2281 /* Send a notify to give a chance for anything that needs to happen
2282 * at the transition to postcopy and after the device state; in particular
2283 * spice needs to trigger a transition now
2284 */
2285 ms->postcopy_after_devices = true;
2286 notifier_list_notify(&migration_state_notifiers, ms);
2287
1d34e4bf
DDAG
2288 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2289
2290 qemu_mutex_unlock_iothread();
2291
58110f0a
VSO
2292 if (migrate_postcopy_ram()) {
2293 /*
2294 * Although this ping is just for debug, it could potentially be
2295 * used for getting a better measurement of downtime at the source.
2296 */
2297 qemu_savevm_send_ping(ms->to_dst_file, 4);
2298 }
1d34e4bf 2299
ced1c616
PB
2300 if (migrate_release_ram()) {
2301 ram_postcopy_migrated_memory_release(ms);
2302 }
2303
89a02a9f 2304 ret = qemu_file_get_error(ms->to_dst_file);
1d34e4bf
DDAG
2305 if (ret) {
2306 error_report("postcopy_start: Migration stream errored");
48781e5b 2307 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf
DDAG
2308 MIGRATION_STATUS_FAILED);
2309 }
2310
2311 return ret;
2312
2313fail_closefb:
2314 qemu_fclose(fb);
2315fail:
48781e5b 2316 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf 2317 MIGRATION_STATUS_FAILED);
ef8d6488
DDAG
2318 if (restart_block) {
2319 /* A failure happened early enough that we know the destination hasn't
2320 * accessed block devices, so we're safe to recover.
2321 */
2322 Error *local_err = NULL;
2323
2324 bdrv_invalidate_cache_all(&local_err);
2325 if (local_err) {
2326 error_report_err(local_err);
2327 }
2328 }
1d34e4bf
DDAG
2329 qemu_mutex_unlock_iothread();
2330 return -1;
2331}
2332
e91d8951
DDAG
2333/**
2334 * migration_maybe_pause: Pause if required to by
2335 * migrate_pause_before_switchover called with the iothread locked
2336 * Returns: 0 on success
2337 */
0331c8ca
DDAG
2338static int migration_maybe_pause(MigrationState *s,
2339 int *current_active_state,
2340 int new_state)
e91d8951
DDAG
2341{
2342 if (!migrate_pause_before_switchover()) {
2343 return 0;
2344 }
2345
2346 /* Since leaving this state is not atomic with posting the semaphore
2347 * it's possible that someone could have issued multiple migrate_continue
2348 * and the semaphore is incorrectly positive at this point;
2349 * the docs say it's undefined to reinit a semaphore that's already
2350 * init'd, so use timedwait to eat up any existing posts.
2351 */
2352 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2353 /* This block intentionally left blank */
2354 }
2355
2356 qemu_mutex_unlock_iothread();
2357 migrate_set_state(&s->state, *current_active_state,
2358 MIGRATION_STATUS_PRE_SWITCHOVER);
2359 qemu_sem_wait(&s->pause_sem);
2360 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
0331c8ca
DDAG
2361 new_state);
2362 *current_active_state = new_state;
e91d8951
DDAG
2363 qemu_mutex_lock_iothread();
2364
0331c8ca 2365 return s->state == new_state ? 0 : -EINVAL;
e91d8951
DDAG
2366}
2367
09f6c85e
DDAG
2368/**
2369 * migration_completion: Used by migration_thread when there's not much left.
2370 * The caller 'breaks' the loop when this returns.
2371 *
2372 * @s: Current migration state
09f6c85e 2373 */
2ad87305 2374static void migration_completion(MigrationState *s)
09f6c85e
DDAG
2375{
2376 int ret;
2ad87305 2377 int current_active_state = s->state;
09f6c85e 2378
b10ac0c4
DDAG
2379 if (s->state == MIGRATION_STATUS_ACTIVE) {
2380 qemu_mutex_lock_iothread();
64909f97 2381 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
b10ac0c4 2382 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
7287cbd4 2383 s->vm_was_running = runstate_is_running();
b10ac0c4
DDAG
2384 ret = global_state_store();
2385
2386 if (!ret) {
a1fbe750 2387 bool inactivate = !migrate_colo_enabled();
b10ac0c4 2388 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
e91d8951 2389 if (ret >= 0) {
0331c8ca
DDAG
2390 ret = migration_maybe_pause(s, &current_active_state,
2391 MIGRATION_STATUS_DEVICE);
e91d8951 2392 }
f07fa4cb
KW
2393 if (ret >= 0) {
2394 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
a1fbe750
FZ
2395 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2396 inactivate);
f07fa4cb 2397 }
a1fbe750
FZ
2398 if (inactivate && ret >= 0) {
2399 s->block_inactive = true;
b10ac0c4
DDAG
2400 }
2401 }
2402 qemu_mutex_unlock_iothread();
09f6c85e 2403
b10ac0c4
DDAG
2404 if (ret < 0) {
2405 goto fail;
09f6c85e 2406 }
b10ac0c4
DDAG
2407 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2408 trace_migration_completion_postcopy_end();
2409
89a02a9f 2410 qemu_savevm_state_complete_postcopy(s->to_dst_file);
b10ac0c4 2411 trace_migration_completion_postcopy_end_after_complete();
09f6c85e 2412 }
09f6c85e 2413
b10ac0c4
DDAG
2414 /*
2415 * If rp was opened we must clean up the thread before
2416 * cleaning everything else up (since if there are no failures
2417 * it will wait for the destination to send it's status in
2418 * a SHUT command).
b10ac0c4 2419 */
0425dc97 2420 if (s->rp_state.from_dst_file) {
b10ac0c4 2421 int rp_error;
0425dc97 2422 trace_migration_return_path_end_before();
b10ac0c4 2423 rp_error = await_return_path_close_on_source(s);
0425dc97 2424 trace_migration_return_path_end_after(rp_error);
b10ac0c4 2425 if (rp_error) {
fe904ea8 2426 goto fail_invalidate;
b10ac0c4 2427 }
09f6c85e
DDAG
2428 }
2429
89a02a9f 2430 if (qemu_file_get_error(s->to_dst_file)) {
09f6c85e 2431 trace_migration_completion_file_err();
fe904ea8 2432 goto fail_invalidate;
09f6c85e
DDAG
2433 }
2434
0b827d5e
HZ
2435 if (!migrate_colo_enabled()) {
2436 migrate_set_state(&s->state, current_active_state,
2437 MIGRATION_STATUS_COMPLETED);
2438 }
2439
09f6c85e
DDAG
2440 return;
2441
fe904ea8
GK
2442fail_invalidate:
2443 /* If not doing postcopy, vm_start() will be called: let's regain
2444 * control on images.
2445 */
6039dd5b
DDAG
2446 if (s->state == MIGRATION_STATUS_ACTIVE ||
2447 s->state == MIGRATION_STATUS_DEVICE) {
fe904ea8
GK
2448 Error *local_err = NULL;
2449
1d2acc31 2450 qemu_mutex_lock_iothread();
fe904ea8
GK
2451 bdrv_invalidate_cache_all(&local_err);
2452 if (local_err) {
2453 error_report_err(local_err);
1d2acc31
HZ
2454 } else {
2455 s->block_inactive = false;
fe904ea8 2456 }
1d2acc31 2457 qemu_mutex_unlock_iothread();
fe904ea8
GK
2458 }
2459
09f6c85e 2460fail:
48781e5b
HZ
2461 migrate_set_state(&s->state, current_active_state,
2462 MIGRATION_STATUS_FAILED);
09f6c85e
DDAG
2463}
2464
35a6ed4f
HZ
2465bool migrate_colo_enabled(void)
2466{
2467 MigrationState *s = migrate_get_current();
2468 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2469}
2470
b23c2ade
PX
2471typedef enum MigThrError {
2472 /* No error detected */
2473 MIG_THR_ERR_NONE = 0,
2474 /* Detected error, but resumed successfully */
2475 MIG_THR_ERR_RECOVERED = 1,
2476 /* Detected fatal error, need to exit */
2477 MIG_THR_ERR_FATAL = 2,
2478} MigThrError;
2479
94190696
PX
2480static int postcopy_resume_handshake(MigrationState *s)
2481{
2482 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2483
2484 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2485 qemu_sem_wait(&s->rp_state.rp_sem);
2486 }
2487
2488 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2489 return 0;
2490 }
2491
2492 return -1;
2493}
2494
135b87b4
PX
2495/* Return zero if success, or <0 for error */
2496static int postcopy_do_resume(MigrationState *s)
2497{
d1b8eadb
PX
2498 int ret;
2499
2500 /*
2501 * Call all the resume_prepare() hooks, so that modules can be
2502 * ready for the migration resume.
2503 */
2504 ret = qemu_savevm_state_resume_prepare(s);
2505 if (ret) {
2506 error_report("%s: resume_prepare() failure detected: %d",
2507 __func__, ret);
2508 return ret;
2509 }
2510
2511 /*
94190696
PX
2512 * Last handshake with destination on the resume (destination will
2513 * switch to postcopy-active afterwards)
d1b8eadb 2514 */
94190696
PX
2515 ret = postcopy_resume_handshake(s);
2516 if (ret) {
2517 error_report("%s: handshake failed: %d", __func__, ret);
2518 return ret;
2519 }
d1b8eadb 2520
135b87b4
PX
2521 return 0;
2522}
2523
b23c2ade
PX
2524/*
2525 * We don't return until we are in a safe state to continue current
2526 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2527 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2528 */
2529static MigThrError postcopy_pause(MigrationState *s)
2530{
2531 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
b23c2ade 2532
135b87b4
PX
2533 while (true) {
2534 migrate_set_state(&s->state, s->state,
2535 MIGRATION_STATUS_POSTCOPY_PAUSED);
b23c2ade 2536
135b87b4
PX
2537 /* Current channel is possibly broken. Release it. */
2538 assert(s->to_dst_file);
2539 qemu_file_shutdown(s->to_dst_file);
2540 qemu_fclose(s->to_dst_file);
2541 s->to_dst_file = NULL;
b23c2ade 2542
135b87b4
PX
2543 error_report("Detected IO failure for postcopy. "
2544 "Migration paused.");
b23c2ade 2545
135b87b4
PX
2546 /*
2547 * We wait until things fixed up. Then someone will setup the
2548 * status back for us.
2549 */
2550 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2551 qemu_sem_wait(&s->postcopy_pause_sem);
2552 }
2553
2554 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2555 /* Woken up by a recover procedure. Give it a shot */
b23c2ade 2556
135b87b4
PX
2557 /*
2558 * Firstly, let's wake up the return path now, with a new
2559 * return path channel.
2560 */
2561 qemu_sem_post(&s->postcopy_pause_rp_sem);
2562
2563 /* Do the resume logic */
2564 if (postcopy_do_resume(s) == 0) {
2565 /* Let's continue! */
2566 trace_postcopy_pause_continued();
2567 return MIG_THR_ERR_RECOVERED;
2568 } else {
2569 /*
2570 * Something wrong happened during the recovery, let's
2571 * pause again. Pause is always better than throwing
2572 * data away.
2573 */
2574 continue;
2575 }
2576 } else {
2577 /* This is not right... Time to quit. */
2578 return MIG_THR_ERR_FATAL;
2579 }
2580 }
b23c2ade
PX
2581}
2582
2583static MigThrError migration_detect_error(MigrationState *s)
2584{
2585 int ret;
2586
2587 /* Try to detect any file errors */
2588 ret = qemu_file_get_error(s->to_dst_file);
2589
2590 if (!ret) {
2591 /* Everything is fine */
2592 return MIG_THR_ERR_NONE;
2593 }
2594
2595 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
2596 /*
2597 * For postcopy, we allow the network to be down for a
2598 * while. After that, it can be continued by a
2599 * recovery phase.
2600 */
2601 return postcopy_pause(s);
2602 } else {
2603 /*
2604 * For precopy (or postcopy with error outside IO), we fail
2605 * with no time.
2606 */
2607 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
2608 trace_migration_thread_file_err();
2609
2610 /* Time to stop the migration, now. */
2611 return MIG_THR_ERR_FATAL;
2612 }
2613}
2614
cf011f08
PX
2615static void migration_calculate_complete(MigrationState *s)
2616{
2617 uint64_t bytes = qemu_ftell(s->to_dst_file);
2618 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2619
2620 s->total_time = end_time - s->start_time;
2621 if (!s->downtime) {
2622 /*
2623 * It's still not set, so we are precopy migration. For
2624 * postcopy, downtime is calculated during postcopy_start().
2625 */
2626 s->downtime = end_time - s->downtime_start;
2627 }
2628
2629 if (s->total_time) {
2630 s->mbps = ((double) bytes * 8.0) / s->total_time / 1000;
2631 }
2632}
2633
b15df1ae
PX
2634static void migration_update_counters(MigrationState *s,
2635 int64_t current_time)
2636{
2637 uint64_t transferred, time_spent;
b15df1ae
PX
2638 double bandwidth;
2639
2640 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2641 return;
2642 }
2643
2644 transferred = qemu_ftell(s->to_dst_file) - s->iteration_initial_bytes;
2645 time_spent = current_time - s->iteration_start_time;
2646 bandwidth = (double)transferred / time_spent;
0781c1ed 2647 s->threshold_size = bandwidth * s->parameters.downtime_limit;
b15df1ae
PX
2648
2649 s->mbps = (((double) transferred * 8.0) /
2650 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2651
2652 /*
2653 * if we haven't sent anything, we don't want to
2654 * recalculate. 10000 is a small enough number for our purposes
2655 */
2656 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2657 s->expected_downtime = ram_counters.dirty_pages_rate *
2658 qemu_target_page_size() / bandwidth;
2659 }
2660
2661 qemu_file_reset_rate_limit(s->to_dst_file);
2662
2663 s->iteration_start_time = current_time;
2664 s->iteration_initial_bytes = qemu_ftell(s->to_dst_file);
2665
2666 trace_migrate_transferred(transferred, time_spent,
0781c1ed 2667 bandwidth, s->threshold_size);
b15df1ae
PX
2668}
2669
2ad87305
PX
2670/* Migration thread iteration status */
2671typedef enum {
2672 MIG_ITERATE_RESUME, /* Resume current iteration */
2673 MIG_ITERATE_SKIP, /* Skip current iteration */
2674 MIG_ITERATE_BREAK, /* Break the loop */
2675} MigIterateState;
2676
2677/*
2678 * Return true if continue to the next iteration directly, false
2679 * otherwise.
2680 */
2681static MigIterateState migration_iteration_run(MigrationState *s)
2682{
47995026 2683 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2ad87305
PX
2684 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2685
47995026
VSO
2686 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2687 &pend_compat, &pend_post);
2688 pending_size = pend_pre + pend_compat + pend_post;
2ad87305
PX
2689
2690 trace_migrate_pending(pending_size, s->threshold_size,
47995026 2691 pend_pre, pend_compat, pend_post);
2ad87305
PX
2692
2693 if (pending_size && pending_size >= s->threshold_size) {
2694 /* Still a significant amount to transfer */
2695 if (migrate_postcopy() && !in_postcopy &&
47995026 2696 pend_pre <= s->threshold_size &&
2ad87305
PX
2697 atomic_read(&s->start_postcopy)) {
2698 if (postcopy_start(s)) {
2699 error_report("%s: postcopy failed to start", __func__);
2700 }
2701 return MIG_ITERATE_SKIP;
2702 }
2703 /* Just another iteration step */
2704 qemu_savevm_state_iterate(s->to_dst_file,
2705 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2706 } else {
2707 trace_migration_thread_low_pending(pending_size);
2708 migration_completion(s);
2709 return MIG_ITERATE_BREAK;
2710 }
2711
2712 return MIG_ITERATE_RESUME;
2713}
2714
199aa6d4
PX
2715static void migration_iteration_finish(MigrationState *s)
2716{
2717 /* If we enabled cpu throttling for auto-converge, turn it off. */
2718 cpu_throttle_stop();
2719
2720 qemu_mutex_lock_iothread();
2721 switch (s->state) {
2722 case MIGRATION_STATUS_COMPLETED:
2723 migration_calculate_complete(s);
2724 runstate_set(RUN_STATE_POSTMIGRATE);
2725 break;
2726
2727 case MIGRATION_STATUS_ACTIVE:
2728 /*
2729 * We should really assert here, but since it's during
2730 * migration, let's try to reduce the usage of assertions.
2731 */
2732 if (!migrate_colo_enabled()) {
2733 error_report("%s: critical error: calling COLO code without "
2734 "COLO enabled", __func__);
2735 }
2736 migrate_start_colo_process(s);
2737 /*
2738 * Fixme: we will run VM in COLO no matter its old running state.
2739 * After exited COLO, we will keep running.
2740 */
2741 s->vm_was_running = true;
2742 /* Fallthrough */
2743 case MIGRATION_STATUS_FAILED:
2744 case MIGRATION_STATUS_CANCELLED:
2745 if (s->vm_was_running) {
2746 vm_start();
2747 } else {
2748 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2749 runstate_set(RUN_STATE_POSTMIGRATE);
2750 }
2751 }
2752 break;
2753
2754 default:
2755 /* Should not reach here, but if so, forgive the VM. */
2756 error_report("%s: Unknown ending state %d", __func__, s->state);
2757 break;
2758 }
2759 qemu_bh_schedule(s->cleanup_bh);
2760 qemu_mutex_unlock_iothread();
2761}
2762
70b20477
DDAG
2763/*
2764 * Master migration thread on the source VM.
2765 * It drives the migration and pumps the data down the outgoing channel.
2766 */
5f496a1b 2767static void *migration_thread(void *opaque)
0d82d0e8 2768{
9848a404 2769 MigrationState *s = opaque;
bc72ad67 2770 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
b23c2ade 2771 MigThrError thr_error;
76f5933a 2772
ab28bd23
PB
2773 rcu_register_thread();
2774
b15df1ae
PX
2775 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2776
89a02a9f 2777 qemu_savevm_state_header(s->to_dst_file);
1d34e4bf 2778
62a02658
PX
2779 /*
2780 * If we opened the return path, we need to make sure dst has it
2781 * opened as well.
2782 */
2783 if (s->rp_state.from_dst_file) {
1d34e4bf 2784 /* Now tell the dest that it should open its end so it can reply */
89a02a9f 2785 qemu_savevm_send_open_return_path(s->to_dst_file);
1d34e4bf
DDAG
2786
2787 /* And do a ping that will make stuff easier to debug */
89a02a9f 2788 qemu_savevm_send_ping(s->to_dst_file, 1);
0425dc97 2789 }
1d34e4bf 2790
58110f0a 2791 if (migrate_postcopy()) {
1d34e4bf
DDAG
2792 /*
2793 * Tell the destination that we *might* want to do postcopy later;
2794 * if the other end can't do postcopy it should fail now, nice and
2795 * early.
2796 */
89a02a9f 2797 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1d34e4bf
DDAG
2798 }
2799
9907e842 2800 qemu_savevm_state_setup(s->to_dst_file);
0d82d0e8 2801
bc72ad67 2802 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
48781e5b
HZ
2803 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2804 MIGRATION_STATUS_ACTIVE);
29ae8a41 2805
9ec055ae
DDAG
2806 trace_migration_thread_setup_complete();
2807
2808 while (s->state == MIGRATION_STATUS_ACTIVE ||
2809 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
a3e879cd 2810 int64_t current_time;
0d82d0e8 2811
89a02a9f 2812 if (!qemu_file_rate_limit(s->to_dst_file)) {
2ad87305
PX
2813 MigIterateState iter_state = migration_iteration_run(s);
2814 if (iter_state == MIG_ITERATE_SKIP) {
2815 continue;
2816 } else if (iter_state == MIG_ITERATE_BREAK) {
09f6c85e 2817 break;
c369f40d
JQ
2818 }
2819 }
f4410a5d 2820
b23c2ade
PX
2821 /*
2822 * Try to detect any kind of failures, and see whether we
2823 * should stop the migration now.
2824 */
2825 thr_error = migration_detect_error(s);
2826 if (thr_error == MIG_THR_ERR_FATAL) {
2827 /* Stop migration */
fd45ee2c 2828 break;
b23c2ade
PX
2829 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
2830 /*
2831 * Just recovered from a e.g. network failure, reset all
2832 * the local variables. This is important to avoid
2833 * breaking transferred_bytes and bandwidth calculation
2834 */
2835 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2836 s->iteration_initial_bytes = 0;
fd45ee2c 2837 }
b15df1ae 2838
bc72ad67 2839 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0d82d0e8 2840
b15df1ae
PX
2841 migration_update_counters(s, current_time);
2842
89a02a9f 2843 if (qemu_file_rate_limit(s->to_dst_file)) {
0d82d0e8 2844 /* usleep expects microseconds */
b15df1ae
PX
2845 g_usleep((s->iteration_start_time + BUFFER_DELAY -
2846 current_time) * 1000);
0d82d0e8 2847 }
a3fa1d78
PB
2848 }
2849
1d34e4bf 2850 trace_migration_thread_after_loop();
199aa6d4 2851 migration_iteration_finish(s);
ab28bd23 2852 rcu_unregister_thread();
0d82d0e8
JQ
2853 return NULL;
2854}
2855
cce8040b 2856void migrate_fd_connect(MigrationState *s, Error *error_in)
0d82d0e8 2857{
d3e35b8f
PX
2858 int64_t rate_limit;
2859 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
2860
2ff30257 2861 s->expected_downtime = s->parameters.downtime_limit;
bb1fadc4 2862 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
cce8040b
DDAG
2863 if (error_in) {
2864 migrate_fd_error(s, error_in);
2865 migrate_fd_cleanup(s);
2866 return;
2867 }
0d82d0e8 2868
d3e35b8f
PX
2869 if (resume) {
2870 /* This is a resumed migration */
2871 rate_limit = INT64_MAX;
2872 } else {
2873 /* This is a fresh new migration */
2874 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
2875 s->expected_downtime = s->parameters.downtime_limit;
2876 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
442773ce 2877
d3e35b8f
PX
2878 /* Notify before starting migration thread */
2879 notifier_list_notify(&migration_state_notifiers, s);
2880 }
2881
2882 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
2883 qemu_file_set_blocking(s->to_dst_file, true);
9287ac27 2884
1d34e4bf 2885 /*
c788ada8
PX
2886 * Open the return path. For postcopy, it is used exclusively. For
2887 * precopy, only if user specified "return-path" capability would
2888 * QEMU uses the return path.
1d34e4bf 2889 */
c788ada8 2890 if (migrate_postcopy_ram() || migrate_use_return_path()) {
d3e35b8f 2891 if (open_return_path_on_source(s, !resume)) {
1d34e4bf 2892 error_report("Unable to open return-path for postcopy");
d3e35b8f 2893 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
1d34e4bf
DDAG
2894 migrate_fd_cleanup(s);
2895 return;
2896 }
2897 }
2898
d3e35b8f 2899 if (resume) {
135b87b4
PX
2900 /* Wakeup the main migration thread to do the recovery */
2901 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
2902 MIGRATION_STATUS_POSTCOPY_RECOVER);
2903 qemu_sem_post(&s->postcopy_pause_sem);
d3e35b8f
PX
2904 return;
2905 }
2906
f986c3d2
JQ
2907 if (multifd_save_setup() != 0) {
2908 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2909 MIGRATION_STATUS_FAILED);
2910 migrate_fd_cleanup(s);
2911 return;
2912 }
009fad7f 2913 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
bb1fadc4 2914 QEMU_THREAD_JOINABLE);
1d34e4bf 2915 s->migration_thread_running = true;
0d82d0e8 2916}
093e3c42 2917
9d18af93
PX
2918void migration_global_dump(Monitor *mon)
2919{
2920 MigrationState *ms = migrate_get_current();
2921
6f0f6428
JQ
2922 monitor_printf(mon, "globals:\n");
2923 monitor_printf(mon, "store-global-state: %s\n",
2924 ms->store_global_state ? "on" : "off");
2925 monitor_printf(mon, "only-migratable: %s\n",
2926 ms->only_migratable ? "on" : "off");
2927 monitor_printf(mon, "send-configuration: %s\n",
2928 ms->send_configuration ? "on" : "off");
2929 monitor_printf(mon, "send-section-footer: %s\n",
2930 ms->send_section_footer ? "on" : "off");
9d18af93
PX
2931}
2932
20814758
PX
2933#define DEFINE_PROP_MIG_CAP(name, x) \
2934 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2935
5272298c
PX
2936static Property migration_properties[] = {
2937 DEFINE_PROP_BOOL("store-global-state", MigrationState,
2938 store_global_state, true),
3df663e5 2939 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
71dd4c1a
PX
2940 DEFINE_PROP_BOOL("send-configuration", MigrationState,
2941 send_configuration, true),
15c38503
PX
2942 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
2943 send_section_footer, true),
89632faf
PX
2944
2945 /* Migration parameters */
741d4086 2946 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
89632faf
PX
2947 parameters.compress_level,
2948 DEFAULT_MIGRATE_COMPRESS_LEVEL),
741d4086 2949 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
89632faf
PX
2950 parameters.compress_threads,
2951 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
741d4086 2952 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
89632faf
PX
2953 parameters.decompress_threads,
2954 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
741d4086 2955 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
89632faf
PX
2956 parameters.cpu_throttle_initial,
2957 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
741d4086 2958 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
89632faf
PX
2959 parameters.cpu_throttle_increment,
2960 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
741d4086 2961 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
89632faf 2962 parameters.max_bandwidth, MAX_THROTTLE),
741d4086 2963 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
89632faf
PX
2964 parameters.downtime_limit,
2965 DEFAULT_MIGRATE_SET_DOWNTIME),
741d4086 2966 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
89632faf
PX
2967 parameters.x_checkpoint_delay,
2968 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
741d4086 2969 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
4075fb1c
JQ
2970 parameters.x_multifd_channels,
2971 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
741d4086 2972 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
0fb86605
JQ
2973 parameters.x_multifd_page_count,
2974 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
73af8dd8
JQ
2975 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
2976 parameters.xbzrle_cache_size,
2977 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
20814758
PX
2978
2979 /* Migration capabilities */
2980 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
2981 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
2982 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
2983 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
2984 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
2985 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
2986 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
2987 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
2988 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
2989 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
2990 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
30126bbf 2991 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
20814758 2992
5272298c
PX
2993 DEFINE_PROP_END_OF_LIST(),
2994};
2995
e5cb7e76
PX
2996static void migration_class_init(ObjectClass *klass, void *data)
2997{
2998 DeviceClass *dc = DEVICE_CLASS(klass);
2999
3000 dc->user_creatable = false;
5272298c 3001 dc->props = migration_properties;
e5cb7e76
PX
3002}
3003
b91bf5e4
MAL
3004static void migration_instance_finalize(Object *obj)
3005{
3006 MigrationState *ms = MIGRATION_OBJ(obj);
3007 MigrationParameters *params = &ms->parameters;
3008
87db1a7d 3009 qemu_mutex_destroy(&ms->error_mutex);
b91bf5e4
MAL
3010 g_free(params->tls_hostname);
3011 g_free(params->tls_creds);
e91d8951 3012 qemu_sem_destroy(&ms->pause_sem);
b23c2ade 3013 qemu_sem_destroy(&ms->postcopy_pause_sem);
14b1742e 3014 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
edd090c7 3015 qemu_sem_destroy(&ms->rp_state.rp_sem);
ab105cc1 3016 error_free(ms->error);
b91bf5e4
MAL
3017}
3018
e5cb7e76
PX
3019static void migration_instance_init(Object *obj)
3020{
3021 MigrationState *ms = MIGRATION_OBJ(obj);
8b0b29dc 3022 MigrationParameters *params = &ms->parameters;
e5cb7e76
PX
3023
3024 ms->state = MIGRATION_STATUS_NONE;
e5cb7e76 3025 ms->mbps = -1;
e91d8951 3026 qemu_sem_init(&ms->pause_sem, 0);
87db1a7d 3027 qemu_mutex_init(&ms->error_mutex);
8b0b29dc
PX
3028
3029 params->tls_hostname = g_strdup("");
3030 params->tls_creds = g_strdup("");
3031
3032 /* Set has_* up only for parameter checks */
3033 params->has_compress_level = true;
3034 params->has_compress_threads = true;
3035 params->has_decompress_threads = true;
3036 params->has_cpu_throttle_initial = true;
3037 params->has_cpu_throttle_increment = true;
3038 params->has_max_bandwidth = true;
3039 params->has_downtime_limit = true;
3040 params->has_x_checkpoint_delay = true;
3041 params->has_block_incremental = true;
4075fb1c 3042 params->has_x_multifd_channels = true;
0fb86605 3043 params->has_x_multifd_page_count = true;
73af8dd8 3044 params->has_xbzrle_cache_size = true;
b23c2ade
PX
3045
3046 qemu_sem_init(&ms->postcopy_pause_sem, 0);
14b1742e 3047 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
edd090c7 3048 qemu_sem_init(&ms->rp_state.rp_sem, 0);
8b0b29dc
PX
3049}
3050
3051/*
3052 * Return true if check pass, false otherwise. Error will be put
3053 * inside errp if provided.
3054 */
3055static bool migration_object_check(MigrationState *ms, Error **errp)
3056{
6b19a7d9
PX
3057 MigrationCapabilityStatusList *head = NULL;
3058 /* Assuming all off */
3059 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3060 int i;
3061
8b0b29dc
PX
3062 if (!migrate_params_check(&ms->parameters, errp)) {
3063 return false;
3064 }
3065
6b19a7d9
PX
3066 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3067 if (ms->enabled_capabilities[i]) {
3068 head = migrate_cap_add(head, i, true);
3069 }
3070 }
3071
3072 ret = migrate_caps_check(cap_list, head, errp);
3073
3074 /* It works with head == NULL */
3075 qapi_free_MigrationCapabilityStatusList(head);
3076
3077 return ret;
e5cb7e76
PX
3078}
3079
3080static const TypeInfo migration_type = {
3081 .name = TYPE_MIGRATION,
01f6e14c 3082 /*
c8d3ff38
PX
3083 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3084 * not created using qdev_create(), it is not attached to the qdev
3085 * device tree, and it is never realized.
3086 *
3087 * TODO: Make this TYPE_OBJECT once QOM provides something like
3088 * TYPE_DEVICE's "-global" properties.
01f6e14c 3089 */
e5cb7e76
PX
3090 .parent = TYPE_DEVICE,
3091 .class_init = migration_class_init,
3092 .class_size = sizeof(MigrationClass),
3093 .instance_size = sizeof(MigrationState),
3094 .instance_init = migration_instance_init,
b91bf5e4 3095 .instance_finalize = migration_instance_finalize,
e5cb7e76
PX
3096};
3097
3098static void register_migration_types(void)
3099{
3100 type_register_static(&migration_type);
3101}
3102
3103type_init(register_migration_types);