]> Git Repo - qemu.git/blame - migration/migration.c
postcopy-ram: add a stub for postcopy_request_shared_page
[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 <[email protected]>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
6b620ca3
PB
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
5bb7910a
AL
14 */
15
1393a485 16#include "qemu/osdep.h"
f348b6d1 17#include "qemu/cutils.h"
d49b6836 18#include "qemu/error-report.h"
795c40b8 19#include "migration/blocker.h"
f4dbe1bf 20#include "exec.h"
7fcac4a2 21#include "fd.h"
61e8b148 22#include "socket.h"
e1a3ecee 23#include "rdma.h"
7b1e1a22 24#include "ram.h"
84a899de 25#include "migration/global_state.h"
c4b63b7c 26#include "migration/misc.h"
6666c96a 27#include "migration.h"
20a519a0 28#include "savevm.h"
40014d81 29#include "qemu-file-channel.h"
08a0aee1 30#include "qemu-file.h"
987772d9 31#include "migration/vmstate.h"
737e150e 32#include "block/block.h"
e688df6b 33#include "qapi/error.h"
9af23989
MA
34#include "qapi/qapi-commands-migration.h"
35#include "qapi/qapi-events-migration.h"
cc7a8ea7 36#include "qapi/qmp/qerror.h"
15280c36 37#include "qapi/qmp/qnull.h"
ab28bd23 38#include "qemu/rcu.h"
2c9e6fec 39#include "block.h"
be07b0ac 40#include "postcopy-ram.h"
766bd176 41#include "qemu/thread.h"
c09e5bb1 42#include "trace.h"
51180423 43#include "exec/target_page.h"
61b67d47 44#include "io/channel-buffer.h"
35a6ed4f 45#include "migration/colo.h"
4ffdb337 46#include "hw/boards.h"
9d18af93 47#include "monitor/monitor.h"
065e2813 48
dc325627 49#define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
5bb7910a 50
5b4e1eb7
JQ
51/* Amount of time to allocate to each "chunk" of bandwidth-throttled
52 * data. */
53#define BUFFER_DELAY 100
54#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
55
2ff30257
AA
56/* Time in milliseconds we are allowed to stop the source,
57 * for sending the last part */
58#define DEFAULT_MIGRATE_SET_DOWNTIME 300
59
87c9cc1c
DHB
60/* Maximum migrate downtime set to 2000 seconds */
61#define MAX_MIGRATE_DOWNTIME_SECONDS 2000
62#define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
63
8706d2d5
LL
64/* Default compression thread count */
65#define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
3fcb38c2
LL
66/* Default decompression thread count, usually decompression is at
67 * least 4 times as fast as compression.*/
68#define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
8706d2d5
LL
69/*0: means nocompress, 1: best speed, ... 9: best compress ratio */
70#define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
1626fee3 71/* Define default autoconverge cpu throttle migration parameters */
d85a31d1
JH
72#define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
73#define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
8706d2d5 74
17ad9b35 75/* Migration XBZRLE default cache size */
73af8dd8 76#define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
17ad9b35 77
68b53591
HZ
78/* The delay time (in ms) between two COLO checkpoints
79 * Note: Please change this default value to 10000 when we support hybrid mode.
80 */
81#define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
4075fb1c 82#define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
0fb86605 83#define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
68b53591 84
99a0db9b
GH
85static NotifierList migration_state_notifiers =
86 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
87
adde220a
DDAG
88static bool deferred_incoming;
89
da6f1790
JQ
90/* Messages sent on the return path from destination to source */
91enum mig_rp_message_type {
92 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
93 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
94 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
95
96 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
97 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
98
99 MIG_RP_MSG_MAX
100};
101
17549e84
JQ
102/* When we add fault tolerance, we could have several
103 migrations at once. For now we don't need to add
104 dynamic creation of migration */
105
e5cb7e76
PX
106static MigrationState *current_migration;
107
8b0b29dc 108static bool migration_object_check(MigrationState *ms, Error **errp);
0331c8ca
DDAG
109static int migration_maybe_pause(MigrationState *s,
110 int *current_active_state,
111 int new_state);
8b0b29dc 112
e5cb7e76
PX
113void migration_object_init(void)
114{
4ffdb337 115 MachineState *ms = MACHINE(qdev_get_machine());
8b0b29dc 116 Error *err = NULL;
4ffdb337 117
e5cb7e76
PX
118 /* This can only be called once. */
119 assert(!current_migration);
120 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
4ffdb337 121
8b0b29dc
PX
122 if (!migration_object_check(current_migration, &err)) {
123 error_report_err(err);
124 exit(1);
125 }
126
4ffdb337
PX
127 /*
128 * We cannot really do this in migration_instance_init() since at
129 * that time global properties are not yet applied, then this
130 * value will be definitely replaced by something else.
131 */
132 if (ms->enforce_config_section) {
133 current_migration->send_configuration = true;
134 }
e5cb7e76
PX
135}
136
1f895604
VSO
137void migration_object_finalize(void)
138{
139 object_unref(OBJECT(current_migration));
140}
141
bca7856a 142/* For outgoing */
859bc756 143MigrationState *migrate_get_current(void)
17549e84 144{
e5cb7e76
PX
145 /* This can only be called after the object created. */
146 assert(current_migration);
147 return current_migration;
17549e84
JQ
148}
149
bca7856a
DDAG
150MigrationIncomingState *migration_incoming_get_current(void)
151{
b4b076da
JQ
152 static bool once;
153 static MigrationIncomingState mis_current;
bca7856a 154
b4b076da
JQ
155 if (!once) {
156 mis_current.state = MIGRATION_STATUS_NONE;
157 memset(&mis_current, 0, sizeof(MigrationIncomingState));
00fa4fc8
DDAG
158 mis_current.postcopy_remote_fds = g_array_new(FALSE, TRUE,
159 sizeof(struct PostCopyFD));
b4b076da
JQ
160 qemu_mutex_init(&mis_current.rp_mutex);
161 qemu_event_init(&mis_current.main_thread_load_event, false);
162 once = true;
163 }
164 return &mis_current;
bca7856a
DDAG
165}
166
167void migration_incoming_state_destroy(void)
168{
b4b076da
JQ
169 struct MigrationIncomingState *mis = migration_incoming_get_current();
170
3482655b 171 if (mis->to_src_file) {
660819b1
PX
172 /* Tell source that we are done */
173 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
3482655b
PX
174 qemu_fclose(mis->to_src_file);
175 mis->to_src_file = NULL;
176 }
177
660819b1
PX
178 if (mis->from_src_file) {
179 qemu_fclose(mis->from_src_file);
180 mis->from_src_file = NULL;
181 }
00fa4fc8
DDAG
182 if (mis->postcopy_remote_fds) {
183 g_array_free(mis->postcopy_remote_fds, TRUE);
184 mis->postcopy_remote_fds = NULL;
185 }
660819b1 186
5089e186 187 qemu_event_reset(&mis->main_thread_load_event);
bca7856a
DDAG
188}
189
b05dc723
JQ
190static void migrate_generate_event(int new_state)
191{
192 if (migrate_use_events()) {
193 qapi_event_send_migration(new_state, &error_abort);
b05dc723
JQ
194 }
195}
196
adde220a
DDAG
197/*
198 * Called on -incoming with a defer: uri.
199 * The migration can be started later after any parameters have been
200 * changed.
201 */
202static void deferred_incoming_migration(Error **errp)
203{
204 if (deferred_incoming) {
205 error_setg(errp, "Incoming migration already deferred");
206 }
207 deferred_incoming = true;
208}
209
da6f1790
JQ
210/*
211 * Send a message on the return channel back to the source
212 * of the migration.
213 */
d6208e35
PX
214static int migrate_send_rp_message(MigrationIncomingState *mis,
215 enum mig_rp_message_type message_type,
216 uint16_t len, void *data)
da6f1790 217{
d6208e35
PX
218 int ret = 0;
219
da6f1790
JQ
220 trace_migrate_send_rp_message((int)message_type, len);
221 qemu_mutex_lock(&mis->rp_mutex);
d6208e35
PX
222
223 /*
224 * It's possible that the file handle got lost due to network
225 * failures.
226 */
227 if (!mis->to_src_file) {
228 ret = -EIO;
229 goto error;
230 }
231
da6f1790
JQ
232 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
233 qemu_put_be16(mis->to_src_file, len);
234 qemu_put_buffer(mis->to_src_file, data, len);
235 qemu_fflush(mis->to_src_file);
d6208e35
PX
236
237 /* It's possible that qemu file got error during sending */
238 ret = qemu_file_get_error(mis->to_src_file);
239
240error:
da6f1790 241 qemu_mutex_unlock(&mis->rp_mutex);
d6208e35 242 return ret;
da6f1790
JQ
243}
244
1e2d90eb
DDAG
245/* Request a range of pages from the source VM at the given
246 * start address.
247 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
248 * as the last request (a name must have been given previously)
249 * Start: Address offset within the RB
250 * Len: Length in bytes required - must be a multiple of pagesize
251 */
d6208e35
PX
252int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
253 ram_addr_t start, size_t len)
1e2d90eb 254{
cb8d4c8f 255 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
1e2d90eb 256 size_t msglen = 12; /* start + len */
d6208e35 257 enum mig_rp_message_type msg_type;
1e2d90eb
DDAG
258
259 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
260 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
261
262 if (rbname) {
263 int rbname_len = strlen(rbname);
264 assert(rbname_len < 256);
265
266 bufc[msglen++] = rbname_len;
267 memcpy(bufc + msglen, rbname, rbname_len);
268 msglen += rbname_len;
d6208e35 269 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
1e2d90eb 270 } else {
d6208e35 271 msg_type = MIG_RP_MSG_REQ_PAGES;
1e2d90eb 272 }
d6208e35
PX
273
274 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
1e2d90eb
DDAG
275}
276
43eaae28 277void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 278{
34c9dd8e
AL
279 const char *p;
280
7cf1fe6d 281 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
adde220a
DDAG
282 if (!strcmp(uri, "defer")) {
283 deferred_incoming_migration(errp);
284 } else if (strstart(uri, "tcp:", &p)) {
43eaae28 285 tcp_start_incoming_migration(p, errp);
2da776db 286#ifdef CONFIG_RDMA
adde220a 287 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
288 rdma_start_incoming_migration(p, errp);
289#endif
adde220a 290 } else if (strstart(uri, "exec:", &p)) {
43eaae28 291 exec_start_incoming_migration(p, errp);
adde220a 292 } else if (strstart(uri, "unix:", &p)) {
43eaae28 293 unix_start_incoming_migration(p, errp);
adde220a 294 } else if (strstart(uri, "fd:", &p)) {
43eaae28 295 fd_start_incoming_migration(p, errp);
adde220a 296 } else {
312fd5f2 297 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 298 }
5bb7910a
AL
299}
300
0aa6aefc
DL
301static void process_incoming_migration_bh(void *opaque)
302{
303 Error *local_err = NULL;
304 MigrationIncomingState *mis = opaque;
305
ace21a58
KW
306 /* Make sure all file formats flush their mutable metadata.
307 * If we get an error here, just don't restart the VM yet. */
0aa6aefc 308 bdrv_invalidate_cache_all(&local_err);
d35ff5e6 309 if (local_err) {
ace21a58 310 error_report_err(local_err);
d35ff5e6
KW
311 local_err = NULL;
312 autostart = false;
313 }
314
0aa6aefc
DL
315 /*
316 * This must happen after all error conditions are dealt with and
317 * we're sure the VM is going to be running on this host.
318 */
319 qemu_announce_self();
320
f986c3d2
JQ
321 if (multifd_load_cleanup(&local_err) != 0) {
322 error_report_err(local_err);
323 autostart = false;
324 }
0aa6aefc
DL
325 /* If global state section was not received or we are in running
326 state, we need to obey autostart. Any other state is set with
327 runstate_set. */
328
329 if (!global_state_received() ||
330 global_state_get_runstate() == RUN_STATE_RUNNING) {
331 if (autostart) {
332 vm_start();
333 } else {
334 runstate_set(RUN_STATE_PAUSED);
335 }
336 } else {
337 runstate_set(global_state_get_runstate());
338 }
0aa6aefc
DL
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_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
345 MIGRATION_STATUS_COMPLETED);
346 qemu_bh_delete(mis->bh);
347 migration_incoming_state_destroy();
348}
349
82a4da79 350static void process_incoming_migration_co(void *opaque)
511c0231 351{
b4b076da 352 MigrationIncomingState *mis = migration_incoming_get_current();
e9bef235 353 PostcopyState ps;
1c12e1f5
PB
354 int ret;
355
4f0fae7f 356 assert(mis->from_src_file);
67f11b5c 357 mis->largest_page_size = qemu_ram_pagesize_largest();
093e3c42 358 postcopy_state_set(POSTCOPY_INCOMING_NONE);
93d7af6f
HZ
359 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
360 MIGRATION_STATUS_ACTIVE);
4f0fae7f 361 ret = qemu_loadvm_state(mis->from_src_file);
bca7856a 362
e9bef235
DDAG
363 ps = postcopy_state_get();
364 trace_process_incoming_migration_co_end(ret, ps);
365 if (ps != POSTCOPY_INCOMING_NONE) {
366 if (ps == POSTCOPY_INCOMING_ADVISE) {
367 /*
368 * Where a migration had postcopy enabled (and thus went to advise)
369 * but managed to complete within the precopy period, we can use
370 * the normal exit.
371 */
372 postcopy_ram_incoming_cleanup(mis);
373 } else if (ret >= 0) {
374 /*
375 * Postcopy was started, cleanup should happen at the end of the
376 * postcopy thread.
377 */
378 trace_process_incoming_migration_co_postcopy_end_main();
379 return;
380 }
381 /* Else if something went wrong then just fall out of the normal exit */
382 }
383
25d0c16f
HZ
384 /* we get COLO info, and know if we are in COLO mode */
385 if (!ret && migration_incoming_enable_colo()) {
386 mis->migration_incoming_co = qemu_coroutine_self();
387 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
388 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
389 mis->have_colo_incoming_thread = true;
390 qemu_coroutine_yield();
391
392 /* Wait checkpoint incoming thread exit before free resource */
393 qemu_thread_join(&mis->colo_incoming_thread);
394 }
395
1c12e1f5 396 if (ret < 0) {
f986c3d2
JQ
397 Error *local_err = NULL;
398
93d7af6f
HZ
399 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
400 MIGRATION_STATUS_FAILED);
db80face 401 error_report("load of migration failed: %s", strerror(-ret));
3a0f2cea 402 qemu_fclose(mis->from_src_file);
f986c3d2
JQ
403 if (multifd_load_cleanup(&local_err) != 0) {
404 error_report_err(local_err);
405 }
4aead692 406 exit(EXIT_FAILURE);
511c0231 407 }
0aa6aefc
DL
408 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
409 qemu_bh_schedule(mis->bh);
511c0231
JQ
410}
411
e595a01a 412static void migration_incoming_setup(QEMUFile *f)
82a4da79 413{
4f0fae7f 414 MigrationIncomingState *mis = migration_incoming_get_current();
82a4da79 415
f986c3d2
JQ
416 if (multifd_load_setup() != 0) {
417 /* We haven't been able to create multifd threads
418 nothing better to do */
419 exit(EXIT_FAILURE);
420 }
421
4f0fae7f
JQ
422 if (!mis->from_src_file) {
423 mis->from_src_file = f;
424 }
06ad5135 425 qemu_file_set_blocking(f, false);
e595a01a
JQ
426}
427
428static void migration_incoming_process(void)
429{
430 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
0b8b8753 431 qemu_coroutine_enter(co);
82a4da79
PB
432}
433
e595a01a
JQ
434void migration_fd_process_incoming(QEMUFile *f)
435{
436 migration_incoming_setup(f);
437 migration_incoming_process();
438}
439
4f0fae7f
JQ
440void migration_ioc_process_incoming(QIOChannel *ioc)
441{
442 MigrationIncomingState *mis = migration_incoming_get_current();
443
444 if (!mis->from_src_file) {
445 QEMUFile *f = qemu_fopen_channel_input(ioc);
446 migration_fd_process_incoming(f);
447 }
448 /* We still only have a single channel. Nothing to do here yet */
449}
450
428d8908
JQ
451/**
452 * @migration_has_all_channels: We have received all channels that we need
453 *
454 * Returns true when we have got connections to all the channels that
455 * we need for migration.
456 */
457bool migration_has_all_channels(void)
458{
459 return true;
460}
461
6decec93
DDAG
462/*
463 * Send a 'SHUT' message on the return channel with the given value
464 * to indicate that we've finished with the RP. Non-0 value indicates
465 * error.
466 */
467void migrate_send_rp_shut(MigrationIncomingState *mis,
468 uint32_t value)
469{
470 uint32_t buf;
471
472 buf = cpu_to_be32(value);
473 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
474}
475
476/*
477 * Send a 'PONG' message on the return channel with the given value
478 * (normally in response to a 'PING')
479 */
480void migrate_send_rp_pong(MigrationIncomingState *mis,
481 uint32_t value)
482{
483 uint32_t buf;
484
485 buf = cpu_to_be32(value);
486 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
487}
488
bbf6da32
OW
489MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
490{
491 MigrationCapabilityStatusList *head = NULL;
492 MigrationCapabilityStatusList *caps;
493 MigrationState *s = migrate_get_current();
494 int i;
495
387eedeb 496 caps = NULL; /* silence compiler warning */
7fb1cf16 497 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
ed1701c6
DDAG
498#ifndef CONFIG_LIVE_BLOCK_MIGRATION
499 if (i == MIGRATION_CAPABILITY_BLOCK) {
500 continue;
501 }
502#endif
bbf6da32
OW
503 if (head == NULL) {
504 head = g_malloc0(sizeof(*caps));
505 caps = head;
506 } else {
507 caps->next = g_malloc0(sizeof(*caps));
508 caps = caps->next;
509 }
510 caps->value =
511 g_malloc(sizeof(*caps->value));
512 caps->value->capability = i;
513 caps->value->state = s->enabled_capabilities[i];
514 }
515
516 return head;
517}
518
85de8323
LL
519MigrationParameters *qmp_query_migrate_parameters(Error **errp)
520{
521 MigrationParameters *params;
522 MigrationState *s = migrate_get_current();
523
e87fae4c 524 /* TODO use QAPI_CLONE() instead of duplicating it inline */
85de8323 525 params = g_malloc0(sizeof(*params));
de63ab61 526 params->has_compress_level = true;
2594f56d 527 params->compress_level = s->parameters.compress_level;
de63ab61 528 params->has_compress_threads = true;
2594f56d 529 params->compress_threads = s->parameters.compress_threads;
de63ab61 530 params->has_decompress_threads = true;
2594f56d 531 params->decompress_threads = s->parameters.decompress_threads;
de63ab61 532 params->has_cpu_throttle_initial = true;
2594f56d 533 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
de63ab61 534 params->has_cpu_throttle_increment = true;
2594f56d 535 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
8cc99dcd 536 params->has_tls_creds = true;
69ef1f36 537 params->tls_creds = g_strdup(s->parameters.tls_creds);
8cc99dcd 538 params->has_tls_hostname = true;
69ef1f36 539 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
2ff30257
AA
540 params->has_max_bandwidth = true;
541 params->max_bandwidth = s->parameters.max_bandwidth;
542 params->has_downtime_limit = true;
543 params->downtime_limit = s->parameters.downtime_limit;
fe39a4d4 544 params->has_x_checkpoint_delay = true;
68b53591 545 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
2833c59b
JQ
546 params->has_block_incremental = true;
547 params->block_incremental = s->parameters.block_incremental;
4075fb1c
JQ
548 params->has_x_multifd_channels = true;
549 params->x_multifd_channels = s->parameters.x_multifd_channels;
0fb86605
JQ
550 params->has_x_multifd_page_count = true;
551 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
73af8dd8
JQ
552 params->has_xbzrle_cache_size = true;
553 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
85de8323
LL
554
555 return params;
556}
557
f6844b99
DDAG
558/*
559 * Return true if we're already in the middle of a migration
560 * (i.e. any of the active or setup states)
561 */
562static bool migration_is_setup_or_active(int state)
563{
564 switch (state) {
565 case MIGRATION_STATUS_ACTIVE:
9ec055ae 566 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
f6844b99 567 case MIGRATION_STATUS_SETUP:
31e06077
DDAG
568 case MIGRATION_STATUS_PRE_SWITCHOVER:
569 case MIGRATION_STATUS_DEVICE:
f6844b99
DDAG
570 return true;
571
572 default:
573 return false;
574
575 }
576}
577
a22463a5
DDAG
578static void populate_ram_info(MigrationInfo *info, MigrationState *s)
579{
580 info->has_ram = true;
581 info->ram = g_malloc0(sizeof(*info->ram));
9360447d 582 info->ram->transferred = ram_counters.transferred;
a22463a5 583 info->ram->total = ram_bytes_total();
9360447d 584 info->ram->duplicate = ram_counters.duplicate;
bedf53c1
JQ
585 /* legacy value. It is not used anymore */
586 info->ram->skipped = 0;
9360447d
JQ
587 info->ram->normal = ram_counters.normal;
588 info->ram->normal_bytes = ram_counters.normal *
20afaed9 589 qemu_target_page_size();
a22463a5 590 info->ram->mbps = s->mbps;
9360447d
JQ
591 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
592 info->ram->postcopy_requests = ram_counters.postcopy_requests;
030ce1f8 593 info->ram->page_size = qemu_target_page_size();
a22463a5 594
114f5aee
JQ
595 if (migrate_use_xbzrle()) {
596 info->has_xbzrle_cache = true;
597 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
598 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
9360447d
JQ
599 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
600 info->xbzrle_cache->pages = xbzrle_counters.pages;
601 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
602 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
603 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
114f5aee
JQ
604 }
605
338182c8
JQ
606 if (cpu_throttle_active()) {
607 info->has_cpu_throttle_percentage = true;
608 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
609 }
610
a22463a5
DDAG
611 if (s->state != MIGRATION_STATUS_COMPLETED) {
612 info->ram->remaining = ram_bytes_remaining();
9360447d 613 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
a22463a5
DDAG
614 }
615}
616
930ac04c
JQ
617static void populate_disk_info(MigrationInfo *info)
618{
619 if (blk_mig_active()) {
620 info->has_disk = true;
621 info->disk = g_malloc0(sizeof(*info->disk));
622 info->disk->transferred = blk_mig_bytes_transferred();
623 info->disk->remaining = blk_mig_bytes_remaining();
624 info->disk->total = blk_mig_bytes_total();
625 }
626}
627
ee86981b 628MigrationInfo *qmp_query_migrate(Error **errp)
5bb7910a 629{
ee86981b 630 MigrationInfo *info = g_malloc0(sizeof(*info));
17549e84
JQ
631 MigrationState *s = migrate_get_current();
632
633 switch (s->state) {
31194731 634 case MIGRATION_STATUS_NONE:
17549e84
JQ
635 /* no migration has happened ever */
636 break;
31194731 637 case MIGRATION_STATUS_SETUP:
29ae8a41 638 info->has_status = true;
ed4fbd10 639 info->has_total_time = false;
29ae8a41 640 break;
31194731
HZ
641 case MIGRATION_STATUS_ACTIVE:
642 case MIGRATION_STATUS_CANCELLING:
9ec055ae 643 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
31e06077
DDAG
644 case MIGRATION_STATUS_PRE_SWITCHOVER:
645 case MIGRATION_STATUS_DEVICE:
c8f9f4f4 646 /* TODO add some postcopy stats */
9ec055ae
DDAG
647 info->has_status = true;
648 info->has_total_time = true;
649 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
4af246a3 650 - s->start_time;
9ec055ae
DDAG
651 info->has_expected_downtime = true;
652 info->expected_downtime = s->expected_downtime;
653 info->has_setup_time = true;
654 info->setup_time = s->setup_time;
655
a22463a5 656 populate_ram_info(info, s);
930ac04c 657 populate_disk_info(info);
17549e84 658 break;
0b827d5e
HZ
659 case MIGRATION_STATUS_COLO:
660 info->has_status = true;
661 /* TODO: display COLO specific information (checkpoint info etc.) */
662 break;
31194731 663 case MIGRATION_STATUS_COMPLETED:
791e7c82 664 info->has_status = true;
00c14997 665 info->has_total_time = true;
7aa939af 666 info->total_time = s->total_time;
9c5a9fcf
JQ
667 info->has_downtime = true;
668 info->downtime = s->downtime;
ed4fbd10
MH
669 info->has_setup_time = true;
670 info->setup_time = s->setup_time;
d5f8a570 671
a22463a5 672 populate_ram_info(info, s);
17549e84 673 break;
31194731 674 case MIGRATION_STATUS_FAILED:
791e7c82 675 info->has_status = true;
d59ce6f3
DB
676 if (s->error) {
677 info->has_error_desc = true;
678 info->error_desc = g_strdup(error_get_pretty(s->error));
679 }
17549e84 680 break;
31194731 681 case MIGRATION_STATUS_CANCELLED:
791e7c82 682 info->has_status = true;
17549e84 683 break;
5bb7910a 684 }
cde63fbe 685 info->status = s->state;
ee86981b
PM
686
687 return info;
5bb7910a
AL
688}
689
4a84214e
PX
690/**
691 * @migration_caps_check - check capability validity
692 *
693 * @cap_list: old capability list, array of bool
694 * @params: new capabilities to be applied soon
695 * @errp: set *errp if the check failed, with reason
696 *
697 * Returns true if check passed, otherwise false.
698 */
699static bool migrate_caps_check(bool *cap_list,
700 MigrationCapabilityStatusList *params,
701 Error **errp)
00458433 702{
00458433 703 MigrationCapabilityStatusList *cap;
4a84214e 704 bool old_postcopy_cap;
d7651f15 705 MigrationIncomingState *mis = migration_incoming_get_current();
00458433 706
4a84214e 707 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
00458433
OW
708
709 for (cap = params; cap; cap = cap->next) {
4a84214e
PX
710 cap_list[cap->value->capability] = cap->value->state;
711 }
712
ed1701c6 713#ifndef CONFIG_LIVE_BLOCK_MIGRATION
4a84214e
PX
714 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
715 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
716 "block migration");
717 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
718 return false;
00458433 719 }
4a84214e 720#endif
53dd370c 721
4a84214e
PX
722 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
723 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
53dd370c
DDAG
724 /* The decompression threads asynchronously write into RAM
725 * rather than use the atomic copies needed to avoid
726 * userfaulting. It should be possible to fix the decompression
727 * threads for compatibility in future.
728 */
4a84214e
PX
729 error_setg(errp, "Postcopy is not currently compatible "
730 "with compression");
731 return false;
53dd370c 732 }
4a84214e 733
096631bd
DDAG
734 /* This check is reasonably expensive, so only when it's being
735 * set the first time, also it's only the destination that needs
736 * special support.
737 */
738 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
d7651f15 739 !postcopy_ram_supported_by_host(mis)) {
096631bd
DDAG
740 /* postcopy_ram_supported_by_host will have emitted a more
741 * detailed message
742 */
4a84214e
PX
743 error_setg(errp, "Postcopy is not supported");
744 return false;
096631bd 745 }
53dd370c 746 }
4a84214e
PX
747
748 return true;
749}
750
751void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
752 Error **errp)
753{
754 MigrationState *s = migrate_get_current();
755 MigrationCapabilityStatusList *cap;
dd0ee30c 756 bool cap_list[MIGRATION_CAPABILITY__MAX];
4a84214e
PX
757
758 if (migration_is_setup_or_active(s->state)) {
759 error_setg(errp, QERR_MIGRATION_ACTIVE);
760 return;
761 }
762
dd0ee30c
PX
763 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
764 if (!migrate_caps_check(cap_list, params, errp)) {
4a84214e
PX
765 return;
766 }
767
768 for (cap = params; cap; cap = cap->next) {
769 s->enabled_capabilities[cap->value->capability] = cap->value->state;
770 }
00458433
OW
771}
772
16d063bc
PX
773/*
774 * Check whether the parameters are valid. Error will be put into errp
775 * (if provided). Return true if valid, otherwise false.
776 */
777static bool migrate_params_check(MigrationParameters *params, Error **errp)
85de8323 778{
7f375e04 779 if (params->has_compress_level &&
741d4086 780 (params->compress_level > 9)) {
c6bd8c70
MA
781 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
782 "is invalid, it should be in the range of 0 to 9");
16d063bc 783 return false;
85de8323 784 }
16d063bc 785
741d4086 786 if (params->has_compress_threads && (params->compress_threads < 1)) {
c6bd8c70
MA
787 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
788 "compress_threads",
789 "is invalid, it should be in the range of 1 to 255");
16d063bc 790 return false;
85de8323 791 }
16d063bc 792
741d4086 793 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
c6bd8c70
MA
794 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
795 "decompress_threads",
796 "is invalid, it should be in the range of 1 to 255");
16d063bc 797 return false;
85de8323 798 }
16d063bc 799
7f375e04
EB
800 if (params->has_cpu_throttle_initial &&
801 (params->cpu_throttle_initial < 1 ||
802 params->cpu_throttle_initial > 99)) {
1626fee3 803 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 804 "cpu_throttle_initial",
1626fee3 805 "an integer in the range of 1 to 99");
16d063bc 806 return false;
1626fee3 807 }
16d063bc 808
7f375e04
EB
809 if (params->has_cpu_throttle_increment &&
810 (params->cpu_throttle_increment < 1 ||
811 params->cpu_throttle_increment > 99)) {
1626fee3 812 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 813 "cpu_throttle_increment",
1626fee3 814 "an integer in the range of 1 to 99");
16d063bc 815 return false;
1626fee3 816 }
16d063bc 817
741d4086 818 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
2ff30257
AA
819 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
820 " range of 0 to %zu bytes/second", SIZE_MAX);
16d063bc 821 return false;
2ff30257 822 }
16d063bc 823
2ff30257 824 if (params->has_downtime_limit &&
741d4086 825 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
87c9cc1c
DHB
826 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
827 "the range of 0 to %d milliseconds",
828 MAX_MIGRATE_DOWNTIME);
16d063bc 829 return false;
2ff30257 830 }
16d063bc 831
741d4086
JQ
832 /* x_checkpoint_delay is now always positive */
833
834 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
4075fb1c
JQ
835 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
836 "multifd_channels",
837 "is invalid, it should be in the range of 1 to 255");
838 return false;
839 }
0fb86605 840 if (params->has_x_multifd_page_count &&
741d4086
JQ
841 (params->x_multifd_page_count < 1 ||
842 params->x_multifd_page_count > 10000)) {
0fb86605
JQ
843 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
844 "multifd_page_count",
845 "is invalid, it should be in the range of 1 to 10000");
846 return false;
847 }
16d063bc 848
73af8dd8
JQ
849 if (params->has_xbzrle_cache_size &&
850 (params->xbzrle_cache_size < qemu_target_page_size() ||
851 !is_power_of_2(params->xbzrle_cache_size))) {
852 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
853 "xbzrle_cache_size",
854 "is invalid, it should be bigger than target page size"
855 " and a power of two");
856 return false;
857 }
858
16d063bc
PX
859 return true;
860}
861
1bda8b3c
MA
862static void migrate_params_test_apply(MigrateSetParameters *params,
863 MigrationParameters *dest)
864{
865 *dest = migrate_get_current()->parameters;
866
867 /* TODO use QAPI_CLONE() instead of duplicating it inline */
868
869 if (params->has_compress_level) {
870 dest->compress_level = params->compress_level;
871 }
872
873 if (params->has_compress_threads) {
874 dest->compress_threads = params->compress_threads;
875 }
876
877 if (params->has_decompress_threads) {
878 dest->decompress_threads = params->decompress_threads;
879 }
880
881 if (params->has_cpu_throttle_initial) {
882 dest->cpu_throttle_initial = params->cpu_throttle_initial;
883 }
884
885 if (params->has_cpu_throttle_increment) {
886 dest->cpu_throttle_increment = params->cpu_throttle_increment;
887 }
888
889 if (params->has_tls_creds) {
01fa5598
MA
890 assert(params->tls_creds->type == QTYPE_QSTRING);
891 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1bda8b3c
MA
892 }
893
894 if (params->has_tls_hostname) {
01fa5598
MA
895 assert(params->tls_hostname->type == QTYPE_QSTRING);
896 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1bda8b3c
MA
897 }
898
899 if (params->has_max_bandwidth) {
900 dest->max_bandwidth = params->max_bandwidth;
901 }
902
903 if (params->has_downtime_limit) {
904 dest->downtime_limit = params->downtime_limit;
905 }
906
907 if (params->has_x_checkpoint_delay) {
908 dest->x_checkpoint_delay = params->x_checkpoint_delay;
909 }
910
911 if (params->has_block_incremental) {
912 dest->block_incremental = params->block_incremental;
913 }
5e7577a1
JQ
914 if (params->has_x_multifd_channels) {
915 dest->x_multifd_channels = params->x_multifd_channels;
916 }
917 if (params->has_x_multifd_page_count) {
918 dest->x_multifd_page_count = params->x_multifd_page_count;
919 }
73af8dd8
JQ
920 if (params->has_xbzrle_cache_size) {
921 dest->xbzrle_cache_size = params->xbzrle_cache_size;
922 }
1bda8b3c
MA
923}
924
73af8dd8 925static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
16d063bc
PX
926{
927 MigrationState *s = migrate_get_current();
928
e87fae4c
MA
929 /* TODO use QAPI_CLONE() instead of duplicating it inline */
930
7f375e04
EB
931 if (params->has_compress_level) {
932 s->parameters.compress_level = params->compress_level;
85de8323 933 }
476c72aa 934
7f375e04
EB
935 if (params->has_compress_threads) {
936 s->parameters.compress_threads = params->compress_threads;
85de8323 937 }
476c72aa 938
7f375e04
EB
939 if (params->has_decompress_threads) {
940 s->parameters.decompress_threads = params->decompress_threads;
85de8323 941 }
476c72aa 942
7f375e04
EB
943 if (params->has_cpu_throttle_initial) {
944 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1626fee3 945 }
476c72aa 946
7f375e04
EB
947 if (params->has_cpu_throttle_increment) {
948 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1626fee3 949 }
476c72aa 950
7f375e04 951 if (params->has_tls_creds) {
69ef1f36 952 g_free(s->parameters.tls_creds);
01fa5598
MA
953 assert(params->tls_creds->type == QTYPE_QSTRING);
954 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
69ef1f36 955 }
476c72aa 956
7f375e04 957 if (params->has_tls_hostname) {
69ef1f36 958 g_free(s->parameters.tls_hostname);
01fa5598
MA
959 assert(params->tls_hostname->type == QTYPE_QSTRING);
960 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
69ef1f36 961 }
476c72aa 962
2ff30257
AA
963 if (params->has_max_bandwidth) {
964 s->parameters.max_bandwidth = params->max_bandwidth;
965 if (s->to_dst_file) {
966 qemu_file_set_rate_limit(s->to_dst_file,
967 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
968 }
969 }
476c72aa 970
2ff30257
AA
971 if (params->has_downtime_limit) {
972 s->parameters.downtime_limit = params->downtime_limit;
973 }
68b53591
HZ
974
975 if (params->has_x_checkpoint_delay) {
976 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
479125d5
HZ
977 if (migration_in_colo_state()) {
978 colo_checkpoint_notify(s);
979 }
68b53591 980 }
476c72aa 981
2833c59b
JQ
982 if (params->has_block_incremental) {
983 s->parameters.block_incremental = params->block_incremental;
984 }
4075fb1c
JQ
985 if (params->has_x_multifd_channels) {
986 s->parameters.x_multifd_channels = params->x_multifd_channels;
987 }
0fb86605
JQ
988 if (params->has_x_multifd_page_count) {
989 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
990 }
73af8dd8
JQ
991 if (params->has_xbzrle_cache_size) {
992 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
993 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
994 }
85de8323
LL
995}
996
1bda8b3c 997void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
476c72aa 998{
1bda8b3c
MA
999 MigrationParameters tmp;
1000
01fa5598
MA
1001 /* TODO Rewrite "" to null instead */
1002 if (params->has_tls_creds
1003 && params->tls_creds->type == QTYPE_QNULL) {
1004 QDECREF(params->tls_creds->u.n);
1005 params->tls_creds->type = QTYPE_QSTRING;
1006 params->tls_creds->u.s = strdup("");
1007 }
1008 /* TODO Rewrite "" to null instead */
1009 if (params->has_tls_hostname
1010 && params->tls_hostname->type == QTYPE_QNULL) {
1011 QDECREF(params->tls_hostname->u.n);
1012 params->tls_hostname->type = QTYPE_QSTRING;
1013 params->tls_hostname->u.s = strdup("");
1014 }
1015
1bda8b3c
MA
1016 migrate_params_test_apply(params, &tmp);
1017
1018 if (!migrate_params_check(&tmp, errp)) {
476c72aa
PX
1019 /* Invalid parameter */
1020 return;
1021 }
1022
73af8dd8 1023 migrate_params_apply(params, errp);
476c72aa
PX
1024}
1025
2594f56d 1026
4886a1bc
DDAG
1027void qmp_migrate_start_postcopy(Error **errp)
1028{
1029 MigrationState *s = migrate_get_current();
1030
1031 if (!migrate_postcopy_ram()) {
a54d340b 1032 error_setg(errp, "Enable postcopy with migrate_set_capability before"
4886a1bc
DDAG
1033 " the start of migration");
1034 return;
1035 }
1036
1037 if (s->state == MIGRATION_STATUS_NONE) {
1038 error_setg(errp, "Postcopy must be started after migration has been"
1039 " started");
1040 return;
1041 }
1042 /*
1043 * we don't error if migration has finished since that would be racy
1044 * with issuing this command.
1045 */
1046 atomic_set(&s->start_postcopy, true);
1047}
1048
065e2813
AL
1049/* shared migration helpers */
1050
48781e5b 1051void migrate_set_state(int *state, int old_state, int new_state)
51cf4c1a 1052{
a31fedee 1053 assert(new_state < MIGRATION_STATUS__MAX);
48781e5b 1054 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
a31fedee 1055 trace_migrate_set_state(MigrationStatus_str(new_state));
b05dc723 1056 migrate_generate_event(new_state);
51cf4c1a
Z
1057 }
1058}
1059
4e4a3d3a
PX
1060static MigrationCapabilityStatusList *migrate_cap_add(
1061 MigrationCapabilityStatusList *list,
1062 MigrationCapability index,
1063 bool state)
2833c59b
JQ
1064{
1065 MigrationCapabilityStatusList *cap;
1066
1067 cap = g_new0(MigrationCapabilityStatusList, 1);
1068 cap->value = g_new0(MigrationCapabilityStatus, 1);
4e4a3d3a
PX
1069 cap->value->capability = index;
1070 cap->value->state = state;
1071 cap->next = list;
1072
1073 return cap;
1074}
1075
1076void migrate_set_block_enabled(bool value, Error **errp)
1077{
1078 MigrationCapabilityStatusList *cap;
1079
1080 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
2833c59b
JQ
1081 qmp_migrate_set_capabilities(cap, errp);
1082 qapi_free_MigrationCapabilityStatusList(cap);
1083}
1084
1085static void migrate_set_block_incremental(MigrationState *s, bool value)
1086{
1087 s->parameters.block_incremental = value;
1088}
1089
1090static void block_cleanup_parameters(MigrationState *s)
1091{
1092 if (s->must_remove_block_options) {
1093 /* setting to false can never fail */
1094 migrate_set_block_enabled(false, &error_abort);
1095 migrate_set_block_incremental(s, false);
1096 s->must_remove_block_options = false;
1097 }
1098}
1099
bb1fadc4 1100static void migrate_fd_cleanup(void *opaque)
065e2813 1101{
bb1fadc4
PB
1102 MigrationState *s = opaque;
1103
1104 qemu_bh_delete(s->cleanup_bh);
1105 s->cleanup_bh = NULL;
1106
0ceccd85
PX
1107 qemu_savevm_state_cleanup();
1108
89a02a9f 1109 if (s->to_dst_file) {
f986c3d2
JQ
1110 Error *local_err = NULL;
1111
9013dca5 1112 trace_migrate_fd_cleanup();
404a7c05 1113 qemu_mutex_unlock_iothread();
1d34e4bf
DDAG
1114 if (s->migration_thread_running) {
1115 qemu_thread_join(&s->thread);
1116 s->migration_thread_running = false;
1117 }
404a7c05
PB
1118 qemu_mutex_lock_iothread();
1119
f986c3d2
JQ
1120 if (multifd_save_cleanup(&local_err) != 0) {
1121 error_report_err(local_err);
1122 }
89a02a9f
HZ
1123 qemu_fclose(s->to_dst_file);
1124 s->to_dst_file = NULL;
065e2813
AL
1125 }
1126
9ec055ae
DDAG
1127 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1128 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
7a2c1721 1129
94f5a437 1130 if (s->state == MIGRATION_STATUS_CANCELLING) {
48781e5b 1131 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
94f5a437 1132 MIGRATION_STATUS_CANCELLED);
7a2c1721 1133 }
a3fa1d78 1134
87db1a7d
JQ
1135 if (s->error) {
1136 /* It is used on info migrate. We can't free it */
1137 error_report_err(error_copy(s->error));
1138 }
a3fa1d78 1139 notifier_list_notify(&migration_state_notifiers, s);
2833c59b 1140 block_cleanup_parameters(s);
065e2813
AL
1141}
1142
87db1a7d
JQ
1143void migrate_set_error(MigrationState *s, const Error *error)
1144{
1145 qemu_mutex_lock(&s->error_mutex);
1146 if (!s->error) {
1147 s->error = error_copy(error);
1148 }
1149 qemu_mutex_unlock(&s->error_mutex);
1150}
1151
d59ce6f3 1152void migrate_fd_error(MigrationState *s, const Error *error)
065e2813 1153{
25174055 1154 trace_migrate_fd_error(error_get_pretty(error));
89a02a9f 1155 assert(s->to_dst_file == NULL);
48781e5b
HZ
1156 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1157 MIGRATION_STATUS_FAILED);
87db1a7d 1158 migrate_set_error(s, error);
458cf28e
JQ
1159}
1160
0edda1c4 1161static void migrate_fd_cancel(MigrationState *s)
065e2813 1162{
6f2b811a 1163 int old_state ;
89a02a9f 1164 QEMUFile *f = migrate_get_current()->to_dst_file;
9013dca5 1165 trace_migrate_fd_cancel();
065e2813 1166
70b20477
DDAG
1167 if (s->rp_state.from_dst_file) {
1168 /* shutdown the rp socket, so causing the rp thread to shutdown */
1169 qemu_file_shutdown(s->rp_state.from_dst_file);
1170 }
1171
6f2b811a
Z
1172 do {
1173 old_state = s->state;
f6844b99 1174 if (!migration_is_setup_or_active(old_state)) {
6f2b811a
Z
1175 break;
1176 }
a7b36b48
DDAG
1177 /* If the migration is paused, kick it out of the pause */
1178 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1179 qemu_sem_post(&s->pause_sem);
1180 }
48781e5b 1181 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
31194731 1182 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
1183
1184 /*
1185 * If we're unlucky the migration code might be stuck somewhere in a
1186 * send/write while the network has failed and is waiting to timeout;
1187 * if we've got shutdown(2) available then we can force it to quit.
1188 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1189 * called in a bh, so there is no race against this cancel.
1190 */
31194731 1191 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
a26ba26e
DDAG
1192 qemu_file_shutdown(f);
1193 }
1d2acc31
HZ
1194 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1195 Error *local_err = NULL;
1196
1197 bdrv_invalidate_cache_all(&local_err);
1198 if (local_err) {
1199 error_report_err(local_err);
1200 } else {
1201 s->block_inactive = false;
1202 }
1203 }
065e2813
AL
1204}
1205
99a0db9b
GH
1206void add_migration_state_change_notifier(Notifier *notify)
1207{
1208 notifier_list_add(&migration_state_notifiers, notify);
1209}
1210
1211void remove_migration_state_change_notifier(Notifier *notify)
1212{
31552529 1213 notifier_remove(notify);
99a0db9b
GH
1214}
1215
02edd2e7 1216bool migration_in_setup(MigrationState *s)
afe2df69 1217{
31194731 1218 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
1219}
1220
7073693b 1221bool migration_has_finished(MigrationState *s)
99a0db9b 1222{
31194731 1223 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 1224}
0edda1c4 1225
afe2df69
GH
1226bool migration_has_failed(MigrationState *s)
1227{
31194731
HZ
1228 return (s->state == MIGRATION_STATUS_CANCELLED ||
1229 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
1230}
1231
5727309d 1232bool migration_in_postcopy(void)
9ec055ae 1233{
5727309d
JQ
1234 MigrationState *s = migrate_get_current();
1235
9ec055ae
DDAG
1236 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1237}
1238
b82fc321
DDAG
1239bool migration_in_postcopy_after_devices(MigrationState *s)
1240{
5727309d 1241 return migration_in_postcopy() && s->postcopy_after_devices;
b82fc321
DDAG
1242}
1243
fab35005 1244bool migration_is_idle(void)
fe44dc91 1245{
fab35005 1246 MigrationState *s = migrate_get_current();
fe44dc91
AA
1247
1248 switch (s->state) {
1249 case MIGRATION_STATUS_NONE:
1250 case MIGRATION_STATUS_CANCELLED:
1251 case MIGRATION_STATUS_COMPLETED:
1252 case MIGRATION_STATUS_FAILED:
1253 return true;
1254 case MIGRATION_STATUS_SETUP:
1255 case MIGRATION_STATUS_CANCELLING:
1256 case MIGRATION_STATUS_ACTIVE:
1257 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1258 case MIGRATION_STATUS_COLO:
31e06077
DDAG
1259 case MIGRATION_STATUS_PRE_SWITCHOVER:
1260 case MIGRATION_STATUS_DEVICE:
fe44dc91
AA
1261 return false;
1262 case MIGRATION_STATUS__MAX:
1263 g_assert_not_reached();
1264 }
1265
1266 return false;
1267}
1268
3e0c8050 1269void migrate_init(MigrationState *s)
0edda1c4 1270{
389775d1
DDAG
1271 /*
1272 * Reinitialise all migration state, except
1273 * parameters/capabilities that the user set, and
1274 * locks.
1275 */
1276 s->bytes_xfer = 0;
1277 s->xfer_limit = 0;
1278 s->cleanup_bh = 0;
89a02a9f 1279 s->to_dst_file = NULL;
389775d1 1280 s->state = MIGRATION_STATUS_NONE;
389775d1
DDAG
1281 s->rp_state.from_dst_file = NULL;
1282 s->rp_state.error = false;
1283 s->mbps = 0.0;
1284 s->downtime = 0;
1285 s->expected_downtime = 0;
389775d1 1286 s->setup_time = 0;
389775d1 1287 s->start_postcopy = false;
b82fc321 1288 s->postcopy_after_devices = false;
389775d1 1289 s->migration_thread_running = false;
d59ce6f3
DB
1290 error_free(s->error);
1291 s->error = NULL;
389775d1 1292
48781e5b 1293 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 1294
4af246a3
PX
1295 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1296 s->total_time = 0;
7287cbd4 1297 s->vm_was_running = false;
b15df1ae
PX
1298 s->iteration_initial_bytes = 0;
1299 s->threshold_size = 0;
0edda1c4 1300}
cab30143 1301
fa2756b7
AL
1302static GSList *migration_blockers;
1303
fe44dc91 1304int migrate_add_blocker(Error *reason, Error **errp)
fa2756b7 1305{
3df663e5 1306 if (migrate_get_current()->only_migratable) {
b67b8c3a
AA
1307 error_propagate(errp, error_copy(reason));
1308 error_prepend(errp, "disallowing migration blocker "
1309 "(--only_migratable) for: ");
1310 return -EACCES;
1311 }
1312
fab35005 1313 if (migration_is_idle()) {
fe44dc91
AA
1314 migration_blockers = g_slist_prepend(migration_blockers, reason);
1315 return 0;
1316 }
1317
1318 error_propagate(errp, error_copy(reason));
1319 error_prepend(errp, "disallowing migration blocker (migration in "
1320 "progress) for: ");
1321 return -EBUSY;
fa2756b7
AL
1322}
1323
1324void migrate_del_blocker(Error *reason)
1325{
1326 migration_blockers = g_slist_remove(migration_blockers, reason);
1327}
1328
bf1ae1f4
DDAG
1329void qmp_migrate_incoming(const char *uri, Error **errp)
1330{
1331 Error *local_err = NULL;
4debb5f5 1332 static bool once = true;
bf1ae1f4
DDAG
1333
1334 if (!deferred_incoming) {
4debb5f5 1335 error_setg(errp, "For use with '-incoming defer'");
bf1ae1f4
DDAG
1336 return;
1337 }
4debb5f5
DDAG
1338 if (!once) {
1339 error_setg(errp, "The incoming migration has already been started");
1340 }
bf1ae1f4
DDAG
1341
1342 qemu_start_incoming_migration(uri, &local_err);
1343
1344 if (local_err) {
1345 error_propagate(errp, local_err);
1346 return;
1347 }
1348
4debb5f5 1349 once = false;
bf1ae1f4
DDAG
1350}
1351
24f3902b
GK
1352bool migration_is_blocked(Error **errp)
1353{
1354 if (qemu_savevm_state_blocked(errp)) {
1355 return true;
1356 }
1357
1358 if (migration_blockers) {
250561e1 1359 error_propagate(errp, error_copy(migration_blockers->data));
24f3902b
GK
1360 return true;
1361 }
1362
1363 return false;
1364}
1365
e1c37d0e
LC
1366void qmp_migrate(const char *uri, bool has_blk, bool blk,
1367 bool has_inc, bool inc, bool has_detach, bool detach,
1368 Error **errp)
cab30143 1369{
be7059cd 1370 Error *local_err = NULL;
17549e84 1371 MigrationState *s = migrate_get_current();
cab30143 1372 const char *p;
cab30143 1373
f6844b99 1374 if (migration_is_setup_or_active(s->state) ||
0b827d5e
HZ
1375 s->state == MIGRATION_STATUS_CANCELLING ||
1376 s->state == MIGRATION_STATUS_COLO) {
c6bd8c70 1377 error_setg(errp, QERR_MIGRATION_ACTIVE);
e1c37d0e 1378 return;
cab30143 1379 }
ca99993a
DDAG
1380 if (runstate_check(RUN_STATE_INMIGRATE)) {
1381 error_setg(errp, "Guest is waiting for an incoming migration");
1382 return;
1383 }
1384
24f3902b 1385 if (migration_is_blocked(errp)) {
e1c37d0e 1386 return;
fa2756b7
AL
1387 }
1388
2833c59b
JQ
1389 if ((has_blk && blk) || (has_inc && inc)) {
1390 if (migrate_use_block() || migrate_use_block_incremental()) {
1391 error_setg(errp, "Command options are incompatible with "
1392 "current migration capabilities");
1393 return;
1394 }
1395 migrate_set_block_enabled(true, &local_err);
1396 if (local_err) {
1397 error_propagate(errp, local_err);
1398 return;
1399 }
1400 s->must_remove_block_options = true;
1401 }
1402
1403 if (has_inc && inc) {
1404 migrate_set_block_incremental(s, true);
1405 }
1406
3e0c8050 1407 migrate_init(s);
cab30143
JQ
1408
1409 if (strstart(uri, "tcp:", &p)) {
f37afb5a 1410 tcp_start_outgoing_migration(s, p, &local_err);
2da776db 1411#ifdef CONFIG_RDMA
41310c68 1412 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
1413 rdma_start_outgoing_migration(s, p, &local_err);
1414#endif
cab30143 1415 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 1416 exec_start_outgoing_migration(s, p, &local_err);
cab30143 1417 } else if (strstart(uri, "unix:", &p)) {
f37afb5a 1418 unix_start_outgoing_migration(s, p, &local_err);
cab30143 1419 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 1420 fd_start_outgoing_migration(s, p, &local_err);
99a0db9b 1421 } else {
c6bd8c70
MA
1422 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1423 "a valid migration protocol");
48781e5b
HZ
1424 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1425 MIGRATION_STATUS_FAILED);
e1c37d0e 1426 return;
cab30143
JQ
1427 }
1428
f37afb5a 1429 if (local_err) {
d59ce6f3 1430 migrate_fd_error(s, local_err);
f37afb5a 1431 error_propagate(errp, local_err);
e1c37d0e 1432 return;
1299c631 1433 }
cab30143
JQ
1434}
1435
6cdedb07 1436void qmp_migrate_cancel(Error **errp)
cab30143 1437{
17549e84 1438 migrate_fd_cancel(migrate_get_current());
cab30143
JQ
1439}
1440
89cfc02c
DDAG
1441void qmp_migrate_continue(MigrationStatus state, Error **errp)
1442{
1443 MigrationState *s = migrate_get_current();
1444 if (s->state != state) {
1445 error_setg(errp, "Migration not in expected state: %s",
1446 MigrationStatus_str(s->state));
1447 return;
1448 }
1449 qemu_sem_post(&s->pause_sem);
1450}
1451
9e1ba4cc
OW
1452void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1453{
73af8dd8
JQ
1454 MigrateSetParameters p = {
1455 .has_xbzrle_cache_size = true,
1456 .xbzrle_cache_size = value,
1457 };
c91e681a 1458
73af8dd8 1459 qmp_migrate_set_parameters(&p, errp);
9e1ba4cc
OW
1460}
1461
1462int64_t qmp_query_migrate_cache_size(Error **errp)
1463{
1464 return migrate_xbzrle_cache_size();
1465}
1466
3dc85383 1467void qmp_migrate_set_speed(int64_t value, Error **errp)
cab30143 1468{
1bda8b3c 1469 MigrateSetParameters p = {
2ff30257
AA
1470 .has_max_bandwidth = true,
1471 .max_bandwidth = value,
1472 };
cab30143 1473
2ff30257 1474 qmp_migrate_set_parameters(&p, errp);
cab30143
JQ
1475}
1476
4f0a993b 1477void qmp_migrate_set_downtime(double value, Error **errp)
cab30143 1478{
87c9cc1c
DHB
1479 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1480 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1481 "the range of 0 to %d seconds",
1482 MAX_MIGRATE_DOWNTIME_SECONDS);
1483 return;
1484 }
1485
2ff30257
AA
1486 value *= 1000; /* Convert to milliseconds */
1487 value = MAX(0, MIN(INT64_MAX, value));
1488
1bda8b3c 1489 MigrateSetParameters p = {
2ff30257
AA
1490 .has_downtime_limit = true,
1491 .downtime_limit = value,
1492 };
1493
1494 qmp_migrate_set_parameters(&p, errp);
99a0db9b 1495}
17ad9b35 1496
53f09a10
PB
1497bool migrate_release_ram(void)
1498{
1499 MigrationState *s;
1500
1501 s = migrate_get_current();
1502
1503 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1504}
1505
53dd370c
DDAG
1506bool migrate_postcopy_ram(void)
1507{
1508 MigrationState *s;
1509
1510 s = migrate_get_current();
1511
32c3db5b 1512 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
53dd370c
DDAG
1513}
1514
58110f0a
VSO
1515bool migrate_postcopy(void)
1516{
1517 return migrate_postcopy_ram();
1518}
1519
bde1e2ec
CV
1520bool migrate_auto_converge(void)
1521{
1522 MigrationState *s;
1523
1524 s = migrate_get_current();
1525
1526 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1527}
1528
323004a3
PL
1529bool migrate_zero_blocks(void)
1530{
1531 MigrationState *s;
1532
1533 s = migrate_get_current();
1534
1535 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1536}
1537
8706d2d5
LL
1538bool migrate_use_compression(void)
1539{
dde4e694
LL
1540 MigrationState *s;
1541
1542 s = migrate_get_current();
1543
1544 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
1545}
1546
1547int migrate_compress_level(void)
1548{
1549 MigrationState *s;
1550
1551 s = migrate_get_current();
1552
2594f56d 1553 return s->parameters.compress_level;
8706d2d5
LL
1554}
1555
1556int migrate_compress_threads(void)
1557{
1558 MigrationState *s;
1559
1560 s = migrate_get_current();
1561
2594f56d 1562 return s->parameters.compress_threads;
8706d2d5
LL
1563}
1564
3fcb38c2
LL
1565int migrate_decompress_threads(void)
1566{
1567 MigrationState *s;
1568
1569 s = migrate_get_current();
1570
2594f56d 1571 return s->parameters.decompress_threads;
3fcb38c2
LL
1572}
1573
b05dc723
JQ
1574bool migrate_use_events(void)
1575{
1576 MigrationState *s;
1577
1578 s = migrate_get_current();
1579
1580 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1581}
1582
30126bbf
JQ
1583bool migrate_use_multifd(void)
1584{
1585 MigrationState *s;
1586
1587 s = migrate_get_current();
1588
1589 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1590}
1591
93fbd031
DDAG
1592bool migrate_pause_before_switchover(void)
1593{
1594 MigrationState *s;
1595
1596 s = migrate_get_current();
1597
1598 return s->enabled_capabilities[
1599 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1600}
1601
4075fb1c
JQ
1602int migrate_multifd_channels(void)
1603{
1604 MigrationState *s;
1605
1606 s = migrate_get_current();
1607
1608 return s->parameters.x_multifd_channels;
1609}
1610
0fb86605
JQ
1611int migrate_multifd_page_count(void)
1612{
1613 MigrationState *s;
1614
1615 s = migrate_get_current();
1616
1617 return s->parameters.x_multifd_page_count;
1618}
1619
17ad9b35
OW
1620int migrate_use_xbzrle(void)
1621{
1622 MigrationState *s;
1623
1624 s = migrate_get_current();
1625
1626 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1627}
1628
1629int64_t migrate_xbzrle_cache_size(void)
1630{
1631 MigrationState *s;
1632
1633 s = migrate_get_current();
1634
73af8dd8 1635 return s->parameters.xbzrle_cache_size;
17ad9b35 1636}
0d82d0e8 1637
2833c59b
JQ
1638bool migrate_use_block(void)
1639{
1640 MigrationState *s;
1641
1642 s = migrate_get_current();
1643
1644 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1645}
1646
c788ada8
PX
1647bool migrate_use_return_path(void)
1648{
1649 MigrationState *s;
1650
1651 s = migrate_get_current();
1652
1653 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
1654}
1655
2833c59b
JQ
1656bool migrate_use_block_incremental(void)
1657{
1658 MigrationState *s;
1659
1660 s = migrate_get_current();
1661
1662 return s->parameters.block_incremental;
1663}
1664
70b20477
DDAG
1665/* migration thread support */
1666/*
1667 * Something bad happened to the RP stream, mark an error
1668 * The caller shall print or trace something to indicate why
1669 */
1670static void mark_source_rp_bad(MigrationState *s)
1671{
1672 s->rp_state.error = true;
1673}
1674
1675static struct rp_cmd_args {
1676 ssize_t len; /* -1 = variable */
1677 const char *name;
1678} rp_cmd_args[] = {
1679 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1680 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1681 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1e2d90eb
DDAG
1682 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1683 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
70b20477
DDAG
1684 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1685};
1686
1e2d90eb
DDAG
1687/*
1688 * Process a request for pages received on the return path,
1689 * We're allowed to send more than requested (e.g. to round to our page size)
1690 * and we don't need to send pages that have already been sent.
1691 */
1692static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1693 ram_addr_t start, size_t len)
1694{
6c595cde
DDAG
1695 long our_host_ps = getpagesize();
1696
1e2d90eb 1697 trace_migrate_handle_rp_req_pages(rbname, start, len);
6c595cde
DDAG
1698
1699 /*
1700 * Since we currently insist on matching page sizes, just sanity check
1701 * we're being asked for whole host pages.
1702 */
1703 if (start & (our_host_ps-1) ||
1704 (len & (our_host_ps-1))) {
1705 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1706 " len: %zd", __func__, start, len);
1707 mark_source_rp_bad(ms);
1708 return;
1709 }
1710
96506894 1711 if (ram_save_queue_pages(rbname, start, len)) {
6c595cde
DDAG
1712 mark_source_rp_bad(ms);
1713 }
1e2d90eb
DDAG
1714}
1715
70b20477
DDAG
1716/*
1717 * Handles messages sent on the return path towards the source VM
1718 *
1719 */
1720static void *source_return_path_thread(void *opaque)
1721{
1722 MigrationState *ms = opaque;
1723 QEMUFile *rp = ms->rp_state.from_dst_file;
1724 uint16_t header_len, header_type;
568b01ca 1725 uint8_t buf[512];
70b20477 1726 uint32_t tmp32, sibling_error;
1e2d90eb
DDAG
1727 ram_addr_t start = 0; /* =0 to silence warning */
1728 size_t len = 0, expected_len;
70b20477
DDAG
1729 int res;
1730
1731 trace_source_return_path_thread_entry();
1732 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1733 migration_is_setup_or_active(ms->state)) {
1734 trace_source_return_path_thread_loop_top();
1735 header_type = qemu_get_be16(rp);
1736 header_len = qemu_get_be16(rp);
1737
7a9ddfbf
PX
1738 if (qemu_file_get_error(rp)) {
1739 mark_source_rp_bad(ms);
1740 goto out;
1741 }
1742
70b20477
DDAG
1743 if (header_type >= MIG_RP_MSG_MAX ||
1744 header_type == MIG_RP_MSG_INVALID) {
1745 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1746 header_type, header_len);
1747 mark_source_rp_bad(ms);
1748 goto out;
1749 }
1750
1751 if ((rp_cmd_args[header_type].len != -1 &&
1752 header_len != rp_cmd_args[header_type].len) ||
568b01ca 1753 header_len > sizeof(buf)) {
70b20477
DDAG
1754 error_report("RP: Received '%s' message (0x%04x) with"
1755 "incorrect length %d expecting %zu",
1756 rp_cmd_args[header_type].name, header_type, header_len,
1757 (size_t)rp_cmd_args[header_type].len);
1758 mark_source_rp_bad(ms);
1759 goto out;
1760 }
1761
1762 /* We know we've got a valid header by this point */
1763 res = qemu_get_buffer(rp, buf, header_len);
1764 if (res != header_len) {
1765 error_report("RP: Failed reading data for message 0x%04x"
1766 " read %d expected %d",
1767 header_type, res, header_len);
1768 mark_source_rp_bad(ms);
1769 goto out;
1770 }
1771
1772 /* OK, we have the message and the data */
1773 switch (header_type) {
1774 case MIG_RP_MSG_SHUT:
4d885131 1775 sibling_error = ldl_be_p(buf);
70b20477
DDAG
1776 trace_source_return_path_thread_shut(sibling_error);
1777 if (sibling_error) {
1778 error_report("RP: Sibling indicated error %d", sibling_error);
1779 mark_source_rp_bad(ms);
1780 }
1781 /*
1782 * We'll let the main thread deal with closing the RP
1783 * we could do a shutdown(2) on it, but we're the only user
1784 * anyway, so there's nothing gained.
1785 */
1786 goto out;
1787
1788 case MIG_RP_MSG_PONG:
4d885131 1789 tmp32 = ldl_be_p(buf);
70b20477
DDAG
1790 trace_source_return_path_thread_pong(tmp32);
1791 break;
1792
1e2d90eb 1793 case MIG_RP_MSG_REQ_PAGES:
4d885131
PM
1794 start = ldq_be_p(buf);
1795 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
1796 migrate_handle_rp_req_pages(ms, NULL, start, len);
1797 break;
1798
1799 case MIG_RP_MSG_REQ_PAGES_ID:
1800 expected_len = 12 + 1; /* header + termination */
1801
1802 if (header_len >= expected_len) {
4d885131
PM
1803 start = ldq_be_p(buf);
1804 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
1805 /* Now we expect an idstr */
1806 tmp32 = buf[12]; /* Length of the following idstr */
1807 buf[13 + tmp32] = '\0';
1808 expected_len += tmp32;
1809 }
1810 if (header_len != expected_len) {
1811 error_report("RP: Req_Page_id with length %d expecting %zd",
1812 header_len, expected_len);
1813 mark_source_rp_bad(ms);
1814 goto out;
1815 }
1816 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1817 break;
1818
70b20477
DDAG
1819 default:
1820 break;
1821 }
1822 }
5df5416e 1823 if (qemu_file_get_error(rp)) {
70b20477
DDAG
1824 trace_source_return_path_thread_bad_end();
1825 mark_source_rp_bad(ms);
1826 }
1827
1828 trace_source_return_path_thread_end();
1829out:
1830 ms->rp_state.from_dst_file = NULL;
1831 qemu_fclose(rp);
1832 return NULL;
1833}
1834
70b20477
DDAG
1835static int open_return_path_on_source(MigrationState *ms)
1836{
1837
89a02a9f 1838 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
70b20477
DDAG
1839 if (!ms->rp_state.from_dst_file) {
1840 return -1;
1841 }
1842
1843 trace_open_return_path_on_source();
1844 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1845 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1846
1847 trace_open_return_path_on_source_continue();
1848
1849 return 0;
1850}
1851
70b20477
DDAG
1852/* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1853static int await_return_path_close_on_source(MigrationState *ms)
1854{
1855 /*
1856 * If this is a normal exit then the destination will send a SHUT and the
1857 * rp_thread will exit, however if there's an error we need to cause
1858 * it to exit.
1859 */
89a02a9f 1860 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
70b20477
DDAG
1861 /*
1862 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1863 * waiting for the destination.
1864 */
1865 qemu_file_shutdown(ms->rp_state.from_dst_file);
1866 mark_source_rp_bad(ms);
1867 }
1868 trace_await_return_path_close_on_source_joining();
1869 qemu_thread_join(&ms->rp_state.rp_thread);
1870 trace_await_return_path_close_on_source_close();
1871 return ms->rp_state.error;
1872}
1873
1d34e4bf
DDAG
1874/*
1875 * Switch from normal iteration to postcopy
1876 * Returns non-0 on error
1877 */
7287cbd4 1878static int postcopy_start(MigrationState *ms)
1d34e4bf
DDAG
1879{
1880 int ret;
61b67d47
DB
1881 QIOChannelBuffer *bioc;
1882 QEMUFile *fb;
1d34e4bf 1883 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
ef8d6488 1884 bool restart_block = false;
0331c8ca
DDAG
1885 int cur_state = MIGRATION_STATUS_ACTIVE;
1886 if (!migrate_pause_before_switchover()) {
1887 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1888 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1889 }
1d34e4bf
DDAG
1890
1891 trace_postcopy_start();
1892 qemu_mutex_lock_iothread();
1893 trace_postcopy_start_set_run();
1894
1895 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1d34e4bf
DDAG
1896 global_state_store();
1897 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
76b1c7fe
KW
1898 if (ret < 0) {
1899 goto fail;
1900 }
1d34e4bf 1901
0331c8ca
DDAG
1902 ret = migration_maybe_pause(ms, &cur_state,
1903 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1904 if (ret < 0) {
1905 goto fail;
1906 }
1907
76b1c7fe 1908 ret = bdrv_inactivate_all();
1d34e4bf
DDAG
1909 if (ret < 0) {
1910 goto fail;
1911 }
ef8d6488 1912 restart_block = true;
1d34e4bf 1913
1c0d249d
DDAG
1914 /*
1915 * Cause any non-postcopiable, but iterative devices to
1916 * send out their final data.
1917 */
a1fbe750 1918 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1c0d249d 1919
1d34e4bf
DDAG
1920 /*
1921 * in Finish migrate and with the io-lock held everything should
1922 * be quiet, but we've potentially still got dirty pages and we
1923 * need to tell the destination to throw any pages it's already received
1924 * that are dirty
1925 */
58110f0a
VSO
1926 if (migrate_postcopy_ram()) {
1927 if (ram_postcopy_send_discard_bitmap(ms)) {
1928 error_report("postcopy send discard bitmap failed");
1929 goto fail;
1930 }
1d34e4bf
DDAG
1931 }
1932
1933 /*
1934 * send rest of state - note things that are doing postcopy
1935 * will notice we're in POSTCOPY_ACTIVE and not actually
1936 * wrap their state up here
1937 */
89a02a9f 1938 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
58110f0a
VSO
1939 if (migrate_postcopy_ram()) {
1940 /* Ping just for debugging, helps line traces up */
1941 qemu_savevm_send_ping(ms->to_dst_file, 2);
1942 }
1d34e4bf
DDAG
1943
1944 /*
1945 * While loading the device state we may trigger page transfer
1946 * requests and the fd must be free to process those, and thus
1947 * the destination must read the whole device state off the fd before
1948 * it starts processing it. Unfortunately the ad-hoc migration format
1949 * doesn't allow the destination to know the size to read without fully
1950 * parsing it through each devices load-state code (especially the open
1951 * coded devices that use get/put).
1952 * So we wrap the device state up in a package with a length at the start;
1953 * to do this we use a qemu_buf to hold the whole of the device state.
1954 */
61b67d47 1955 bioc = qio_channel_buffer_new(4096);
6f01f136 1956 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
61b67d47
DB
1957 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
1958 object_unref(OBJECT(bioc));
1d34e4bf 1959
c76201ab
DDAG
1960 /*
1961 * Make sure the receiver can get incoming pages before we send the rest
1962 * of the state
1963 */
1964 qemu_savevm_send_postcopy_listen(fb);
1965
a1fbe750 1966 qemu_savevm_state_complete_precopy(fb, false, false);
58110f0a
VSO
1967 if (migrate_postcopy_ram()) {
1968 qemu_savevm_send_ping(fb, 3);
1969 }
1d34e4bf
DDAG
1970
1971 qemu_savevm_send_postcopy_run(fb);
1972
1973 /* <><> end of stuff going into the package */
1d34e4bf 1974
ef8d6488
DDAG
1975 /* Last point of recovery; as soon as we send the package the destination
1976 * can open devices and potentially start running.
1977 * Lets just check again we've not got any errors.
1978 */
1979 ret = qemu_file_get_error(ms->to_dst_file);
1980 if (ret) {
1981 error_report("postcopy_start: Migration stream errored (pre package)");
1982 goto fail_closefb;
1983 }
1984
1985 restart_block = false;
1986
1d34e4bf 1987 /* Now send that blob */
61b67d47 1988 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1d34e4bf
DDAG
1989 goto fail_closefb;
1990 }
1991 qemu_fclose(fb);
b82fc321
DDAG
1992
1993 /* Send a notify to give a chance for anything that needs to happen
1994 * at the transition to postcopy and after the device state; in particular
1995 * spice needs to trigger a transition now
1996 */
1997 ms->postcopy_after_devices = true;
1998 notifier_list_notify(&migration_state_notifiers, ms);
1999
1d34e4bf
DDAG
2000 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2001
2002 qemu_mutex_unlock_iothread();
2003
58110f0a
VSO
2004 if (migrate_postcopy_ram()) {
2005 /*
2006 * Although this ping is just for debug, it could potentially be
2007 * used for getting a better measurement of downtime at the source.
2008 */
2009 qemu_savevm_send_ping(ms->to_dst_file, 4);
2010 }
1d34e4bf 2011
ced1c616
PB
2012 if (migrate_release_ram()) {
2013 ram_postcopy_migrated_memory_release(ms);
2014 }
2015
89a02a9f 2016 ret = qemu_file_get_error(ms->to_dst_file);
1d34e4bf
DDAG
2017 if (ret) {
2018 error_report("postcopy_start: Migration stream errored");
48781e5b 2019 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf
DDAG
2020 MIGRATION_STATUS_FAILED);
2021 }
2022
2023 return ret;
2024
2025fail_closefb:
2026 qemu_fclose(fb);
2027fail:
48781e5b 2028 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf 2029 MIGRATION_STATUS_FAILED);
ef8d6488
DDAG
2030 if (restart_block) {
2031 /* A failure happened early enough that we know the destination hasn't
2032 * accessed block devices, so we're safe to recover.
2033 */
2034 Error *local_err = NULL;
2035
2036 bdrv_invalidate_cache_all(&local_err);
2037 if (local_err) {
2038 error_report_err(local_err);
2039 }
2040 }
1d34e4bf
DDAG
2041 qemu_mutex_unlock_iothread();
2042 return -1;
2043}
2044
e91d8951
DDAG
2045/**
2046 * migration_maybe_pause: Pause if required to by
2047 * migrate_pause_before_switchover called with the iothread locked
2048 * Returns: 0 on success
2049 */
0331c8ca
DDAG
2050static int migration_maybe_pause(MigrationState *s,
2051 int *current_active_state,
2052 int new_state)
e91d8951
DDAG
2053{
2054 if (!migrate_pause_before_switchover()) {
2055 return 0;
2056 }
2057
2058 /* Since leaving this state is not atomic with posting the semaphore
2059 * it's possible that someone could have issued multiple migrate_continue
2060 * and the semaphore is incorrectly positive at this point;
2061 * the docs say it's undefined to reinit a semaphore that's already
2062 * init'd, so use timedwait to eat up any existing posts.
2063 */
2064 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2065 /* This block intentionally left blank */
2066 }
2067
2068 qemu_mutex_unlock_iothread();
2069 migrate_set_state(&s->state, *current_active_state,
2070 MIGRATION_STATUS_PRE_SWITCHOVER);
2071 qemu_sem_wait(&s->pause_sem);
2072 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
0331c8ca
DDAG
2073 new_state);
2074 *current_active_state = new_state;
e91d8951
DDAG
2075 qemu_mutex_lock_iothread();
2076
0331c8ca 2077 return s->state == new_state ? 0 : -EINVAL;
e91d8951
DDAG
2078}
2079
09f6c85e
DDAG
2080/**
2081 * migration_completion: Used by migration_thread when there's not much left.
2082 * The caller 'breaks' the loop when this returns.
2083 *
2084 * @s: Current migration state
09f6c85e 2085 */
2ad87305 2086static void migration_completion(MigrationState *s)
09f6c85e
DDAG
2087{
2088 int ret;
2ad87305 2089 int current_active_state = s->state;
09f6c85e 2090
b10ac0c4
DDAG
2091 if (s->state == MIGRATION_STATUS_ACTIVE) {
2092 qemu_mutex_lock_iothread();
64909f97 2093 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
b10ac0c4 2094 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
7287cbd4 2095 s->vm_was_running = runstate_is_running();
b10ac0c4
DDAG
2096 ret = global_state_store();
2097
2098 if (!ret) {
a1fbe750 2099 bool inactivate = !migrate_colo_enabled();
b10ac0c4 2100 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
e91d8951 2101 if (ret >= 0) {
0331c8ca
DDAG
2102 ret = migration_maybe_pause(s, &current_active_state,
2103 MIGRATION_STATUS_DEVICE);
e91d8951 2104 }
f07fa4cb
KW
2105 if (ret >= 0) {
2106 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
a1fbe750
FZ
2107 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2108 inactivate);
f07fa4cb 2109 }
a1fbe750
FZ
2110 if (inactivate && ret >= 0) {
2111 s->block_inactive = true;
b10ac0c4
DDAG
2112 }
2113 }
2114 qemu_mutex_unlock_iothread();
09f6c85e 2115
b10ac0c4
DDAG
2116 if (ret < 0) {
2117 goto fail;
09f6c85e 2118 }
b10ac0c4
DDAG
2119 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2120 trace_migration_completion_postcopy_end();
2121
89a02a9f 2122 qemu_savevm_state_complete_postcopy(s->to_dst_file);
b10ac0c4 2123 trace_migration_completion_postcopy_end_after_complete();
09f6c85e 2124 }
09f6c85e 2125
b10ac0c4
DDAG
2126 /*
2127 * If rp was opened we must clean up the thread before
2128 * cleaning everything else up (since if there are no failures
2129 * it will wait for the destination to send it's status in
2130 * a SHUT command).
b10ac0c4 2131 */
0425dc97 2132 if (s->rp_state.from_dst_file) {
b10ac0c4 2133 int rp_error;
0425dc97 2134 trace_migration_return_path_end_before();
b10ac0c4 2135 rp_error = await_return_path_close_on_source(s);
0425dc97 2136 trace_migration_return_path_end_after(rp_error);
b10ac0c4 2137 if (rp_error) {
fe904ea8 2138 goto fail_invalidate;
b10ac0c4 2139 }
09f6c85e
DDAG
2140 }
2141
89a02a9f 2142 if (qemu_file_get_error(s->to_dst_file)) {
09f6c85e 2143 trace_migration_completion_file_err();
fe904ea8 2144 goto fail_invalidate;
09f6c85e
DDAG
2145 }
2146
0b827d5e
HZ
2147 if (!migrate_colo_enabled()) {
2148 migrate_set_state(&s->state, current_active_state,
2149 MIGRATION_STATUS_COMPLETED);
2150 }
2151
09f6c85e
DDAG
2152 return;
2153
fe904ea8
GK
2154fail_invalidate:
2155 /* If not doing postcopy, vm_start() will be called: let's regain
2156 * control on images.
2157 */
6039dd5b
DDAG
2158 if (s->state == MIGRATION_STATUS_ACTIVE ||
2159 s->state == MIGRATION_STATUS_DEVICE) {
fe904ea8
GK
2160 Error *local_err = NULL;
2161
1d2acc31 2162 qemu_mutex_lock_iothread();
fe904ea8
GK
2163 bdrv_invalidate_cache_all(&local_err);
2164 if (local_err) {
2165 error_report_err(local_err);
1d2acc31
HZ
2166 } else {
2167 s->block_inactive = false;
fe904ea8 2168 }
1d2acc31 2169 qemu_mutex_unlock_iothread();
fe904ea8
GK
2170 }
2171
09f6c85e 2172fail:
48781e5b
HZ
2173 migrate_set_state(&s->state, current_active_state,
2174 MIGRATION_STATUS_FAILED);
09f6c85e
DDAG
2175}
2176
35a6ed4f
HZ
2177bool migrate_colo_enabled(void)
2178{
2179 MigrationState *s = migrate_get_current();
2180 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2181}
2182
cf011f08
PX
2183static void migration_calculate_complete(MigrationState *s)
2184{
2185 uint64_t bytes = qemu_ftell(s->to_dst_file);
2186 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2187
2188 s->total_time = end_time - s->start_time;
2189 if (!s->downtime) {
2190 /*
2191 * It's still not set, so we are precopy migration. For
2192 * postcopy, downtime is calculated during postcopy_start().
2193 */
2194 s->downtime = end_time - s->downtime_start;
2195 }
2196
2197 if (s->total_time) {
2198 s->mbps = ((double) bytes * 8.0) / s->total_time / 1000;
2199 }
2200}
2201
b15df1ae
PX
2202static void migration_update_counters(MigrationState *s,
2203 int64_t current_time)
2204{
2205 uint64_t transferred, time_spent;
b15df1ae
PX
2206 double bandwidth;
2207
2208 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2209 return;
2210 }
2211
2212 transferred = qemu_ftell(s->to_dst_file) - s->iteration_initial_bytes;
2213 time_spent = current_time - s->iteration_start_time;
2214 bandwidth = (double)transferred / time_spent;
0781c1ed 2215 s->threshold_size = bandwidth * s->parameters.downtime_limit;
b15df1ae
PX
2216
2217 s->mbps = (((double) transferred * 8.0) /
2218 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2219
2220 /*
2221 * if we haven't sent anything, we don't want to
2222 * recalculate. 10000 is a small enough number for our purposes
2223 */
2224 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2225 s->expected_downtime = ram_counters.dirty_pages_rate *
2226 qemu_target_page_size() / bandwidth;
2227 }
2228
2229 qemu_file_reset_rate_limit(s->to_dst_file);
2230
2231 s->iteration_start_time = current_time;
2232 s->iteration_initial_bytes = qemu_ftell(s->to_dst_file);
2233
2234 trace_migrate_transferred(transferred, time_spent,
0781c1ed 2235 bandwidth, s->threshold_size);
b15df1ae
PX
2236}
2237
2ad87305
PX
2238/* Migration thread iteration status */
2239typedef enum {
2240 MIG_ITERATE_RESUME, /* Resume current iteration */
2241 MIG_ITERATE_SKIP, /* Skip current iteration */
2242 MIG_ITERATE_BREAK, /* Break the loop */
2243} MigIterateState;
2244
2245/*
2246 * Return true if continue to the next iteration directly, false
2247 * otherwise.
2248 */
2249static MigIterateState migration_iteration_run(MigrationState *s)
2250{
2251 uint64_t pending_size, pend_post, pend_nonpost;
2252 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2253
2254 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size,
2255 &pend_nonpost, &pend_post);
2256 pending_size = pend_nonpost + pend_post;
2257
2258 trace_migrate_pending(pending_size, s->threshold_size,
2259 pend_post, pend_nonpost);
2260
2261 if (pending_size && pending_size >= s->threshold_size) {
2262 /* Still a significant amount to transfer */
2263 if (migrate_postcopy() && !in_postcopy &&
2264 pend_nonpost <= s->threshold_size &&
2265 atomic_read(&s->start_postcopy)) {
2266 if (postcopy_start(s)) {
2267 error_report("%s: postcopy failed to start", __func__);
2268 }
2269 return MIG_ITERATE_SKIP;
2270 }
2271 /* Just another iteration step */
2272 qemu_savevm_state_iterate(s->to_dst_file,
2273 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2274 } else {
2275 trace_migration_thread_low_pending(pending_size);
2276 migration_completion(s);
2277 return MIG_ITERATE_BREAK;
2278 }
2279
2280 return MIG_ITERATE_RESUME;
2281}
2282
199aa6d4
PX
2283static void migration_iteration_finish(MigrationState *s)
2284{
2285 /* If we enabled cpu throttling for auto-converge, turn it off. */
2286 cpu_throttle_stop();
2287
2288 qemu_mutex_lock_iothread();
2289 switch (s->state) {
2290 case MIGRATION_STATUS_COMPLETED:
2291 migration_calculate_complete(s);
2292 runstate_set(RUN_STATE_POSTMIGRATE);
2293 break;
2294
2295 case MIGRATION_STATUS_ACTIVE:
2296 /*
2297 * We should really assert here, but since it's during
2298 * migration, let's try to reduce the usage of assertions.
2299 */
2300 if (!migrate_colo_enabled()) {
2301 error_report("%s: critical error: calling COLO code without "
2302 "COLO enabled", __func__);
2303 }
2304 migrate_start_colo_process(s);
2305 /*
2306 * Fixme: we will run VM in COLO no matter its old running state.
2307 * After exited COLO, we will keep running.
2308 */
2309 s->vm_was_running = true;
2310 /* Fallthrough */
2311 case MIGRATION_STATUS_FAILED:
2312 case MIGRATION_STATUS_CANCELLED:
2313 if (s->vm_was_running) {
2314 vm_start();
2315 } else {
2316 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2317 runstate_set(RUN_STATE_POSTMIGRATE);
2318 }
2319 }
2320 break;
2321
2322 default:
2323 /* Should not reach here, but if so, forgive the VM. */
2324 error_report("%s: Unknown ending state %d", __func__, s->state);
2325 break;
2326 }
2327 qemu_bh_schedule(s->cleanup_bh);
2328 qemu_mutex_unlock_iothread();
2329}
2330
70b20477
DDAG
2331/*
2332 * Master migration thread on the source VM.
2333 * It drives the migration and pumps the data down the outgoing channel.
2334 */
5f496a1b 2335static void *migration_thread(void *opaque)
0d82d0e8 2336{
9848a404 2337 MigrationState *s = opaque;
bc72ad67 2338 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
76f5933a 2339
ab28bd23
PB
2340 rcu_register_thread();
2341
b15df1ae
PX
2342 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2343
89a02a9f 2344 qemu_savevm_state_header(s->to_dst_file);
1d34e4bf 2345
62a02658
PX
2346 /*
2347 * If we opened the return path, we need to make sure dst has it
2348 * opened as well.
2349 */
2350 if (s->rp_state.from_dst_file) {
1d34e4bf 2351 /* Now tell the dest that it should open its end so it can reply */
89a02a9f 2352 qemu_savevm_send_open_return_path(s->to_dst_file);
1d34e4bf
DDAG
2353
2354 /* And do a ping that will make stuff easier to debug */
89a02a9f 2355 qemu_savevm_send_ping(s->to_dst_file, 1);
0425dc97 2356 }
1d34e4bf 2357
58110f0a 2358 if (migrate_postcopy()) {
1d34e4bf
DDAG
2359 /*
2360 * Tell the destination that we *might* want to do postcopy later;
2361 * if the other end can't do postcopy it should fail now, nice and
2362 * early.
2363 */
89a02a9f 2364 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1d34e4bf
DDAG
2365 }
2366
9907e842 2367 qemu_savevm_state_setup(s->to_dst_file);
0d82d0e8 2368
bc72ad67 2369 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
48781e5b
HZ
2370 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2371 MIGRATION_STATUS_ACTIVE);
29ae8a41 2372
9ec055ae
DDAG
2373 trace_migration_thread_setup_complete();
2374
2375 while (s->state == MIGRATION_STATUS_ACTIVE ||
2376 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
a3e879cd 2377 int64_t current_time;
0d82d0e8 2378
89a02a9f 2379 if (!qemu_file_rate_limit(s->to_dst_file)) {
2ad87305
PX
2380 MigIterateState iter_state = migration_iteration_run(s);
2381 if (iter_state == MIG_ITERATE_SKIP) {
2382 continue;
2383 } else if (iter_state == MIG_ITERATE_BREAK) {
09f6c85e 2384 break;
c369f40d
JQ
2385 }
2386 }
f4410a5d 2387
89a02a9f 2388 if (qemu_file_get_error(s->to_dst_file)) {
2ad87305
PX
2389 if (migration_is_setup_or_active(s->state)) {
2390 migrate_set_state(&s->state, s->state,
2391 MIGRATION_STATUS_FAILED);
2392 }
1d34e4bf 2393 trace_migration_thread_file_err();
fd45ee2c
PB
2394 break;
2395 }
b15df1ae 2396
bc72ad67 2397 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0d82d0e8 2398
b15df1ae
PX
2399 migration_update_counters(s, current_time);
2400
89a02a9f 2401 if (qemu_file_rate_limit(s->to_dst_file)) {
0d82d0e8 2402 /* usleep expects microseconds */
b15df1ae
PX
2403 g_usleep((s->iteration_start_time + BUFFER_DELAY -
2404 current_time) * 1000);
0d82d0e8 2405 }
a3fa1d78
PB
2406 }
2407
1d34e4bf 2408 trace_migration_thread_after_loop();
199aa6d4 2409 migration_iteration_finish(s);
ab28bd23 2410 rcu_unregister_thread();
0d82d0e8
JQ
2411 return NULL;
2412}
2413
cce8040b 2414void migrate_fd_connect(MigrationState *s, Error *error_in)
0d82d0e8 2415{
2ff30257 2416 s->expected_downtime = s->parameters.downtime_limit;
bb1fadc4 2417 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
cce8040b
DDAG
2418 if (error_in) {
2419 migrate_fd_error(s, error_in);
2420 migrate_fd_cleanup(s);
2421 return;
2422 }
0d82d0e8 2423
9e4d2b98 2424 qemu_file_set_blocking(s->to_dst_file, true);
89a02a9f 2425 qemu_file_set_rate_limit(s->to_dst_file,
2ff30257 2426 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
442773ce 2427
9287ac27
SH
2428 /* Notify before starting migration thread */
2429 notifier_list_notify(&migration_state_notifiers, s);
2430
1d34e4bf 2431 /*
c788ada8
PX
2432 * Open the return path. For postcopy, it is used exclusively. For
2433 * precopy, only if user specified "return-path" capability would
2434 * QEMU uses the return path.
1d34e4bf 2435 */
c788ada8 2436 if (migrate_postcopy_ram() || migrate_use_return_path()) {
1d34e4bf
DDAG
2437 if (open_return_path_on_source(s)) {
2438 error_report("Unable to open return-path for postcopy");
48781e5b 2439 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1d34e4bf
DDAG
2440 MIGRATION_STATUS_FAILED);
2441 migrate_fd_cleanup(s);
2442 return;
2443 }
2444 }
2445
f986c3d2
JQ
2446 if (multifd_save_setup() != 0) {
2447 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2448 MIGRATION_STATUS_FAILED);
2449 migrate_fd_cleanup(s);
2450 return;
2451 }
009fad7f 2452 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
bb1fadc4 2453 QEMU_THREAD_JOINABLE);
1d34e4bf 2454 s->migration_thread_running = true;
0d82d0e8 2455}
093e3c42 2456
9d18af93
PX
2457void migration_global_dump(Monitor *mon)
2458{
2459 MigrationState *ms = migrate_get_current();
2460
6f0f6428
JQ
2461 monitor_printf(mon, "globals:\n");
2462 monitor_printf(mon, "store-global-state: %s\n",
2463 ms->store_global_state ? "on" : "off");
2464 monitor_printf(mon, "only-migratable: %s\n",
2465 ms->only_migratable ? "on" : "off");
2466 monitor_printf(mon, "send-configuration: %s\n",
2467 ms->send_configuration ? "on" : "off");
2468 monitor_printf(mon, "send-section-footer: %s\n",
2469 ms->send_section_footer ? "on" : "off");
9d18af93
PX
2470}
2471
20814758
PX
2472#define DEFINE_PROP_MIG_CAP(name, x) \
2473 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2474
5272298c
PX
2475static Property migration_properties[] = {
2476 DEFINE_PROP_BOOL("store-global-state", MigrationState,
2477 store_global_state, true),
3df663e5 2478 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
71dd4c1a
PX
2479 DEFINE_PROP_BOOL("send-configuration", MigrationState,
2480 send_configuration, true),
15c38503
PX
2481 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
2482 send_section_footer, true),
89632faf
PX
2483
2484 /* Migration parameters */
741d4086 2485 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
89632faf
PX
2486 parameters.compress_level,
2487 DEFAULT_MIGRATE_COMPRESS_LEVEL),
741d4086 2488 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
89632faf
PX
2489 parameters.compress_threads,
2490 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
741d4086 2491 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
89632faf
PX
2492 parameters.decompress_threads,
2493 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
741d4086 2494 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
89632faf
PX
2495 parameters.cpu_throttle_initial,
2496 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
741d4086 2497 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
89632faf
PX
2498 parameters.cpu_throttle_increment,
2499 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
741d4086 2500 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
89632faf 2501 parameters.max_bandwidth, MAX_THROTTLE),
741d4086 2502 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
89632faf
PX
2503 parameters.downtime_limit,
2504 DEFAULT_MIGRATE_SET_DOWNTIME),
741d4086 2505 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
89632faf
PX
2506 parameters.x_checkpoint_delay,
2507 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
741d4086 2508 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
4075fb1c
JQ
2509 parameters.x_multifd_channels,
2510 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
741d4086 2511 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
0fb86605
JQ
2512 parameters.x_multifd_page_count,
2513 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
73af8dd8
JQ
2514 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
2515 parameters.xbzrle_cache_size,
2516 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
20814758
PX
2517
2518 /* Migration capabilities */
2519 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
2520 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
2521 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
2522 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
2523 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
2524 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
2525 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
2526 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
2527 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
2528 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
2529 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
30126bbf 2530 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
20814758 2531
5272298c
PX
2532 DEFINE_PROP_END_OF_LIST(),
2533};
2534
e5cb7e76
PX
2535static void migration_class_init(ObjectClass *klass, void *data)
2536{
2537 DeviceClass *dc = DEVICE_CLASS(klass);
2538
2539 dc->user_creatable = false;
5272298c 2540 dc->props = migration_properties;
e5cb7e76
PX
2541}
2542
b91bf5e4
MAL
2543static void migration_instance_finalize(Object *obj)
2544{
2545 MigrationState *ms = MIGRATION_OBJ(obj);
2546 MigrationParameters *params = &ms->parameters;
2547
87db1a7d 2548 qemu_mutex_destroy(&ms->error_mutex);
b91bf5e4
MAL
2549 g_free(params->tls_hostname);
2550 g_free(params->tls_creds);
e91d8951 2551 qemu_sem_destroy(&ms->pause_sem);
ab105cc1 2552 error_free(ms->error);
b91bf5e4
MAL
2553}
2554
e5cb7e76
PX
2555static void migration_instance_init(Object *obj)
2556{
2557 MigrationState *ms = MIGRATION_OBJ(obj);
8b0b29dc 2558 MigrationParameters *params = &ms->parameters;
e5cb7e76
PX
2559
2560 ms->state = MIGRATION_STATUS_NONE;
e5cb7e76 2561 ms->mbps = -1;
e91d8951 2562 qemu_sem_init(&ms->pause_sem, 0);
87db1a7d 2563 qemu_mutex_init(&ms->error_mutex);
8b0b29dc
PX
2564
2565 params->tls_hostname = g_strdup("");
2566 params->tls_creds = g_strdup("");
2567
2568 /* Set has_* up only for parameter checks */
2569 params->has_compress_level = true;
2570 params->has_compress_threads = true;
2571 params->has_decompress_threads = true;
2572 params->has_cpu_throttle_initial = true;
2573 params->has_cpu_throttle_increment = true;
2574 params->has_max_bandwidth = true;
2575 params->has_downtime_limit = true;
2576 params->has_x_checkpoint_delay = true;
2577 params->has_block_incremental = true;
4075fb1c 2578 params->has_x_multifd_channels = true;
0fb86605 2579 params->has_x_multifd_page_count = true;
73af8dd8 2580 params->has_xbzrle_cache_size = true;
8b0b29dc
PX
2581}
2582
2583/*
2584 * Return true if check pass, false otherwise. Error will be put
2585 * inside errp if provided.
2586 */
2587static bool migration_object_check(MigrationState *ms, Error **errp)
2588{
6b19a7d9
PX
2589 MigrationCapabilityStatusList *head = NULL;
2590 /* Assuming all off */
2591 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
2592 int i;
2593
8b0b29dc
PX
2594 if (!migrate_params_check(&ms->parameters, errp)) {
2595 return false;
2596 }
2597
6b19a7d9
PX
2598 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
2599 if (ms->enabled_capabilities[i]) {
2600 head = migrate_cap_add(head, i, true);
2601 }
2602 }
2603
2604 ret = migrate_caps_check(cap_list, head, errp);
2605
2606 /* It works with head == NULL */
2607 qapi_free_MigrationCapabilityStatusList(head);
2608
2609 return ret;
e5cb7e76
PX
2610}
2611
2612static const TypeInfo migration_type = {
2613 .name = TYPE_MIGRATION,
01f6e14c 2614 /*
c8d3ff38
PX
2615 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2616 * not created using qdev_create(), it is not attached to the qdev
2617 * device tree, and it is never realized.
2618 *
2619 * TODO: Make this TYPE_OBJECT once QOM provides something like
2620 * TYPE_DEVICE's "-global" properties.
01f6e14c 2621 */
e5cb7e76
PX
2622 .parent = TYPE_DEVICE,
2623 .class_init = migration_class_init,
2624 .class_size = sizeof(MigrationClass),
2625 .instance_size = sizeof(MigrationState),
2626 .instance_init = migration_instance_init,
b91bf5e4 2627 .instance_finalize = migration_instance_finalize,
e5cb7e76
PX
2628};
2629
2630static void register_migration_types(void)
2631{
2632 type_register_static(&migration_type);
2633}
2634
2635type_init(register_migration_types);
This page took 1.115324 seconds and 4 git commands to generate.