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