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