]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
migration: init dst in migration_object_init too
[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
24f3902b
GK
1478bool migration_is_blocked(Error **errp)
1479{
1480 if (qemu_savevm_state_blocked(errp)) {
1481 return true;
1482 }
1483
1484 if (migration_blockers) {
250561e1 1485 error_propagate(errp, error_copy(migration_blockers->data));
24f3902b
GK
1486 return true;
1487 }
1488
1489 return false;
1490}
1491
d3e35b8f
PX
1492/* Returns true if continue to migrate, or false if error detected */
1493static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1494 bool resume, Error **errp)
cab30143 1495{
be7059cd 1496 Error *local_err = NULL;
d3e35b8f
PX
1497
1498 if (resume) {
1499 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1500 error_setg(errp, "Cannot resume if there is no "
1501 "paused migration");
1502 return false;
1503 }
1504 /* This is a resume, skip init status */
1505 return true;
1506 }
cab30143 1507
f6844b99 1508 if (migration_is_setup_or_active(s->state) ||
0b827d5e
HZ
1509 s->state == MIGRATION_STATUS_CANCELLING ||
1510 s->state == MIGRATION_STATUS_COLO) {
c6bd8c70 1511 error_setg(errp, QERR_MIGRATION_ACTIVE);
d3e35b8f 1512 return false;
cab30143 1513 }
d3e35b8f 1514
ca99993a
DDAG
1515 if (runstate_check(RUN_STATE_INMIGRATE)) {
1516 error_setg(errp, "Guest is waiting for an incoming migration");
d3e35b8f 1517 return false;
ca99993a
DDAG
1518 }
1519
24f3902b 1520 if (migration_is_blocked(errp)) {
d3e35b8f 1521 return false;
fa2756b7
AL
1522 }
1523
d3e35b8f 1524 if (blk || blk_inc) {
2833c59b
JQ
1525 if (migrate_use_block() || migrate_use_block_incremental()) {
1526 error_setg(errp, "Command options are incompatible with "
1527 "current migration capabilities");
d3e35b8f 1528 return false;
2833c59b
JQ
1529 }
1530 migrate_set_block_enabled(true, &local_err);
1531 if (local_err) {
1532 error_propagate(errp, local_err);
d3e35b8f 1533 return false;
2833c59b
JQ
1534 }
1535 s->must_remove_block_options = true;
1536 }
1537
d3e35b8f 1538 if (blk_inc) {
2833c59b
JQ
1539 migrate_set_block_incremental(s, true);
1540 }
1541
3e0c8050 1542 migrate_init(s);
cab30143 1543
d3e35b8f
PX
1544 return true;
1545}
1546
1547void qmp_migrate(const char *uri, bool has_blk, bool blk,
1548 bool has_inc, bool inc, bool has_detach, bool detach,
1549 bool has_resume, bool resume, Error **errp)
1550{
1551 Error *local_err = NULL;
1552 MigrationState *s = migrate_get_current();
1553 const char *p;
1554
1555 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1556 has_resume && resume, errp)) {
1557 /* Error detected, put into errp */
1558 return;
1559 }
1560
cab30143 1561 if (strstart(uri, "tcp:", &p)) {
f37afb5a 1562 tcp_start_outgoing_migration(s, p, &local_err);
2da776db 1563#ifdef CONFIG_RDMA
41310c68 1564 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
1565 rdma_start_outgoing_migration(s, p, &local_err);
1566#endif
cab30143 1567 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 1568 exec_start_outgoing_migration(s, p, &local_err);
cab30143 1569 } else if (strstart(uri, "unix:", &p)) {
f37afb5a 1570 unix_start_outgoing_migration(s, p, &local_err);
cab30143 1571 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 1572 fd_start_outgoing_migration(s, p, &local_err);
99a0db9b 1573 } else {
c6bd8c70
MA
1574 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1575 "a valid migration protocol");
48781e5b
HZ
1576 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1577 MIGRATION_STATUS_FAILED);
09576e74 1578 block_cleanup_parameters(s);
e1c37d0e 1579 return;
cab30143
JQ
1580 }
1581
f37afb5a 1582 if (local_err) {
d59ce6f3 1583 migrate_fd_error(s, local_err);
f37afb5a 1584 error_propagate(errp, local_err);
e1c37d0e 1585 return;
1299c631 1586 }
cab30143
JQ
1587}
1588
6cdedb07 1589void qmp_migrate_cancel(Error **errp)
cab30143 1590{
17549e84 1591 migrate_fd_cancel(migrate_get_current());
cab30143
JQ
1592}
1593
89cfc02c
DDAG
1594void qmp_migrate_continue(MigrationStatus state, Error **errp)
1595{
1596 MigrationState *s = migrate_get_current();
1597 if (s->state != state) {
1598 error_setg(errp, "Migration not in expected state: %s",
1599 MigrationStatus_str(s->state));
1600 return;
1601 }
1602 qemu_sem_post(&s->pause_sem);
1603}
1604
9e1ba4cc
OW
1605void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1606{
73af8dd8
JQ
1607 MigrateSetParameters p = {
1608 .has_xbzrle_cache_size = true,
1609 .xbzrle_cache_size = value,
1610 };
c91e681a 1611
73af8dd8 1612 qmp_migrate_set_parameters(&p, errp);
9e1ba4cc
OW
1613}
1614
1615int64_t qmp_query_migrate_cache_size(Error **errp)
1616{
1617 return migrate_xbzrle_cache_size();
1618}
1619
3dc85383 1620void qmp_migrate_set_speed(int64_t value, Error **errp)
cab30143 1621{
1bda8b3c 1622 MigrateSetParameters p = {
2ff30257
AA
1623 .has_max_bandwidth = true,
1624 .max_bandwidth = value,
1625 };
cab30143 1626
2ff30257 1627 qmp_migrate_set_parameters(&p, errp);
cab30143
JQ
1628}
1629
4f0a993b 1630void qmp_migrate_set_downtime(double value, Error **errp)
cab30143 1631{
87c9cc1c
DHB
1632 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1633 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1634 "the range of 0 to %d seconds",
1635 MAX_MIGRATE_DOWNTIME_SECONDS);
1636 return;
1637 }
1638
2ff30257
AA
1639 value *= 1000; /* Convert to milliseconds */
1640 value = MAX(0, MIN(INT64_MAX, value));
1641
1bda8b3c 1642 MigrateSetParameters p = {
2ff30257
AA
1643 .has_downtime_limit = true,
1644 .downtime_limit = value,
1645 };
1646
1647 qmp_migrate_set_parameters(&p, errp);
99a0db9b 1648}
17ad9b35 1649
53f09a10
PB
1650bool migrate_release_ram(void)
1651{
1652 MigrationState *s;
1653
1654 s = migrate_get_current();
1655
1656 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1657}
1658
53dd370c
DDAG
1659bool migrate_postcopy_ram(void)
1660{
1661 MigrationState *s;
1662
1663 s = migrate_get_current();
1664
32c3db5b 1665 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
53dd370c
DDAG
1666}
1667
58110f0a
VSO
1668bool migrate_postcopy(void)
1669{
dd6bb914 1670 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
58110f0a
VSO
1671}
1672
bde1e2ec
CV
1673bool migrate_auto_converge(void)
1674{
1675 MigrationState *s;
1676
1677 s = migrate_get_current();
1678
1679 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1680}
1681
323004a3
PL
1682bool migrate_zero_blocks(void)
1683{
1684 MigrationState *s;
1685
1686 s = migrate_get_current();
1687
1688 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1689}
1690
f22f928e
AP
1691bool migrate_postcopy_blocktime(void)
1692{
1693 MigrationState *s;
1694
1695 s = migrate_get_current();
1696
1697 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
1698}
1699
8706d2d5
LL
1700bool migrate_use_compression(void)
1701{
dde4e694
LL
1702 MigrationState *s;
1703
1704 s = migrate_get_current();
1705
1706 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
1707}
1708
1709int migrate_compress_level(void)
1710{
1711 MigrationState *s;
1712
1713 s = migrate_get_current();
1714
2594f56d 1715 return s->parameters.compress_level;
8706d2d5
LL
1716}
1717
1718int migrate_compress_threads(void)
1719{
1720 MigrationState *s;
1721
1722 s = migrate_get_current();
1723
2594f56d 1724 return s->parameters.compress_threads;
8706d2d5
LL
1725}
1726
3fcb38c2
LL
1727int migrate_decompress_threads(void)
1728{
1729 MigrationState *s;
1730
1731 s = migrate_get_current();
1732
2594f56d 1733 return s->parameters.decompress_threads;
3fcb38c2
LL
1734}
1735
55efc8c2
VSO
1736bool migrate_dirty_bitmaps(void)
1737{
1738 MigrationState *s;
1739
1740 s = migrate_get_current();
1741
1742 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1743}
1744
b05dc723
JQ
1745bool migrate_use_events(void)
1746{
1747 MigrationState *s;
1748
1749 s = migrate_get_current();
1750
1751 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1752}
1753
30126bbf
JQ
1754bool migrate_use_multifd(void)
1755{
1756 MigrationState *s;
1757
1758 s = migrate_get_current();
1759
1760 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1761}
1762
93fbd031
DDAG
1763bool migrate_pause_before_switchover(void)
1764{
1765 MigrationState *s;
1766
1767 s = migrate_get_current();
1768
1769 return s->enabled_capabilities[
1770 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1771}
1772
4075fb1c
JQ
1773int migrate_multifd_channels(void)
1774{
1775 MigrationState *s;
1776
1777 s = migrate_get_current();
1778
1779 return s->parameters.x_multifd_channels;
1780}
1781
0fb86605
JQ
1782int migrate_multifd_page_count(void)
1783{
1784 MigrationState *s;
1785
1786 s = migrate_get_current();
1787
1788 return s->parameters.x_multifd_page_count;
1789}
1790
17ad9b35
OW
1791int migrate_use_xbzrle(void)
1792{
1793 MigrationState *s;
1794
1795 s = migrate_get_current();
1796
1797 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1798}
1799
1800int64_t migrate_xbzrle_cache_size(void)
1801{
1802 MigrationState *s;
1803
1804 s = migrate_get_current();
1805
73af8dd8 1806 return s->parameters.xbzrle_cache_size;
17ad9b35 1807}
0d82d0e8 1808
2833c59b
JQ
1809bool migrate_use_block(void)
1810{
1811 MigrationState *s;
1812
1813 s = migrate_get_current();
1814
1815 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1816}
1817
c788ada8
PX
1818bool migrate_use_return_path(void)
1819{
1820 MigrationState *s;
1821
1822 s = migrate_get_current();
1823
1824 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
1825}
1826
2833c59b
JQ
1827bool migrate_use_block_incremental(void)
1828{
1829 MigrationState *s;
1830
1831 s = migrate_get_current();
1832
1833 return s->parameters.block_incremental;
1834}
1835
70b20477
DDAG
1836/* migration thread support */
1837/*
1838 * Something bad happened to the RP stream, mark an error
1839 * The caller shall print or trace something to indicate why
1840 */
1841static void mark_source_rp_bad(MigrationState *s)
1842{
1843 s->rp_state.error = true;
1844}
1845
1846static struct rp_cmd_args {
1847 ssize_t len; /* -1 = variable */
1848 const char *name;
1849} rp_cmd_args[] = {
1850 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1851 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1852 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1e2d90eb
DDAG
1853 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1854 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
a335debb 1855 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
13955b89 1856 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
70b20477
DDAG
1857 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1858};
1859
1e2d90eb
DDAG
1860/*
1861 * Process a request for pages received on the return path,
1862 * We're allowed to send more than requested (e.g. to round to our page size)
1863 * and we don't need to send pages that have already been sent.
1864 */
1865static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1866 ram_addr_t start, size_t len)
1867{
6c595cde
DDAG
1868 long our_host_ps = getpagesize();
1869
1e2d90eb 1870 trace_migrate_handle_rp_req_pages(rbname, start, len);
6c595cde
DDAG
1871
1872 /*
1873 * Since we currently insist on matching page sizes, just sanity check
1874 * we're being asked for whole host pages.
1875 */
1876 if (start & (our_host_ps-1) ||
1877 (len & (our_host_ps-1))) {
1878 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1879 " len: %zd", __func__, start, len);
1880 mark_source_rp_bad(ms);
1881 return;
1882 }
1883
96506894 1884 if (ram_save_queue_pages(rbname, start, len)) {
6c595cde
DDAG
1885 mark_source_rp_bad(ms);
1886 }
1e2d90eb
DDAG
1887}
1888
14b1742e
PX
1889/* Return true to retry, false to quit */
1890static bool postcopy_pause_return_path_thread(MigrationState *s)
1891{
1892 trace_postcopy_pause_return_path();
1893
1894 qemu_sem_wait(&s->postcopy_pause_rp_sem);
1895
1896 trace_postcopy_pause_return_path_continued();
1897
1898 return true;
1899}
1900
a335debb
PX
1901static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
1902{
1903 RAMBlock *block = qemu_ram_block_by_name(block_name);
1904
1905 if (!block) {
1906 error_report("%s: invalid block name '%s'", __func__, block_name);
1907 return -EINVAL;
1908 }
1909
1910 /* Fetch the received bitmap and refresh the dirty bitmap */
1911 return ram_dirty_bitmap_reload(s, block);
1912}
1913
13955b89
PX
1914static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
1915{
1916 trace_source_return_path_thread_resume_ack(value);
1917
1918 if (value != MIGRATION_RESUME_ACK_VALUE) {
1919 error_report("%s: illegal resume_ack value %"PRIu32,
1920 __func__, value);
1921 return -1;
1922 }
1923
1924 /* Now both sides are active. */
1925 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
1926 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1927
94190696
PX
1928 /* Notify send thread that time to continue send pages */
1929 qemu_sem_post(&s->rp_state.rp_sem);
13955b89
PX
1930
1931 return 0;
1932}
1933
70b20477
DDAG
1934/*
1935 * Handles messages sent on the return path towards the source VM
1936 *
1937 */
1938static void *source_return_path_thread(void *opaque)
1939{
1940 MigrationState *ms = opaque;
1941 QEMUFile *rp = ms->rp_state.from_dst_file;
1942 uint16_t header_len, header_type;
568b01ca 1943 uint8_t buf[512];
70b20477 1944 uint32_t tmp32, sibling_error;
1e2d90eb
DDAG
1945 ram_addr_t start = 0; /* =0 to silence warning */
1946 size_t len = 0, expected_len;
70b20477
DDAG
1947 int res;
1948
1949 trace_source_return_path_thread_entry();
14b1742e
PX
1950
1951retry:
70b20477
DDAG
1952 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1953 migration_is_setup_or_active(ms->state)) {
1954 trace_source_return_path_thread_loop_top();
1955 header_type = qemu_get_be16(rp);
1956 header_len = qemu_get_be16(rp);
1957
7a9ddfbf
PX
1958 if (qemu_file_get_error(rp)) {
1959 mark_source_rp_bad(ms);
1960 goto out;
1961 }
1962
70b20477
DDAG
1963 if (header_type >= MIG_RP_MSG_MAX ||
1964 header_type == MIG_RP_MSG_INVALID) {
1965 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1966 header_type, header_len);
1967 mark_source_rp_bad(ms);
1968 goto out;
1969 }
1970
1971 if ((rp_cmd_args[header_type].len != -1 &&
1972 header_len != rp_cmd_args[header_type].len) ||
568b01ca 1973 header_len > sizeof(buf)) {
70b20477
DDAG
1974 error_report("RP: Received '%s' message (0x%04x) with"
1975 "incorrect length %d expecting %zu",
1976 rp_cmd_args[header_type].name, header_type, header_len,
1977 (size_t)rp_cmd_args[header_type].len);
1978 mark_source_rp_bad(ms);
1979 goto out;
1980 }
1981
1982 /* We know we've got a valid header by this point */
1983 res = qemu_get_buffer(rp, buf, header_len);
1984 if (res != header_len) {
1985 error_report("RP: Failed reading data for message 0x%04x"
1986 " read %d expected %d",
1987 header_type, res, header_len);
1988 mark_source_rp_bad(ms);
1989 goto out;
1990 }
1991
1992 /* OK, we have the message and the data */
1993 switch (header_type) {
1994 case MIG_RP_MSG_SHUT:
4d885131 1995 sibling_error = ldl_be_p(buf);
70b20477
DDAG
1996 trace_source_return_path_thread_shut(sibling_error);
1997 if (sibling_error) {
1998 error_report("RP: Sibling indicated error %d", sibling_error);
1999 mark_source_rp_bad(ms);
2000 }
2001 /*
2002 * We'll let the main thread deal with closing the RP
2003 * we could do a shutdown(2) on it, but we're the only user
2004 * anyway, so there's nothing gained.
2005 */
2006 goto out;
2007
2008 case MIG_RP_MSG_PONG:
4d885131 2009 tmp32 = ldl_be_p(buf);
70b20477
DDAG
2010 trace_source_return_path_thread_pong(tmp32);
2011 break;
2012
1e2d90eb 2013 case MIG_RP_MSG_REQ_PAGES:
4d885131
PM
2014 start = ldq_be_p(buf);
2015 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2016 migrate_handle_rp_req_pages(ms, NULL, start, len);
2017 break;
2018
2019 case MIG_RP_MSG_REQ_PAGES_ID:
2020 expected_len = 12 + 1; /* header + termination */
2021
2022 if (header_len >= expected_len) {
4d885131
PM
2023 start = ldq_be_p(buf);
2024 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2025 /* Now we expect an idstr */
2026 tmp32 = buf[12]; /* Length of the following idstr */
2027 buf[13 + tmp32] = '\0';
2028 expected_len += tmp32;
2029 }
2030 if (header_len != expected_len) {
2031 error_report("RP: Req_Page_id with length %d expecting %zd",
2032 header_len, expected_len);
2033 mark_source_rp_bad(ms);
2034 goto out;
2035 }
2036 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2037 break;
2038
a335debb
PX
2039 case MIG_RP_MSG_RECV_BITMAP:
2040 if (header_len < 1) {
2041 error_report("%s: missing block name", __func__);
2042 mark_source_rp_bad(ms);
2043 goto out;
2044 }
2045 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2046 buf[buf[0] + 1] = '\0';
2047 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2048 mark_source_rp_bad(ms);
2049 goto out;
2050 }
2051 break;
2052
13955b89
PX
2053 case MIG_RP_MSG_RESUME_ACK:
2054 tmp32 = ldl_be_p(buf);
2055 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2056 mark_source_rp_bad(ms);
2057 goto out;
2058 }
2059 break;
2060
70b20477
DDAG
2061 default:
2062 break;
2063 }
2064 }
14b1742e
PX
2065
2066out:
2067 res = qemu_file_get_error(rp);
2068 if (res) {
2069 if (res == -EIO) {
2070 /*
2071 * Maybe there is something we can do: it looks like a
2072 * network down issue, and we pause for a recovery.
2073 */
2074 if (postcopy_pause_return_path_thread(ms)) {
2075 /* Reload rp, reset the rest */
2076 rp = ms->rp_state.from_dst_file;
2077 ms->rp_state.error = false;
2078 goto retry;
2079 }
2080 }
2081
70b20477
DDAG
2082 trace_source_return_path_thread_bad_end();
2083 mark_source_rp_bad(ms);
2084 }
2085
2086 trace_source_return_path_thread_end();
70b20477
DDAG
2087 ms->rp_state.from_dst_file = NULL;
2088 qemu_fclose(rp);
2089 return NULL;
2090}
2091
d3e35b8f
PX
2092static int open_return_path_on_source(MigrationState *ms,
2093 bool create_thread)
70b20477
DDAG
2094{
2095
89a02a9f 2096 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
70b20477
DDAG
2097 if (!ms->rp_state.from_dst_file) {
2098 return -1;
2099 }
2100
2101 trace_open_return_path_on_source();
d3e35b8f
PX
2102
2103 if (!create_thread) {
2104 /* We're done */
2105 return 0;
2106 }
2107
70b20477
DDAG
2108 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2109 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2110
2111 trace_open_return_path_on_source_continue();
2112
2113 return 0;
2114}
2115
70b20477
DDAG
2116/* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2117static int await_return_path_close_on_source(MigrationState *ms)
2118{
2119 /*
2120 * If this is a normal exit then the destination will send a SHUT and the
2121 * rp_thread will exit, however if there's an error we need to cause
2122 * it to exit.
2123 */
89a02a9f 2124 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
70b20477
DDAG
2125 /*
2126 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2127 * waiting for the destination.
2128 */
2129 qemu_file_shutdown(ms->rp_state.from_dst_file);
2130 mark_source_rp_bad(ms);
2131 }
2132 trace_await_return_path_close_on_source_joining();
2133 qemu_thread_join(&ms->rp_state.rp_thread);
2134 trace_await_return_path_close_on_source_close();
2135 return ms->rp_state.error;
2136}
2137
1d34e4bf
DDAG
2138/*
2139 * Switch from normal iteration to postcopy
2140 * Returns non-0 on error
2141 */
7287cbd4 2142static int postcopy_start(MigrationState *ms)
1d34e4bf
DDAG
2143{
2144 int ret;
61b67d47
DB
2145 QIOChannelBuffer *bioc;
2146 QEMUFile *fb;
1d34e4bf 2147 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
ef8d6488 2148 bool restart_block = false;
0331c8ca
DDAG
2149 int cur_state = MIGRATION_STATUS_ACTIVE;
2150 if (!migrate_pause_before_switchover()) {
2151 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2152 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2153 }
1d34e4bf
DDAG
2154
2155 trace_postcopy_start();
2156 qemu_mutex_lock_iothread();
2157 trace_postcopy_start_set_run();
2158
2159 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1d34e4bf
DDAG
2160 global_state_store();
2161 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
76b1c7fe
KW
2162 if (ret < 0) {
2163 goto fail;
2164 }
1d34e4bf 2165
0331c8ca
DDAG
2166 ret = migration_maybe_pause(ms, &cur_state,
2167 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2168 if (ret < 0) {
2169 goto fail;
2170 }
2171
76b1c7fe 2172 ret = bdrv_inactivate_all();
1d34e4bf
DDAG
2173 if (ret < 0) {
2174 goto fail;
2175 }
ef8d6488 2176 restart_block = true;
1d34e4bf 2177
1c0d249d
DDAG
2178 /*
2179 * Cause any non-postcopiable, but iterative devices to
2180 * send out their final data.
2181 */
a1fbe750 2182 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1c0d249d 2183
1d34e4bf
DDAG
2184 /*
2185 * in Finish migrate and with the io-lock held everything should
2186 * be quiet, but we've potentially still got dirty pages and we
2187 * need to tell the destination to throw any pages it's already received
2188 * that are dirty
2189 */
58110f0a
VSO
2190 if (migrate_postcopy_ram()) {
2191 if (ram_postcopy_send_discard_bitmap(ms)) {
2192 error_report("postcopy send discard bitmap failed");
2193 goto fail;
2194 }
1d34e4bf
DDAG
2195 }
2196
2197 /*
2198 * send rest of state - note things that are doing postcopy
2199 * will notice we're in POSTCOPY_ACTIVE and not actually
2200 * wrap their state up here
2201 */
89a02a9f 2202 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
58110f0a
VSO
2203 if (migrate_postcopy_ram()) {
2204 /* Ping just for debugging, helps line traces up */
2205 qemu_savevm_send_ping(ms->to_dst_file, 2);
2206 }
1d34e4bf
DDAG
2207
2208 /*
2209 * While loading the device state we may trigger page transfer
2210 * requests and the fd must be free to process those, and thus
2211 * the destination must read the whole device state off the fd before
2212 * it starts processing it. Unfortunately the ad-hoc migration format
2213 * doesn't allow the destination to know the size to read without fully
2214 * parsing it through each devices load-state code (especially the open
2215 * coded devices that use get/put).
2216 * So we wrap the device state up in a package with a length at the start;
2217 * to do this we use a qemu_buf to hold the whole of the device state.
2218 */
61b67d47 2219 bioc = qio_channel_buffer_new(4096);
6f01f136 2220 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
61b67d47
DB
2221 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2222 object_unref(OBJECT(bioc));
1d34e4bf 2223
c76201ab
DDAG
2224 /*
2225 * Make sure the receiver can get incoming pages before we send the rest
2226 * of the state
2227 */
2228 qemu_savevm_send_postcopy_listen(fb);
2229
a1fbe750 2230 qemu_savevm_state_complete_precopy(fb, false, false);
58110f0a
VSO
2231 if (migrate_postcopy_ram()) {
2232 qemu_savevm_send_ping(fb, 3);
2233 }
1d34e4bf
DDAG
2234
2235 qemu_savevm_send_postcopy_run(fb);
2236
2237 /* <><> end of stuff going into the package */
1d34e4bf 2238
ef8d6488
DDAG
2239 /* Last point of recovery; as soon as we send the package the destination
2240 * can open devices and potentially start running.
2241 * Lets just check again we've not got any errors.
2242 */
2243 ret = qemu_file_get_error(ms->to_dst_file);
2244 if (ret) {
2245 error_report("postcopy_start: Migration stream errored (pre package)");
2246 goto fail_closefb;
2247 }
2248
2249 restart_block = false;
2250
1d34e4bf 2251 /* Now send that blob */
61b67d47 2252 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1d34e4bf
DDAG
2253 goto fail_closefb;
2254 }
2255 qemu_fclose(fb);
b82fc321
DDAG
2256
2257 /* Send a notify to give a chance for anything that needs to happen
2258 * at the transition to postcopy and after the device state; in particular
2259 * spice needs to trigger a transition now
2260 */
2261 ms->postcopy_after_devices = true;
2262 notifier_list_notify(&migration_state_notifiers, ms);
2263
1d34e4bf
DDAG
2264 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2265
2266 qemu_mutex_unlock_iothread();
2267
58110f0a
VSO
2268 if (migrate_postcopy_ram()) {
2269 /*
2270 * Although this ping is just for debug, it could potentially be
2271 * used for getting a better measurement of downtime at the source.
2272 */
2273 qemu_savevm_send_ping(ms->to_dst_file, 4);
2274 }
1d34e4bf 2275
ced1c616
PB
2276 if (migrate_release_ram()) {
2277 ram_postcopy_migrated_memory_release(ms);
2278 }
2279
89a02a9f 2280 ret = qemu_file_get_error(ms->to_dst_file);
1d34e4bf
DDAG
2281 if (ret) {
2282 error_report("postcopy_start: Migration stream errored");
48781e5b 2283 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf
DDAG
2284 MIGRATION_STATUS_FAILED);
2285 }
2286
2287 return ret;
2288
2289fail_closefb:
2290 qemu_fclose(fb);
2291fail:
48781e5b 2292 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf 2293 MIGRATION_STATUS_FAILED);
ef8d6488
DDAG
2294 if (restart_block) {
2295 /* A failure happened early enough that we know the destination hasn't
2296 * accessed block devices, so we're safe to recover.
2297 */
2298 Error *local_err = NULL;
2299
2300 bdrv_invalidate_cache_all(&local_err);
2301 if (local_err) {
2302 error_report_err(local_err);
2303 }
2304 }
1d34e4bf
DDAG
2305 qemu_mutex_unlock_iothread();
2306 return -1;
2307}
2308
e91d8951
DDAG
2309/**
2310 * migration_maybe_pause: Pause if required to by
2311 * migrate_pause_before_switchover called with the iothread locked
2312 * Returns: 0 on success
2313 */
0331c8ca
DDAG
2314static int migration_maybe_pause(MigrationState *s,
2315 int *current_active_state,
2316 int new_state)
e91d8951
DDAG
2317{
2318 if (!migrate_pause_before_switchover()) {
2319 return 0;
2320 }
2321
2322 /* Since leaving this state is not atomic with posting the semaphore
2323 * it's possible that someone could have issued multiple migrate_continue
2324 * and the semaphore is incorrectly positive at this point;
2325 * the docs say it's undefined to reinit a semaphore that's already
2326 * init'd, so use timedwait to eat up any existing posts.
2327 */
2328 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2329 /* This block intentionally left blank */
2330 }
2331
2332 qemu_mutex_unlock_iothread();
2333 migrate_set_state(&s->state, *current_active_state,
2334 MIGRATION_STATUS_PRE_SWITCHOVER);
2335 qemu_sem_wait(&s->pause_sem);
2336 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
0331c8ca
DDAG
2337 new_state);
2338 *current_active_state = new_state;
e91d8951
DDAG
2339 qemu_mutex_lock_iothread();
2340
0331c8ca 2341 return s->state == new_state ? 0 : -EINVAL;
e91d8951
DDAG
2342}
2343
09f6c85e
DDAG
2344/**
2345 * migration_completion: Used by migration_thread when there's not much left.
2346 * The caller 'breaks' the loop when this returns.
2347 *
2348 * @s: Current migration state
09f6c85e 2349 */
2ad87305 2350static void migration_completion(MigrationState *s)
09f6c85e
DDAG
2351{
2352 int ret;
2ad87305 2353 int current_active_state = s->state;
09f6c85e 2354
b10ac0c4
DDAG
2355 if (s->state == MIGRATION_STATUS_ACTIVE) {
2356 qemu_mutex_lock_iothread();
64909f97 2357 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
b10ac0c4 2358 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
7287cbd4 2359 s->vm_was_running = runstate_is_running();
b10ac0c4
DDAG
2360 ret = global_state_store();
2361
2362 if (!ret) {
a1fbe750 2363 bool inactivate = !migrate_colo_enabled();
b10ac0c4 2364 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
e91d8951 2365 if (ret >= 0) {
0331c8ca
DDAG
2366 ret = migration_maybe_pause(s, &current_active_state,
2367 MIGRATION_STATUS_DEVICE);
e91d8951 2368 }
f07fa4cb
KW
2369 if (ret >= 0) {
2370 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
a1fbe750
FZ
2371 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2372 inactivate);
f07fa4cb 2373 }
a1fbe750
FZ
2374 if (inactivate && ret >= 0) {
2375 s->block_inactive = true;
b10ac0c4
DDAG
2376 }
2377 }
2378 qemu_mutex_unlock_iothread();
09f6c85e 2379
b10ac0c4
DDAG
2380 if (ret < 0) {
2381 goto fail;
09f6c85e 2382 }
b10ac0c4
DDAG
2383 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2384 trace_migration_completion_postcopy_end();
2385
89a02a9f 2386 qemu_savevm_state_complete_postcopy(s->to_dst_file);
b10ac0c4 2387 trace_migration_completion_postcopy_end_after_complete();
09f6c85e 2388 }
09f6c85e 2389
b10ac0c4
DDAG
2390 /*
2391 * If rp was opened we must clean up the thread before
2392 * cleaning everything else up (since if there are no failures
2393 * it will wait for the destination to send it's status in
2394 * a SHUT command).
b10ac0c4 2395 */
0425dc97 2396 if (s->rp_state.from_dst_file) {
b10ac0c4 2397 int rp_error;
0425dc97 2398 trace_migration_return_path_end_before();
b10ac0c4 2399 rp_error = await_return_path_close_on_source(s);
0425dc97 2400 trace_migration_return_path_end_after(rp_error);
b10ac0c4 2401 if (rp_error) {
fe904ea8 2402 goto fail_invalidate;
b10ac0c4 2403 }
09f6c85e
DDAG
2404 }
2405
89a02a9f 2406 if (qemu_file_get_error(s->to_dst_file)) {
09f6c85e 2407 trace_migration_completion_file_err();
fe904ea8 2408 goto fail_invalidate;
09f6c85e
DDAG
2409 }
2410
0b827d5e
HZ
2411 if (!migrate_colo_enabled()) {
2412 migrate_set_state(&s->state, current_active_state,
2413 MIGRATION_STATUS_COMPLETED);
2414 }
2415
09f6c85e
DDAG
2416 return;
2417
fe904ea8
GK
2418fail_invalidate:
2419 /* If not doing postcopy, vm_start() will be called: let's regain
2420 * control on images.
2421 */
6039dd5b
DDAG
2422 if (s->state == MIGRATION_STATUS_ACTIVE ||
2423 s->state == MIGRATION_STATUS_DEVICE) {
fe904ea8
GK
2424 Error *local_err = NULL;
2425
1d2acc31 2426 qemu_mutex_lock_iothread();
fe904ea8
GK
2427 bdrv_invalidate_cache_all(&local_err);
2428 if (local_err) {
2429 error_report_err(local_err);
1d2acc31
HZ
2430 } else {
2431 s->block_inactive = false;
fe904ea8 2432 }
1d2acc31 2433 qemu_mutex_unlock_iothread();
fe904ea8
GK
2434 }
2435
09f6c85e 2436fail:
48781e5b
HZ
2437 migrate_set_state(&s->state, current_active_state,
2438 MIGRATION_STATUS_FAILED);
09f6c85e
DDAG
2439}
2440
35a6ed4f
HZ
2441bool migrate_colo_enabled(void)
2442{
2443 MigrationState *s = migrate_get_current();
2444 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2445}
2446
b23c2ade
PX
2447typedef enum MigThrError {
2448 /* No error detected */
2449 MIG_THR_ERR_NONE = 0,
2450 /* Detected error, but resumed successfully */
2451 MIG_THR_ERR_RECOVERED = 1,
2452 /* Detected fatal error, need to exit */
2453 MIG_THR_ERR_FATAL = 2,
2454} MigThrError;
2455
94190696
PX
2456static int postcopy_resume_handshake(MigrationState *s)
2457{
2458 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2459
2460 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2461 qemu_sem_wait(&s->rp_state.rp_sem);
2462 }
2463
2464 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2465 return 0;
2466 }
2467
2468 return -1;
2469}
2470
135b87b4
PX
2471/* Return zero if success, or <0 for error */
2472static int postcopy_do_resume(MigrationState *s)
2473{
d1b8eadb
PX
2474 int ret;
2475
2476 /*
2477 * Call all the resume_prepare() hooks, so that modules can be
2478 * ready for the migration resume.
2479 */
2480 ret = qemu_savevm_state_resume_prepare(s);
2481 if (ret) {
2482 error_report("%s: resume_prepare() failure detected: %d",
2483 __func__, ret);
2484 return ret;
2485 }
2486
2487 /*
94190696
PX
2488 * Last handshake with destination on the resume (destination will
2489 * switch to postcopy-active afterwards)
d1b8eadb 2490 */
94190696
PX
2491 ret = postcopy_resume_handshake(s);
2492 if (ret) {
2493 error_report("%s: handshake failed: %d", __func__, ret);
2494 return ret;
2495 }
d1b8eadb 2496
135b87b4
PX
2497 return 0;
2498}
2499
b23c2ade
PX
2500/*
2501 * We don't return until we are in a safe state to continue current
2502 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2503 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2504 */
2505static MigThrError postcopy_pause(MigrationState *s)
2506{
2507 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
b23c2ade 2508
135b87b4
PX
2509 while (true) {
2510 migrate_set_state(&s->state, s->state,
2511 MIGRATION_STATUS_POSTCOPY_PAUSED);
b23c2ade 2512
135b87b4
PX
2513 /* Current channel is possibly broken. Release it. */
2514 assert(s->to_dst_file);
2515 qemu_file_shutdown(s->to_dst_file);
2516 qemu_fclose(s->to_dst_file);
2517 s->to_dst_file = NULL;
b23c2ade 2518
135b87b4
PX
2519 error_report("Detected IO failure for postcopy. "
2520 "Migration paused.");
b23c2ade 2521
135b87b4
PX
2522 /*
2523 * We wait until things fixed up. Then someone will setup the
2524 * status back for us.
2525 */
2526 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2527 qemu_sem_wait(&s->postcopy_pause_sem);
2528 }
2529
2530 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2531 /* Woken up by a recover procedure. Give it a shot */
b23c2ade 2532
135b87b4
PX
2533 /*
2534 * Firstly, let's wake up the return path now, with a new
2535 * return path channel.
2536 */
2537 qemu_sem_post(&s->postcopy_pause_rp_sem);
2538
2539 /* Do the resume logic */
2540 if (postcopy_do_resume(s) == 0) {
2541 /* Let's continue! */
2542 trace_postcopy_pause_continued();
2543 return MIG_THR_ERR_RECOVERED;
2544 } else {
2545 /*
2546 * Something wrong happened during the recovery, let's
2547 * pause again. Pause is always better than throwing
2548 * data away.
2549 */
2550 continue;
2551 }
2552 } else {
2553 /* This is not right... Time to quit. */
2554 return MIG_THR_ERR_FATAL;
2555 }
2556 }
b23c2ade
PX
2557}
2558
2559static MigThrError migration_detect_error(MigrationState *s)
2560{
2561 int ret;
2562
2563 /* Try to detect any file errors */
2564 ret = qemu_file_get_error(s->to_dst_file);
2565
2566 if (!ret) {
2567 /* Everything is fine */
2568 return MIG_THR_ERR_NONE;
2569 }
2570
2571 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
2572 /*
2573 * For postcopy, we allow the network to be down for a
2574 * while. After that, it can be continued by a
2575 * recovery phase.
2576 */
2577 return postcopy_pause(s);
2578 } else {
2579 /*
2580 * For precopy (or postcopy with error outside IO), we fail
2581 * with no time.
2582 */
2583 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
2584 trace_migration_thread_file_err();
2585
2586 /* Time to stop the migration, now. */
2587 return MIG_THR_ERR_FATAL;
2588 }
2589}
2590
cf011f08
PX
2591static void migration_calculate_complete(MigrationState *s)
2592{
2593 uint64_t bytes = qemu_ftell(s->to_dst_file);
2594 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2595
2596 s->total_time = end_time - s->start_time;
2597 if (!s->downtime) {
2598 /*
2599 * It's still not set, so we are precopy migration. For
2600 * postcopy, downtime is calculated during postcopy_start().
2601 */
2602 s->downtime = end_time - s->downtime_start;
2603 }
2604
2605 if (s->total_time) {
2606 s->mbps = ((double) bytes * 8.0) / s->total_time / 1000;
2607 }
2608}
2609
b15df1ae
PX
2610static void migration_update_counters(MigrationState *s,
2611 int64_t current_time)
2612{
2613 uint64_t transferred, time_spent;
b15df1ae
PX
2614 double bandwidth;
2615
2616 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2617 return;
2618 }
2619
2620 transferred = qemu_ftell(s->to_dst_file) - s->iteration_initial_bytes;
2621 time_spent = current_time - s->iteration_start_time;
2622 bandwidth = (double)transferred / time_spent;
0781c1ed 2623 s->threshold_size = bandwidth * s->parameters.downtime_limit;
b15df1ae
PX
2624
2625 s->mbps = (((double) transferred * 8.0) /
2626 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2627
2628 /*
2629 * if we haven't sent anything, we don't want to
2630 * recalculate. 10000 is a small enough number for our purposes
2631 */
2632 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2633 s->expected_downtime = ram_counters.dirty_pages_rate *
2634 qemu_target_page_size() / bandwidth;
2635 }
2636
2637 qemu_file_reset_rate_limit(s->to_dst_file);
2638
2639 s->iteration_start_time = current_time;
2640 s->iteration_initial_bytes = qemu_ftell(s->to_dst_file);
2641
2642 trace_migrate_transferred(transferred, time_spent,
0781c1ed 2643 bandwidth, s->threshold_size);
b15df1ae
PX
2644}
2645
2ad87305
PX
2646/* Migration thread iteration status */
2647typedef enum {
2648 MIG_ITERATE_RESUME, /* Resume current iteration */
2649 MIG_ITERATE_SKIP, /* Skip current iteration */
2650 MIG_ITERATE_BREAK, /* Break the loop */
2651} MigIterateState;
2652
2653/*
2654 * Return true if continue to the next iteration directly, false
2655 * otherwise.
2656 */
2657static MigIterateState migration_iteration_run(MigrationState *s)
2658{
47995026 2659 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2ad87305
PX
2660 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2661
47995026
VSO
2662 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2663 &pend_compat, &pend_post);
2664 pending_size = pend_pre + pend_compat + pend_post;
2ad87305
PX
2665
2666 trace_migrate_pending(pending_size, s->threshold_size,
47995026 2667 pend_pre, pend_compat, pend_post);
2ad87305
PX
2668
2669 if (pending_size && pending_size >= s->threshold_size) {
2670 /* Still a significant amount to transfer */
2671 if (migrate_postcopy() && !in_postcopy &&
47995026 2672 pend_pre <= s->threshold_size &&
2ad87305
PX
2673 atomic_read(&s->start_postcopy)) {
2674 if (postcopy_start(s)) {
2675 error_report("%s: postcopy failed to start", __func__);
2676 }
2677 return MIG_ITERATE_SKIP;
2678 }
2679 /* Just another iteration step */
2680 qemu_savevm_state_iterate(s->to_dst_file,
2681 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2682 } else {
2683 trace_migration_thread_low_pending(pending_size);
2684 migration_completion(s);
2685 return MIG_ITERATE_BREAK;
2686 }
2687
2688 return MIG_ITERATE_RESUME;
2689}
2690
199aa6d4
PX
2691static void migration_iteration_finish(MigrationState *s)
2692{
2693 /* If we enabled cpu throttling for auto-converge, turn it off. */
2694 cpu_throttle_stop();
2695
2696 qemu_mutex_lock_iothread();
2697 switch (s->state) {
2698 case MIGRATION_STATUS_COMPLETED:
2699 migration_calculate_complete(s);
2700 runstate_set(RUN_STATE_POSTMIGRATE);
2701 break;
2702
2703 case MIGRATION_STATUS_ACTIVE:
2704 /*
2705 * We should really assert here, but since it's during
2706 * migration, let's try to reduce the usage of assertions.
2707 */
2708 if (!migrate_colo_enabled()) {
2709 error_report("%s: critical error: calling COLO code without "
2710 "COLO enabled", __func__);
2711 }
2712 migrate_start_colo_process(s);
2713 /*
2714 * Fixme: we will run VM in COLO no matter its old running state.
2715 * After exited COLO, we will keep running.
2716 */
2717 s->vm_was_running = true;
2718 /* Fallthrough */
2719 case MIGRATION_STATUS_FAILED:
2720 case MIGRATION_STATUS_CANCELLED:
2721 if (s->vm_was_running) {
2722 vm_start();
2723 } else {
2724 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2725 runstate_set(RUN_STATE_POSTMIGRATE);
2726 }
2727 }
2728 break;
2729
2730 default:
2731 /* Should not reach here, but if so, forgive the VM. */
2732 error_report("%s: Unknown ending state %d", __func__, s->state);
2733 break;
2734 }
2735 qemu_bh_schedule(s->cleanup_bh);
2736 qemu_mutex_unlock_iothread();
2737}
2738
70b20477
DDAG
2739/*
2740 * Master migration thread on the source VM.
2741 * It drives the migration and pumps the data down the outgoing channel.
2742 */
5f496a1b 2743static void *migration_thread(void *opaque)
0d82d0e8 2744{
9848a404 2745 MigrationState *s = opaque;
bc72ad67 2746 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
b23c2ade 2747 MigThrError thr_error;
76f5933a 2748
ab28bd23
PB
2749 rcu_register_thread();
2750
b15df1ae
PX
2751 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2752
89a02a9f 2753 qemu_savevm_state_header(s->to_dst_file);
1d34e4bf 2754
62a02658
PX
2755 /*
2756 * If we opened the return path, we need to make sure dst has it
2757 * opened as well.
2758 */
2759 if (s->rp_state.from_dst_file) {
1d34e4bf 2760 /* Now tell the dest that it should open its end so it can reply */
89a02a9f 2761 qemu_savevm_send_open_return_path(s->to_dst_file);
1d34e4bf
DDAG
2762
2763 /* And do a ping that will make stuff easier to debug */
89a02a9f 2764 qemu_savevm_send_ping(s->to_dst_file, 1);
0425dc97 2765 }
1d34e4bf 2766
58110f0a 2767 if (migrate_postcopy()) {
1d34e4bf
DDAG
2768 /*
2769 * Tell the destination that we *might* want to do postcopy later;
2770 * if the other end can't do postcopy it should fail now, nice and
2771 * early.
2772 */
89a02a9f 2773 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1d34e4bf
DDAG
2774 }
2775
9907e842 2776 qemu_savevm_state_setup(s->to_dst_file);
0d82d0e8 2777
bc72ad67 2778 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
48781e5b
HZ
2779 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2780 MIGRATION_STATUS_ACTIVE);
29ae8a41 2781
9ec055ae
DDAG
2782 trace_migration_thread_setup_complete();
2783
2784 while (s->state == MIGRATION_STATUS_ACTIVE ||
2785 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
a3e879cd 2786 int64_t current_time;
0d82d0e8 2787
89a02a9f 2788 if (!qemu_file_rate_limit(s->to_dst_file)) {
2ad87305
PX
2789 MigIterateState iter_state = migration_iteration_run(s);
2790 if (iter_state == MIG_ITERATE_SKIP) {
2791 continue;
2792 } else if (iter_state == MIG_ITERATE_BREAK) {
09f6c85e 2793 break;
c369f40d
JQ
2794 }
2795 }
f4410a5d 2796
b23c2ade
PX
2797 /*
2798 * Try to detect any kind of failures, and see whether we
2799 * should stop the migration now.
2800 */
2801 thr_error = migration_detect_error(s);
2802 if (thr_error == MIG_THR_ERR_FATAL) {
2803 /* Stop migration */
fd45ee2c 2804 break;
b23c2ade
PX
2805 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
2806 /*
2807 * Just recovered from a e.g. network failure, reset all
2808 * the local variables. This is important to avoid
2809 * breaking transferred_bytes and bandwidth calculation
2810 */
2811 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2812 s->iteration_initial_bytes = 0;
fd45ee2c 2813 }
b15df1ae 2814
bc72ad67 2815 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0d82d0e8 2816
b15df1ae
PX
2817 migration_update_counters(s, current_time);
2818
89a02a9f 2819 if (qemu_file_rate_limit(s->to_dst_file)) {
0d82d0e8 2820 /* usleep expects microseconds */
b15df1ae
PX
2821 g_usleep((s->iteration_start_time + BUFFER_DELAY -
2822 current_time) * 1000);
0d82d0e8 2823 }
a3fa1d78
PB
2824 }
2825
1d34e4bf 2826 trace_migration_thread_after_loop();
199aa6d4 2827 migration_iteration_finish(s);
ab28bd23 2828 rcu_unregister_thread();
0d82d0e8
JQ
2829 return NULL;
2830}
2831
cce8040b 2832void migrate_fd_connect(MigrationState *s, Error *error_in)
0d82d0e8 2833{
d3e35b8f
PX
2834 int64_t rate_limit;
2835 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
2836
2ff30257 2837 s->expected_downtime = s->parameters.downtime_limit;
bb1fadc4 2838 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
cce8040b
DDAG
2839 if (error_in) {
2840 migrate_fd_error(s, error_in);
2841 migrate_fd_cleanup(s);
2842 return;
2843 }
0d82d0e8 2844
d3e35b8f
PX
2845 if (resume) {
2846 /* This is a resumed migration */
2847 rate_limit = INT64_MAX;
2848 } else {
2849 /* This is a fresh new migration */
2850 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
2851 s->expected_downtime = s->parameters.downtime_limit;
2852 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
442773ce 2853
d3e35b8f
PX
2854 /* Notify before starting migration thread */
2855 notifier_list_notify(&migration_state_notifiers, s);
2856 }
2857
2858 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
2859 qemu_file_set_blocking(s->to_dst_file, true);
9287ac27 2860
1d34e4bf 2861 /*
c788ada8
PX
2862 * Open the return path. For postcopy, it is used exclusively. For
2863 * precopy, only if user specified "return-path" capability would
2864 * QEMU uses the return path.
1d34e4bf 2865 */
c788ada8 2866 if (migrate_postcopy_ram() || migrate_use_return_path()) {
d3e35b8f 2867 if (open_return_path_on_source(s, !resume)) {
1d34e4bf 2868 error_report("Unable to open return-path for postcopy");
d3e35b8f 2869 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
1d34e4bf
DDAG
2870 migrate_fd_cleanup(s);
2871 return;
2872 }
2873 }
2874
d3e35b8f 2875 if (resume) {
135b87b4
PX
2876 /* Wakeup the main migration thread to do the recovery */
2877 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
2878 MIGRATION_STATUS_POSTCOPY_RECOVER);
2879 qemu_sem_post(&s->postcopy_pause_sem);
d3e35b8f
PX
2880 return;
2881 }
2882
f986c3d2
JQ
2883 if (multifd_save_setup() != 0) {
2884 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2885 MIGRATION_STATUS_FAILED);
2886 migrate_fd_cleanup(s);
2887 return;
2888 }
009fad7f 2889 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
bb1fadc4 2890 QEMU_THREAD_JOINABLE);
1d34e4bf 2891 s->migration_thread_running = true;
0d82d0e8 2892}
093e3c42 2893
9d18af93
PX
2894void migration_global_dump(Monitor *mon)
2895{
2896 MigrationState *ms = migrate_get_current();
2897
6f0f6428
JQ
2898 monitor_printf(mon, "globals:\n");
2899 monitor_printf(mon, "store-global-state: %s\n",
2900 ms->store_global_state ? "on" : "off");
2901 monitor_printf(mon, "only-migratable: %s\n",
2902 ms->only_migratable ? "on" : "off");
2903 monitor_printf(mon, "send-configuration: %s\n",
2904 ms->send_configuration ? "on" : "off");
2905 monitor_printf(mon, "send-section-footer: %s\n",
2906 ms->send_section_footer ? "on" : "off");
9d18af93
PX
2907}
2908
20814758
PX
2909#define DEFINE_PROP_MIG_CAP(name, x) \
2910 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2911
5272298c
PX
2912static Property migration_properties[] = {
2913 DEFINE_PROP_BOOL("store-global-state", MigrationState,
2914 store_global_state, true),
3df663e5 2915 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
71dd4c1a
PX
2916 DEFINE_PROP_BOOL("send-configuration", MigrationState,
2917 send_configuration, true),
15c38503
PX
2918 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
2919 send_section_footer, true),
89632faf
PX
2920
2921 /* Migration parameters */
741d4086 2922 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
89632faf
PX
2923 parameters.compress_level,
2924 DEFAULT_MIGRATE_COMPRESS_LEVEL),
741d4086 2925 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
89632faf
PX
2926 parameters.compress_threads,
2927 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
741d4086 2928 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
89632faf
PX
2929 parameters.decompress_threads,
2930 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
741d4086 2931 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
89632faf
PX
2932 parameters.cpu_throttle_initial,
2933 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
741d4086 2934 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
89632faf
PX
2935 parameters.cpu_throttle_increment,
2936 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
741d4086 2937 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
89632faf 2938 parameters.max_bandwidth, MAX_THROTTLE),
741d4086 2939 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
89632faf
PX
2940 parameters.downtime_limit,
2941 DEFAULT_MIGRATE_SET_DOWNTIME),
741d4086 2942 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
89632faf
PX
2943 parameters.x_checkpoint_delay,
2944 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
741d4086 2945 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
4075fb1c
JQ
2946 parameters.x_multifd_channels,
2947 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
741d4086 2948 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
0fb86605
JQ
2949 parameters.x_multifd_page_count,
2950 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
73af8dd8
JQ
2951 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
2952 parameters.xbzrle_cache_size,
2953 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
20814758
PX
2954
2955 /* Migration capabilities */
2956 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
2957 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
2958 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
2959 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
2960 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
2961 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
2962 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
2963 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
2964 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
2965 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
2966 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
30126bbf 2967 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
20814758 2968
5272298c
PX
2969 DEFINE_PROP_END_OF_LIST(),
2970};
2971
e5cb7e76
PX
2972static void migration_class_init(ObjectClass *klass, void *data)
2973{
2974 DeviceClass *dc = DEVICE_CLASS(klass);
2975
2976 dc->user_creatable = false;
5272298c 2977 dc->props = migration_properties;
e5cb7e76
PX
2978}
2979
b91bf5e4
MAL
2980static void migration_instance_finalize(Object *obj)
2981{
2982 MigrationState *ms = MIGRATION_OBJ(obj);
2983 MigrationParameters *params = &ms->parameters;
2984
87db1a7d 2985 qemu_mutex_destroy(&ms->error_mutex);
b91bf5e4
MAL
2986 g_free(params->tls_hostname);
2987 g_free(params->tls_creds);
e91d8951 2988 qemu_sem_destroy(&ms->pause_sem);
b23c2ade 2989 qemu_sem_destroy(&ms->postcopy_pause_sem);
14b1742e 2990 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
edd090c7 2991 qemu_sem_destroy(&ms->rp_state.rp_sem);
ab105cc1 2992 error_free(ms->error);
b91bf5e4
MAL
2993}
2994
e5cb7e76
PX
2995static void migration_instance_init(Object *obj)
2996{
2997 MigrationState *ms = MIGRATION_OBJ(obj);
8b0b29dc 2998 MigrationParameters *params = &ms->parameters;
e5cb7e76
PX
2999
3000 ms->state = MIGRATION_STATUS_NONE;
e5cb7e76 3001 ms->mbps = -1;
e91d8951 3002 qemu_sem_init(&ms->pause_sem, 0);
87db1a7d 3003 qemu_mutex_init(&ms->error_mutex);
8b0b29dc
PX
3004
3005 params->tls_hostname = g_strdup("");
3006 params->tls_creds = g_strdup("");
3007
3008 /* Set has_* up only for parameter checks */
3009 params->has_compress_level = true;
3010 params->has_compress_threads = true;
3011 params->has_decompress_threads = true;
3012 params->has_cpu_throttle_initial = true;
3013 params->has_cpu_throttle_increment = true;
3014 params->has_max_bandwidth = true;
3015 params->has_downtime_limit = true;
3016 params->has_x_checkpoint_delay = true;
3017 params->has_block_incremental = true;
4075fb1c 3018 params->has_x_multifd_channels = true;
0fb86605 3019 params->has_x_multifd_page_count = true;
73af8dd8 3020 params->has_xbzrle_cache_size = true;
b23c2ade
PX
3021
3022 qemu_sem_init(&ms->postcopy_pause_sem, 0);
14b1742e 3023 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
edd090c7 3024 qemu_sem_init(&ms->rp_state.rp_sem, 0);
8b0b29dc
PX
3025}
3026
3027/*
3028 * Return true if check pass, false otherwise. Error will be put
3029 * inside errp if provided.
3030 */
3031static bool migration_object_check(MigrationState *ms, Error **errp)
3032{
6b19a7d9
PX
3033 MigrationCapabilityStatusList *head = NULL;
3034 /* Assuming all off */
3035 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3036 int i;
3037
8b0b29dc
PX
3038 if (!migrate_params_check(&ms->parameters, errp)) {
3039 return false;
3040 }
3041
6b19a7d9
PX
3042 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3043 if (ms->enabled_capabilities[i]) {
3044 head = migrate_cap_add(head, i, true);
3045 }
3046 }
3047
3048 ret = migrate_caps_check(cap_list, head, errp);
3049
3050 /* It works with head == NULL */
3051 qapi_free_MigrationCapabilityStatusList(head);
3052
3053 return ret;
e5cb7e76
PX
3054}
3055
3056static const TypeInfo migration_type = {
3057 .name = TYPE_MIGRATION,
01f6e14c 3058 /*
c8d3ff38
PX
3059 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3060 * not created using qdev_create(), it is not attached to the qdev
3061 * device tree, and it is never realized.
3062 *
3063 * TODO: Make this TYPE_OBJECT once QOM provides something like
3064 * TYPE_DEVICE's "-global" properties.
01f6e14c 3065 */
e5cb7e76
PX
3066 .parent = TYPE_DEVICE,
3067 .class_init = migration_class_init,
3068 .class_size = sizeof(MigrationClass),
3069 .instance_size = sizeof(MigrationState),
3070 .instance_init = migration_instance_init,
b91bf5e4 3071 .instance_finalize = migration_instance_finalize,
e5cb7e76
PX
3072};
3073
3074static void register_migration_types(void)
3075{
3076 type_register_static(&migration_type);
3077}
3078
3079type_init(register_migration_types);