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