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