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