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