]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
Postcopy: Maintain unsentmap
[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
093e3c42
DDAG
60/*
61 * Current state of incoming postcopy; note this is not part of
62 * MigrationIncomingState since it's state is used during cleanup
63 * at the end as MIS is being freed.
64 */
65static PostcopyState incoming_postcopy_state;
66
17549e84
JQ
67/* When we add fault tolerance, we could have several
68 migrations at once. For now we don't need to add
69 dynamic creation of migration */
70
bca7856a 71/* For outgoing */
859bc756 72MigrationState *migrate_get_current(void)
17549e84
JQ
73{
74 static MigrationState current_migration = {
31194731 75 .state = MIGRATION_STATUS_NONE,
d0ae46c1 76 .bandwidth_limit = MAX_THROTTLE,
17ad9b35 77 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
7e114f8c 78 .mbps = -1,
43c60a81
LL
79 .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
80 DEFAULT_MIGRATE_COMPRESS_LEVEL,
81 .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
82 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
83 .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
84 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
1626fee3
JH
85 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
86 DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL,
87 .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
88 DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT,
17549e84
JQ
89 };
90
91 return &current_migration;
92}
93
bca7856a
DDAG
94/* For incoming */
95static MigrationIncomingState *mis_current;
96
97MigrationIncomingState *migration_incoming_get_current(void)
98{
99 return mis_current;
100}
101
102MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
103{
97f3ad35 104 mis_current = g_new0(MigrationIncomingState, 1);
42e2aa56 105 mis_current->from_src_file = f;
1a8f46f8 106 QLIST_INIT(&mis_current->loadvm_handlers);
6decec93 107 qemu_mutex_init(&mis_current->rp_mutex);
7b89bf27 108 qemu_event_init(&mis_current->main_thread_load_event, false);
bca7856a
DDAG
109
110 return mis_current;
111}
112
113void migration_incoming_state_destroy(void)
114{
7b89bf27 115 qemu_event_destroy(&mis_current->main_thread_load_event);
1a8f46f8 116 loadvm_free_handlers(mis_current);
bca7856a
DDAG
117 g_free(mis_current);
118 mis_current = NULL;
119}
120
df4b1024
JQ
121
122typedef struct {
13d16814 123 bool optional;
df4b1024
JQ
124 uint32_t size;
125 uint8_t runstate[100];
172c4356
JQ
126 RunState state;
127 bool received;
df4b1024
JQ
128} GlobalState;
129
130static GlobalState global_state;
131
560d027b 132int global_state_store(void)
df4b1024
JQ
133{
134 if (!runstate_store((char *)global_state.runstate,
135 sizeof(global_state.runstate))) {
136 error_report("runstate name too big: %s", global_state.runstate);
137 trace_migrate_state_too_big();
138 return -EINVAL;
139 }
140 return 0;
141}
142
c69adea4
AP
143void global_state_store_running(void)
144{
145 const char *state = RunState_lookup[RUN_STATE_RUNNING];
146 strncpy((char *)global_state.runstate,
147 state, sizeof(global_state.runstate));
148}
149
172c4356 150static bool global_state_received(void)
df4b1024 151{
172c4356
JQ
152 return global_state.received;
153}
154
155static RunState global_state_get_runstate(void)
156{
157 return global_state.state;
df4b1024
JQ
158}
159
13d16814
JQ
160void global_state_set_optional(void)
161{
162 global_state.optional = true;
163}
164
165static bool global_state_needed(void *opaque)
166{
167 GlobalState *s = opaque;
168 char *runstate = (char *)s->runstate;
169
170 /* If it is not optional, it is mandatory */
171
172 if (s->optional == false) {
173 return true;
174 }
175
176 /* If state is running or paused, it is not needed */
177
178 if (strcmp(runstate, "running") == 0 ||
179 strcmp(runstate, "paused") == 0) {
180 return false;
181 }
182
183 /* for any other state it is needed */
184 return true;
185}
186
df4b1024
JQ
187static int global_state_post_load(void *opaque, int version_id)
188{
189 GlobalState *s = opaque;
172c4356
JQ
190 Error *local_err = NULL;
191 int r;
df4b1024
JQ
192 char *runstate = (char *)s->runstate;
193
172c4356 194 s->received = true;
df4b1024
JQ
195 trace_migrate_global_state_post_load(runstate);
196
172c4356 197 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE_MAX,
df4b1024
JQ
198 -1, &local_err);
199
172c4356
JQ
200 if (r == -1) {
201 if (local_err) {
202 error_report_err(local_err);
df4b1024 203 }
172c4356 204 return -EINVAL;
df4b1024 205 }
172c4356 206 s->state = r;
df4b1024 207
172c4356 208 return 0;
df4b1024
JQ
209}
210
211static void global_state_pre_save(void *opaque)
212{
213 GlobalState *s = opaque;
214
215 trace_migrate_global_state_pre_save((char *)s->runstate);
216 s->size = strlen((char *)s->runstate) + 1;
217}
218
219static const VMStateDescription vmstate_globalstate = {
220 .name = "globalstate",
221 .version_id = 1,
222 .minimum_version_id = 1,
223 .post_load = global_state_post_load,
224 .pre_save = global_state_pre_save,
13d16814 225 .needed = global_state_needed,
df4b1024
JQ
226 .fields = (VMStateField[]) {
227 VMSTATE_UINT32(size, GlobalState),
228 VMSTATE_BUFFER(runstate, GlobalState),
229 VMSTATE_END_OF_LIST()
230 },
231};
232
233void register_global_state(void)
234{
235 /* We would use it independently that we receive it */
236 strcpy((char *)&global_state.runstate, "");
172c4356 237 global_state.received = false;
df4b1024
JQ
238 vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
239}
240
b05dc723
JQ
241static void migrate_generate_event(int new_state)
242{
243 if (migrate_use_events()) {
244 qapi_event_send_migration(new_state, &error_abort);
b05dc723
JQ
245 }
246}
247
adde220a
DDAG
248/*
249 * Called on -incoming with a defer: uri.
250 * The migration can be started later after any parameters have been
251 * changed.
252 */
253static void deferred_incoming_migration(Error **errp)
254{
255 if (deferred_incoming) {
256 error_setg(errp, "Incoming migration already deferred");
257 }
258 deferred_incoming = true;
259}
260
43eaae28 261void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 262{
34c9dd8e
AL
263 const char *p;
264
7cf1fe6d 265 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
adde220a
DDAG
266 if (!strcmp(uri, "defer")) {
267 deferred_incoming_migration(errp);
268 } else if (strstart(uri, "tcp:", &p)) {
43eaae28 269 tcp_start_incoming_migration(p, errp);
2da776db 270#ifdef CONFIG_RDMA
adde220a 271 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
272 rdma_start_incoming_migration(p, errp);
273#endif
065e2813 274#if !defined(WIN32)
adde220a 275 } else if (strstart(uri, "exec:", &p)) {
43eaae28 276 exec_start_incoming_migration(p, errp);
adde220a 277 } else if (strstart(uri, "unix:", &p)) {
43eaae28 278 unix_start_incoming_migration(p, errp);
adde220a 279 } else if (strstart(uri, "fd:", &p)) {
43eaae28 280 fd_start_incoming_migration(p, errp);
065e2813 281#endif
adde220a 282 } else {
312fd5f2 283 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 284 }
5bb7910a
AL
285}
286
82a4da79 287static void process_incoming_migration_co(void *opaque)
511c0231 288{
82a4da79 289 QEMUFile *f = opaque;
5a8a30db 290 Error *local_err = NULL;
1c12e1f5
PB
291 int ret;
292
bca7856a 293 migration_incoming_state_new(f);
093e3c42 294 postcopy_state_set(POSTCOPY_INCOMING_NONE);
7cf1fe6d 295 migrate_generate_event(MIGRATION_STATUS_ACTIVE);
1c12e1f5 296 ret = qemu_loadvm_state(f);
bca7856a 297
1c12e1f5 298 qemu_fclose(f);
905f26f2 299 free_xbzrle_decoded_buf();
bca7856a
DDAG
300 migration_incoming_state_destroy();
301
1c12e1f5 302 if (ret < 0) {
7cf1fe6d 303 migrate_generate_event(MIGRATION_STATUS_FAILED);
db80face 304 error_report("load of migration failed: %s", strerror(-ret));
3fcb38c2 305 migrate_decompress_threads_join();
4aead692 306 exit(EXIT_FAILURE);
511c0231 307 }
511c0231 308
0f15423c 309 /* Make sure all file formats flush their mutable metadata */
5a8a30db
KW
310 bdrv_invalidate_cache_all(&local_err);
311 if (local_err) {
ed1f3e00 312 migrate_generate_event(MIGRATION_STATUS_FAILED);
97baf9d9 313 error_report_err(local_err);
3fcb38c2 314 migrate_decompress_threads_join();
5a8a30db
KW
315 exit(EXIT_FAILURE);
316 }
0f15423c 317
92e37622
AS
318 /*
319 * This must happen after all error conditions are dealt with and
320 * we're sure the VM is going to be running on this host.
321 */
322 qemu_announce_self();
323
172c4356
JQ
324 /* If global state section was not received or we are in running
325 state, we need to obey autostart. Any other state is set with
326 runstate_set. */
df4b1024 327
172c4356
JQ
328 if (!global_state_received() ||
329 global_state_get_runstate() == RUN_STATE_RUNNING) {
df4b1024
JQ
330 if (autostart) {
331 vm_start();
332 } else {
333 runstate_set(RUN_STATE_PAUSED);
334 }
172c4356
JQ
335 } else {
336 runstate_set(global_state_get_runstate());
f5bbfba1 337 }
3fcb38c2 338 migrate_decompress_threads_join();
ed1f3e00
DDAG
339 /*
340 * This must happen after any state changes since as soon as an external
341 * observer sees this event they might start to prod at the VM assuming
342 * it's ready to use.
343 */
344 migrate_generate_event(MIGRATION_STATUS_COMPLETED);
511c0231
JQ
345}
346
82a4da79
PB
347void process_incoming_migration(QEMUFile *f)
348{
349 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
350 int fd = qemu_get_fd(f);
351
352 assert(fd != -1);
3fcb38c2 353 migrate_decompress_threads_create();
f9e8cacc 354 qemu_set_nonblock(fd);
82a4da79
PB
355 qemu_coroutine_enter(co, f);
356}
357
6decec93
DDAG
358/*
359 * Send a message on the return channel back to the source
360 * of the migration.
361 */
362void migrate_send_rp_message(MigrationIncomingState *mis,
363 enum mig_rp_message_type message_type,
364 uint16_t len, void *data)
365{
366 trace_migrate_send_rp_message((int)message_type, len);
367 qemu_mutex_lock(&mis->rp_mutex);
368 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
369 qemu_put_be16(mis->to_src_file, len);
370 qemu_put_buffer(mis->to_src_file, data, len);
371 qemu_fflush(mis->to_src_file);
372 qemu_mutex_unlock(&mis->rp_mutex);
373}
374
375/*
376 * Send a 'SHUT' message on the return channel with the given value
377 * to indicate that we've finished with the RP. Non-0 value indicates
378 * error.
379 */
380void migrate_send_rp_shut(MigrationIncomingState *mis,
381 uint32_t value)
382{
383 uint32_t buf;
384
385 buf = cpu_to_be32(value);
386 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
387}
388
389/*
390 * Send a 'PONG' message on the return channel with the given value
391 * (normally in response to a 'PING')
392 */
393void migrate_send_rp_pong(MigrationIncomingState *mis,
394 uint32_t value)
395{
396 uint32_t buf;
397
398 buf = cpu_to_be32(value);
399 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
400}
401
a0a3fd60
GC
402/* amount of nanoseconds we are willing to wait for migration to be down.
403 * the choice of nanoseconds is because it is the maximum resolution that
404 * get_clock() can achieve. It is an internal measure. All user-visible
405 * units must be in seconds */
f7cd55a0 406static uint64_t max_downtime = 300000000;
a0a3fd60
GC
407
408uint64_t migrate_max_downtime(void)
409{
410 return max_downtime;
411}
412
bbf6da32
OW
413MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
414{
415 MigrationCapabilityStatusList *head = NULL;
416 MigrationCapabilityStatusList *caps;
417 MigrationState *s = migrate_get_current();
418 int i;
419
387eedeb 420 caps = NULL; /* silence compiler warning */
bbf6da32
OW
421 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
422 if (head == NULL) {
423 head = g_malloc0(sizeof(*caps));
424 caps = head;
425 } else {
426 caps->next = g_malloc0(sizeof(*caps));
427 caps = caps->next;
428 }
429 caps->value =
430 g_malloc(sizeof(*caps->value));
431 caps->value->capability = i;
432 caps->value->state = s->enabled_capabilities[i];
433 }
434
435 return head;
436}
437
85de8323
LL
438MigrationParameters *qmp_query_migrate_parameters(Error **errp)
439{
440 MigrationParameters *params;
441 MigrationState *s = migrate_get_current();
442
443 params = g_malloc0(sizeof(*params));
444 params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
445 params->compress_threads =
446 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
447 params->decompress_threads =
448 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1626fee3
JH
449 params->x_cpu_throttle_initial =
450 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
451 params->x_cpu_throttle_increment =
452 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
85de8323
LL
453
454 return params;
455}
456
f6844b99
DDAG
457/*
458 * Return true if we're already in the middle of a migration
459 * (i.e. any of the active or setup states)
460 */
461static bool migration_is_setup_or_active(int state)
462{
463 switch (state) {
464 case MIGRATION_STATUS_ACTIVE:
9ec055ae 465 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
f6844b99
DDAG
466 case MIGRATION_STATUS_SETUP:
467 return true;
468
469 default:
470 return false;
471
472 }
473}
474
f36d55af
OW
475static void get_xbzrle_cache_stats(MigrationInfo *info)
476{
477 if (migrate_use_xbzrle()) {
478 info->has_xbzrle_cache = true;
479 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
480 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
481 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
482 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
483 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
8bc39233 484 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
f36d55af
OW
485 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
486 }
487}
488
791e7c82 489MigrationInfo *qmp_query_migrate(Error **errp)
5bb7910a 490{
791e7c82 491 MigrationInfo *info = g_malloc0(sizeof(*info));
17549e84
JQ
492 MigrationState *s = migrate_get_current();
493
494 switch (s->state) {
31194731 495 case MIGRATION_STATUS_NONE:
17549e84
JQ
496 /* no migration has happened ever */
497 break;
31194731 498 case MIGRATION_STATUS_SETUP:
29ae8a41 499 info->has_status = true;
ed4fbd10 500 info->has_total_time = false;
29ae8a41 501 break;
31194731
HZ
502 case MIGRATION_STATUS_ACTIVE:
503 case MIGRATION_STATUS_CANCELLING:
791e7c82 504 info->has_status = true;
7aa939af 505 info->has_total_time = true;
bc72ad67 506 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
7aa939af 507 - s->total_time;
2c52ddf1
JQ
508 info->has_expected_downtime = true;
509 info->expected_downtime = s->expected_downtime;
ed4fbd10
MH
510 info->has_setup_time = true;
511 info->setup_time = s->setup_time;
17549e84 512
791e7c82
LC
513 info->has_ram = true;
514 info->ram = g_malloc0(sizeof(*info->ram));
515 info->ram->transferred = ram_bytes_transferred();
516 info->ram->remaining = ram_bytes_remaining();
517 info->ram->total = ram_bytes_total();
004d4c10 518 info->ram->duplicate = dup_mig_pages_transferred();
f1c72795 519 info->ram->skipped = skipped_mig_pages_transferred();
004d4c10
OW
520 info->ram->normal = norm_mig_pages_transferred();
521 info->ram->normal_bytes = norm_mig_bytes_transferred();
8d017193 522 info->ram->dirty_pages_rate = s->dirty_pages_rate;
7e114f8c 523 info->ram->mbps = s->mbps;
58570ed8 524 info->ram->dirty_sync_count = s->dirty_sync_count;
8d017193 525
17549e84 526 if (blk_mig_active()) {
791e7c82
LC
527 info->has_disk = true;
528 info->disk = g_malloc0(sizeof(*info->disk));
529 info->disk->transferred = blk_mig_bytes_transferred();
530 info->disk->remaining = blk_mig_bytes_remaining();
531 info->disk->total = blk_mig_bytes_total();
ff8d81d8 532 }
f36d55af 533
4782893e
JH
534 if (cpu_throttle_active()) {
535 info->has_x_cpu_throttle_percentage = true;
536 info->x_cpu_throttle_percentage = cpu_throttle_get_percentage();
537 }
538
9ec055ae
DDAG
539 get_xbzrle_cache_stats(info);
540 break;
541 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
542 /* Mostly the same as active; TODO add some postcopy stats */
543 info->has_status = true;
544 info->has_total_time = true;
545 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
546 - s->total_time;
547 info->has_expected_downtime = true;
548 info->expected_downtime = s->expected_downtime;
549 info->has_setup_time = true;
550 info->setup_time = s->setup_time;
551
552 info->has_ram = true;
553 info->ram = g_malloc0(sizeof(*info->ram));
554 info->ram->transferred = ram_bytes_transferred();
555 info->ram->remaining = ram_bytes_remaining();
556 info->ram->total = ram_bytes_total();
557 info->ram->duplicate = dup_mig_pages_transferred();
558 info->ram->skipped = skipped_mig_pages_transferred();
559 info->ram->normal = norm_mig_pages_transferred();
560 info->ram->normal_bytes = norm_mig_bytes_transferred();
561 info->ram->dirty_pages_rate = s->dirty_pages_rate;
562 info->ram->mbps = s->mbps;
563
564 if (blk_mig_active()) {
565 info->has_disk = true;
566 info->disk = g_malloc0(sizeof(*info->disk));
567 info->disk->transferred = blk_mig_bytes_transferred();
568 info->disk->remaining = blk_mig_bytes_remaining();
569 info->disk->total = blk_mig_bytes_total();
570 }
571
f36d55af 572 get_xbzrle_cache_stats(info);
17549e84 573 break;
31194731 574 case MIGRATION_STATUS_COMPLETED:
f36d55af
OW
575 get_xbzrle_cache_stats(info);
576
791e7c82 577 info->has_status = true;
00c14997 578 info->has_total_time = true;
7aa939af 579 info->total_time = s->total_time;
9c5a9fcf
JQ
580 info->has_downtime = true;
581 info->downtime = s->downtime;
ed4fbd10
MH
582 info->has_setup_time = true;
583 info->setup_time = s->setup_time;
d5f8a570
JQ
584
585 info->has_ram = true;
586 info->ram = g_malloc0(sizeof(*info->ram));
587 info->ram->transferred = ram_bytes_transferred();
588 info->ram->remaining = 0;
589 info->ram->total = ram_bytes_total();
004d4c10 590 info->ram->duplicate = dup_mig_pages_transferred();
f1c72795 591 info->ram->skipped = skipped_mig_pages_transferred();
004d4c10
OW
592 info->ram->normal = norm_mig_pages_transferred();
593 info->ram->normal_bytes = norm_mig_bytes_transferred();
7e114f8c 594 info->ram->mbps = s->mbps;
58570ed8 595 info->ram->dirty_sync_count = s->dirty_sync_count;
17549e84 596 break;
31194731 597 case MIGRATION_STATUS_FAILED:
791e7c82 598 info->has_status = true;
17549e84 599 break;
31194731 600 case MIGRATION_STATUS_CANCELLED:
791e7c82 601 info->has_status = true;
17549e84 602 break;
5bb7910a 603 }
cde63fbe 604 info->status = s->state;
791e7c82
LC
605
606 return info;
5bb7910a
AL
607}
608
00458433
OW
609void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
610 Error **errp)
611{
612 MigrationState *s = migrate_get_current();
613 MigrationCapabilityStatusList *cap;
614
f6844b99 615 if (migration_is_setup_or_active(s->state)) {
c6bd8c70 616 error_setg(errp, QERR_MIGRATION_ACTIVE);
00458433
OW
617 return;
618 }
619
620 for (cap = params; cap; cap = cap->next) {
621 s->enabled_capabilities[cap->value->capability] = cap->value->state;
622 }
53dd370c
DDAG
623
624 if (migrate_postcopy_ram()) {
625 if (migrate_use_compression()) {
626 /* The decompression threads asynchronously write into RAM
627 * rather than use the atomic copies needed to avoid
628 * userfaulting. It should be possible to fix the decompression
629 * threads for compatibility in future.
630 */
631 error_report("Postcopy is not currently compatible with "
632 "compression");
633 s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM] =
634 false;
635 }
636 }
00458433
OW
637}
638
85de8323
LL
639void qmp_migrate_set_parameters(bool has_compress_level,
640 int64_t compress_level,
641 bool has_compress_threads,
642 int64_t compress_threads,
643 bool has_decompress_threads,
1626fee3
JH
644 int64_t decompress_threads,
645 bool has_x_cpu_throttle_initial,
646 int64_t x_cpu_throttle_initial,
647 bool has_x_cpu_throttle_increment,
648 int64_t x_cpu_throttle_increment, Error **errp)
85de8323
LL
649{
650 MigrationState *s = migrate_get_current();
651
652 if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
c6bd8c70
MA
653 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
654 "is invalid, it should be in the range of 0 to 9");
85de8323
LL
655 return;
656 }
657 if (has_compress_threads &&
658 (compress_threads < 1 || compress_threads > 255)) {
c6bd8c70
MA
659 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
660 "compress_threads",
661 "is invalid, it should be in the range of 1 to 255");
85de8323
LL
662 return;
663 }
664 if (has_decompress_threads &&
665 (decompress_threads < 1 || decompress_threads > 255)) {
c6bd8c70
MA
666 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
667 "decompress_threads",
668 "is invalid, it should be in the range of 1 to 255");
85de8323
LL
669 return;
670 }
1626fee3
JH
671 if (has_x_cpu_throttle_initial &&
672 (x_cpu_throttle_initial < 1 || x_cpu_throttle_initial > 99)) {
673 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
674 "x_cpu_throttle_initial",
675 "an integer in the range of 1 to 99");
676 }
677 if (has_x_cpu_throttle_increment &&
678 (x_cpu_throttle_increment < 1 || x_cpu_throttle_increment > 99)) {
679 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
680 "x_cpu_throttle_increment",
681 "an integer in the range of 1 to 99");
682 }
85de8323
LL
683
684 if (has_compress_level) {
685 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
686 }
687 if (has_compress_threads) {
688 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
689 }
690 if (has_decompress_threads) {
691 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
692 decompress_threads;
693 }
1626fee3
JH
694 if (has_x_cpu_throttle_initial) {
695 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
696 x_cpu_throttle_initial;
697 }
698
699 if (has_x_cpu_throttle_increment) {
700 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
701 x_cpu_throttle_increment;
702 }
85de8323
LL
703}
704
4886a1bc
DDAG
705void qmp_migrate_start_postcopy(Error **errp)
706{
707 MigrationState *s = migrate_get_current();
708
709 if (!migrate_postcopy_ram()) {
710 error_setg(errp, "Enable postcopy with migration_set_capability before"
711 " the start of migration");
712 return;
713 }
714
715 if (s->state == MIGRATION_STATUS_NONE) {
716 error_setg(errp, "Postcopy must be started after migration has been"
717 " started");
718 return;
719 }
720 /*
721 * we don't error if migration has finished since that would be racy
722 * with issuing this command.
723 */
724 atomic_set(&s->start_postcopy, true);
725}
726
065e2813
AL
727/* shared migration helpers */
728
51cf4c1a
Z
729static void migrate_set_state(MigrationState *s, int old_state, int new_state)
730{
a5c17b5f 731 if (atomic_cmpxchg(&s->state, old_state, new_state) == old_state) {
4ba4bc5e 732 trace_migrate_set_state(new_state);
b05dc723 733 migrate_generate_event(new_state);
51cf4c1a
Z
734 }
735}
736
bb1fadc4 737static void migrate_fd_cleanup(void *opaque)
065e2813 738{
bb1fadc4
PB
739 MigrationState *s = opaque;
740
741 qemu_bh_delete(s->cleanup_bh);
742 s->cleanup_bh = NULL;
743
065e2813 744 if (s->file) {
9013dca5 745 trace_migrate_fd_cleanup();
404a7c05
PB
746 qemu_mutex_unlock_iothread();
747 qemu_thread_join(&s->thread);
748 qemu_mutex_lock_iothread();
749
8706d2d5 750 migrate_compress_threads_join();
6f190a06
PB
751 qemu_fclose(s->file);
752 s->file = NULL;
065e2813
AL
753 }
754
9ec055ae
DDAG
755 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
756 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
7a2c1721 757
94f5a437
LL
758 if (s->state == MIGRATION_STATUS_CANCELLING) {
759 migrate_set_state(s, MIGRATION_STATUS_CANCELLING,
760 MIGRATION_STATUS_CANCELLED);
7a2c1721 761 }
a3fa1d78
PB
762
763 notifier_list_notify(&migration_state_notifiers, s);
065e2813
AL
764}
765
8b6b99b3 766void migrate_fd_error(MigrationState *s)
065e2813 767{
9013dca5 768 trace_migrate_fd_error();
bb1fadc4 769 assert(s->file == NULL);
7844337d 770 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
bb1fadc4 771 notifier_list_notify(&migration_state_notifiers, s);
458cf28e
JQ
772}
773
0edda1c4 774static void migrate_fd_cancel(MigrationState *s)
065e2813 775{
6f2b811a 776 int old_state ;
a26ba26e 777 QEMUFile *f = migrate_get_current()->file;
9013dca5 778 trace_migrate_fd_cancel();
065e2813 779
70b20477
DDAG
780 if (s->rp_state.from_dst_file) {
781 /* shutdown the rp socket, so causing the rp thread to shutdown */
782 qemu_file_shutdown(s->rp_state.from_dst_file);
783 }
784
6f2b811a
Z
785 do {
786 old_state = s->state;
f6844b99 787 if (!migration_is_setup_or_active(old_state)) {
6f2b811a
Z
788 break;
789 }
31194731
HZ
790 migrate_set_state(s, old_state, MIGRATION_STATUS_CANCELLING);
791 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
792
793 /*
794 * If we're unlucky the migration code might be stuck somewhere in a
795 * send/write while the network has failed and is waiting to timeout;
796 * if we've got shutdown(2) available then we can force it to quit.
797 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
798 * called in a bh, so there is no race against this cancel.
799 */
31194731 800 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
a26ba26e
DDAG
801 qemu_file_shutdown(f);
802 }
065e2813
AL
803}
804
99a0db9b
GH
805void add_migration_state_change_notifier(Notifier *notify)
806{
807 notifier_list_add(&migration_state_notifiers, notify);
808}
809
810void remove_migration_state_change_notifier(Notifier *notify)
811{
31552529 812 notifier_remove(notify);
99a0db9b
GH
813}
814
02edd2e7 815bool migration_in_setup(MigrationState *s)
afe2df69 816{
31194731 817 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
818}
819
7073693b 820bool migration_has_finished(MigrationState *s)
99a0db9b 821{
31194731 822 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 823}
0edda1c4 824
afe2df69
GH
825bool migration_has_failed(MigrationState *s)
826{
31194731
HZ
827 return (s->state == MIGRATION_STATUS_CANCELLED ||
828 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
829}
830
9ec055ae
DDAG
831bool migration_in_postcopy(MigrationState *s)
832{
833 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
834}
835
aefeb18b 836MigrationState *migrate_init(const MigrationParams *params)
0edda1c4 837{
17549e84 838 MigrationState *s = migrate_get_current();
d0ae46c1 839 int64_t bandwidth_limit = s->bandwidth_limit;
bbf6da32 840 bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
17ad9b35 841 int64_t xbzrle_cache_size = s->xbzrle_cache_size;
43c60a81
LL
842 int compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
843 int compress_thread_count =
844 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
845 int decompress_thread_count =
846 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1626fee3
JH
847 int x_cpu_throttle_initial =
848 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
849 int x_cpu_throttle_increment =
850 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
bbf6da32
OW
851
852 memcpy(enabled_capabilities, s->enabled_capabilities,
853 sizeof(enabled_capabilities));
0edda1c4 854
17549e84 855 memset(s, 0, sizeof(*s));
6607ae23 856 s->params = *params;
bbf6da32
OW
857 memcpy(s->enabled_capabilities, enabled_capabilities,
858 sizeof(enabled_capabilities));
17ad9b35 859 s->xbzrle_cache_size = xbzrle_cache_size;
1299c631 860
43c60a81
LL
861 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
862 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
863 compress_thread_count;
864 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
865 decompress_thread_count;
1626fee3
JH
866 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
867 x_cpu_throttle_initial;
868 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
869 x_cpu_throttle_increment;
0edda1c4 870 s->bandwidth_limit = bandwidth_limit;
7844337d 871 migrate_set_state(s, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 872
bc72ad67 873 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0edda1c4
JQ
874 return s;
875}
cab30143 876
fa2756b7
AL
877static GSList *migration_blockers;
878
879void migrate_add_blocker(Error *reason)
880{
881 migration_blockers = g_slist_prepend(migration_blockers, reason);
882}
883
884void migrate_del_blocker(Error *reason)
885{
886 migration_blockers = g_slist_remove(migration_blockers, reason);
887}
888
bf1ae1f4
DDAG
889void qmp_migrate_incoming(const char *uri, Error **errp)
890{
891 Error *local_err = NULL;
4debb5f5 892 static bool once = true;
bf1ae1f4
DDAG
893
894 if (!deferred_incoming) {
4debb5f5 895 error_setg(errp, "For use with '-incoming defer'");
bf1ae1f4
DDAG
896 return;
897 }
4debb5f5
DDAG
898 if (!once) {
899 error_setg(errp, "The incoming migration has already been started");
900 }
bf1ae1f4
DDAG
901
902 qemu_start_incoming_migration(uri, &local_err);
903
904 if (local_err) {
905 error_propagate(errp, local_err);
906 return;
907 }
908
4debb5f5 909 once = false;
bf1ae1f4
DDAG
910}
911
e1c37d0e
LC
912void qmp_migrate(const char *uri, bool has_blk, bool blk,
913 bool has_inc, bool inc, bool has_detach, bool detach,
914 Error **errp)
cab30143 915{
be7059cd 916 Error *local_err = NULL;
17549e84 917 MigrationState *s = migrate_get_current();
6607ae23 918 MigrationParams params;
cab30143 919 const char *p;
cab30143 920
8c0426ae
PP
921 params.blk = has_blk && blk;
922 params.shared = has_inc && inc;
6607ae23 923
f6844b99 924 if (migration_is_setup_or_active(s->state) ||
31194731 925 s->state == MIGRATION_STATUS_CANCELLING) {
c6bd8c70 926 error_setg(errp, QERR_MIGRATION_ACTIVE);
e1c37d0e 927 return;
cab30143 928 }
ca99993a
DDAG
929 if (runstate_check(RUN_STATE_INMIGRATE)) {
930 error_setg(errp, "Guest is waiting for an incoming migration");
931 return;
932 }
933
e1c37d0e
LC
934 if (qemu_savevm_state_blocked(errp)) {
935 return;
cab30143
JQ
936 }
937
fa2756b7 938 if (migration_blockers) {
e1c37d0e
LC
939 *errp = error_copy(migration_blockers->data);
940 return;
fa2756b7
AL
941 }
942
656a2334
JQ
943 /* We are starting a new migration, so we want to start in a clean
944 state. This change is only needed if previous migration
945 failed/was cancelled. We don't use migrate_set_state() because
946 we are setting the initial state, not changing it. */
947 s->state = MIGRATION_STATUS_NONE;
948
6607ae23 949 s = migrate_init(&params);
cab30143
JQ
950
951 if (strstart(uri, "tcp:", &p)) {
f37afb5a 952 tcp_start_outgoing_migration(s, p, &local_err);
2da776db 953#ifdef CONFIG_RDMA
41310c68 954 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
955 rdma_start_outgoing_migration(s, p, &local_err);
956#endif
cab30143
JQ
957#if !defined(WIN32)
958 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 959 exec_start_outgoing_migration(s, p, &local_err);
cab30143 960 } else if (strstart(uri, "unix:", &p)) {
f37afb5a 961 unix_start_outgoing_migration(s, p, &local_err);
cab30143 962 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 963 fd_start_outgoing_migration(s, p, &local_err);
cab30143 964#endif
99a0db9b 965 } else {
c6bd8c70
MA
966 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
967 "a valid migration protocol");
7844337d 968 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
e1c37d0e 969 return;
cab30143
JQ
970 }
971
f37afb5a 972 if (local_err) {
342ab8d1 973 migrate_fd_error(s);
f37afb5a 974 error_propagate(errp, local_err);
e1c37d0e 975 return;
1299c631 976 }
cab30143
JQ
977}
978
6cdedb07 979void qmp_migrate_cancel(Error **errp)
cab30143 980{
17549e84 981 migrate_fd_cancel(migrate_get_current());
cab30143
JQ
982}
983
9e1ba4cc
OW
984void qmp_migrate_set_cache_size(int64_t value, Error **errp)
985{
986 MigrationState *s = migrate_get_current();
c91e681a 987 int64_t new_size;
9e1ba4cc
OW
988
989 /* Check for truncation */
990 if (value != (size_t)value) {
c6bd8c70
MA
991 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
992 "exceeding address space");
9e1ba4cc
OW
993 return;
994 }
995
a5615b14
OW
996 /* Cache should not be larger than guest ram size */
997 if (value > ram_bytes_total()) {
c6bd8c70
MA
998 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
999 "exceeds guest ram size ");
a5615b14
OW
1000 return;
1001 }
1002
c91e681a
OW
1003 new_size = xbzrle_cache_resize(value);
1004 if (new_size < 0) {
c6bd8c70
MA
1005 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1006 "is smaller than page size");
c91e681a
OW
1007 return;
1008 }
1009
1010 s->xbzrle_cache_size = new_size;
9e1ba4cc
OW
1011}
1012
1013int64_t qmp_query_migrate_cache_size(Error **errp)
1014{
1015 return migrate_xbzrle_cache_size();
1016}
1017
3dc85383 1018void qmp_migrate_set_speed(int64_t value, Error **errp)
cab30143 1019{
cab30143
JQ
1020 MigrationState *s;
1021
3dc85383
LC
1022 if (value < 0) {
1023 value = 0;
99a0db9b 1024 }
442773ce
PB
1025 if (value > SIZE_MAX) {
1026 value = SIZE_MAX;
1027 }
cab30143 1028
17549e84 1029 s = migrate_get_current();
3dc85383 1030 s->bandwidth_limit = value;
442773ce
PB
1031 if (s->file) {
1032 qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
1033 }
cab30143
JQ
1034}
1035
4f0a993b 1036void qmp_migrate_set_downtime(double value, Error **errp)
cab30143 1037{
4f0a993b
LC
1038 value *= 1e9;
1039 value = MAX(0, MIN(UINT64_MAX, value));
1040 max_downtime = (uint64_t)value;
99a0db9b 1041}
17ad9b35 1042
53dd370c
DDAG
1043bool migrate_postcopy_ram(void)
1044{
1045 MigrationState *s;
1046
1047 s = migrate_get_current();
1048
1049 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM];
1050}
1051
bde1e2ec
CV
1052bool migrate_auto_converge(void)
1053{
1054 MigrationState *s;
1055
1056 s = migrate_get_current();
1057
1058 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1059}
1060
323004a3
PL
1061bool migrate_zero_blocks(void)
1062{
1063 MigrationState *s;
1064
1065 s = migrate_get_current();
1066
1067 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1068}
1069
8706d2d5
LL
1070bool migrate_use_compression(void)
1071{
dde4e694
LL
1072 MigrationState *s;
1073
1074 s = migrate_get_current();
1075
1076 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
1077}
1078
1079int migrate_compress_level(void)
1080{
1081 MigrationState *s;
1082
1083 s = migrate_get_current();
1084
43c60a81 1085 return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
8706d2d5
LL
1086}
1087
1088int migrate_compress_threads(void)
1089{
1090 MigrationState *s;
1091
1092 s = migrate_get_current();
1093
43c60a81 1094 return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
8706d2d5
LL
1095}
1096
3fcb38c2
LL
1097int migrate_decompress_threads(void)
1098{
1099 MigrationState *s;
1100
1101 s = migrate_get_current();
1102
43c60a81 1103 return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
3fcb38c2
LL
1104}
1105
b05dc723
JQ
1106bool migrate_use_events(void)
1107{
1108 MigrationState *s;
1109
1110 s = migrate_get_current();
1111
1112 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1113}
1114
17ad9b35
OW
1115int migrate_use_xbzrle(void)
1116{
1117 MigrationState *s;
1118
1119 s = migrate_get_current();
1120
1121 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1122}
1123
1124int64_t migrate_xbzrle_cache_size(void)
1125{
1126 MigrationState *s;
1127
1128 s = migrate_get_current();
1129
1130 return s->xbzrle_cache_size;
1131}
0d82d0e8 1132
70b20477
DDAG
1133/* migration thread support */
1134/*
1135 * Something bad happened to the RP stream, mark an error
1136 * The caller shall print or trace something to indicate why
1137 */
1138static void mark_source_rp_bad(MigrationState *s)
1139{
1140 s->rp_state.error = true;
1141}
1142
1143static struct rp_cmd_args {
1144 ssize_t len; /* -1 = variable */
1145 const char *name;
1146} rp_cmd_args[] = {
1147 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1148 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1149 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1150 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1151};
1152
1153/*
1154 * Handles messages sent on the return path towards the source VM
1155 *
1156 */
1157static void *source_return_path_thread(void *opaque)
1158{
1159 MigrationState *ms = opaque;
1160 QEMUFile *rp = ms->rp_state.from_dst_file;
1161 uint16_t header_len, header_type;
1162 const int max_len = 512;
1163 uint8_t buf[max_len];
1164 uint32_t tmp32, sibling_error;
1165 int res;
1166
1167 trace_source_return_path_thread_entry();
1168 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1169 migration_is_setup_or_active(ms->state)) {
1170 trace_source_return_path_thread_loop_top();
1171 header_type = qemu_get_be16(rp);
1172 header_len = qemu_get_be16(rp);
1173
1174 if (header_type >= MIG_RP_MSG_MAX ||
1175 header_type == MIG_RP_MSG_INVALID) {
1176 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1177 header_type, header_len);
1178 mark_source_rp_bad(ms);
1179 goto out;
1180 }
1181
1182 if ((rp_cmd_args[header_type].len != -1 &&
1183 header_len != rp_cmd_args[header_type].len) ||
1184 header_len > max_len) {
1185 error_report("RP: Received '%s' message (0x%04x) with"
1186 "incorrect length %d expecting %zu",
1187 rp_cmd_args[header_type].name, header_type, header_len,
1188 (size_t)rp_cmd_args[header_type].len);
1189 mark_source_rp_bad(ms);
1190 goto out;
1191 }
1192
1193 /* We know we've got a valid header by this point */
1194 res = qemu_get_buffer(rp, buf, header_len);
1195 if (res != header_len) {
1196 error_report("RP: Failed reading data for message 0x%04x"
1197 " read %d expected %d",
1198 header_type, res, header_len);
1199 mark_source_rp_bad(ms);
1200 goto out;
1201 }
1202
1203 /* OK, we have the message and the data */
1204 switch (header_type) {
1205 case MIG_RP_MSG_SHUT:
1206 sibling_error = be32_to_cpup((uint32_t *)buf);
1207 trace_source_return_path_thread_shut(sibling_error);
1208 if (sibling_error) {
1209 error_report("RP: Sibling indicated error %d", sibling_error);
1210 mark_source_rp_bad(ms);
1211 }
1212 /*
1213 * We'll let the main thread deal with closing the RP
1214 * we could do a shutdown(2) on it, but we're the only user
1215 * anyway, so there's nothing gained.
1216 */
1217 goto out;
1218
1219 case MIG_RP_MSG_PONG:
1220 tmp32 = be32_to_cpup((uint32_t *)buf);
1221 trace_source_return_path_thread_pong(tmp32);
1222 break;
1223
1224 default:
1225 break;
1226 }
1227 }
1228 if (rp && qemu_file_get_error(rp)) {
1229 trace_source_return_path_thread_bad_end();
1230 mark_source_rp_bad(ms);
1231 }
1232
1233 trace_source_return_path_thread_end();
1234out:
1235 ms->rp_state.from_dst_file = NULL;
1236 qemu_fclose(rp);
1237 return NULL;
1238}
1239
1240__attribute__ (( unused )) /* Until later in patch series */
1241static int open_return_path_on_source(MigrationState *ms)
1242{
1243
1244 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->file);
1245 if (!ms->rp_state.from_dst_file) {
1246 return -1;
1247 }
1248
1249 trace_open_return_path_on_source();
1250 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1251 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1252
1253 trace_open_return_path_on_source_continue();
1254
1255 return 0;
1256}
1257
1258__attribute__ (( unused )) /* Until later in patch series */
1259/* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1260static int await_return_path_close_on_source(MigrationState *ms)
1261{
1262 /*
1263 * If this is a normal exit then the destination will send a SHUT and the
1264 * rp_thread will exit, however if there's an error we need to cause
1265 * it to exit.
1266 */
1267 if (qemu_file_get_error(ms->file) && ms->rp_state.from_dst_file) {
1268 /*
1269 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1270 * waiting for the destination.
1271 */
1272 qemu_file_shutdown(ms->rp_state.from_dst_file);
1273 mark_source_rp_bad(ms);
1274 }
1275 trace_await_return_path_close_on_source_joining();
1276 qemu_thread_join(&ms->rp_state.rp_thread);
1277 trace_await_return_path_close_on_source_close();
1278 return ms->rp_state.error;
1279}
1280
09f6c85e
DDAG
1281/**
1282 * migration_completion: Used by migration_thread when there's not much left.
1283 * The caller 'breaks' the loop when this returns.
1284 *
1285 * @s: Current migration state
36f48567 1286 * @current_active_state: The migration state we expect to be in
09f6c85e
DDAG
1287 * @*old_vm_running: Pointer to old_vm_running flag
1288 * @*start_time: Pointer to time to update
1289 */
36f48567
DDAG
1290static void migration_completion(MigrationState *s, int current_active_state,
1291 bool *old_vm_running,
09f6c85e
DDAG
1292 int64_t *start_time)
1293{
1294 int ret;
1295
1296 qemu_mutex_lock_iothread();
1297 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1298 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1299 *old_vm_running = runstate_is_running();
1300
1301 ret = global_state_store();
1302 if (!ret) {
1303 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1304 if (ret >= 0) {
1305 qemu_file_set_rate_limit(s->file, INT64_MAX);
a3e06c3d 1306 qemu_savevm_state_complete_precopy(s->file);
09f6c85e
DDAG
1307 }
1308 }
1309 qemu_mutex_unlock_iothread();
1310
1311 if (ret < 0) {
1312 goto fail;
1313 }
1314
1315 if (qemu_file_get_error(s->file)) {
1316 trace_migration_completion_file_err();
1317 goto fail;
1318 }
1319
36f48567 1320 migrate_set_state(s, current_active_state, MIGRATION_STATUS_COMPLETED);
09f6c85e
DDAG
1321 return;
1322
1323fail:
36f48567 1324 migrate_set_state(s, current_active_state, MIGRATION_STATUS_FAILED);
09f6c85e
DDAG
1325}
1326
70b20477
DDAG
1327/*
1328 * Master migration thread on the source VM.
1329 * It drives the migration and pumps the data down the outgoing channel.
1330 */
5f496a1b 1331static void *migration_thread(void *opaque)
0d82d0e8 1332{
9848a404 1333 MigrationState *s = opaque;
bc72ad67
AB
1334 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1335 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
be7172e2 1336 int64_t initial_bytes = 0;
0d82d0e8 1337 int64_t max_size = 0;
a3fa1d78 1338 int64_t start_time = initial_time;
94f5a437 1339 int64_t end_time;
a3fa1d78 1340 bool old_vm_running = false;
76f5933a 1341
ab28bd23
PB
1342 rcu_register_thread();
1343
f796baa1 1344 qemu_savevm_state_header(s->file);
dba433c0 1345 qemu_savevm_state_begin(s->file, &s->params);
0d82d0e8 1346
bc72ad67 1347 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
31194731 1348 migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_ACTIVE);
29ae8a41 1349
9ec055ae
DDAG
1350 trace_migration_thread_setup_complete();
1351
1352 while (s->state == MIGRATION_STATUS_ACTIVE ||
1353 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
a3e879cd 1354 int64_t current_time;
c369f40d 1355 uint64_t pending_size;
0d82d0e8 1356
a0ff044b 1357 if (!qemu_file_rate_limit(s->file)) {
c31b098f
DDAG
1358 uint64_t pend_post, pend_nonpost;
1359
1360 qemu_savevm_state_pending(s->file, max_size, &pend_nonpost,
1361 &pend_post);
1362 pending_size = pend_nonpost + pend_post;
1363 trace_migrate_pending(pending_size, max_size,
1364 pend_post, pend_nonpost);
b22ff1fb 1365 if (pending_size && pending_size >= max_size) {
dba433c0 1366 qemu_savevm_state_iterate(s->file);
c369f40d 1367 } else {
09f6c85e 1368 trace_migration_thread_low_pending(pending_size);
36f48567
DDAG
1369 migration_completion(s, MIGRATION_STATUS_ACTIVE,
1370 &old_vm_running, &start_time);
09f6c85e 1371 break;
c369f40d
JQ
1372 }
1373 }
f4410a5d 1374
fd45ee2c 1375 if (qemu_file_get_error(s->file)) {
31194731
HZ
1376 migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
1377 MIGRATION_STATUS_FAILED);
fd45ee2c
PB
1378 break;
1379 }
bc72ad67 1380 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0d82d0e8 1381 if (current_time >= initial_time + BUFFER_DELAY) {
be7172e2 1382 uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
77417f10 1383 uint64_t time_spent = current_time - initial_time;
0d82d0e8
JQ
1384 double bandwidth = transferred_bytes / time_spent;
1385 max_size = bandwidth * migrate_max_downtime() / 1000000;
1386
7e114f8c
MH
1387 s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1388 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1389
9013dca5
AK
1390 trace_migrate_transferred(transferred_bytes, time_spent,
1391 bandwidth, max_size);
90f8ae72
JQ
1392 /* if we haven't sent anything, we don't want to recalculate
1393 10000 is a small enough number for our purposes */
1394 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1395 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1396 }
0d82d0e8 1397
1964a397 1398 qemu_file_reset_rate_limit(s->file);
0d82d0e8 1399 initial_time = current_time;
be7172e2 1400 initial_bytes = qemu_ftell(s->file);
0d82d0e8 1401 }
a0ff044b 1402 if (qemu_file_rate_limit(s->file)) {
0d82d0e8
JQ
1403 /* usleep expects microseconds */
1404 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1405 }
a3fa1d78
PB
1406 }
1407
070afca2
JH
1408 /* If we enabled cpu throttling for auto-converge, turn it off. */
1409 cpu_throttle_stop();
94f5a437 1410 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
070afca2 1411
f4410a5d 1412 qemu_mutex_lock_iothread();
ea7415fa 1413 qemu_savevm_state_cleanup();
31194731 1414 if (s->state == MIGRATION_STATUS_COMPLETED) {
d6ed7312 1415 uint64_t transferred_bytes = qemu_ftell(s->file);
a3fa1d78
PB
1416 s->total_time = end_time - s->total_time;
1417 s->downtime = end_time - start_time;
d6ed7312
PL
1418 if (s->total_time) {
1419 s->mbps = (((double) transferred_bytes * 8.0) /
1420 ((double) s->total_time)) / 1000;
1421 }
a3fa1d78
PB
1422 runstate_set(RUN_STATE_POSTMIGRATE);
1423 } else {
1424 if (old_vm_running) {
a3fa1d78 1425 vm_start();
dba433c0 1426 }
0d82d0e8 1427 }
bb1fadc4 1428 qemu_bh_schedule(s->cleanup_bh);
dba433c0 1429 qemu_mutex_unlock_iothread();
f4410a5d 1430
ab28bd23 1431 rcu_unregister_thread();
0d82d0e8
JQ
1432 return NULL;
1433}
1434
9848a404 1435void migrate_fd_connect(MigrationState *s)
0d82d0e8 1436{
cc283e3b
JQ
1437 /* This is a best 1st approximation. ns to ms */
1438 s->expected_downtime = max_downtime/1000000;
bb1fadc4 1439 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
0d82d0e8 1440
442773ce
PB
1441 qemu_file_set_rate_limit(s->file,
1442 s->bandwidth_limit / XFER_LIMIT_RATIO);
1443
9287ac27
SH
1444 /* Notify before starting migration thread */
1445 notifier_list_notify(&migration_state_notifiers, s);
1446
8706d2d5 1447 migrate_compress_threads_create();
4900116e 1448 qemu_thread_create(&s->thread, "migration", migration_thread, s,
bb1fadc4 1449 QEMU_THREAD_JOINABLE);
0d82d0e8 1450}
093e3c42
DDAG
1451
1452PostcopyState postcopy_state_get(void)
1453{
1454 return atomic_mb_read(&incoming_postcopy_state);
1455}
1456
1457/* Set the state and return the old state */
1458PostcopyState postcopy_state_set(PostcopyState new_state)
1459{
1460 return atomic_xchg(&incoming_postcopy_state, new_state);
1461}
1462