]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
migration: Split qemu-file.h
[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"
6a1751b7 19#include "qemu/main-loop.h"
795c40b8 20#include "migration/blocker.h"
caf71f86 21#include "migration/migration.h"
20a519a0 22#include "savevm.h"
40014d81 23#include "qemu-file-channel.h"
08a0aee1 24#include "qemu-file.h"
987772d9 25#include "migration/vmstate.h"
9c17d615 26#include "sysemu/sysemu.h"
737e150e 27#include "block/block.h"
cc7a8ea7 28#include "qapi/qmp/qerror.h"
6c595cde 29#include "qapi/util.h"
1de7afc9 30#include "qemu/sockets.h"
ab28bd23 31#include "qemu/rcu.h"
caf71f86 32#include "migration/block.h"
be07b0ac 33#include "postcopy-ram.h"
766bd176 34#include "qemu/thread.h"
791e7c82 35#include "qmp-commands.h"
c09e5bb1 36#include "trace.h"
598cd2bd 37#include "qapi-event.h"
070afca2 38#include "qom/cpu.h"
6c595cde
DDAG
39#include "exec/memory.h"
40#include "exec/address-spaces.h"
51180423 41#include "exec/target_page.h"
61b67d47 42#include "io/channel-buffer.h"
e1226365 43#include "io/channel-tls.h"
35a6ed4f 44#include "migration/colo.h"
065e2813 45
dc325627 46#define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
5bb7910a 47
5b4e1eb7
JQ
48/* Amount of time to allocate to each "chunk" of bandwidth-throttled
49 * data. */
50#define BUFFER_DELAY 100
51#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
52
2ff30257
AA
53/* Time in milliseconds we are allowed to stop the source,
54 * for sending the last part */
55#define DEFAULT_MIGRATE_SET_DOWNTIME 300
56
87c9cc1c
DHB
57/* Maximum migrate downtime set to 2000 seconds */
58#define MAX_MIGRATE_DOWNTIME_SECONDS 2000
59#define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
60
8706d2d5
LL
61/* Default compression thread count */
62#define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
3fcb38c2
LL
63/* Default decompression thread count, usually decompression is at
64 * least 4 times as fast as compression.*/
65#define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
8706d2d5
LL
66/*0: means nocompress, 1: best speed, ... 9: best compress ratio */
67#define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
1626fee3 68/* Define default autoconverge cpu throttle migration parameters */
d85a31d1
JH
69#define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
70#define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
8706d2d5 71
17ad9b35
OW
72/* Migration XBZRLE default cache size */
73#define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
74
68b53591
HZ
75/* The delay time (in ms) between two COLO checkpoints
76 * Note: Please change this default value to 10000 when we support hybrid mode.
77 */
78#define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
79
99a0db9b
GH
80static NotifierList migration_state_notifiers =
81 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
82
adde220a
DDAG
83static bool deferred_incoming;
84
17549e84
JQ
85/* When we add fault tolerance, we could have several
86 migrations at once. For now we don't need to add
87 dynamic creation of migration */
88
bca7856a 89/* For outgoing */
859bc756 90MigrationState *migrate_get_current(void)
17549e84 91{
6c595cde 92 static bool once;
17549e84 93 static MigrationState current_migration = {
31194731 94 .state = MIGRATION_STATUS_NONE,
17ad9b35 95 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
7e114f8c 96 .mbps = -1,
2594f56d
DB
97 .parameters = {
98 .compress_level = DEFAULT_MIGRATE_COMPRESS_LEVEL,
99 .compress_threads = DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
100 .decompress_threads = DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
101 .cpu_throttle_initial = DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL,
102 .cpu_throttle_increment = DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT,
2ff30257
AA
103 .max_bandwidth = MAX_THROTTLE,
104 .downtime_limit = DEFAULT_MIGRATE_SET_DOWNTIME,
68b53591 105 .x_checkpoint_delay = DEFAULT_MIGRATE_X_CHECKPOINT_DELAY,
2594f56d 106 },
17549e84
JQ
107 };
108
6c595cde 109 if (!once) {
4af245dc
DB
110 current_migration.parameters.tls_creds = g_strdup("");
111 current_migration.parameters.tls_hostname = g_strdup("");
6c595cde
DDAG
112 once = true;
113 }
17549e84
JQ
114 return &current_migration;
115}
116
bca7856a
DDAG
117MigrationIncomingState *migration_incoming_get_current(void)
118{
b4b076da
JQ
119 static bool once;
120 static MigrationIncomingState mis_current;
bca7856a 121
b4b076da
JQ
122 if (!once) {
123 mis_current.state = MIGRATION_STATUS_NONE;
124 memset(&mis_current, 0, sizeof(MigrationIncomingState));
b4b076da
JQ
125 qemu_mutex_init(&mis_current.rp_mutex);
126 qemu_event_init(&mis_current.main_thread_load_event, false);
127 once = true;
128 }
129 return &mis_current;
bca7856a
DDAG
130}
131
132void migration_incoming_state_destroy(void)
133{
b4b076da
JQ
134 struct MigrationIncomingState *mis = migration_incoming_get_current();
135
3482655b 136 if (mis->to_src_file) {
660819b1
PX
137 /* Tell source that we are done */
138 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
3482655b
PX
139 qemu_fclose(mis->to_src_file);
140 mis->to_src_file = NULL;
141 }
142
660819b1
PX
143 if (mis->from_src_file) {
144 qemu_fclose(mis->from_src_file);
145 mis->from_src_file = NULL;
146 }
147
b4b076da 148 qemu_event_destroy(&mis->main_thread_load_event);
bca7856a
DDAG
149}
150
df4b1024
JQ
151
152typedef struct {
13d16814 153 bool optional;
df4b1024
JQ
154 uint32_t size;
155 uint8_t runstate[100];
172c4356
JQ
156 RunState state;
157 bool received;
df4b1024
JQ
158} GlobalState;
159
160static GlobalState global_state;
161
560d027b 162int global_state_store(void)
df4b1024
JQ
163{
164 if (!runstate_store((char *)global_state.runstate,
165 sizeof(global_state.runstate))) {
166 error_report("runstate name too big: %s", global_state.runstate);
167 trace_migrate_state_too_big();
168 return -EINVAL;
169 }
170 return 0;
171}
172
c69adea4
AP
173void global_state_store_running(void)
174{
175 const char *state = RunState_lookup[RUN_STATE_RUNNING];
176 strncpy((char *)global_state.runstate,
177 state, sizeof(global_state.runstate));
178}
179
172c4356 180static bool global_state_received(void)
df4b1024 181{
172c4356
JQ
182 return global_state.received;
183}
184
185static RunState global_state_get_runstate(void)
186{
187 return global_state.state;
df4b1024
JQ
188}
189
13d16814
JQ
190void global_state_set_optional(void)
191{
192 global_state.optional = true;
193}
194
195static bool global_state_needed(void *opaque)
196{
197 GlobalState *s = opaque;
198 char *runstate = (char *)s->runstate;
199
200 /* If it is not optional, it is mandatory */
201
202 if (s->optional == false) {
203 return true;
204 }
205
206 /* If state is running or paused, it is not needed */
207
208 if (strcmp(runstate, "running") == 0 ||
209 strcmp(runstate, "paused") == 0) {
210 return false;
211 }
212
213 /* for any other state it is needed */
214 return true;
215}
216
df4b1024
JQ
217static int global_state_post_load(void *opaque, int version_id)
218{
219 GlobalState *s = opaque;
172c4356
JQ
220 Error *local_err = NULL;
221 int r;
df4b1024
JQ
222 char *runstate = (char *)s->runstate;
223
172c4356 224 s->received = true;
df4b1024
JQ
225 trace_migrate_global_state_post_load(runstate);
226
7fb1cf16 227 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE__MAX,
df4b1024
JQ
228 -1, &local_err);
229
172c4356
JQ
230 if (r == -1) {
231 if (local_err) {
232 error_report_err(local_err);
df4b1024 233 }
172c4356 234 return -EINVAL;
df4b1024 235 }
172c4356 236 s->state = r;
df4b1024 237
172c4356 238 return 0;
df4b1024
JQ
239}
240
241static void global_state_pre_save(void *opaque)
242{
243 GlobalState *s = opaque;
244
245 trace_migrate_global_state_pre_save((char *)s->runstate);
246 s->size = strlen((char *)s->runstate) + 1;
247}
248
249static const VMStateDescription vmstate_globalstate = {
250 .name = "globalstate",
251 .version_id = 1,
252 .minimum_version_id = 1,
253 .post_load = global_state_post_load,
254 .pre_save = global_state_pre_save,
13d16814 255 .needed = global_state_needed,
df4b1024
JQ
256 .fields = (VMStateField[]) {
257 VMSTATE_UINT32(size, GlobalState),
258 VMSTATE_BUFFER(runstate, GlobalState),
259 VMSTATE_END_OF_LIST()
260 },
261};
262
263void register_global_state(void)
264{
265 /* We would use it independently that we receive it */
266 strcpy((char *)&global_state.runstate, "");
172c4356 267 global_state.received = false;
df4b1024
JQ
268 vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
269}
270
b05dc723
JQ
271static void migrate_generate_event(int new_state)
272{
273 if (migrate_use_events()) {
274 qapi_event_send_migration(new_state, &error_abort);
b05dc723
JQ
275 }
276}
277
adde220a
DDAG
278/*
279 * Called on -incoming with a defer: uri.
280 * The migration can be started later after any parameters have been
281 * changed.
282 */
283static void deferred_incoming_migration(Error **errp)
284{
285 if (deferred_incoming) {
286 error_setg(errp, "Incoming migration already deferred");
287 }
288 deferred_incoming = true;
289}
290
1e2d90eb
DDAG
291/* Request a range of pages from the source VM at the given
292 * start address.
293 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
294 * as the last request (a name must have been given previously)
295 * Start: Address offset within the RB
296 * Len: Length in bytes required - must be a multiple of pagesize
297 */
298void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
299 ram_addr_t start, size_t len)
300{
cb8d4c8f 301 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
1e2d90eb
DDAG
302 size_t msglen = 12; /* start + len */
303
304 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
305 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
306
307 if (rbname) {
308 int rbname_len = strlen(rbname);
309 assert(rbname_len < 256);
310
311 bufc[msglen++] = rbname_len;
312 memcpy(bufc + msglen, rbname, rbname_len);
313 msglen += rbname_len;
314 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES_ID, msglen, bufc);
315 } else {
316 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES, msglen, bufc);
317 }
318}
319
43eaae28 320void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 321{
34c9dd8e
AL
322 const char *p;
323
7cf1fe6d 324 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
adde220a
DDAG
325 if (!strcmp(uri, "defer")) {
326 deferred_incoming_migration(errp);
327 } else if (strstart(uri, "tcp:", &p)) {
43eaae28 328 tcp_start_incoming_migration(p, errp);
2da776db 329#ifdef CONFIG_RDMA
adde220a 330 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
331 rdma_start_incoming_migration(p, errp);
332#endif
adde220a 333 } else if (strstart(uri, "exec:", &p)) {
43eaae28 334 exec_start_incoming_migration(p, errp);
adde220a 335 } else if (strstart(uri, "unix:", &p)) {
43eaae28 336 unix_start_incoming_migration(p, errp);
adde220a 337 } else if (strstart(uri, "fd:", &p)) {
43eaae28 338 fd_start_incoming_migration(p, errp);
adde220a 339 } else {
312fd5f2 340 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 341 }
5bb7910a
AL
342}
343
0aa6aefc
DL
344static void process_incoming_migration_bh(void *opaque)
345{
346 Error *local_err = NULL;
347 MigrationIncomingState *mis = opaque;
348
ace21a58
KW
349 /* Make sure all file formats flush their mutable metadata.
350 * If we get an error here, just don't restart the VM yet. */
0aa6aefc 351 bdrv_invalidate_cache_all(&local_err);
d35ff5e6 352 if (local_err) {
ace21a58 353 error_report_err(local_err);
d35ff5e6
KW
354 local_err = NULL;
355 autostart = false;
356 }
357
0aa6aefc
DL
358 /*
359 * This must happen after all error conditions are dealt with and
360 * we're sure the VM is going to be running on this host.
361 */
362 qemu_announce_self();
363
364 /* If global state section was not received or we are in running
365 state, we need to obey autostart. Any other state is set with
366 runstate_set. */
367
368 if (!global_state_received() ||
369 global_state_get_runstate() == RUN_STATE_RUNNING) {
370 if (autostart) {
371 vm_start();
372 } else {
373 runstate_set(RUN_STATE_PAUSED);
374 }
375 } else {
376 runstate_set(global_state_get_runstate());
377 }
378 migrate_decompress_threads_join();
379 /*
380 * This must happen after any state changes since as soon as an external
381 * observer sees this event they might start to prod at the VM assuming
382 * it's ready to use.
383 */
384 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
385 MIGRATION_STATUS_COMPLETED);
386 qemu_bh_delete(mis->bh);
387 migration_incoming_state_destroy();
388}
389
82a4da79 390static void process_incoming_migration_co(void *opaque)
511c0231 391{
82a4da79 392 QEMUFile *f = opaque;
b4b076da 393 MigrationIncomingState *mis = migration_incoming_get_current();
e9bef235 394 PostcopyState ps;
1c12e1f5
PB
395 int ret;
396
b4b076da 397 mis->from_src_file = f;
67f11b5c 398 mis->largest_page_size = qemu_ram_pagesize_largest();
093e3c42 399 postcopy_state_set(POSTCOPY_INCOMING_NONE);
93d7af6f
HZ
400 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
401 MIGRATION_STATUS_ACTIVE);
1c12e1f5 402 ret = qemu_loadvm_state(f);
bca7856a 403
e9bef235
DDAG
404 ps = postcopy_state_get();
405 trace_process_incoming_migration_co_end(ret, ps);
406 if (ps != POSTCOPY_INCOMING_NONE) {
407 if (ps == POSTCOPY_INCOMING_ADVISE) {
408 /*
409 * Where a migration had postcopy enabled (and thus went to advise)
410 * but managed to complete within the precopy period, we can use
411 * the normal exit.
412 */
413 postcopy_ram_incoming_cleanup(mis);
414 } else if (ret >= 0) {
415 /*
416 * Postcopy was started, cleanup should happen at the end of the
417 * postcopy thread.
418 */
419 trace_process_incoming_migration_co_postcopy_end_main();
420 return;
421 }
422 /* Else if something went wrong then just fall out of the normal exit */
423 }
424
25d0c16f
HZ
425 /* we get COLO info, and know if we are in COLO mode */
426 if (!ret && migration_incoming_enable_colo()) {
427 mis->migration_incoming_co = qemu_coroutine_self();
428 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
429 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
430 mis->have_colo_incoming_thread = true;
431 qemu_coroutine_yield();
432
433 /* Wait checkpoint incoming thread exit before free resource */
434 qemu_thread_join(&mis->colo_incoming_thread);
435 }
436
1c12e1f5 437 if (ret < 0) {
93d7af6f
HZ
438 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
439 MIGRATION_STATUS_FAILED);
db80face 440 error_report("load of migration failed: %s", strerror(-ret));
3fcb38c2 441 migrate_decompress_threads_join();
4aead692 442 exit(EXIT_FAILURE);
511c0231 443 }
511c0231 444
e8199e48
LV
445 free_xbzrle_decoded_buf();
446
0aa6aefc
DL
447 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
448 qemu_bh_schedule(mis->bh);
511c0231
JQ
449}
450
22724f49 451void migration_fd_process_incoming(QEMUFile *f)
82a4da79 452{
0b8b8753 453 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, f);
82a4da79 454
3fcb38c2 455 migrate_decompress_threads_create();
06ad5135 456 qemu_file_set_blocking(f, false);
0b8b8753 457 qemu_coroutine_enter(co);
82a4da79
PB
458}
459
6decec93
DDAG
460/*
461 * Send a message on the return channel back to the source
462 * of the migration.
463 */
464void migrate_send_rp_message(MigrationIncomingState *mis,
465 enum mig_rp_message_type message_type,
466 uint16_t len, void *data)
467{
468 trace_migrate_send_rp_message((int)message_type, len);
469 qemu_mutex_lock(&mis->rp_mutex);
470 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
471 qemu_put_be16(mis->to_src_file, len);
472 qemu_put_buffer(mis->to_src_file, data, len);
473 qemu_fflush(mis->to_src_file);
474 qemu_mutex_unlock(&mis->rp_mutex);
475}
476
477/*
478 * Send a 'SHUT' message on the return channel with the given value
479 * to indicate that we've finished with the RP. Non-0 value indicates
480 * error.
481 */
482void migrate_send_rp_shut(MigrationIncomingState *mis,
483 uint32_t value)
484{
485 uint32_t buf;
486
487 buf = cpu_to_be32(value);
488 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
489}
490
491/*
492 * Send a 'PONG' message on the return channel with the given value
493 * (normally in response to a 'PING')
494 */
495void migrate_send_rp_pong(MigrationIncomingState *mis,
496 uint32_t value)
497{
498 uint32_t buf;
499
500 buf = cpu_to_be32(value);
501 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
502}
503
bbf6da32
OW
504MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
505{
506 MigrationCapabilityStatusList *head = NULL;
507 MigrationCapabilityStatusList *caps;
508 MigrationState *s = migrate_get_current();
509 int i;
510
387eedeb 511 caps = NULL; /* silence compiler warning */
7fb1cf16 512 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
ed1701c6
DDAG
513#ifndef CONFIG_LIVE_BLOCK_MIGRATION
514 if (i == MIGRATION_CAPABILITY_BLOCK) {
515 continue;
516 }
517#endif
35a6ed4f
HZ
518 if (i == MIGRATION_CAPABILITY_X_COLO && !colo_supported()) {
519 continue;
520 }
bbf6da32
OW
521 if (head == NULL) {
522 head = g_malloc0(sizeof(*caps));
523 caps = head;
524 } else {
525 caps->next = g_malloc0(sizeof(*caps));
526 caps = caps->next;
527 }
528 caps->value =
529 g_malloc(sizeof(*caps->value));
530 caps->value->capability = i;
531 caps->value->state = s->enabled_capabilities[i];
532 }
533
534 return head;
535}
536
85de8323
LL
537MigrationParameters *qmp_query_migrate_parameters(Error **errp)
538{
539 MigrationParameters *params;
540 MigrationState *s = migrate_get_current();
541
542 params = g_malloc0(sizeof(*params));
de63ab61 543 params->has_compress_level = true;
2594f56d 544 params->compress_level = s->parameters.compress_level;
de63ab61 545 params->has_compress_threads = true;
2594f56d 546 params->compress_threads = s->parameters.compress_threads;
de63ab61 547 params->has_decompress_threads = true;
2594f56d 548 params->decompress_threads = s->parameters.decompress_threads;
de63ab61 549 params->has_cpu_throttle_initial = true;
2594f56d 550 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
de63ab61 551 params->has_cpu_throttle_increment = true;
2594f56d 552 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
de63ab61 553 params->has_tls_creds = !!s->parameters.tls_creds;
69ef1f36 554 params->tls_creds = g_strdup(s->parameters.tls_creds);
de63ab61 555 params->has_tls_hostname = !!s->parameters.tls_hostname;
69ef1f36 556 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
2ff30257
AA
557 params->has_max_bandwidth = true;
558 params->max_bandwidth = s->parameters.max_bandwidth;
559 params->has_downtime_limit = true;
560 params->downtime_limit = s->parameters.downtime_limit;
fe39a4d4 561 params->has_x_checkpoint_delay = true;
68b53591 562 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
2833c59b
JQ
563 params->has_block_incremental = true;
564 params->block_incremental = s->parameters.block_incremental;
85de8323
LL
565
566 return params;
567}
568
f6844b99
DDAG
569/*
570 * Return true if we're already in the middle of a migration
571 * (i.e. any of the active or setup states)
572 */
573static bool migration_is_setup_or_active(int state)
574{
575 switch (state) {
576 case MIGRATION_STATUS_ACTIVE:
9ec055ae 577 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
f6844b99
DDAG
578 case MIGRATION_STATUS_SETUP:
579 return true;
580
581 default:
582 return false;
583
584 }
585}
586
f36d55af
OW
587static void get_xbzrle_cache_stats(MigrationInfo *info)
588{
589 if (migrate_use_xbzrle()) {
590 info->has_xbzrle_cache = true;
591 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
592 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
593 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
594 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
595 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
8bc39233 596 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
f36d55af
OW
597 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
598 }
599}
600
a22463a5
DDAG
601static void populate_ram_info(MigrationInfo *info, MigrationState *s)
602{
603 info->has_ram = true;
604 info->ram = g_malloc0(sizeof(*info->ram));
605 info->ram->transferred = ram_bytes_transferred();
606 info->ram->total = ram_bytes_total();
607 info->ram->duplicate = dup_mig_pages_transferred();
bedf53c1
JQ
608 /* legacy value. It is not used anymore */
609 info->ram->skipped = 0;
a22463a5 610 info->ram->normal = norm_mig_pages_transferred();
29cc3d8a 611 info->ram->normal_bytes = norm_mig_pages_transferred() *
20afaed9 612 qemu_target_page_size();
a22463a5 613 info->ram->mbps = s->mbps;
42d219d3 614 info->ram->dirty_sync_count = ram_dirty_sync_count();
96506894 615 info->ram->postcopy_requests = ram_postcopy_requests();
030ce1f8 616 info->ram->page_size = qemu_target_page_size();
a22463a5
DDAG
617
618 if (s->state != MIGRATION_STATUS_COMPLETED) {
619 info->ram->remaining = ram_bytes_remaining();
47ad8619 620 info->ram->dirty_pages_rate = ram_dirty_pages_rate();
a22463a5
DDAG
621 }
622}
623
791e7c82 624MigrationInfo *qmp_query_migrate(Error **errp)
5bb7910a 625{
791e7c82 626 MigrationInfo *info = g_malloc0(sizeof(*info));
17549e84
JQ
627 MigrationState *s = migrate_get_current();
628
629 switch (s->state) {
31194731 630 case MIGRATION_STATUS_NONE:
17549e84
JQ
631 /* no migration has happened ever */
632 break;
31194731 633 case MIGRATION_STATUS_SETUP:
29ae8a41 634 info->has_status = true;
ed4fbd10 635 info->has_total_time = false;
29ae8a41 636 break;
31194731
HZ
637 case MIGRATION_STATUS_ACTIVE:
638 case MIGRATION_STATUS_CANCELLING:
791e7c82 639 info->has_status = true;
7aa939af 640 info->has_total_time = true;
bc72ad67 641 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
7aa939af 642 - s->total_time;
2c52ddf1
JQ
643 info->has_expected_downtime = true;
644 info->expected_downtime = s->expected_downtime;
ed4fbd10
MH
645 info->has_setup_time = true;
646 info->setup_time = s->setup_time;
17549e84 647
a22463a5 648 populate_ram_info(info, s);
8d017193 649
17549e84 650 if (blk_mig_active()) {
791e7c82
LC
651 info->has_disk = true;
652 info->disk = g_malloc0(sizeof(*info->disk));
653 info->disk->transferred = blk_mig_bytes_transferred();
654 info->disk->remaining = blk_mig_bytes_remaining();
655 info->disk->total = blk_mig_bytes_total();
ff8d81d8 656 }
f36d55af 657
4782893e 658 if (cpu_throttle_active()) {
d85a31d1
JH
659 info->has_cpu_throttle_percentage = true;
660 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
4782893e
JH
661 }
662
9ec055ae
DDAG
663 get_xbzrle_cache_stats(info);
664 break;
665 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
666 /* Mostly the same as active; TODO add some postcopy stats */
667 info->has_status = true;
668 info->has_total_time = true;
669 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
670 - s->total_time;
671 info->has_expected_downtime = true;
672 info->expected_downtime = s->expected_downtime;
673 info->has_setup_time = true;
674 info->setup_time = s->setup_time;
675
a22463a5 676 populate_ram_info(info, s);
9ec055ae
DDAG
677
678 if (blk_mig_active()) {
679 info->has_disk = true;
680 info->disk = g_malloc0(sizeof(*info->disk));
681 info->disk->transferred = blk_mig_bytes_transferred();
682 info->disk->remaining = blk_mig_bytes_remaining();
683 info->disk->total = blk_mig_bytes_total();
684 }
685
f36d55af 686 get_xbzrle_cache_stats(info);
17549e84 687 break;
0b827d5e
HZ
688 case MIGRATION_STATUS_COLO:
689 info->has_status = true;
690 /* TODO: display COLO specific information (checkpoint info etc.) */
691 break;
31194731 692 case MIGRATION_STATUS_COMPLETED:
f36d55af
OW
693 get_xbzrle_cache_stats(info);
694
791e7c82 695 info->has_status = true;
00c14997 696 info->has_total_time = true;
7aa939af 697 info->total_time = s->total_time;
9c5a9fcf
JQ
698 info->has_downtime = true;
699 info->downtime = s->downtime;
ed4fbd10
MH
700 info->has_setup_time = true;
701 info->setup_time = s->setup_time;
d5f8a570 702
a22463a5 703 populate_ram_info(info, s);
17549e84 704 break;
31194731 705 case MIGRATION_STATUS_FAILED:
791e7c82 706 info->has_status = true;
d59ce6f3
DB
707 if (s->error) {
708 info->has_error_desc = true;
709 info->error_desc = g_strdup(error_get_pretty(s->error));
710 }
17549e84 711 break;
31194731 712 case MIGRATION_STATUS_CANCELLED:
791e7c82 713 info->has_status = true;
17549e84 714 break;
5bb7910a 715 }
cde63fbe 716 info->status = s->state;
791e7c82
LC
717
718 return info;
5bb7910a
AL
719}
720
00458433
OW
721void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
722 Error **errp)
723{
724 MigrationState *s = migrate_get_current();
725 MigrationCapabilityStatusList *cap;
096631bd 726 bool old_postcopy_cap = migrate_postcopy_ram();
00458433 727
f6844b99 728 if (migration_is_setup_or_active(s->state)) {
c6bd8c70 729 error_setg(errp, QERR_MIGRATION_ACTIVE);
00458433
OW
730 return;
731 }
732
733 for (cap = params; cap; cap = cap->next) {
ed1701c6
DDAG
734#ifndef CONFIG_LIVE_BLOCK_MIGRATION
735 if (cap->value->capability == MIGRATION_CAPABILITY_BLOCK
736 && cap->value->state) {
737 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
738 "block migration");
739 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
740 continue;
741 }
742#endif
35a6ed4f
HZ
743 if (cap->value->capability == MIGRATION_CAPABILITY_X_COLO) {
744 if (!colo_supported()) {
745 error_setg(errp, "COLO is not currently supported, please"
746 " configure with --enable-colo option in order to"
747 " support COLO feature");
748 continue;
749 }
750 }
00458433
OW
751 s->enabled_capabilities[cap->value->capability] = cap->value->state;
752 }
53dd370c
DDAG
753
754 if (migrate_postcopy_ram()) {
755 if (migrate_use_compression()) {
756 /* The decompression threads asynchronously write into RAM
757 * rather than use the atomic copies needed to avoid
758 * userfaulting. It should be possible to fix the decompression
759 * threads for compatibility in future.
760 */
761 error_report("Postcopy is not currently compatible with "
762 "compression");
32c3db5b 763 s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM] =
53dd370c
DDAG
764 false;
765 }
096631bd
DDAG
766 /* This check is reasonably expensive, so only when it's being
767 * set the first time, also it's only the destination that needs
768 * special support.
769 */
770 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
771 !postcopy_ram_supported_by_host()) {
772 /* postcopy_ram_supported_by_host will have emitted a more
773 * detailed message
774 */
775 error_report("Postcopy is not supported");
776 s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM] =
777 false;
778 }
53dd370c 779 }
00458433
OW
780}
781
7f375e04 782void qmp_migrate_set_parameters(MigrationParameters *params, Error **errp)
85de8323
LL
783{
784 MigrationState *s = migrate_get_current();
785
7f375e04
EB
786 if (params->has_compress_level &&
787 (params->compress_level < 0 || params->compress_level > 9)) {
c6bd8c70
MA
788 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
789 "is invalid, it should be in the range of 0 to 9");
85de8323
LL
790 return;
791 }
7f375e04
EB
792 if (params->has_compress_threads &&
793 (params->compress_threads < 1 || params->compress_threads > 255)) {
c6bd8c70
MA
794 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
795 "compress_threads",
796 "is invalid, it should be in the range of 1 to 255");
85de8323
LL
797 return;
798 }
7f375e04
EB
799 if (params->has_decompress_threads &&
800 (params->decompress_threads < 1 || params->decompress_threads > 255)) {
c6bd8c70
MA
801 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
802 "decompress_threads",
803 "is invalid, it should be in the range of 1 to 255");
85de8323
LL
804 return;
805 }
7f375e04
EB
806 if (params->has_cpu_throttle_initial &&
807 (params->cpu_throttle_initial < 1 ||
808 params->cpu_throttle_initial > 99)) {
1626fee3 809 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 810 "cpu_throttle_initial",
1626fee3 811 "an integer in the range of 1 to 99");
091ecc8b 812 return;
1626fee3 813 }
7f375e04
EB
814 if (params->has_cpu_throttle_increment &&
815 (params->cpu_throttle_increment < 1 ||
816 params->cpu_throttle_increment > 99)) {
1626fee3 817 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 818 "cpu_throttle_increment",
1626fee3 819 "an integer in the range of 1 to 99");
091ecc8b 820 return;
1626fee3 821 }
2ff30257
AA
822 if (params->has_max_bandwidth &&
823 (params->max_bandwidth < 0 || params->max_bandwidth > SIZE_MAX)) {
824 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
825 " range of 0 to %zu bytes/second", SIZE_MAX);
826 return;
827 }
828 if (params->has_downtime_limit &&
87c9cc1c
DHB
829 (params->downtime_limit < 0 ||
830 params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
831 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
832 "the range of 0 to %d milliseconds",
833 MAX_MIGRATE_DOWNTIME);
2ff30257
AA
834 return;
835 }
68b53591
HZ
836 if (params->has_x_checkpoint_delay && (params->x_checkpoint_delay < 0)) {
837 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
838 "x_checkpoint_delay",
839 "is invalid, it should be positive");
840 }
85de8323 841
7f375e04
EB
842 if (params->has_compress_level) {
843 s->parameters.compress_level = params->compress_level;
85de8323 844 }
7f375e04
EB
845 if (params->has_compress_threads) {
846 s->parameters.compress_threads = params->compress_threads;
85de8323 847 }
7f375e04
EB
848 if (params->has_decompress_threads) {
849 s->parameters.decompress_threads = params->decompress_threads;
85de8323 850 }
7f375e04
EB
851 if (params->has_cpu_throttle_initial) {
852 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1626fee3 853 }
7f375e04
EB
854 if (params->has_cpu_throttle_increment) {
855 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1626fee3 856 }
7f375e04 857 if (params->has_tls_creds) {
69ef1f36 858 g_free(s->parameters.tls_creds);
7f375e04 859 s->parameters.tls_creds = g_strdup(params->tls_creds);
69ef1f36 860 }
7f375e04 861 if (params->has_tls_hostname) {
69ef1f36 862 g_free(s->parameters.tls_hostname);
7f375e04 863 s->parameters.tls_hostname = g_strdup(params->tls_hostname);
69ef1f36 864 }
2ff30257
AA
865 if (params->has_max_bandwidth) {
866 s->parameters.max_bandwidth = params->max_bandwidth;
867 if (s->to_dst_file) {
868 qemu_file_set_rate_limit(s->to_dst_file,
869 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
870 }
871 }
872 if (params->has_downtime_limit) {
873 s->parameters.downtime_limit = params->downtime_limit;
874 }
68b53591
HZ
875
876 if (params->has_x_checkpoint_delay) {
877 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
479125d5
HZ
878 if (migration_in_colo_state()) {
879 colo_checkpoint_notify(s);
880 }
68b53591 881 }
2833c59b
JQ
882 if (params->has_block_incremental) {
883 s->parameters.block_incremental = params->block_incremental;
884 }
85de8323
LL
885}
886
2594f56d 887
4886a1bc
DDAG
888void qmp_migrate_start_postcopy(Error **errp)
889{
890 MigrationState *s = migrate_get_current();
891
892 if (!migrate_postcopy_ram()) {
a54d340b 893 error_setg(errp, "Enable postcopy with migrate_set_capability before"
4886a1bc
DDAG
894 " the start of migration");
895 return;
896 }
897
898 if (s->state == MIGRATION_STATUS_NONE) {
899 error_setg(errp, "Postcopy must be started after migration has been"
900 " started");
901 return;
902 }
903 /*
904 * we don't error if migration has finished since that would be racy
905 * with issuing this command.
906 */
907 atomic_set(&s->start_postcopy, true);
908}
909
065e2813
AL
910/* shared migration helpers */
911
48781e5b 912void migrate_set_state(int *state, int old_state, int new_state)
51cf4c1a 913{
48781e5b 914 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
4ba4bc5e 915 trace_migrate_set_state(new_state);
b05dc723 916 migrate_generate_event(new_state);
51cf4c1a
Z
917 }
918}
919
2833c59b
JQ
920void migrate_set_block_enabled(bool value, Error **errp)
921{
922 MigrationCapabilityStatusList *cap;
923
924 cap = g_new0(MigrationCapabilityStatusList, 1);
925 cap->value = g_new0(MigrationCapabilityStatus, 1);
926 cap->value->capability = MIGRATION_CAPABILITY_BLOCK;
927 cap->value->state = value;
928 qmp_migrate_set_capabilities(cap, errp);
929 qapi_free_MigrationCapabilityStatusList(cap);
930}
931
932static void migrate_set_block_incremental(MigrationState *s, bool value)
933{
934 s->parameters.block_incremental = value;
935}
936
937static void block_cleanup_parameters(MigrationState *s)
938{
939 if (s->must_remove_block_options) {
940 /* setting to false can never fail */
941 migrate_set_block_enabled(false, &error_abort);
942 migrate_set_block_incremental(s, false);
943 s->must_remove_block_options = false;
944 }
945}
946
bb1fadc4 947static void migrate_fd_cleanup(void *opaque)
065e2813 948{
bb1fadc4
PB
949 MigrationState *s = opaque;
950
951 qemu_bh_delete(s->cleanup_bh);
952 s->cleanup_bh = NULL;
953
ec481c6c 954 migration_page_queue_free();
6c595cde 955
89a02a9f 956 if (s->to_dst_file) {
9013dca5 957 trace_migrate_fd_cleanup();
404a7c05 958 qemu_mutex_unlock_iothread();
1d34e4bf
DDAG
959 if (s->migration_thread_running) {
960 qemu_thread_join(&s->thread);
961 s->migration_thread_running = false;
962 }
404a7c05
PB
963 qemu_mutex_lock_iothread();
964
8706d2d5 965 migrate_compress_threads_join();
89a02a9f
HZ
966 qemu_fclose(s->to_dst_file);
967 s->to_dst_file = NULL;
065e2813
AL
968 }
969
9ec055ae
DDAG
970 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
971 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
7a2c1721 972
94f5a437 973 if (s->state == MIGRATION_STATUS_CANCELLING) {
48781e5b 974 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
94f5a437 975 MIGRATION_STATUS_CANCELLED);
7a2c1721 976 }
a3fa1d78
PB
977
978 notifier_list_notify(&migration_state_notifiers, s);
2833c59b 979 block_cleanup_parameters(s);
065e2813
AL
980}
981
d59ce6f3 982void migrate_fd_error(MigrationState *s, const Error *error)
065e2813 983{
25174055 984 trace_migrate_fd_error(error_get_pretty(error));
89a02a9f 985 assert(s->to_dst_file == NULL);
48781e5b
HZ
986 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
987 MIGRATION_STATUS_FAILED);
d59ce6f3
DB
988 if (!s->error) {
989 s->error = error_copy(error);
990 }
bb1fadc4 991 notifier_list_notify(&migration_state_notifiers, s);
2833c59b 992 block_cleanup_parameters(s);
458cf28e
JQ
993}
994
0edda1c4 995static void migrate_fd_cancel(MigrationState *s)
065e2813 996{
6f2b811a 997 int old_state ;
89a02a9f 998 QEMUFile *f = migrate_get_current()->to_dst_file;
9013dca5 999 trace_migrate_fd_cancel();
065e2813 1000
70b20477
DDAG
1001 if (s->rp_state.from_dst_file) {
1002 /* shutdown the rp socket, so causing the rp thread to shutdown */
1003 qemu_file_shutdown(s->rp_state.from_dst_file);
1004 }
1005
6f2b811a
Z
1006 do {
1007 old_state = s->state;
f6844b99 1008 if (!migration_is_setup_or_active(old_state)) {
6f2b811a
Z
1009 break;
1010 }
48781e5b 1011 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
31194731 1012 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
1013
1014 /*
1015 * If we're unlucky the migration code might be stuck somewhere in a
1016 * send/write while the network has failed and is waiting to timeout;
1017 * if we've got shutdown(2) available then we can force it to quit.
1018 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1019 * called in a bh, so there is no race against this cancel.
1020 */
31194731 1021 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
a26ba26e
DDAG
1022 qemu_file_shutdown(f);
1023 }
1d2acc31
HZ
1024 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1025 Error *local_err = NULL;
1026
1027 bdrv_invalidate_cache_all(&local_err);
1028 if (local_err) {
1029 error_report_err(local_err);
1030 } else {
1031 s->block_inactive = false;
1032 }
1033 }
2833c59b 1034 block_cleanup_parameters(s);
065e2813
AL
1035}
1036
99a0db9b
GH
1037void add_migration_state_change_notifier(Notifier *notify)
1038{
1039 notifier_list_add(&migration_state_notifiers, notify);
1040}
1041
1042void remove_migration_state_change_notifier(Notifier *notify)
1043{
31552529 1044 notifier_remove(notify);
99a0db9b
GH
1045}
1046
02edd2e7 1047bool migration_in_setup(MigrationState *s)
afe2df69 1048{
31194731 1049 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
1050}
1051
7073693b 1052bool migration_has_finished(MigrationState *s)
99a0db9b 1053{
31194731 1054 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 1055}
0edda1c4 1056
afe2df69
GH
1057bool migration_has_failed(MigrationState *s)
1058{
31194731
HZ
1059 return (s->state == MIGRATION_STATUS_CANCELLED ||
1060 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
1061}
1062
5727309d 1063bool migration_in_postcopy(void)
9ec055ae 1064{
5727309d
JQ
1065 MigrationState *s = migrate_get_current();
1066
9ec055ae
DDAG
1067 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1068}
1069
b82fc321
DDAG
1070bool migration_in_postcopy_after_devices(MigrationState *s)
1071{
5727309d 1072 return migration_in_postcopy() && s->postcopy_after_devices;
b82fc321
DDAG
1073}
1074
fab35005 1075bool migration_is_idle(void)
fe44dc91 1076{
fab35005 1077 MigrationState *s = migrate_get_current();
fe44dc91
AA
1078
1079 switch (s->state) {
1080 case MIGRATION_STATUS_NONE:
1081 case MIGRATION_STATUS_CANCELLED:
1082 case MIGRATION_STATUS_COMPLETED:
1083 case MIGRATION_STATUS_FAILED:
1084 return true;
1085 case MIGRATION_STATUS_SETUP:
1086 case MIGRATION_STATUS_CANCELLING:
1087 case MIGRATION_STATUS_ACTIVE:
1088 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1089 case MIGRATION_STATUS_COLO:
1090 return false;
1091 case MIGRATION_STATUS__MAX:
1092 g_assert_not_reached();
1093 }
1094
1095 return false;
1096}
1097
a0762d9e 1098MigrationState *migrate_init(void)
0edda1c4 1099{
17549e84 1100 MigrationState *s = migrate_get_current();
bbf6da32 1101
389775d1
DDAG
1102 /*
1103 * Reinitialise all migration state, except
1104 * parameters/capabilities that the user set, and
1105 * locks.
1106 */
1107 s->bytes_xfer = 0;
1108 s->xfer_limit = 0;
1109 s->cleanup_bh = 0;
89a02a9f 1110 s->to_dst_file = NULL;
389775d1 1111 s->state = MIGRATION_STATUS_NONE;
389775d1
DDAG
1112 s->rp_state.from_dst_file = NULL;
1113 s->rp_state.error = false;
1114 s->mbps = 0.0;
1115 s->downtime = 0;
1116 s->expected_downtime = 0;
389775d1 1117 s->setup_time = 0;
389775d1 1118 s->start_postcopy = false;
b82fc321 1119 s->postcopy_after_devices = false;
389775d1 1120 s->migration_thread_running = false;
d59ce6f3
DB
1121 error_free(s->error);
1122 s->error = NULL;
389775d1 1123
48781e5b 1124 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 1125
bc72ad67 1126 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0edda1c4
JQ
1127 return s;
1128}
cab30143 1129
fa2756b7
AL
1130static GSList *migration_blockers;
1131
fe44dc91 1132int migrate_add_blocker(Error *reason, Error **errp)
fa2756b7 1133{
b67b8c3a
AA
1134 if (only_migratable) {
1135 error_propagate(errp, error_copy(reason));
1136 error_prepend(errp, "disallowing migration blocker "
1137 "(--only_migratable) for: ");
1138 return -EACCES;
1139 }
1140
fab35005 1141 if (migration_is_idle()) {
fe44dc91
AA
1142 migration_blockers = g_slist_prepend(migration_blockers, reason);
1143 return 0;
1144 }
1145
1146 error_propagate(errp, error_copy(reason));
1147 error_prepend(errp, "disallowing migration blocker (migration in "
1148 "progress) for: ");
1149 return -EBUSY;
fa2756b7
AL
1150}
1151
1152void migrate_del_blocker(Error *reason)
1153{
1154 migration_blockers = g_slist_remove(migration_blockers, reason);
1155}
1156
bf1ae1f4
DDAG
1157void qmp_migrate_incoming(const char *uri, Error **errp)
1158{
1159 Error *local_err = NULL;
4debb5f5 1160 static bool once = true;
bf1ae1f4
DDAG
1161
1162 if (!deferred_incoming) {
4debb5f5 1163 error_setg(errp, "For use with '-incoming defer'");
bf1ae1f4
DDAG
1164 return;
1165 }
4debb5f5
DDAG
1166 if (!once) {
1167 error_setg(errp, "The incoming migration has already been started");
1168 }
bf1ae1f4
DDAG
1169
1170 qemu_start_incoming_migration(uri, &local_err);
1171
1172 if (local_err) {
1173 error_propagate(errp, local_err);
1174 return;
1175 }
1176
4debb5f5 1177 once = false;
bf1ae1f4
DDAG
1178}
1179
24f3902b
GK
1180bool migration_is_blocked(Error **errp)
1181{
1182 if (qemu_savevm_state_blocked(errp)) {
1183 return true;
1184 }
1185
1186 if (migration_blockers) {
1187 *errp = error_copy(migration_blockers->data);
1188 return true;
1189 }
1190
1191 return false;
1192}
1193
e1c37d0e
LC
1194void qmp_migrate(const char *uri, bool has_blk, bool blk,
1195 bool has_inc, bool inc, bool has_detach, bool detach,
1196 Error **errp)
cab30143 1197{
be7059cd 1198 Error *local_err = NULL;
17549e84 1199 MigrationState *s = migrate_get_current();
cab30143 1200 const char *p;
cab30143 1201
f6844b99 1202 if (migration_is_setup_or_active(s->state) ||
0b827d5e
HZ
1203 s->state == MIGRATION_STATUS_CANCELLING ||
1204 s->state == MIGRATION_STATUS_COLO) {
c6bd8c70 1205 error_setg(errp, QERR_MIGRATION_ACTIVE);
e1c37d0e 1206 return;
cab30143 1207 }
ca99993a
DDAG
1208 if (runstate_check(RUN_STATE_INMIGRATE)) {
1209 error_setg(errp, "Guest is waiting for an incoming migration");
1210 return;
1211 }
1212
24f3902b 1213 if (migration_is_blocked(errp)) {
e1c37d0e 1214 return;
fa2756b7
AL
1215 }
1216
2833c59b
JQ
1217 if ((has_blk && blk) || (has_inc && inc)) {
1218 if (migrate_use_block() || migrate_use_block_incremental()) {
1219 error_setg(errp, "Command options are incompatible with "
1220 "current migration capabilities");
1221 return;
1222 }
1223 migrate_set_block_enabled(true, &local_err);
1224 if (local_err) {
1225 error_propagate(errp, local_err);
1226 return;
1227 }
1228 s->must_remove_block_options = true;
1229 }
1230
1231 if (has_inc && inc) {
1232 migrate_set_block_incremental(s, true);
1233 }
1234
a0762d9e 1235 s = migrate_init();
cab30143
JQ
1236
1237 if (strstart(uri, "tcp:", &p)) {
f37afb5a 1238 tcp_start_outgoing_migration(s, p, &local_err);
2da776db 1239#ifdef CONFIG_RDMA
41310c68 1240 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
1241 rdma_start_outgoing_migration(s, p, &local_err);
1242#endif
cab30143 1243 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 1244 exec_start_outgoing_migration(s, p, &local_err);
cab30143 1245 } else if (strstart(uri, "unix:", &p)) {
f37afb5a 1246 unix_start_outgoing_migration(s, p, &local_err);
cab30143 1247 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 1248 fd_start_outgoing_migration(s, p, &local_err);
99a0db9b 1249 } else {
c6bd8c70
MA
1250 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1251 "a valid migration protocol");
48781e5b
HZ
1252 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1253 MIGRATION_STATUS_FAILED);
e1c37d0e 1254 return;
cab30143
JQ
1255 }
1256
f37afb5a 1257 if (local_err) {
d59ce6f3 1258 migrate_fd_error(s, local_err);
f37afb5a 1259 error_propagate(errp, local_err);
e1c37d0e 1260 return;
1299c631 1261 }
cab30143
JQ
1262}
1263
6cdedb07 1264void qmp_migrate_cancel(Error **errp)
cab30143 1265{
17549e84 1266 migrate_fd_cancel(migrate_get_current());
cab30143
JQ
1267}
1268
9e1ba4cc
OW
1269void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1270{
1271 MigrationState *s = migrate_get_current();
c91e681a 1272 int64_t new_size;
9e1ba4cc
OW
1273
1274 /* Check for truncation */
1275 if (value != (size_t)value) {
c6bd8c70
MA
1276 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1277 "exceeding address space");
9e1ba4cc
OW
1278 return;
1279 }
1280
a5615b14
OW
1281 /* Cache should not be larger than guest ram size */
1282 if (value > ram_bytes_total()) {
c6bd8c70
MA
1283 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1284 "exceeds guest ram size ");
a5615b14
OW
1285 return;
1286 }
1287
c91e681a
OW
1288 new_size = xbzrle_cache_resize(value);
1289 if (new_size < 0) {
c6bd8c70
MA
1290 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1291 "is smaller than page size");
c91e681a
OW
1292 return;
1293 }
1294
1295 s->xbzrle_cache_size = new_size;
9e1ba4cc
OW
1296}
1297
1298int64_t qmp_query_migrate_cache_size(Error **errp)
1299{
1300 return migrate_xbzrle_cache_size();
1301}
1302
3dc85383 1303void qmp_migrate_set_speed(int64_t value, Error **errp)
cab30143 1304{
2ff30257
AA
1305 MigrationParameters p = {
1306 .has_max_bandwidth = true,
1307 .max_bandwidth = value,
1308 };
cab30143 1309
2ff30257 1310 qmp_migrate_set_parameters(&p, errp);
cab30143
JQ
1311}
1312
4f0a993b 1313void qmp_migrate_set_downtime(double value, Error **errp)
cab30143 1314{
87c9cc1c
DHB
1315 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1316 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1317 "the range of 0 to %d seconds",
1318 MAX_MIGRATE_DOWNTIME_SECONDS);
1319 return;
1320 }
1321
2ff30257
AA
1322 value *= 1000; /* Convert to milliseconds */
1323 value = MAX(0, MIN(INT64_MAX, value));
1324
1325 MigrationParameters p = {
1326 .has_downtime_limit = true,
1327 .downtime_limit = value,
1328 };
1329
1330 qmp_migrate_set_parameters(&p, errp);
99a0db9b 1331}
17ad9b35 1332
53f09a10
PB
1333bool migrate_release_ram(void)
1334{
1335 MigrationState *s;
1336
1337 s = migrate_get_current();
1338
1339 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1340}
1341
53dd370c
DDAG
1342bool migrate_postcopy_ram(void)
1343{
1344 MigrationState *s;
1345
1346 s = migrate_get_current();
1347
32c3db5b 1348 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
53dd370c
DDAG
1349}
1350
bde1e2ec
CV
1351bool migrate_auto_converge(void)
1352{
1353 MigrationState *s;
1354
1355 s = migrate_get_current();
1356
1357 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1358}
1359
323004a3
PL
1360bool migrate_zero_blocks(void)
1361{
1362 MigrationState *s;
1363
1364 s = migrate_get_current();
1365
1366 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1367}
1368
8706d2d5
LL
1369bool migrate_use_compression(void)
1370{
dde4e694
LL
1371 MigrationState *s;
1372
1373 s = migrate_get_current();
1374
1375 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
1376}
1377
1378int migrate_compress_level(void)
1379{
1380 MigrationState *s;
1381
1382 s = migrate_get_current();
1383
2594f56d 1384 return s->parameters.compress_level;
8706d2d5
LL
1385}
1386
1387int migrate_compress_threads(void)
1388{
1389 MigrationState *s;
1390
1391 s = migrate_get_current();
1392
2594f56d 1393 return s->parameters.compress_threads;
8706d2d5
LL
1394}
1395
3fcb38c2
LL
1396int migrate_decompress_threads(void)
1397{
1398 MigrationState *s;
1399
1400 s = migrate_get_current();
1401
2594f56d 1402 return s->parameters.decompress_threads;
3fcb38c2
LL
1403}
1404
b05dc723
JQ
1405bool migrate_use_events(void)
1406{
1407 MigrationState *s;
1408
1409 s = migrate_get_current();
1410
1411 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1412}
1413
17ad9b35
OW
1414int migrate_use_xbzrle(void)
1415{
1416 MigrationState *s;
1417
1418 s = migrate_get_current();
1419
1420 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1421}
1422
1423int64_t migrate_xbzrle_cache_size(void)
1424{
1425 MigrationState *s;
1426
1427 s = migrate_get_current();
1428
1429 return s->xbzrle_cache_size;
1430}
0d82d0e8 1431
2833c59b
JQ
1432bool migrate_use_block(void)
1433{
1434 MigrationState *s;
1435
1436 s = migrate_get_current();
1437
1438 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1439}
1440
1441bool migrate_use_block_incremental(void)
1442{
1443 MigrationState *s;
1444
1445 s = migrate_get_current();
1446
1447 return s->parameters.block_incremental;
1448}
1449
70b20477
DDAG
1450/* migration thread support */
1451/*
1452 * Something bad happened to the RP stream, mark an error
1453 * The caller shall print or trace something to indicate why
1454 */
1455static void mark_source_rp_bad(MigrationState *s)
1456{
1457 s->rp_state.error = true;
1458}
1459
1460static struct rp_cmd_args {
1461 ssize_t len; /* -1 = variable */
1462 const char *name;
1463} rp_cmd_args[] = {
1464 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1465 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1466 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1e2d90eb
DDAG
1467 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1468 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
70b20477
DDAG
1469 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1470};
1471
1e2d90eb
DDAG
1472/*
1473 * Process a request for pages received on the return path,
1474 * We're allowed to send more than requested (e.g. to round to our page size)
1475 * and we don't need to send pages that have already been sent.
1476 */
1477static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1478 ram_addr_t start, size_t len)
1479{
6c595cde
DDAG
1480 long our_host_ps = getpagesize();
1481
1e2d90eb 1482 trace_migrate_handle_rp_req_pages(rbname, start, len);
6c595cde
DDAG
1483
1484 /*
1485 * Since we currently insist on matching page sizes, just sanity check
1486 * we're being asked for whole host pages.
1487 */
1488 if (start & (our_host_ps-1) ||
1489 (len & (our_host_ps-1))) {
1490 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1491 " len: %zd", __func__, start, len);
1492 mark_source_rp_bad(ms);
1493 return;
1494 }
1495
96506894 1496 if (ram_save_queue_pages(rbname, start, len)) {
6c595cde
DDAG
1497 mark_source_rp_bad(ms);
1498 }
1e2d90eb
DDAG
1499}
1500
70b20477
DDAG
1501/*
1502 * Handles messages sent on the return path towards the source VM
1503 *
1504 */
1505static void *source_return_path_thread(void *opaque)
1506{
1507 MigrationState *ms = opaque;
1508 QEMUFile *rp = ms->rp_state.from_dst_file;
1509 uint16_t header_len, header_type;
568b01ca 1510 uint8_t buf[512];
70b20477 1511 uint32_t tmp32, sibling_error;
1e2d90eb
DDAG
1512 ram_addr_t start = 0; /* =0 to silence warning */
1513 size_t len = 0, expected_len;
70b20477
DDAG
1514 int res;
1515
1516 trace_source_return_path_thread_entry();
1517 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1518 migration_is_setup_or_active(ms->state)) {
1519 trace_source_return_path_thread_loop_top();
1520 header_type = qemu_get_be16(rp);
1521 header_len = qemu_get_be16(rp);
1522
1523 if (header_type >= MIG_RP_MSG_MAX ||
1524 header_type == MIG_RP_MSG_INVALID) {
1525 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1526 header_type, header_len);
1527 mark_source_rp_bad(ms);
1528 goto out;
1529 }
1530
1531 if ((rp_cmd_args[header_type].len != -1 &&
1532 header_len != rp_cmd_args[header_type].len) ||
568b01ca 1533 header_len > sizeof(buf)) {
70b20477
DDAG
1534 error_report("RP: Received '%s' message (0x%04x) with"
1535 "incorrect length %d expecting %zu",
1536 rp_cmd_args[header_type].name, header_type, header_len,
1537 (size_t)rp_cmd_args[header_type].len);
1538 mark_source_rp_bad(ms);
1539 goto out;
1540 }
1541
1542 /* We know we've got a valid header by this point */
1543 res = qemu_get_buffer(rp, buf, header_len);
1544 if (res != header_len) {
1545 error_report("RP: Failed reading data for message 0x%04x"
1546 " read %d expected %d",
1547 header_type, res, header_len);
1548 mark_source_rp_bad(ms);
1549 goto out;
1550 }
1551
1552 /* OK, we have the message and the data */
1553 switch (header_type) {
1554 case MIG_RP_MSG_SHUT:
4d885131 1555 sibling_error = ldl_be_p(buf);
70b20477
DDAG
1556 trace_source_return_path_thread_shut(sibling_error);
1557 if (sibling_error) {
1558 error_report("RP: Sibling indicated error %d", sibling_error);
1559 mark_source_rp_bad(ms);
1560 }
1561 /*
1562 * We'll let the main thread deal with closing the RP
1563 * we could do a shutdown(2) on it, but we're the only user
1564 * anyway, so there's nothing gained.
1565 */
1566 goto out;
1567
1568 case MIG_RP_MSG_PONG:
4d885131 1569 tmp32 = ldl_be_p(buf);
70b20477
DDAG
1570 trace_source_return_path_thread_pong(tmp32);
1571 break;
1572
1e2d90eb 1573 case MIG_RP_MSG_REQ_PAGES:
4d885131
PM
1574 start = ldq_be_p(buf);
1575 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
1576 migrate_handle_rp_req_pages(ms, NULL, start, len);
1577 break;
1578
1579 case MIG_RP_MSG_REQ_PAGES_ID:
1580 expected_len = 12 + 1; /* header + termination */
1581
1582 if (header_len >= expected_len) {
4d885131
PM
1583 start = ldq_be_p(buf);
1584 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
1585 /* Now we expect an idstr */
1586 tmp32 = buf[12]; /* Length of the following idstr */
1587 buf[13 + tmp32] = '\0';
1588 expected_len += tmp32;
1589 }
1590 if (header_len != expected_len) {
1591 error_report("RP: Req_Page_id with length %d expecting %zd",
1592 header_len, expected_len);
1593 mark_source_rp_bad(ms);
1594 goto out;
1595 }
1596 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1597 break;
1598
70b20477
DDAG
1599 default:
1600 break;
1601 }
1602 }
5df5416e 1603 if (qemu_file_get_error(rp)) {
70b20477
DDAG
1604 trace_source_return_path_thread_bad_end();
1605 mark_source_rp_bad(ms);
1606 }
1607
1608 trace_source_return_path_thread_end();
1609out:
1610 ms->rp_state.from_dst_file = NULL;
1611 qemu_fclose(rp);
1612 return NULL;
1613}
1614
70b20477
DDAG
1615static int open_return_path_on_source(MigrationState *ms)
1616{
1617
89a02a9f 1618 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
70b20477
DDAG
1619 if (!ms->rp_state.from_dst_file) {
1620 return -1;
1621 }
1622
1623 trace_open_return_path_on_source();
1624 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1625 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1626
1627 trace_open_return_path_on_source_continue();
1628
1629 return 0;
1630}
1631
70b20477
DDAG
1632/* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1633static int await_return_path_close_on_source(MigrationState *ms)
1634{
1635 /*
1636 * If this is a normal exit then the destination will send a SHUT and the
1637 * rp_thread will exit, however if there's an error we need to cause
1638 * it to exit.
1639 */
89a02a9f 1640 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
70b20477
DDAG
1641 /*
1642 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1643 * waiting for the destination.
1644 */
1645 qemu_file_shutdown(ms->rp_state.from_dst_file);
1646 mark_source_rp_bad(ms);
1647 }
1648 trace_await_return_path_close_on_source_joining();
1649 qemu_thread_join(&ms->rp_state.rp_thread);
1650 trace_await_return_path_close_on_source_close();
1651 return ms->rp_state.error;
1652}
1653
1d34e4bf
DDAG
1654/*
1655 * Switch from normal iteration to postcopy
1656 * Returns non-0 on error
1657 */
1658static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1659{
1660 int ret;
61b67d47
DB
1661 QIOChannelBuffer *bioc;
1662 QEMUFile *fb;
1d34e4bf 1663 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
ef8d6488 1664 bool restart_block = false;
48781e5b 1665 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1d34e4bf
DDAG
1666 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1667
1668 trace_postcopy_start();
1669 qemu_mutex_lock_iothread();
1670 trace_postcopy_start_set_run();
1671
1672 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1673 *old_vm_running = runstate_is_running();
1674 global_state_store();
1675 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
76b1c7fe
KW
1676 if (ret < 0) {
1677 goto fail;
1678 }
1d34e4bf 1679
76b1c7fe 1680 ret = bdrv_inactivate_all();
1d34e4bf
DDAG
1681 if (ret < 0) {
1682 goto fail;
1683 }
ef8d6488 1684 restart_block = true;
1d34e4bf 1685
1c0d249d
DDAG
1686 /*
1687 * Cause any non-postcopiable, but iterative devices to
1688 * send out their final data.
1689 */
89a02a9f 1690 qemu_savevm_state_complete_precopy(ms->to_dst_file, true);
1c0d249d 1691
1d34e4bf
DDAG
1692 /*
1693 * in Finish migrate and with the io-lock held everything should
1694 * be quiet, but we've potentially still got dirty pages and we
1695 * need to tell the destination to throw any pages it's already received
1696 * that are dirty
1697 */
1698 if (ram_postcopy_send_discard_bitmap(ms)) {
1699 error_report("postcopy send discard bitmap failed");
1700 goto fail;
1701 }
1702
1703 /*
1704 * send rest of state - note things that are doing postcopy
1705 * will notice we're in POSTCOPY_ACTIVE and not actually
1706 * wrap their state up here
1707 */
89a02a9f 1708 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
1d34e4bf 1709 /* Ping just for debugging, helps line traces up */
89a02a9f 1710 qemu_savevm_send_ping(ms->to_dst_file, 2);
1d34e4bf
DDAG
1711
1712 /*
1713 * While loading the device state we may trigger page transfer
1714 * requests and the fd must be free to process those, and thus
1715 * the destination must read the whole device state off the fd before
1716 * it starts processing it. Unfortunately the ad-hoc migration format
1717 * doesn't allow the destination to know the size to read without fully
1718 * parsing it through each devices load-state code (especially the open
1719 * coded devices that use get/put).
1720 * So we wrap the device state up in a package with a length at the start;
1721 * to do this we use a qemu_buf to hold the whole of the device state.
1722 */
61b67d47 1723 bioc = qio_channel_buffer_new(4096);
6f01f136 1724 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
61b67d47
DB
1725 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
1726 object_unref(OBJECT(bioc));
1d34e4bf 1727
c76201ab
DDAG
1728 /*
1729 * Make sure the receiver can get incoming pages before we send the rest
1730 * of the state
1731 */
1732 qemu_savevm_send_postcopy_listen(fb);
1733
1c0d249d 1734 qemu_savevm_state_complete_precopy(fb, false);
1d34e4bf
DDAG
1735 qemu_savevm_send_ping(fb, 3);
1736
1737 qemu_savevm_send_postcopy_run(fb);
1738
1739 /* <><> end of stuff going into the package */
1d34e4bf 1740
ef8d6488
DDAG
1741 /* Last point of recovery; as soon as we send the package the destination
1742 * can open devices and potentially start running.
1743 * Lets just check again we've not got any errors.
1744 */
1745 ret = qemu_file_get_error(ms->to_dst_file);
1746 if (ret) {
1747 error_report("postcopy_start: Migration stream errored (pre package)");
1748 goto fail_closefb;
1749 }
1750
1751 restart_block = false;
1752
1d34e4bf 1753 /* Now send that blob */
61b67d47 1754 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1d34e4bf
DDAG
1755 goto fail_closefb;
1756 }
1757 qemu_fclose(fb);
b82fc321
DDAG
1758
1759 /* Send a notify to give a chance for anything that needs to happen
1760 * at the transition to postcopy and after the device state; in particular
1761 * spice needs to trigger a transition now
1762 */
1763 ms->postcopy_after_devices = true;
1764 notifier_list_notify(&migration_state_notifiers, ms);
1765
1d34e4bf
DDAG
1766 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1767
1768 qemu_mutex_unlock_iothread();
1769
1770 /*
1771 * Although this ping is just for debug, it could potentially be
1772 * used for getting a better measurement of downtime at the source.
1773 */
89a02a9f 1774 qemu_savevm_send_ping(ms->to_dst_file, 4);
1d34e4bf 1775
ced1c616
PB
1776 if (migrate_release_ram()) {
1777 ram_postcopy_migrated_memory_release(ms);
1778 }
1779
89a02a9f 1780 ret = qemu_file_get_error(ms->to_dst_file);
1d34e4bf
DDAG
1781 if (ret) {
1782 error_report("postcopy_start: Migration stream errored");
48781e5b 1783 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf
DDAG
1784 MIGRATION_STATUS_FAILED);
1785 }
1786
1787 return ret;
1788
1789fail_closefb:
1790 qemu_fclose(fb);
1791fail:
48781e5b 1792 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf 1793 MIGRATION_STATUS_FAILED);
ef8d6488
DDAG
1794 if (restart_block) {
1795 /* A failure happened early enough that we know the destination hasn't
1796 * accessed block devices, so we're safe to recover.
1797 */
1798 Error *local_err = NULL;
1799
1800 bdrv_invalidate_cache_all(&local_err);
1801 if (local_err) {
1802 error_report_err(local_err);
1803 }
1804 }
1d34e4bf
DDAG
1805 qemu_mutex_unlock_iothread();
1806 return -1;
1807}
1808
09f6c85e
DDAG
1809/**
1810 * migration_completion: Used by migration_thread when there's not much left.
1811 * The caller 'breaks' the loop when this returns.
1812 *
1813 * @s: Current migration state
36f48567 1814 * @current_active_state: The migration state we expect to be in
09f6c85e
DDAG
1815 * @*old_vm_running: Pointer to old_vm_running flag
1816 * @*start_time: Pointer to time to update
1817 */
36f48567
DDAG
1818static void migration_completion(MigrationState *s, int current_active_state,
1819 bool *old_vm_running,
09f6c85e
DDAG
1820 int64_t *start_time)
1821{
1822 int ret;
1823
b10ac0c4
DDAG
1824 if (s->state == MIGRATION_STATUS_ACTIVE) {
1825 qemu_mutex_lock_iothread();
1826 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1827 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1828 *old_vm_running = runstate_is_running();
1829 ret = global_state_store();
1830
1831 if (!ret) {
1832 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
0b827d5e
HZ
1833 /*
1834 * Don't mark the image with BDRV_O_INACTIVE flag if
1835 * we will go into COLO stage later.
1836 */
1837 if (ret >= 0 && !migrate_colo_enabled()) {
76b1c7fe
KW
1838 ret = bdrv_inactivate_all();
1839 }
b10ac0c4 1840 if (ret >= 0) {
89a02a9f
HZ
1841 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
1842 qemu_savevm_state_complete_precopy(s->to_dst_file, false);
1d2acc31 1843 s->block_inactive = true;
b10ac0c4
DDAG
1844 }
1845 }
1846 qemu_mutex_unlock_iothread();
09f6c85e 1847
b10ac0c4
DDAG
1848 if (ret < 0) {
1849 goto fail;
09f6c85e 1850 }
b10ac0c4
DDAG
1851 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1852 trace_migration_completion_postcopy_end();
1853
89a02a9f 1854 qemu_savevm_state_complete_postcopy(s->to_dst_file);
b10ac0c4 1855 trace_migration_completion_postcopy_end_after_complete();
09f6c85e 1856 }
09f6c85e 1857
b10ac0c4
DDAG
1858 /*
1859 * If rp was opened we must clean up the thread before
1860 * cleaning everything else up (since if there are no failures
1861 * it will wait for the destination to send it's status in
1862 * a SHUT command).
1863 * Postcopy opens rp if enabled (even if it's not avtivated)
1864 */
1865 if (migrate_postcopy_ram()) {
1866 int rp_error;
1867 trace_migration_completion_postcopy_end_before_rp();
1868 rp_error = await_return_path_close_on_source(s);
1869 trace_migration_completion_postcopy_end_after_rp(rp_error);
1870 if (rp_error) {
fe904ea8 1871 goto fail_invalidate;
b10ac0c4 1872 }
09f6c85e
DDAG
1873 }
1874
89a02a9f 1875 if (qemu_file_get_error(s->to_dst_file)) {
09f6c85e 1876 trace_migration_completion_file_err();
fe904ea8 1877 goto fail_invalidate;
09f6c85e
DDAG
1878 }
1879
0b827d5e
HZ
1880 if (!migrate_colo_enabled()) {
1881 migrate_set_state(&s->state, current_active_state,
1882 MIGRATION_STATUS_COMPLETED);
1883 }
1884
09f6c85e
DDAG
1885 return;
1886
fe904ea8
GK
1887fail_invalidate:
1888 /* If not doing postcopy, vm_start() will be called: let's regain
1889 * control on images.
1890 */
1891 if (s->state == MIGRATION_STATUS_ACTIVE) {
1892 Error *local_err = NULL;
1893
1d2acc31 1894 qemu_mutex_lock_iothread();
fe904ea8
GK
1895 bdrv_invalidate_cache_all(&local_err);
1896 if (local_err) {
1897 error_report_err(local_err);
1d2acc31
HZ
1898 } else {
1899 s->block_inactive = false;
fe904ea8 1900 }
1d2acc31 1901 qemu_mutex_unlock_iothread();
fe904ea8
GK
1902 }
1903
09f6c85e 1904fail:
48781e5b
HZ
1905 migrate_set_state(&s->state, current_active_state,
1906 MIGRATION_STATUS_FAILED);
09f6c85e
DDAG
1907}
1908
35a6ed4f
HZ
1909bool migrate_colo_enabled(void)
1910{
1911 MigrationState *s = migrate_get_current();
1912 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
1913}
1914
70b20477
DDAG
1915/*
1916 * Master migration thread on the source VM.
1917 * It drives the migration and pumps the data down the outgoing channel.
1918 */
5f496a1b 1919static void *migration_thread(void *opaque)
0d82d0e8 1920{
9848a404 1921 MigrationState *s = opaque;
1d34e4bf 1922 /* Used by the bandwidth calcs, updated later */
bc72ad67
AB
1923 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1924 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
be7172e2 1925 int64_t initial_bytes = 0;
faec066a
PX
1926 /*
1927 * The final stage happens when the remaining data is smaller than
1928 * this threshold; it's calculated from the requested downtime and
1929 * measured bandwidth
1930 */
1931 int64_t threshold_size = 0;
a3fa1d78 1932 int64_t start_time = initial_time;
94f5a437 1933 int64_t end_time;
a3fa1d78 1934 bool old_vm_running = false;
1d34e4bf
DDAG
1935 bool entered_postcopy = false;
1936 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1937 enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
0b827d5e 1938 bool enable_colo = migrate_colo_enabled();
76f5933a 1939
ab28bd23
PB
1940 rcu_register_thread();
1941
89a02a9f 1942 qemu_savevm_state_header(s->to_dst_file);
1d34e4bf
DDAG
1943
1944 if (migrate_postcopy_ram()) {
1945 /* Now tell the dest that it should open its end so it can reply */
89a02a9f 1946 qemu_savevm_send_open_return_path(s->to_dst_file);
1d34e4bf
DDAG
1947
1948 /* And do a ping that will make stuff easier to debug */
89a02a9f 1949 qemu_savevm_send_ping(s->to_dst_file, 1);
1d34e4bf
DDAG
1950
1951 /*
1952 * Tell the destination that we *might* want to do postcopy later;
1953 * if the other end can't do postcopy it should fail now, nice and
1954 * early.
1955 */
89a02a9f 1956 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1d34e4bf
DDAG
1957 }
1958
a0762d9e 1959 qemu_savevm_state_begin(s->to_dst_file);
0d82d0e8 1960
bc72ad67 1961 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
48781e5b
HZ
1962 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1963 MIGRATION_STATUS_ACTIVE);
29ae8a41 1964
9ec055ae
DDAG
1965 trace_migration_thread_setup_complete();
1966
1967 while (s->state == MIGRATION_STATUS_ACTIVE ||
1968 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
a3e879cd 1969 int64_t current_time;
c369f40d 1970 uint64_t pending_size;
0d82d0e8 1971
89a02a9f 1972 if (!qemu_file_rate_limit(s->to_dst_file)) {
c31b098f
DDAG
1973 uint64_t pend_post, pend_nonpost;
1974
faec066a
PX
1975 qemu_savevm_state_pending(s->to_dst_file, threshold_size,
1976 &pend_nonpost, &pend_post);
c31b098f 1977 pending_size = pend_nonpost + pend_post;
faec066a 1978 trace_migrate_pending(pending_size, threshold_size,
c31b098f 1979 pend_post, pend_nonpost);
faec066a 1980 if (pending_size && pending_size >= threshold_size) {
1d34e4bf
DDAG
1981 /* Still a significant amount to transfer */
1982
1d34e4bf
DDAG
1983 if (migrate_postcopy_ram() &&
1984 s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
faec066a 1985 pend_nonpost <= threshold_size &&
1d34e4bf
DDAG
1986 atomic_read(&s->start_postcopy)) {
1987
1988 if (!postcopy_start(s, &old_vm_running)) {
1989 current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1990 entered_postcopy = true;
1991 }
1992
1993 continue;
1994 }
1995 /* Just another iteration step */
89a02a9f 1996 qemu_savevm_state_iterate(s->to_dst_file, entered_postcopy);
c369f40d 1997 } else {
09f6c85e 1998 trace_migration_thread_low_pending(pending_size);
1d34e4bf 1999 migration_completion(s, current_active_state,
36f48567 2000 &old_vm_running, &start_time);
09f6c85e 2001 break;
c369f40d
JQ
2002 }
2003 }
f4410a5d 2004
89a02a9f 2005 if (qemu_file_get_error(s->to_dst_file)) {
48781e5b
HZ
2006 migrate_set_state(&s->state, current_active_state,
2007 MIGRATION_STATUS_FAILED);
1d34e4bf 2008 trace_migration_thread_file_err();
fd45ee2c
PB
2009 break;
2010 }
bc72ad67 2011 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0d82d0e8 2012 if (current_time >= initial_time + BUFFER_DELAY) {
89a02a9f
HZ
2013 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file) -
2014 initial_bytes;
77417f10 2015 uint64_t time_spent = current_time - initial_time;
a694ee34 2016 double bandwidth = (double)transferred_bytes / time_spent;
faec066a 2017 threshold_size = bandwidth * s->parameters.downtime_limit;
0d82d0e8 2018
5b648de0
WY
2019 s->mbps = (((double) transferred_bytes * 8.0) /
2020 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
7e114f8c 2021
9013dca5 2022 trace_migrate_transferred(transferred_bytes, time_spent,
faec066a 2023 bandwidth, threshold_size);
90f8ae72
JQ
2024 /* if we haven't sent anything, we don't want to recalculate
2025 10000 is a small enough number for our purposes */
47ad8619
JQ
2026 if (ram_dirty_pages_rate() && transferred_bytes > 10000) {
2027 s->expected_downtime = ram_dirty_pages_rate() *
20afaed9 2028 qemu_target_page_size() / bandwidth;
90f8ae72 2029 }
0d82d0e8 2030
89a02a9f 2031 qemu_file_reset_rate_limit(s->to_dst_file);
0d82d0e8 2032 initial_time = current_time;
89a02a9f 2033 initial_bytes = qemu_ftell(s->to_dst_file);
0d82d0e8 2034 }
89a02a9f 2035 if (qemu_file_rate_limit(s->to_dst_file)) {
0d82d0e8
JQ
2036 /* usleep expects microseconds */
2037 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
2038 }
a3fa1d78
PB
2039 }
2040
1d34e4bf 2041 trace_migration_thread_after_loop();
070afca2
JH
2042 /* If we enabled cpu throttling for auto-converge, turn it off. */
2043 cpu_throttle_stop();
94f5a437 2044 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
070afca2 2045
f4410a5d 2046 qemu_mutex_lock_iothread();
0b827d5e
HZ
2047 /*
2048 * The resource has been allocated by migration will be reused in COLO
2049 * process, so don't release them.
2050 */
2051 if (!enable_colo) {
2052 qemu_savevm_state_cleanup();
2053 }
31194731 2054 if (s->state == MIGRATION_STATUS_COMPLETED) {
89a02a9f 2055 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file);
a3fa1d78 2056 s->total_time = end_time - s->total_time;
1d34e4bf
DDAG
2057 if (!entered_postcopy) {
2058 s->downtime = end_time - start_time;
2059 }
d6ed7312
PL
2060 if (s->total_time) {
2061 s->mbps = (((double) transferred_bytes * 8.0) /
2062 ((double) s->total_time)) / 1000;
2063 }
a3fa1d78
PB
2064 runstate_set(RUN_STATE_POSTMIGRATE);
2065 } else {
0b827d5e
HZ
2066 if (s->state == MIGRATION_STATUS_ACTIVE && enable_colo) {
2067 migrate_start_colo_process(s);
2068 qemu_savevm_state_cleanup();
2069 /*
2070 * Fixme: we will run VM in COLO no matter its old running state.
2071 * After exited COLO, we will keep running.
2072 */
2073 old_vm_running = true;
2074 }
1d34e4bf 2075 if (old_vm_running && !entered_postcopy) {
a3fa1d78 2076 vm_start();
42da5550
DDAG
2077 } else {
2078 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2079 runstate_set(RUN_STATE_POSTMIGRATE);
2080 }
dba433c0 2081 }
0d82d0e8 2082 }
bb1fadc4 2083 qemu_bh_schedule(s->cleanup_bh);
dba433c0 2084 qemu_mutex_unlock_iothread();
f4410a5d 2085
ab28bd23 2086 rcu_unregister_thread();
0d82d0e8
JQ
2087 return NULL;
2088}
2089
9848a404 2090void migrate_fd_connect(MigrationState *s)
0d82d0e8 2091{
2ff30257 2092 s->expected_downtime = s->parameters.downtime_limit;
bb1fadc4 2093 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
0d82d0e8 2094
9e4d2b98 2095 qemu_file_set_blocking(s->to_dst_file, true);
89a02a9f 2096 qemu_file_set_rate_limit(s->to_dst_file,
2ff30257 2097 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
442773ce 2098
9287ac27
SH
2099 /* Notify before starting migration thread */
2100 notifier_list_notify(&migration_state_notifiers, s);
2101
1d34e4bf
DDAG
2102 /*
2103 * Open the return path; currently for postcopy but other things might
2104 * also want it.
2105 */
2106 if (migrate_postcopy_ram()) {
2107 if (open_return_path_on_source(s)) {
2108 error_report("Unable to open return-path for postcopy");
48781e5b 2109 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1d34e4bf
DDAG
2110 MIGRATION_STATUS_FAILED);
2111 migrate_fd_cleanup(s);
2112 return;
2113 }
2114 }
2115
8706d2d5 2116 migrate_compress_threads_create();
009fad7f 2117 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
bb1fadc4 2118 QEMU_THREAD_JOINABLE);
1d34e4bf 2119 s->migration_thread_running = true;
0d82d0e8 2120}
093e3c42 2121