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