]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
Migration: Generate the completed event only when we complete
[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
16#include "qemu-common.h"
d49b6836 17#include "qemu/error-report.h"
6a1751b7 18#include "qemu/main-loop.h"
caf71f86 19#include "migration/migration.h"
0d82d0e8 20#include "migration/qemu-file.h"
9c17d615 21#include "sysemu/sysemu.h"
737e150e 22#include "block/block.h"
cc7a8ea7 23#include "qapi/qmp/qerror.h"
1de7afc9 24#include "qemu/sockets.h"
ab28bd23 25#include "qemu/rcu.h"
caf71f86 26#include "migration/block.h"
766bd176 27#include "qemu/thread.h"
791e7c82 28#include "qmp-commands.h"
c09e5bb1 29#include "trace.h"
df4b1024 30#include "qapi/util.h"
598cd2bd 31#include "qapi-event.h"
070afca2 32#include "qom/cpu.h"
065e2813 33
dc325627 34#define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
5bb7910a 35
5b4e1eb7
JQ
36/* Amount of time to allocate to each "chunk" of bandwidth-throttled
37 * data. */
38#define BUFFER_DELAY 100
39#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
40
8706d2d5
LL
41/* Default compression thread count */
42#define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
3fcb38c2
LL
43/* Default decompression thread count, usually decompression is at
44 * least 4 times as fast as compression.*/
45#define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
8706d2d5
LL
46/*0: means nocompress, 1: best speed, ... 9: best compress ratio */
47#define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
1626fee3
JH
48/* Define default autoconverge cpu throttle migration parameters */
49#define DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL 20
50#define DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT 10
8706d2d5 51
17ad9b35
OW
52/* Migration XBZRLE default cache size */
53#define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
54
99a0db9b
GH
55static NotifierList migration_state_notifiers =
56 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
57
adde220a
DDAG
58static bool deferred_incoming;
59
17549e84
JQ
60/* When we add fault tolerance, we could have several
61 migrations at once. For now we don't need to add
62 dynamic creation of migration */
63
bca7856a 64/* For outgoing */
859bc756 65MigrationState *migrate_get_current(void)
17549e84
JQ
66{
67 static MigrationState current_migration = {
31194731 68 .state = MIGRATION_STATUS_NONE,
d0ae46c1 69 .bandwidth_limit = MAX_THROTTLE,
17ad9b35 70 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
7e114f8c 71 .mbps = -1,
43c60a81
LL
72 .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
73 DEFAULT_MIGRATE_COMPRESS_LEVEL,
74 .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
75 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
76 .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
77 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
1626fee3
JH
78 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
79 DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL,
80 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
81 DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT,
17549e84
JQ
82 };
83
84 return &current_migration;
85}
86
bca7856a
DDAG
87/* For incoming */
88static MigrationIncomingState *mis_current;
89
90MigrationIncomingState *migration_incoming_get_current(void)
91{
92 return mis_current;
93}
94
95MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
96{
97f3ad35 97 mis_current = g_new0(MigrationIncomingState, 1);
bca7856a 98 mis_current->file = f;
1a8f46f8 99 QLIST_INIT(&mis_current->loadvm_handlers);
bca7856a
DDAG
100
101 return mis_current;
102}
103
104void migration_incoming_state_destroy(void)
105{
1a8f46f8 106 loadvm_free_handlers(mis_current);
bca7856a
DDAG
107 g_free(mis_current);
108 mis_current = NULL;
109}
110
df4b1024
JQ
111
112typedef struct {
13d16814 113 bool optional;
df4b1024
JQ
114 uint32_t size;
115 uint8_t runstate[100];
172c4356
JQ
116 RunState state;
117 bool received;
df4b1024
JQ
118} GlobalState;
119
120static GlobalState global_state;
121
560d027b 122int global_state_store(void)
df4b1024
JQ
123{
124 if (!runstate_store((char *)global_state.runstate,
125 sizeof(global_state.runstate))) {
126 error_report("runstate name too big: %s", global_state.runstate);
127 trace_migrate_state_too_big();
128 return -EINVAL;
129 }
130 return 0;
131}
132
c69adea4
AP
133void global_state_store_running(void)
134{
135 const char *state = RunState_lookup[RUN_STATE_RUNNING];
136 strncpy((char *)global_state.runstate,
137 state, sizeof(global_state.runstate));
138}
139
172c4356 140static bool global_state_received(void)
df4b1024 141{
172c4356
JQ
142 return global_state.received;
143}
144
145static RunState global_state_get_runstate(void)
146{
147 return global_state.state;
df4b1024
JQ
148}
149
13d16814
JQ
150void global_state_set_optional(void)
151{
152 global_state.optional = true;
153}
154
155static bool global_state_needed(void *opaque)
156{
157 GlobalState *s = opaque;
158 char *runstate = (char *)s->runstate;
159
160 /* If it is not optional, it is mandatory */
161
162 if (s->optional == false) {
163 return true;
164 }
165
166 /* If state is running or paused, it is not needed */
167
168 if (strcmp(runstate, "running") == 0 ||
169 strcmp(runstate, "paused") == 0) {
170 return false;
171 }
172
173 /* for any other state it is needed */
174 return true;
175}
176
df4b1024
JQ
177static int global_state_post_load(void *opaque, int version_id)
178{
179 GlobalState *s = opaque;
172c4356
JQ
180 Error *local_err = NULL;
181 int r;
df4b1024
JQ
182 char *runstate = (char *)s->runstate;
183
172c4356 184 s->received = true;
df4b1024
JQ
185 trace_migrate_global_state_post_load(runstate);
186
172c4356 187 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE_MAX,
df4b1024
JQ
188 -1, &local_err);
189
172c4356
JQ
190 if (r == -1) {
191 if (local_err) {
192 error_report_err(local_err);
df4b1024 193 }
172c4356 194 return -EINVAL;
df4b1024 195 }
172c4356 196 s->state = r;
df4b1024 197
172c4356 198 return 0;
df4b1024
JQ
199}
200
201static void global_state_pre_save(void *opaque)
202{
203 GlobalState *s = opaque;
204
205 trace_migrate_global_state_pre_save((char *)s->runstate);
206 s->size = strlen((char *)s->runstate) + 1;
207}
208
209static const VMStateDescription vmstate_globalstate = {
210 .name = "globalstate",
211 .version_id = 1,
212 .minimum_version_id = 1,
213 .post_load = global_state_post_load,
214 .pre_save = global_state_pre_save,
13d16814 215 .needed = global_state_needed,
df4b1024
JQ
216 .fields = (VMStateField[]) {
217 VMSTATE_UINT32(size, GlobalState),
218 VMSTATE_BUFFER(runstate, GlobalState),
219 VMSTATE_END_OF_LIST()
220 },
221};
222
223void register_global_state(void)
224{
225 /* We would use it independently that we receive it */
226 strcpy((char *)&global_state.runstate, "");
172c4356 227 global_state.received = false;
df4b1024
JQ
228 vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
229}
230
b05dc723
JQ
231static void migrate_generate_event(int new_state)
232{
233 if (migrate_use_events()) {
234 qapi_event_send_migration(new_state, &error_abort);
b05dc723
JQ
235 }
236}
237
adde220a
DDAG
238/*
239 * Called on -incoming with a defer: uri.
240 * The migration can be started later after any parameters have been
241 * changed.
242 */
243static void deferred_incoming_migration(Error **errp)
244{
245 if (deferred_incoming) {
246 error_setg(errp, "Incoming migration already deferred");
247 }
248 deferred_incoming = true;
249}
250
43eaae28 251void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 252{
34c9dd8e
AL
253 const char *p;
254
7cf1fe6d 255 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
adde220a
DDAG
256 if (!strcmp(uri, "defer")) {
257 deferred_incoming_migration(errp);
258 } else if (strstart(uri, "tcp:", &p)) {
43eaae28 259 tcp_start_incoming_migration(p, errp);
2da776db 260#ifdef CONFIG_RDMA
adde220a 261 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
262 rdma_start_incoming_migration(p, errp);
263#endif
065e2813 264#if !defined(WIN32)
adde220a 265 } else if (strstart(uri, "exec:", &p)) {
43eaae28 266 exec_start_incoming_migration(p, errp);
adde220a 267 } else if (strstart(uri, "unix:", &p)) {
43eaae28 268 unix_start_incoming_migration(p, errp);
adde220a 269 } else if (strstart(uri, "fd:", &p)) {
43eaae28 270 fd_start_incoming_migration(p, errp);
065e2813 271#endif
adde220a 272 } else {
312fd5f2 273 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 274 }
5bb7910a
AL
275}
276
82a4da79 277static void process_incoming_migration_co(void *opaque)
511c0231 278{
82a4da79 279 QEMUFile *f = opaque;
5a8a30db 280 Error *local_err = NULL;
1c12e1f5
PB
281 int ret;
282
bca7856a 283 migration_incoming_state_new(f);
7cf1fe6d 284 migrate_generate_event(MIGRATION_STATUS_ACTIVE);
1c12e1f5 285 ret = qemu_loadvm_state(f);
bca7856a 286
1c12e1f5 287 qemu_fclose(f);
905f26f2 288 free_xbzrle_decoded_buf();
bca7856a
DDAG
289 migration_incoming_state_destroy();
290
1c12e1f5 291 if (ret < 0) {
7cf1fe6d 292 migrate_generate_event(MIGRATION_STATUS_FAILED);
db80face 293 error_report("load of migration failed: %s", strerror(-ret));
3fcb38c2 294 migrate_decompress_threads_join();
4aead692 295 exit(EXIT_FAILURE);
511c0231
JQ
296 }
297 qemu_announce_self();
511c0231 298
0f15423c 299 /* Make sure all file formats flush their mutable metadata */
5a8a30db
KW
300 bdrv_invalidate_cache_all(&local_err);
301 if (local_err) {
ed1f3e00 302 migrate_generate_event(MIGRATION_STATUS_FAILED);
97baf9d9 303 error_report_err(local_err);
3fcb38c2 304 migrate_decompress_threads_join();
5a8a30db
KW
305 exit(EXIT_FAILURE);
306 }
0f15423c 307
172c4356
JQ
308 /* If global state section was not received or we are in running
309 state, we need to obey autostart. Any other state is set with
310 runstate_set. */
df4b1024 311
172c4356
JQ
312 if (!global_state_received() ||
313 global_state_get_runstate() == RUN_STATE_RUNNING) {
df4b1024
JQ
314 if (autostart) {
315 vm_start();
316 } else {
317 runstate_set(RUN_STATE_PAUSED);
318 }
172c4356
JQ
319 } else {
320 runstate_set(global_state_get_runstate());
f5bbfba1 321 }
3fcb38c2 322 migrate_decompress_threads_join();
ed1f3e00
DDAG
323 /*
324 * This must happen after any state changes since as soon as an external
325 * observer sees this event they might start to prod at the VM assuming
326 * it's ready to use.
327 */
328 migrate_generate_event(MIGRATION_STATUS_COMPLETED);
511c0231
JQ
329}
330
82a4da79
PB
331void process_incoming_migration(QEMUFile *f)
332{
333 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
334 int fd = qemu_get_fd(f);
335
336 assert(fd != -1);
3fcb38c2 337 migrate_decompress_threads_create();
f9e8cacc 338 qemu_set_nonblock(fd);
82a4da79
PB
339 qemu_coroutine_enter(co, f);
340}
341
a0a3fd60
GC
342/* amount of nanoseconds we are willing to wait for migration to be down.
343 * the choice of nanoseconds is because it is the maximum resolution that
344 * get_clock() can achieve. It is an internal measure. All user-visible
345 * units must be in seconds */
f7cd55a0 346static uint64_t max_downtime = 300000000;
a0a3fd60
GC
347
348uint64_t migrate_max_downtime(void)
349{
350 return max_downtime;
351}
352
bbf6da32
OW
353MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
354{
355 MigrationCapabilityStatusList *head = NULL;
356 MigrationCapabilityStatusList *caps;
357 MigrationState *s = migrate_get_current();
358 int i;
359
387eedeb 360 caps = NULL; /* silence compiler warning */
bbf6da32
OW
361 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
362 if (head == NULL) {
363 head = g_malloc0(sizeof(*caps));
364 caps = head;
365 } else {
366 caps->next = g_malloc0(sizeof(*caps));
367 caps = caps->next;
368 }
369 caps->value =
370 g_malloc(sizeof(*caps->value));
371 caps->value->capability = i;
372 caps->value->state = s->enabled_capabilities[i];
373 }
374
375 return head;
376}
377
85de8323
LL
378MigrationParameters *qmp_query_migrate_parameters(Error **errp)
379{
380 MigrationParameters *params;
381 MigrationState *s = migrate_get_current();
382
383 params = g_malloc0(sizeof(*params));
384 params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
385 params->compress_threads =
386 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
387 params->decompress_threads =
388 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1626fee3
JH
389 params->x_cpu_throttle_initial =
390 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
391 params->x_cpu_throttle_increment =
392 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
85de8323
LL
393
394 return params;
395}
396
f36d55af
OW
397static void get_xbzrle_cache_stats(MigrationInfo *info)
398{
399 if (migrate_use_xbzrle()) {
400 info->has_xbzrle_cache = true;
401 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
402 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
403 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
404 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
405 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
8bc39233 406 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
f36d55af
OW
407 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
408 }
409}
410
791e7c82 411MigrationInfo *qmp_query_migrate(Error **errp)
5bb7910a 412{
791e7c82 413 MigrationInfo *info = g_malloc0(sizeof(*info));
17549e84
JQ
414 MigrationState *s = migrate_get_current();
415
416 switch (s->state) {
31194731 417 case MIGRATION_STATUS_NONE:
17549e84
JQ
418 /* no migration has happened ever */
419 break;
31194731 420 case MIGRATION_STATUS_SETUP:
29ae8a41 421 info->has_status = true;
ed4fbd10 422 info->has_total_time = false;
29ae8a41 423 break;
31194731
HZ
424 case MIGRATION_STATUS_ACTIVE:
425 case MIGRATION_STATUS_CANCELLING:
791e7c82 426 info->has_status = true;
7aa939af 427 info->has_total_time = true;
bc72ad67 428 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
7aa939af 429 - s->total_time;
2c52ddf1
JQ
430 info->has_expected_downtime = true;
431 info->expected_downtime = s->expected_downtime;
ed4fbd10
MH
432 info->has_setup_time = true;
433 info->setup_time = s->setup_time;
17549e84 434
791e7c82
LC
435 info->has_ram = true;
436 info->ram = g_malloc0(sizeof(*info->ram));
437 info->ram->transferred = ram_bytes_transferred();
438 info->ram->remaining = ram_bytes_remaining();
439 info->ram->total = ram_bytes_total();
004d4c10 440 info->ram->duplicate = dup_mig_pages_transferred();
f1c72795 441 info->ram->skipped = skipped_mig_pages_transferred();
004d4c10
OW
442 info->ram->normal = norm_mig_pages_transferred();
443 info->ram->normal_bytes = norm_mig_bytes_transferred();
8d017193 444 info->ram->dirty_pages_rate = s->dirty_pages_rate;
7e114f8c 445 info->ram->mbps = s->mbps;
58570ed8 446 info->ram->dirty_sync_count = s->dirty_sync_count;
8d017193 447
17549e84 448 if (blk_mig_active()) {
791e7c82
LC
449 info->has_disk = true;
450 info->disk = g_malloc0(sizeof(*info->disk));
451 info->disk->transferred = blk_mig_bytes_transferred();
452 info->disk->remaining = blk_mig_bytes_remaining();
453 info->disk->total = blk_mig_bytes_total();
ff8d81d8 454 }
f36d55af 455
4782893e
JH
456 if (cpu_throttle_active()) {
457 info->has_x_cpu_throttle_percentage = true;
458 info->x_cpu_throttle_percentage = cpu_throttle_get_percentage();
459 }
460
f36d55af 461 get_xbzrle_cache_stats(info);
17549e84 462 break;
31194731 463 case MIGRATION_STATUS_COMPLETED:
f36d55af
OW
464 get_xbzrle_cache_stats(info);
465
791e7c82 466 info->has_status = true;
00c14997 467 info->has_total_time = true;
7aa939af 468 info->total_time = s->total_time;
9c5a9fcf
JQ
469 info->has_downtime = true;
470 info->downtime = s->downtime;
ed4fbd10
MH
471 info->has_setup_time = true;
472 info->setup_time = s->setup_time;
d5f8a570
JQ
473
474 info->has_ram = true;
475 info->ram = g_malloc0(sizeof(*info->ram));
476 info->ram->transferred = ram_bytes_transferred();
477 info->ram->remaining = 0;
478 info->ram->total = ram_bytes_total();
004d4c10 479 info->ram->duplicate = dup_mig_pages_transferred();
f1c72795 480 info->ram->skipped = skipped_mig_pages_transferred();
004d4c10
OW
481 info->ram->normal = norm_mig_pages_transferred();
482 info->ram->normal_bytes = norm_mig_bytes_transferred();
7e114f8c 483 info->ram->mbps = s->mbps;
58570ed8 484 info->ram->dirty_sync_count = s->dirty_sync_count;
17549e84 485 break;
31194731 486 case MIGRATION_STATUS_FAILED:
791e7c82 487 info->has_status = true;
17549e84 488 break;
31194731 489 case MIGRATION_STATUS_CANCELLED:
791e7c82 490 info->has_status = true;
17549e84 491 break;
5bb7910a 492 }
cde63fbe 493 info->status = s->state;
791e7c82
LC
494
495 return info;
5bb7910a
AL
496}
497
00458433
OW
498void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
499 Error **errp)
500{
501 MigrationState *s = migrate_get_current();
502 MigrationCapabilityStatusList *cap;
503
31194731
HZ
504 if (s->state == MIGRATION_STATUS_ACTIVE ||
505 s->state == MIGRATION_STATUS_SETUP) {
c6bd8c70 506 error_setg(errp, QERR_MIGRATION_ACTIVE);
00458433
OW
507 return;
508 }
509
510 for (cap = params; cap; cap = cap->next) {
511 s->enabled_capabilities[cap->value->capability] = cap->value->state;
512 }
513}
514
85de8323
LL
515void qmp_migrate_set_parameters(bool has_compress_level,
516 int64_t compress_level,
517 bool has_compress_threads,
518 int64_t compress_threads,
519 bool has_decompress_threads,
1626fee3
JH
520 int64_t decompress_threads,
521 bool has_x_cpu_throttle_initial,
522 int64_t x_cpu_throttle_initial,
523 bool has_x_cpu_throttle_increment,
524 int64_t x_cpu_throttle_increment, Error **errp)
85de8323
LL
525{
526 MigrationState *s = migrate_get_current();
527
528 if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
c6bd8c70
MA
529 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
530 "is invalid, it should be in the range of 0 to 9");
85de8323
LL
531 return;
532 }
533 if (has_compress_threads &&
534 (compress_threads < 1 || compress_threads > 255)) {
c6bd8c70
MA
535 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
536 "compress_threads",
537 "is invalid, it should be in the range of 1 to 255");
85de8323
LL
538 return;
539 }
540 if (has_decompress_threads &&
541 (decompress_threads < 1 || decompress_threads > 255)) {
c6bd8c70
MA
542 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
543 "decompress_threads",
544 "is invalid, it should be in the range of 1 to 255");
85de8323
LL
545 return;
546 }
1626fee3
JH
547 if (has_x_cpu_throttle_initial &&
548 (x_cpu_throttle_initial < 1 || x_cpu_throttle_initial > 99)) {
549 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
550 "x_cpu_throttle_initial",
551 "an integer in the range of 1 to 99");
552 }
553 if (has_x_cpu_throttle_increment &&
554 (x_cpu_throttle_increment < 1 || x_cpu_throttle_increment > 99)) {
555 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
556 "x_cpu_throttle_increment",
557 "an integer in the range of 1 to 99");
558 }
85de8323
LL
559
560 if (has_compress_level) {
561 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
562 }
563 if (has_compress_threads) {
564 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
565 }
566 if (has_decompress_threads) {
567 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
568 decompress_threads;
569 }
1626fee3
JH
570 if (has_x_cpu_throttle_initial) {
571 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
572 x_cpu_throttle_initial;
573 }
574
575 if (has_x_cpu_throttle_increment) {
576 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
577 x_cpu_throttle_increment;
578 }
85de8323
LL
579}
580
065e2813
AL
581/* shared migration helpers */
582
51cf4c1a
Z
583static void migrate_set_state(MigrationState *s, int old_state, int new_state)
584{
a5c17b5f 585 if (atomic_cmpxchg(&s->state, old_state, new_state) == old_state) {
4ba4bc5e 586 trace_migrate_set_state(new_state);
b05dc723 587 migrate_generate_event(new_state);
51cf4c1a
Z
588 }
589}
590
bb1fadc4 591static void migrate_fd_cleanup(void *opaque)
065e2813 592{
bb1fadc4
PB
593 MigrationState *s = opaque;
594
595 qemu_bh_delete(s->cleanup_bh);
596 s->cleanup_bh = NULL;
597
065e2813 598 if (s->file) {
9013dca5 599 trace_migrate_fd_cleanup();
404a7c05
PB
600 qemu_mutex_unlock_iothread();
601 qemu_thread_join(&s->thread);
602 qemu_mutex_lock_iothread();
603
8706d2d5 604 migrate_compress_threads_join();
6f190a06
PB
605 qemu_fclose(s->file);
606 s->file = NULL;
065e2813
AL
607 }
608
31194731 609 assert(s->state != MIGRATION_STATUS_ACTIVE);
7a2c1721 610
31194731 611 if (s->state != MIGRATION_STATUS_COMPLETED) {
7a2c1721 612 qemu_savevm_state_cancel();
31194731
HZ
613 if (s->state == MIGRATION_STATUS_CANCELLING) {
614 migrate_set_state(s, MIGRATION_STATUS_CANCELLING,
615 MIGRATION_STATUS_CANCELLED);
51cf4c1a 616 }
7a2c1721 617 }
a3fa1d78
PB
618
619 notifier_list_notify(&migration_state_notifiers, s);
065e2813
AL
620}
621
8b6b99b3 622void migrate_fd_error(MigrationState *s)
065e2813 623{
9013dca5 624 trace_migrate_fd_error();
bb1fadc4 625 assert(s->file == NULL);
7844337d 626 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
bb1fadc4 627 notifier_list_notify(&migration_state_notifiers, s);
458cf28e
JQ
628}
629
0edda1c4 630static void migrate_fd_cancel(MigrationState *s)
065e2813 631{
6f2b811a 632 int old_state ;
a26ba26e 633 QEMUFile *f = migrate_get_current()->file;
9013dca5 634 trace_migrate_fd_cancel();
065e2813 635
6f2b811a
Z
636 do {
637 old_state = s->state;
31194731
HZ
638 if (old_state != MIGRATION_STATUS_SETUP &&
639 old_state != MIGRATION_STATUS_ACTIVE) {
6f2b811a
Z
640 break;
641 }
31194731
HZ
642 migrate_set_state(s, old_state, MIGRATION_STATUS_CANCELLING);
643 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
644
645 /*
646 * If we're unlucky the migration code might be stuck somewhere in a
647 * send/write while the network has failed and is waiting to timeout;
648 * if we've got shutdown(2) available then we can force it to quit.
649 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
650 * called in a bh, so there is no race against this cancel.
651 */
31194731 652 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
a26ba26e
DDAG
653 qemu_file_shutdown(f);
654 }
065e2813
AL
655}
656
99a0db9b
GH
657void add_migration_state_change_notifier(Notifier *notify)
658{
659 notifier_list_add(&migration_state_notifiers, notify);
660}
661
662void remove_migration_state_change_notifier(Notifier *notify)
663{
31552529 664 notifier_remove(notify);
99a0db9b
GH
665}
666
02edd2e7 667bool migration_in_setup(MigrationState *s)
afe2df69 668{
31194731 669 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
670}
671
7073693b 672bool migration_has_finished(MigrationState *s)
99a0db9b 673{
31194731 674 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 675}
0edda1c4 676
afe2df69
GH
677bool migration_has_failed(MigrationState *s)
678{
31194731
HZ
679 return (s->state == MIGRATION_STATUS_CANCELLED ||
680 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
681}
682
6607ae23 683static MigrationState *migrate_init(const MigrationParams *params)
0edda1c4 684{
17549e84 685 MigrationState *s = migrate_get_current();
d0ae46c1 686 int64_t bandwidth_limit = s->bandwidth_limit;
bbf6da32 687 bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
17ad9b35 688 int64_t xbzrle_cache_size = s->xbzrle_cache_size;
43c60a81
LL
689 int compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
690 int compress_thread_count =
691 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
692 int decompress_thread_count =
693 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1626fee3
JH
694 int x_cpu_throttle_initial =
695 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
696 int x_cpu_throttle_increment =
697 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
bbf6da32
OW
698
699 memcpy(enabled_capabilities, s->enabled_capabilities,
700 sizeof(enabled_capabilities));
0edda1c4 701
17549e84 702 memset(s, 0, sizeof(*s));
6607ae23 703 s->params = *params;
bbf6da32
OW
704 memcpy(s->enabled_capabilities, enabled_capabilities,
705 sizeof(enabled_capabilities));
17ad9b35 706 s->xbzrle_cache_size = xbzrle_cache_size;
1299c631 707
43c60a81
LL
708 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
709 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
710 compress_thread_count;
711 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
712 decompress_thread_count;
1626fee3
JH
713 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
714 x_cpu_throttle_initial;
715 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
716 x_cpu_throttle_increment;
0edda1c4 717 s->bandwidth_limit = bandwidth_limit;
7844337d 718 migrate_set_state(s, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 719
bc72ad67 720 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0edda1c4
JQ
721 return s;
722}
cab30143 723
fa2756b7
AL
724static GSList *migration_blockers;
725
726void migrate_add_blocker(Error *reason)
727{
728 migration_blockers = g_slist_prepend(migration_blockers, reason);
729}
730
731void migrate_del_blocker(Error *reason)
732{
733 migration_blockers = g_slist_remove(migration_blockers, reason);
734}
735
bf1ae1f4
DDAG
736void qmp_migrate_incoming(const char *uri, Error **errp)
737{
738 Error *local_err = NULL;
4debb5f5 739 static bool once = true;
bf1ae1f4
DDAG
740
741 if (!deferred_incoming) {
4debb5f5 742 error_setg(errp, "For use with '-incoming defer'");
bf1ae1f4
DDAG
743 return;
744 }
4debb5f5
DDAG
745 if (!once) {
746 error_setg(errp, "The incoming migration has already been started");
747 }
bf1ae1f4
DDAG
748
749 qemu_start_incoming_migration(uri, &local_err);
750
751 if (local_err) {
752 error_propagate(errp, local_err);
753 return;
754 }
755
4debb5f5 756 once = false;
bf1ae1f4
DDAG
757}
758
e1c37d0e
LC
759void qmp_migrate(const char *uri, bool has_blk, bool blk,
760 bool has_inc, bool inc, bool has_detach, bool detach,
761 Error **errp)
cab30143 762{
be7059cd 763 Error *local_err = NULL;
17549e84 764 MigrationState *s = migrate_get_current();
6607ae23 765 MigrationParams params;
cab30143 766 const char *p;
cab30143 767
8c0426ae
PP
768 params.blk = has_blk && blk;
769 params.shared = has_inc && inc;
6607ae23 770
31194731
HZ
771 if (s->state == MIGRATION_STATUS_ACTIVE ||
772 s->state == MIGRATION_STATUS_SETUP ||
773 s->state == MIGRATION_STATUS_CANCELLING) {
c6bd8c70 774 error_setg(errp, QERR_MIGRATION_ACTIVE);
e1c37d0e 775 return;
cab30143 776 }
ca99993a
DDAG
777 if (runstate_check(RUN_STATE_INMIGRATE)) {
778 error_setg(errp, "Guest is waiting for an incoming migration");
779 return;
780 }
781
e1c37d0e
LC
782 if (qemu_savevm_state_blocked(errp)) {
783 return;
cab30143
JQ
784 }
785
fa2756b7 786 if (migration_blockers) {
e1c37d0e
LC
787 *errp = error_copy(migration_blockers->data);
788 return;
fa2756b7
AL
789 }
790
656a2334
JQ
791 /* We are starting a new migration, so we want to start in a clean
792 state. This change is only needed if previous migration
793 failed/was cancelled. We don't use migrate_set_state() because
794 we are setting the initial state, not changing it. */
795 s->state = MIGRATION_STATUS_NONE;
796
6607ae23 797 s = migrate_init(&params);
cab30143
JQ
798
799 if (strstart(uri, "tcp:", &p)) {
f37afb5a 800 tcp_start_outgoing_migration(s, p, &local_err);
2da776db 801#ifdef CONFIG_RDMA
41310c68 802 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
803 rdma_start_outgoing_migration(s, p, &local_err);
804#endif
cab30143
JQ
805#if !defined(WIN32)
806 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 807 exec_start_outgoing_migration(s, p, &local_err);
cab30143 808 } else if (strstart(uri, "unix:", &p)) {
f37afb5a 809 unix_start_outgoing_migration(s, p, &local_err);
cab30143 810 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 811 fd_start_outgoing_migration(s, p, &local_err);
cab30143 812#endif
99a0db9b 813 } else {
c6bd8c70
MA
814 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
815 "a valid migration protocol");
7844337d 816 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
e1c37d0e 817 return;
cab30143
JQ
818 }
819
f37afb5a 820 if (local_err) {
342ab8d1 821 migrate_fd_error(s);
f37afb5a 822 error_propagate(errp, local_err);
e1c37d0e 823 return;
1299c631 824 }
cab30143
JQ
825}
826
6cdedb07 827void qmp_migrate_cancel(Error **errp)
cab30143 828{
17549e84 829 migrate_fd_cancel(migrate_get_current());
cab30143
JQ
830}
831
9e1ba4cc
OW
832void qmp_migrate_set_cache_size(int64_t value, Error **errp)
833{
834 MigrationState *s = migrate_get_current();
c91e681a 835 int64_t new_size;
9e1ba4cc
OW
836
837 /* Check for truncation */
838 if (value != (size_t)value) {
c6bd8c70
MA
839 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
840 "exceeding address space");
9e1ba4cc
OW
841 return;
842 }
843
a5615b14
OW
844 /* Cache should not be larger than guest ram size */
845 if (value > ram_bytes_total()) {
c6bd8c70
MA
846 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
847 "exceeds guest ram size ");
a5615b14
OW
848 return;
849 }
850
c91e681a
OW
851 new_size = xbzrle_cache_resize(value);
852 if (new_size < 0) {
c6bd8c70
MA
853 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
854 "is smaller than page size");
c91e681a
OW
855 return;
856 }
857
858 s->xbzrle_cache_size = new_size;
9e1ba4cc
OW
859}
860
861int64_t qmp_query_migrate_cache_size(Error **errp)
862{
863 return migrate_xbzrle_cache_size();
864}
865
3dc85383 866void qmp_migrate_set_speed(int64_t value, Error **errp)
cab30143 867{
cab30143
JQ
868 MigrationState *s;
869
3dc85383
LC
870 if (value < 0) {
871 value = 0;
99a0db9b 872 }
442773ce
PB
873 if (value > SIZE_MAX) {
874 value = SIZE_MAX;
875 }
cab30143 876
17549e84 877 s = migrate_get_current();
3dc85383 878 s->bandwidth_limit = value;
442773ce
PB
879 if (s->file) {
880 qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
881 }
cab30143
JQ
882}
883
4f0a993b 884void qmp_migrate_set_downtime(double value, Error **errp)
cab30143 885{
4f0a993b
LC
886 value *= 1e9;
887 value = MAX(0, MIN(UINT64_MAX, value));
888 max_downtime = (uint64_t)value;
99a0db9b 889}
17ad9b35 890
bde1e2ec
CV
891bool migrate_auto_converge(void)
892{
893 MigrationState *s;
894
895 s = migrate_get_current();
896
897 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
898}
899
323004a3
PL
900bool migrate_zero_blocks(void)
901{
902 MigrationState *s;
903
904 s = migrate_get_current();
905
906 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
907}
908
8706d2d5
LL
909bool migrate_use_compression(void)
910{
dde4e694
LL
911 MigrationState *s;
912
913 s = migrate_get_current();
914
915 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
916}
917
918int migrate_compress_level(void)
919{
920 MigrationState *s;
921
922 s = migrate_get_current();
923
43c60a81 924 return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
8706d2d5
LL
925}
926
927int migrate_compress_threads(void)
928{
929 MigrationState *s;
930
931 s = migrate_get_current();
932
43c60a81 933 return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
8706d2d5
LL
934}
935
3fcb38c2
LL
936int migrate_decompress_threads(void)
937{
938 MigrationState *s;
939
940 s = migrate_get_current();
941
43c60a81 942 return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
3fcb38c2
LL
943}
944
b05dc723
JQ
945bool migrate_use_events(void)
946{
947 MigrationState *s;
948
949 s = migrate_get_current();
950
951 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
952}
953
17ad9b35
OW
954int migrate_use_xbzrle(void)
955{
956 MigrationState *s;
957
958 s = migrate_get_current();
959
960 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
961}
962
963int64_t migrate_xbzrle_cache_size(void)
964{
965 MigrationState *s;
966
967 s = migrate_get_current();
968
969 return s->xbzrle_cache_size;
970}
0d82d0e8 971
09f6c85e
DDAG
972/**
973 * migration_completion: Used by migration_thread when there's not much left.
974 * The caller 'breaks' the loop when this returns.
975 *
976 * @s: Current migration state
977 * @*old_vm_running: Pointer to old_vm_running flag
978 * @*start_time: Pointer to time to update
979 */
980static void migration_completion(MigrationState *s, bool *old_vm_running,
981 int64_t *start_time)
982{
983 int ret;
984
985 qemu_mutex_lock_iothread();
986 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
987 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
988 *old_vm_running = runstate_is_running();
989
990 ret = global_state_store();
991 if (!ret) {
992 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
993 if (ret >= 0) {
994 qemu_file_set_rate_limit(s->file, INT64_MAX);
995 qemu_savevm_state_complete(s->file);
996 }
997 }
998 qemu_mutex_unlock_iothread();
999
1000 if (ret < 0) {
1001 goto fail;
1002 }
1003
1004 if (qemu_file_get_error(s->file)) {
1005 trace_migration_completion_file_err();
1006 goto fail;
1007 }
1008
1009 migrate_set_state(s, MIGRATION_STATUS_ACTIVE, MIGRATION_STATUS_COMPLETED);
1010 return;
1011
1012fail:
1013 migrate_set_state(s, MIGRATION_STATUS_ACTIVE, MIGRATION_STATUS_FAILED);
1014}
1015
0d82d0e8
JQ
1016/* migration thread support */
1017
5f496a1b 1018static void *migration_thread(void *opaque)
0d82d0e8 1019{
9848a404 1020 MigrationState *s = opaque;
bc72ad67
AB
1021 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1022 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
be7172e2 1023 int64_t initial_bytes = 0;
0d82d0e8 1024 int64_t max_size = 0;
a3fa1d78
PB
1025 int64_t start_time = initial_time;
1026 bool old_vm_running = false;
76f5933a 1027
ab28bd23
PB
1028 rcu_register_thread();
1029
f796baa1 1030 qemu_savevm_state_header(s->file);
dba433c0 1031 qemu_savevm_state_begin(s->file, &s->params);
0d82d0e8 1032
bc72ad67 1033 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
31194731 1034 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_ACTIVE);
29ae8a41 1035
31194731 1036 while (s->state == MIGRATION_STATUS_ACTIVE) {
a3e879cd 1037 int64_t current_time;
c369f40d 1038 uint64_t pending_size;
0d82d0e8 1039
a0ff044b 1040 if (!qemu_file_rate_limit(s->file)) {
c369f40d 1041 pending_size = qemu_savevm_state_pending(s->file, max_size);
9013dca5 1042 trace_migrate_pending(pending_size, max_size);
b22ff1fb 1043 if (pending_size && pending_size >= max_size) {
dba433c0 1044 qemu_savevm_state_iterate(s->file);
c369f40d 1045 } else {
09f6c85e
DDAG
1046 trace_migration_thread_low_pending(pending_size);
1047 migration_completion(s, &old_vm_running, &start_time);
1048 break;
c369f40d
JQ
1049 }
1050 }
f4410a5d 1051
fd45ee2c 1052 if (qemu_file_get_error(s->file)) {
31194731
HZ
1053 migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
1054 MIGRATION_STATUS_FAILED);
fd45ee2c
PB
1055 break;
1056 }
bc72ad67 1057 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0d82d0e8 1058 if (current_time >= initial_time + BUFFER_DELAY) {
be7172e2 1059 uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
77417f10 1060 uint64_t time_spent = current_time - initial_time;
0d82d0e8
JQ
1061 double bandwidth = transferred_bytes / time_spent;
1062 max_size = bandwidth * migrate_max_downtime() / 1000000;
1063
7e114f8c
MH
1064 s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1065 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1066
9013dca5
AK
1067 trace_migrate_transferred(transferred_bytes, time_spent,
1068 bandwidth, max_size);
90f8ae72
JQ
1069 /* if we haven't sent anything, we don't want to recalculate
1070 10000 is a small enough number for our purposes */
1071 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1072 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1073 }
0d82d0e8 1074
1964a397 1075 qemu_file_reset_rate_limit(s->file);
0d82d0e8 1076 initial_time = current_time;
be7172e2 1077 initial_bytes = qemu_ftell(s->file);
0d82d0e8 1078 }
a0ff044b 1079 if (qemu_file_rate_limit(s->file)) {
0d82d0e8
JQ
1080 /* usleep expects microseconds */
1081 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1082 }
a3fa1d78
PB
1083 }
1084
070afca2
JH
1085 /* If we enabled cpu throttling for auto-converge, turn it off. */
1086 cpu_throttle_stop();
1087
f4410a5d 1088 qemu_mutex_lock_iothread();
31194731 1089 if (s->state == MIGRATION_STATUS_COMPLETED) {
bc72ad67 1090 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
d6ed7312 1091 uint64_t transferred_bytes = qemu_ftell(s->file);
a3fa1d78
PB
1092 s->total_time = end_time - s->total_time;
1093 s->downtime = end_time - start_time;
d6ed7312
PL
1094 if (s->total_time) {
1095 s->mbps = (((double) transferred_bytes * 8.0) /
1096 ((double) s->total_time)) / 1000;
1097 }
a3fa1d78
PB
1098 runstate_set(RUN_STATE_POSTMIGRATE);
1099 } else {
1100 if (old_vm_running) {
a3fa1d78 1101 vm_start();
dba433c0 1102 }
0d82d0e8 1103 }
bb1fadc4 1104 qemu_bh_schedule(s->cleanup_bh);
dba433c0 1105 qemu_mutex_unlock_iothread();
f4410a5d 1106
ab28bd23 1107 rcu_unregister_thread();
0d82d0e8
JQ
1108 return NULL;
1109}
1110
9848a404 1111void migrate_fd_connect(MigrationState *s)
0d82d0e8 1112{
cc283e3b
JQ
1113 /* This is a best 1st approximation. ns to ms */
1114 s->expected_downtime = max_downtime/1000000;
bb1fadc4 1115 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
0d82d0e8 1116
442773ce
PB
1117 qemu_file_set_rate_limit(s->file,
1118 s->bandwidth_limit / XFER_LIMIT_RATIO);
1119
9287ac27
SH
1120 /* Notify before starting migration thread */
1121 notifier_list_notify(&migration_state_notifiers, s);
1122
8706d2d5 1123 migrate_compress_threads_create();
4900116e 1124 qemu_thread_create(&s->thread, "migration", migration_thread, s,
bb1fadc4 1125 QEMU_THREAD_JOINABLE);
0d82d0e8 1126}