]> git.proxmox.com Git - mirror_qemu.git/blame - migration/migration.c
Clean up inclusion of sysemu/sysemu.h
[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"
db725815 19#include "qemu/main-loop.h"
795c40b8 20#include "migration/blocker.h"
f4dbe1bf 21#include "exec.h"
7fcac4a2 22#include "fd.h"
61e8b148 23#include "socket.h"
e1a3ecee 24#include "rdma.h"
7b1e1a22 25#include "ram.h"
84a899de 26#include "migration/global_state.h"
c4b63b7c 27#include "migration/misc.h"
6666c96a 28#include "migration.h"
20a519a0 29#include "savevm.h"
40014d81 30#include "qemu-file-channel.h"
08a0aee1 31#include "qemu-file.h"
987772d9 32#include "migration/vmstate.h"
737e150e 33#include "block/block.h"
e688df6b 34#include "qapi/error.h"
9aca82ba
JQ
35#include "qapi/clone-visitor.h"
36#include "qapi/qapi-visit-sockets.h"
9af23989
MA
37#include "qapi/qapi-commands-migration.h"
38#include "qapi/qapi-events-migration.h"
cc7a8ea7 39#include "qapi/qmp/qerror.h"
15280c36 40#include "qapi/qmp/qnull.h"
ab28bd23 41#include "qemu/rcu.h"
2c9e6fec 42#include "block.h"
be07b0ac 43#include "postcopy-ram.h"
766bd176 44#include "qemu/thread.h"
c09e5bb1 45#include "trace.h"
51180423 46#include "exec/target_page.h"
61b67d47 47#include "io/channel-buffer.h"
35a6ed4f 48#include "migration/colo.h"
4ffdb337 49#include "hw/boards.h"
a27bd6c7 50#include "hw/qdev-properties.h"
9d18af93 51#include "monitor/monitor.h"
50510ea2 52#include "net/announce.h"
065e2813 53
dc325627 54#define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
5bb7910a 55
5b4e1eb7
JQ
56/* Amount of time to allocate to each "chunk" of bandwidth-throttled
57 * data. */
58#define BUFFER_DELAY 100
59#define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
60
2ff30257
AA
61/* Time in milliseconds we are allowed to stop the source,
62 * for sending the last part */
63#define DEFAULT_MIGRATE_SET_DOWNTIME 300
64
87c9cc1c
DHB
65/* Maximum migrate downtime set to 2000 seconds */
66#define MAX_MIGRATE_DOWNTIME_SECONDS 2000
67#define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
68
8706d2d5
LL
69/* Default compression thread count */
70#define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
3fcb38c2
LL
71/* Default decompression thread count, usually decompression is at
72 * least 4 times as fast as compression.*/
73#define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
8706d2d5
LL
74/*0: means nocompress, 1: best speed, ... 9: best compress ratio */
75#define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
1626fee3 76/* Define default autoconverge cpu throttle migration parameters */
d85a31d1
JH
77#define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
78#define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
4cbc9c7f 79#define DEFAULT_MIGRATE_MAX_CPU_THROTTLE 99
8706d2d5 80
17ad9b35 81/* Migration XBZRLE default cache size */
73af8dd8 82#define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
17ad9b35 83
131b2153
ZC
84/* The delay time (in ms) between two COLO checkpoints */
85#define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY (200 * 100)
4075fb1c 86#define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
68b53591 87
7e555c6c
DDAG
88/* Background transfer rate for postcopy, 0 means unlimited, note
89 * that page requests can still exceed this limit.
90 */
91#define DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH 0
92
ee3d96ba
DDAG
93/*
94 * Parameters for self_announce_delay giving a stream of RARP/ARP
95 * packets after migration.
96 */
97#define DEFAULT_MIGRATE_ANNOUNCE_INITIAL 50
98#define DEFAULT_MIGRATE_ANNOUNCE_MAX 550
99#define DEFAULT_MIGRATE_ANNOUNCE_ROUNDS 5
100#define DEFAULT_MIGRATE_ANNOUNCE_STEP 100
101
99a0db9b
GH
102static NotifierList migration_state_notifiers =
103 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
104
adde220a
DDAG
105static bool deferred_incoming;
106
da6f1790
JQ
107/* Messages sent on the return path from destination to source */
108enum mig_rp_message_type {
109 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
110 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
111 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
112
113 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
114 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
a335debb 115 MIG_RP_MSG_RECV_BITMAP, /* send recved_bitmap back to source */
13955b89 116 MIG_RP_MSG_RESUME_ACK, /* tell source that we are ready to resume */
da6f1790
JQ
117
118 MIG_RP_MSG_MAX
119};
120
17549e84
JQ
121/* When we add fault tolerance, we could have several
122 migrations at once. For now we don't need to add
123 dynamic creation of migration */
124
e5cb7e76 125static MigrationState *current_migration;
e1b1b1bc 126static MigrationIncomingState *current_incoming;
e5cb7e76 127
8b0b29dc 128static bool migration_object_check(MigrationState *ms, Error **errp);
0331c8ca
DDAG
129static int migration_maybe_pause(MigrationState *s,
130 int *current_active_state,
131 int new_state);
892ae715 132static void migrate_fd_cancel(MigrationState *s);
8b0b29dc 133
e5cb7e76
PX
134void migration_object_init(void)
135{
4ffdb337 136 MachineState *ms = MACHINE(qdev_get_machine());
8b0b29dc 137 Error *err = NULL;
4ffdb337 138
e5cb7e76
PX
139 /* This can only be called once. */
140 assert(!current_migration);
141 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
4ffdb337 142
e1b1b1bc
PX
143 /*
144 * Init the migrate incoming object as well no matter whether
145 * we'll use it or not.
146 */
147 assert(!current_incoming);
148 current_incoming = g_new0(MigrationIncomingState, 1);
149 current_incoming->state = MIGRATION_STATUS_NONE;
150 current_incoming->postcopy_remote_fds =
151 g_array_new(FALSE, TRUE, sizeof(struct PostCopyFD));
152 qemu_mutex_init(&current_incoming->rp_mutex);
153 qemu_event_init(&current_incoming->main_thread_load_event, false);
154 qemu_sem_init(&current_incoming->postcopy_pause_sem_dst, 0);
155 qemu_sem_init(&current_incoming->postcopy_pause_sem_fault, 0);
156
157 init_dirty_bitmap_incoming_migration();
158
8b0b29dc
PX
159 if (!migration_object_check(current_migration, &err)) {
160 error_report_err(err);
161 exit(1);
162 }
163
4ffdb337
PX
164 /*
165 * We cannot really do this in migration_instance_init() since at
166 * that time global properties are not yet applied, then this
167 * value will be definitely replaced by something else.
168 */
169 if (ms->enforce_config_section) {
170 current_migration->send_configuration = true;
171 }
e5cb7e76
PX
172}
173
892ae715 174void migration_shutdown(void)
1f895604 175{
892ae715
DDAG
176 /*
177 * Cancel the current migration - that will (eventually)
178 * stop the migration using this structure
179 */
180 migrate_fd_cancel(current_migration);
1f895604
VSO
181 object_unref(OBJECT(current_migration));
182}
183
bca7856a 184/* For outgoing */
859bc756 185MigrationState *migrate_get_current(void)
17549e84 186{
e5cb7e76
PX
187 /* This can only be called after the object created. */
188 assert(current_migration);
189 return current_migration;
17549e84
JQ
190}
191
bca7856a
DDAG
192MigrationIncomingState *migration_incoming_get_current(void)
193{
e1b1b1bc
PX
194 assert(current_incoming);
195 return current_incoming;
bca7856a
DDAG
196}
197
198void migration_incoming_state_destroy(void)
199{
b4b076da
JQ
200 struct MigrationIncomingState *mis = migration_incoming_get_current();
201
3482655b 202 if (mis->to_src_file) {
660819b1
PX
203 /* Tell source that we are done */
204 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
3482655b
PX
205 qemu_fclose(mis->to_src_file);
206 mis->to_src_file = NULL;
207 }
208
660819b1
PX
209 if (mis->from_src_file) {
210 qemu_fclose(mis->from_src_file);
211 mis->from_src_file = NULL;
212 }
00fa4fc8
DDAG
213 if (mis->postcopy_remote_fds) {
214 g_array_free(mis->postcopy_remote_fds, TRUE);
215 mis->postcopy_remote_fds = NULL;
216 }
660819b1 217
5089e186 218 qemu_event_reset(&mis->main_thread_load_event);
9aca82ba
JQ
219
220 if (mis->socket_address_list) {
221 qapi_free_SocketAddressList(mis->socket_address_list);
222 mis->socket_address_list = NULL;
223 }
bca7856a
DDAG
224}
225
b05dc723
JQ
226static void migrate_generate_event(int new_state)
227{
228 if (migrate_use_events()) {
3ab72385 229 qapi_event_send_migration(new_state);
b05dc723
JQ
230 }
231}
232
0f073f44
DDAG
233static bool migrate_late_block_activate(void)
234{
235 MigrationState *s;
236
237 s = migrate_get_current();
238
239 return s->enabled_capabilities[
240 MIGRATION_CAPABILITY_LATE_BLOCK_ACTIVATE];
241}
242
adde220a
DDAG
243/*
244 * Called on -incoming with a defer: uri.
245 * The migration can be started later after any parameters have been
246 * changed.
247 */
248static void deferred_incoming_migration(Error **errp)
249{
250 if (deferred_incoming) {
251 error_setg(errp, "Incoming migration already deferred");
252 }
253 deferred_incoming = true;
254}
255
da6f1790
JQ
256/*
257 * Send a message on the return channel back to the source
258 * of the migration.
259 */
d6208e35
PX
260static int migrate_send_rp_message(MigrationIncomingState *mis,
261 enum mig_rp_message_type message_type,
262 uint16_t len, void *data)
da6f1790 263{
d6208e35
PX
264 int ret = 0;
265
da6f1790
JQ
266 trace_migrate_send_rp_message((int)message_type, len);
267 qemu_mutex_lock(&mis->rp_mutex);
d6208e35
PX
268
269 /*
270 * It's possible that the file handle got lost due to network
271 * failures.
272 */
273 if (!mis->to_src_file) {
274 ret = -EIO;
275 goto error;
276 }
277
da6f1790
JQ
278 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
279 qemu_put_be16(mis->to_src_file, len);
280 qemu_put_buffer(mis->to_src_file, data, len);
281 qemu_fflush(mis->to_src_file);
d6208e35
PX
282
283 /* It's possible that qemu file got error during sending */
284 ret = qemu_file_get_error(mis->to_src_file);
285
286error:
da6f1790 287 qemu_mutex_unlock(&mis->rp_mutex);
d6208e35 288 return ret;
da6f1790
JQ
289}
290
1e2d90eb
DDAG
291/* Request a range of pages from the source VM at the given
292 * start address.
293 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
294 * as the last request (a name must have been given previously)
295 * Start: Address offset within the RB
296 * Len: Length in bytes required - must be a multiple of pagesize
297 */
d6208e35
PX
298int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
299 ram_addr_t start, size_t len)
1e2d90eb 300{
cb8d4c8f 301 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
1e2d90eb 302 size_t msglen = 12; /* start + len */
d6208e35 303 enum mig_rp_message_type msg_type;
1e2d90eb
DDAG
304
305 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
306 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
307
308 if (rbname) {
309 int rbname_len = strlen(rbname);
310 assert(rbname_len < 256);
311
312 bufc[msglen++] = rbname_len;
313 memcpy(bufc + msglen, rbname, rbname_len);
314 msglen += rbname_len;
d6208e35 315 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
1e2d90eb 316 } else {
d6208e35 317 msg_type = MIG_RP_MSG_REQ_PAGES;
1e2d90eb 318 }
d6208e35
PX
319
320 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
1e2d90eb
DDAG
321}
322
aad555c2
ZC
323static bool migration_colo_enabled;
324bool migration_incoming_colo_enabled(void)
325{
326 return migration_colo_enabled;
327}
328
329void migration_incoming_disable_colo(void)
330{
331 migration_colo_enabled = false;
332}
333
334void migration_incoming_enable_colo(void)
335{
336 migration_colo_enabled = true;
337}
338
9aca82ba
JQ
339void migrate_add_address(SocketAddress *address)
340{
341 MigrationIncomingState *mis = migration_incoming_get_current();
342 SocketAddressList *addrs;
343
344 addrs = g_new0(SocketAddressList, 1);
345 addrs->next = mis->socket_address_list;
346 mis->socket_address_list = addrs;
347 addrs->value = QAPI_CLONE(SocketAddress, address);
348}
349
43eaae28 350void qemu_start_incoming_migration(const char *uri, Error **errp)
5bb7910a 351{
34c9dd8e
AL
352 const char *p;
353
3ab72385 354 qapi_event_send_migration(MIGRATION_STATUS_SETUP);
adde220a
DDAG
355 if (!strcmp(uri, "defer")) {
356 deferred_incoming_migration(errp);
357 } else if (strstart(uri, "tcp:", &p)) {
43eaae28 358 tcp_start_incoming_migration(p, errp);
2da776db 359#ifdef CONFIG_RDMA
adde220a 360 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
361 rdma_start_incoming_migration(p, errp);
362#endif
adde220a 363 } else if (strstart(uri, "exec:", &p)) {
43eaae28 364 exec_start_incoming_migration(p, errp);
adde220a 365 } else if (strstart(uri, "unix:", &p)) {
43eaae28 366 unix_start_incoming_migration(p, errp);
adde220a 367 } else if (strstart(uri, "fd:", &p)) {
43eaae28 368 fd_start_incoming_migration(p, errp);
adde220a 369 } else {
312fd5f2 370 error_setg(errp, "unknown migration protocol: %s", uri);
8ca5e801 371 }
5bb7910a
AL
372}
373
0aa6aefc
DL
374static void process_incoming_migration_bh(void *opaque)
375{
376 Error *local_err = NULL;
377 MigrationIncomingState *mis = opaque;
378
0f073f44
DDAG
379 /* If capability late_block_activate is set:
380 * Only fire up the block code now if we're going to restart the
381 * VM, else 'cont' will do it.
382 * This causes file locking to happen; so we don't want it to happen
383 * unless we really are starting the VM.
384 */
385 if (!migrate_late_block_activate() ||
386 (autostart && (!global_state_received() ||
387 global_state_get_runstate() == RUN_STATE_RUNNING))) {
388 /* Make sure all file formats flush their mutable metadata.
389 * If we get an error here, just don't restart the VM yet. */
390 bdrv_invalidate_cache_all(&local_err);
391 if (local_err) {
392 error_report_err(local_err);
393 local_err = NULL;
394 autostart = false;
395 }
d35ff5e6
KW
396 }
397
0aa6aefc
DL
398 /*
399 * This must happen after all error conditions are dealt with and
400 * we're sure the VM is going to be running on this host.
401 */
7659505c 402 qemu_announce_self(&mis->announce_timer, migrate_announce_params());
0aa6aefc 403
f986c3d2
JQ
404 if (multifd_load_cleanup(&local_err) != 0) {
405 error_report_err(local_err);
406 autostart = false;
407 }
0aa6aefc
DL
408 /* If global state section was not received or we are in running
409 state, we need to obey autostart. Any other state is set with
410 runstate_set. */
411
b35ebdf0
VSO
412 dirty_bitmap_mig_before_vm_start();
413
0aa6aefc
DL
414 if (!global_state_received() ||
415 global_state_get_runstate() == RUN_STATE_RUNNING) {
416 if (autostart) {
417 vm_start();
418 } else {
419 runstate_set(RUN_STATE_PAUSED);
420 }
db009729
ZC
421 } else if (migration_incoming_colo_enabled()) {
422 migration_incoming_disable_colo();
423 vm_start();
0aa6aefc
DL
424 } else {
425 runstate_set(global_state_get_runstate());
426 }
0aa6aefc
DL
427 /*
428 * This must happen after any state changes since as soon as an external
429 * observer sees this event they might start to prod at the VM assuming
430 * it's ready to use.
431 */
432 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
433 MIGRATION_STATUS_COMPLETED);
434 qemu_bh_delete(mis->bh);
435 migration_incoming_state_destroy();
436}
437
82a4da79 438static void process_incoming_migration_co(void *opaque)
511c0231 439{
b4b076da 440 MigrationIncomingState *mis = migration_incoming_get_current();
e9bef235 441 PostcopyState ps;
1c12e1f5 442 int ret;
8e48ac95 443 Error *local_err = NULL;
1c12e1f5 444
4f0fae7f 445 assert(mis->from_src_file);
92370989 446 mis->migration_incoming_co = qemu_coroutine_self();
67f11b5c 447 mis->largest_page_size = qemu_ram_pagesize_largest();
093e3c42 448 postcopy_state_set(POSTCOPY_INCOMING_NONE);
93d7af6f
HZ
449 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
450 MIGRATION_STATUS_ACTIVE);
4f0fae7f 451 ret = qemu_loadvm_state(mis->from_src_file);
bca7856a 452
e9bef235
DDAG
453 ps = postcopy_state_get();
454 trace_process_incoming_migration_co_end(ret, ps);
455 if (ps != POSTCOPY_INCOMING_NONE) {
456 if (ps == POSTCOPY_INCOMING_ADVISE) {
457 /*
458 * Where a migration had postcopy enabled (and thus went to advise)
459 * but managed to complete within the precopy period, we can use
460 * the normal exit.
461 */
462 postcopy_ram_incoming_cleanup(mis);
463 } else if (ret >= 0) {
464 /*
465 * Postcopy was started, cleanup should happen at the end of the
466 * postcopy thread.
467 */
468 trace_process_incoming_migration_co_postcopy_end_main();
469 return;
470 }
471 /* Else if something went wrong then just fall out of the normal exit */
472 }
473
25d0c16f 474 /* we get COLO info, and know if we are in COLO mode */
aad555c2 475 if (!ret && migration_incoming_colo_enabled()) {
8e48ac95
ZC
476 /* Make sure all file formats flush their mutable metadata */
477 bdrv_invalidate_cache_all(&local_err);
478 if (local_err) {
8e48ac95 479 error_report_err(local_err);
6d99c2d4 480 goto fail;
8e48ac95
ZC
481 }
482
13af18f2
ZC
483 if (colo_init_ram_cache() < 0) {
484 error_report("Init ram cache failed");
6d99c2d4 485 goto fail;
13af18f2
ZC
486 }
487
25d0c16f
HZ
488 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
489 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
490 mis->have_colo_incoming_thread = true;
491 qemu_coroutine_yield();
492
493 /* Wait checkpoint incoming thread exit before free resource */
494 qemu_thread_join(&mis->colo_incoming_thread);
13af18f2
ZC
495 /* We hold the global iothread lock, so it is safe here */
496 colo_release_ram_cache();
25d0c16f
HZ
497 }
498
1c12e1f5 499 if (ret < 0) {
db80face 500 error_report("load of migration failed: %s", strerror(-ret));
6d99c2d4 501 goto fail;
511c0231 502 }
0aa6aefc
DL
503 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
504 qemu_bh_schedule(mis->bh);
92370989 505 mis->migration_incoming_co = NULL;
6d99c2d4
FL
506 return;
507fail:
508 local_err = NULL;
509 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
510 MIGRATION_STATUS_FAILED);
511 qemu_fclose(mis->from_src_file);
512 if (multifd_load_cleanup(&local_err) != 0) {
513 error_report_err(local_err);
514 }
515 exit(EXIT_FAILURE);
511c0231
JQ
516}
517
e595a01a 518static void migration_incoming_setup(QEMUFile *f)
82a4da79 519{
4f0fae7f 520 MigrationIncomingState *mis = migration_incoming_get_current();
82a4da79 521
f986c3d2
JQ
522 if (multifd_load_setup() != 0) {
523 /* We haven't been able to create multifd threads
524 nothing better to do */
525 exit(EXIT_FAILURE);
526 }
527
4f0fae7f
JQ
528 if (!mis->from_src_file) {
529 mis->from_src_file = f;
530 }
06ad5135 531 qemu_file_set_blocking(f, false);
e595a01a
JQ
532}
533
36c2f8be 534void migration_incoming_process(void)
e595a01a
JQ
535{
536 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
0b8b8753 537 qemu_coroutine_enter(co);
82a4da79
PB
538}
539
884835fa
PX
540/* Returns true if recovered from a paused migration, otherwise false */
541static bool postcopy_try_recover(QEMUFile *f)
e595a01a 542{
d96c9e8d
PX
543 MigrationIncomingState *mis = migration_incoming_get_current();
544
545 if (mis->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
546 /* Resumed from a paused postcopy migration */
547
548 mis->from_src_file = f;
549 /* Postcopy has standalone thread to do vm load */
550 qemu_file_set_blocking(f, true);
551
552 /* Re-configure the return path */
553 mis->to_src_file = qemu_file_get_return_path(f);
554
555 migrate_set_state(&mis->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
556 MIGRATION_STATUS_POSTCOPY_RECOVER);
557
558 /*
559 * Here, we only wake up the main loading thread (while the
560 * fault thread will still be waiting), so that we can receive
561 * commands from source now, and answer it if needed. The
562 * fault thread will be woken up afterwards until we are sure
563 * that source is ready to reply to page requests.
564 */
565 qemu_sem_post(&mis->postcopy_pause_sem_dst);
884835fa
PX
566 return true;
567 }
568
569 return false;
570}
571
572void migration_fd_process_incoming(QEMUFile *f)
573{
574 if (postcopy_try_recover(f)) {
575 return;
d96c9e8d 576 }
884835fa
PX
577
578 migration_incoming_setup(f);
579 migration_incoming_process();
e595a01a
JQ
580}
581
49ed0d24 582void migration_ioc_process_incoming(QIOChannel *ioc, Error **errp)
4f0fae7f
JQ
583{
584 MigrationIncomingState *mis = migration_incoming_get_current();
a429e7f4 585 bool start_migration;
4f0fae7f
JQ
586
587 if (!mis->from_src_file) {
a429e7f4 588 /* The first connection (multifd may have multiple) */
4f0fae7f 589 QEMUFile *f = qemu_fopen_channel_input(ioc);
a429e7f4
PX
590
591 /* If it's a recovery, we're done */
884835fa
PX
592 if (postcopy_try_recover(f)) {
593 return;
594 }
a429e7f4 595
36c2f8be 596 migration_incoming_setup(f);
a429e7f4
PX
597
598 /*
599 * Common migration only needs one channel, so we can start
600 * right now. Multifd needs more than one channel, we wait.
601 */
602 start_migration = !migrate_use_multifd();
603 } else {
49ed0d24 604 Error *local_err = NULL;
a429e7f4
PX
605 /* Multiple connections */
606 assert(migrate_use_multifd());
49ed0d24
FL
607 start_migration = multifd_recv_new_channel(ioc, &local_err);
608 if (local_err) {
609 error_propagate(errp, local_err);
610 return;
611 }
4f0fae7f 612 }
81e62053 613
a429e7f4 614 if (start_migration) {
81e62053
PX
615 migration_incoming_process();
616 }
4f0fae7f
JQ
617}
618
428d8908
JQ
619/**
620 * @migration_has_all_channels: We have received all channels that we need
621 *
622 * Returns true when we have got connections to all the channels that
623 * we need for migration.
624 */
625bool migration_has_all_channels(void)
626{
ca273df3 627 MigrationIncomingState *mis = migration_incoming_get_current();
62c1e0ca
JQ
628 bool all_channels;
629
630 all_channels = multifd_recv_all_channels_created();
631
ca273df3 632 return all_channels && mis->from_src_file != NULL;
428d8908
JQ
633}
634
6decec93
DDAG
635/*
636 * Send a 'SHUT' message on the return channel with the given value
637 * to indicate that we've finished with the RP. Non-0 value indicates
638 * error.
639 */
640void migrate_send_rp_shut(MigrationIncomingState *mis,
641 uint32_t value)
642{
643 uint32_t buf;
644
645 buf = cpu_to_be32(value);
646 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
647}
648
649/*
650 * Send a 'PONG' message on the return channel with the given value
651 * (normally in response to a 'PING')
652 */
653void migrate_send_rp_pong(MigrationIncomingState *mis,
654 uint32_t value)
655{
656 uint32_t buf;
657
658 buf = cpu_to_be32(value);
659 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
660}
661
a335debb
PX
662void migrate_send_rp_recv_bitmap(MigrationIncomingState *mis,
663 char *block_name)
664{
665 char buf[512];
666 int len;
667 int64_t res;
668
669 /*
670 * First, we send the header part. It contains only the len of
671 * idstr, and the idstr itself.
672 */
673 len = strlen(block_name);
674 buf[0] = len;
675 memcpy(buf + 1, block_name, len);
676
677 if (mis->state != MIGRATION_STATUS_POSTCOPY_RECOVER) {
678 error_report("%s: MSG_RP_RECV_BITMAP only used for recovery",
679 __func__);
680 return;
681 }
682
683 migrate_send_rp_message(mis, MIG_RP_MSG_RECV_BITMAP, len + 1, buf);
684
685 /*
686 * Next, we dump the received bitmap to the stream.
687 *
688 * TODO: currently we are safe since we are the only one that is
689 * using the to_src_file handle (fault thread is still paused),
690 * and it's ok even not taking the mutex. However the best way is
691 * to take the lock before sending the message header, and release
692 * the lock after sending the bitmap.
693 */
694 qemu_mutex_lock(&mis->rp_mutex);
695 res = ramblock_recv_bitmap_send(mis->to_src_file, block_name);
696 qemu_mutex_unlock(&mis->rp_mutex);
697
698 trace_migrate_send_rp_recv_bitmap(block_name, res);
699}
700
13955b89
PX
701void migrate_send_rp_resume_ack(MigrationIncomingState *mis, uint32_t value)
702{
703 uint32_t buf;
704
705 buf = cpu_to_be32(value);
706 migrate_send_rp_message(mis, MIG_RP_MSG_RESUME_ACK, sizeof(buf), &buf);
707}
708
bbf6da32
OW
709MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
710{
711 MigrationCapabilityStatusList *head = NULL;
712 MigrationCapabilityStatusList *caps;
713 MigrationState *s = migrate_get_current();
714 int i;
715
387eedeb 716 caps = NULL; /* silence compiler warning */
7fb1cf16 717 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
ed1701c6
DDAG
718#ifndef CONFIG_LIVE_BLOCK_MIGRATION
719 if (i == MIGRATION_CAPABILITY_BLOCK) {
720 continue;
721 }
722#endif
bbf6da32
OW
723 if (head == NULL) {
724 head = g_malloc0(sizeof(*caps));
725 caps = head;
726 } else {
727 caps->next = g_malloc0(sizeof(*caps));
728 caps = caps->next;
729 }
730 caps->value =
731 g_malloc(sizeof(*caps->value));
732 caps->value->capability = i;
733 caps->value->state = s->enabled_capabilities[i];
734 }
735
736 return head;
737}
738
85de8323
LL
739MigrationParameters *qmp_query_migrate_parameters(Error **errp)
740{
741 MigrationParameters *params;
742 MigrationState *s = migrate_get_current();
743
e87fae4c 744 /* TODO use QAPI_CLONE() instead of duplicating it inline */
85de8323 745 params = g_malloc0(sizeof(*params));
de63ab61 746 params->has_compress_level = true;
2594f56d 747 params->compress_level = s->parameters.compress_level;
de63ab61 748 params->has_compress_threads = true;
2594f56d 749 params->compress_threads = s->parameters.compress_threads;
1d58872a
XG
750 params->has_compress_wait_thread = true;
751 params->compress_wait_thread = s->parameters.compress_wait_thread;
de63ab61 752 params->has_decompress_threads = true;
2594f56d 753 params->decompress_threads = s->parameters.decompress_threads;
de63ab61 754 params->has_cpu_throttle_initial = true;
2594f56d 755 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
de63ab61 756 params->has_cpu_throttle_increment = true;
2594f56d 757 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
8cc99dcd 758 params->has_tls_creds = true;
69ef1f36 759 params->tls_creds = g_strdup(s->parameters.tls_creds);
8cc99dcd 760 params->has_tls_hostname = true;
69ef1f36 761 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
d2f1d29b
DB
762 params->has_tls_authz = true;
763 params->tls_authz = g_strdup(s->parameters.tls_authz);
2ff30257
AA
764 params->has_max_bandwidth = true;
765 params->max_bandwidth = s->parameters.max_bandwidth;
766 params->has_downtime_limit = true;
767 params->downtime_limit = s->parameters.downtime_limit;
fe39a4d4 768 params->has_x_checkpoint_delay = true;
68b53591 769 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
2833c59b
JQ
770 params->has_block_incremental = true;
771 params->block_incremental = s->parameters.block_incremental;
cbfd6c95
JQ
772 params->has_multifd_channels = true;
773 params->multifd_channels = s->parameters.multifd_channels;
73af8dd8
JQ
774 params->has_xbzrle_cache_size = true;
775 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
7e555c6c
DDAG
776 params->has_max_postcopy_bandwidth = true;
777 params->max_postcopy_bandwidth = s->parameters.max_postcopy_bandwidth;
4cbc9c7f
LQ
778 params->has_max_cpu_throttle = true;
779 params->max_cpu_throttle = s->parameters.max_cpu_throttle;
ee3d96ba
DDAG
780 params->has_announce_initial = true;
781 params->announce_initial = s->parameters.announce_initial;
782 params->has_announce_max = true;
783 params->announce_max = s->parameters.announce_max;
784 params->has_announce_rounds = true;
785 params->announce_rounds = s->parameters.announce_rounds;
786 params->has_announce_step = true;
787 params->announce_step = s->parameters.announce_step;
85de8323
LL
788
789 return params;
790}
791
ee3d96ba
DDAG
792AnnounceParameters *migrate_announce_params(void)
793{
794 static AnnounceParameters ap;
795
796 MigrationState *s = migrate_get_current();
797
798 ap.initial = s->parameters.announce_initial;
799 ap.max = s->parameters.announce_max;
800 ap.rounds = s->parameters.announce_rounds;
801 ap.step = s->parameters.announce_step;
802
803 return &ap;
804}
805
f6844b99
DDAG
806/*
807 * Return true if we're already in the middle of a migration
808 * (i.e. any of the active or setup states)
809 */
3d63da16 810bool migration_is_setup_or_active(int state)
f6844b99
DDAG
811{
812 switch (state) {
813 case MIGRATION_STATUS_ACTIVE:
9ec055ae 814 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
a688d2c1 815 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 816 case MIGRATION_STATUS_POSTCOPY_RECOVER:
f6844b99 817 case MIGRATION_STATUS_SETUP:
31e06077
DDAG
818 case MIGRATION_STATUS_PRE_SWITCHOVER:
819 case MIGRATION_STATUS_DEVICE:
f6844b99
DDAG
820 return true;
821
822 default:
823 return false;
824
825 }
826}
827
a22463a5
DDAG
828static void populate_ram_info(MigrationInfo *info, MigrationState *s)
829{
830 info->has_ram = true;
831 info->ram = g_malloc0(sizeof(*info->ram));
9360447d 832 info->ram->transferred = ram_counters.transferred;
a22463a5 833 info->ram->total = ram_bytes_total();
9360447d 834 info->ram->duplicate = ram_counters.duplicate;
bedf53c1
JQ
835 /* legacy value. It is not used anymore */
836 info->ram->skipped = 0;
9360447d
JQ
837 info->ram->normal = ram_counters.normal;
838 info->ram->normal_bytes = ram_counters.normal *
20afaed9 839 qemu_target_page_size();
a22463a5 840 info->ram->mbps = s->mbps;
9360447d
JQ
841 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
842 info->ram->postcopy_requests = ram_counters.postcopy_requests;
030ce1f8 843 info->ram->page_size = qemu_target_page_size();
a61c45bd 844 info->ram->multifd_bytes = ram_counters.multifd_bytes;
aecbfe9c 845 info->ram->pages_per_second = s->pages_per_second;
a22463a5 846
114f5aee
JQ
847 if (migrate_use_xbzrle()) {
848 info->has_xbzrle_cache = true;
849 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
850 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
9360447d
JQ
851 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
852 info->xbzrle_cache->pages = xbzrle_counters.pages;
853 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
854 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
855 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
114f5aee
JQ
856 }
857
76e03000
XG
858 if (migrate_use_compression()) {
859 info->has_compression = true;
860 info->compression = g_malloc0(sizeof(*info->compression));
861 info->compression->pages = compression_counters.pages;
862 info->compression->busy = compression_counters.busy;
863 info->compression->busy_rate = compression_counters.busy_rate;
864 info->compression->compressed_size =
865 compression_counters.compressed_size;
866 info->compression->compression_rate =
867 compression_counters.compression_rate;
868 }
869
338182c8
JQ
870 if (cpu_throttle_active()) {
871 info->has_cpu_throttle_percentage = true;
872 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
873 }
874
a22463a5
DDAG
875 if (s->state != MIGRATION_STATUS_COMPLETED) {
876 info->ram->remaining = ram_bytes_remaining();
9360447d 877 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
a22463a5
DDAG
878 }
879}
880
930ac04c
JQ
881static void populate_disk_info(MigrationInfo *info)
882{
883 if (blk_mig_active()) {
884 info->has_disk = true;
885 info->disk = g_malloc0(sizeof(*info->disk));
886 info->disk->transferred = blk_mig_bytes_transferred();
887 info->disk->remaining = blk_mig_bytes_remaining();
888 info->disk->total = blk_mig_bytes_total();
889 }
890}
891
65ace060 892static void fill_source_migration_info(MigrationInfo *info)
5bb7910a 893{
17549e84
JQ
894 MigrationState *s = migrate_get_current();
895
896 switch (s->state) {
31194731 897 case MIGRATION_STATUS_NONE:
17549e84 898 /* no migration has happened ever */
65ace060
AP
899 /* do not overwrite destination migration status */
900 return;
17549e84 901 break;
31194731 902 case MIGRATION_STATUS_SETUP:
29ae8a41 903 info->has_status = true;
ed4fbd10 904 info->has_total_time = false;
29ae8a41 905 break;
31194731
HZ
906 case MIGRATION_STATUS_ACTIVE:
907 case MIGRATION_STATUS_CANCELLING:
9ec055ae 908 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
31e06077
DDAG
909 case MIGRATION_STATUS_PRE_SWITCHOVER:
910 case MIGRATION_STATUS_DEVICE:
a688d2c1 911 case MIGRATION_STATUS_POSTCOPY_PAUSED:
135b87b4 912 case MIGRATION_STATUS_POSTCOPY_RECOVER:
c8f9f4f4 913 /* TODO add some postcopy stats */
9ec055ae
DDAG
914 info->has_status = true;
915 info->has_total_time = true;
916 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
4af246a3 917 - s->start_time;
9ec055ae
DDAG
918 info->has_expected_downtime = true;
919 info->expected_downtime = s->expected_downtime;
920 info->has_setup_time = true;
921 info->setup_time = s->setup_time;
922
a22463a5 923 populate_ram_info(info, s);
930ac04c 924 populate_disk_info(info);
17549e84 925 break;
0b827d5e
HZ
926 case MIGRATION_STATUS_COLO:
927 info->has_status = true;
928 /* TODO: display COLO specific information (checkpoint info etc.) */
929 break;
31194731 930 case MIGRATION_STATUS_COMPLETED:
791e7c82 931 info->has_status = true;
00c14997 932 info->has_total_time = true;
7aa939af 933 info->total_time = s->total_time;
9c5a9fcf
JQ
934 info->has_downtime = true;
935 info->downtime = s->downtime;
ed4fbd10
MH
936 info->has_setup_time = true;
937 info->setup_time = s->setup_time;
d5f8a570 938
a22463a5 939 populate_ram_info(info, s);
17549e84 940 break;
31194731 941 case MIGRATION_STATUS_FAILED:
791e7c82 942 info->has_status = true;
d59ce6f3
DB
943 if (s->error) {
944 info->has_error_desc = true;
945 info->error_desc = g_strdup(error_get_pretty(s->error));
946 }
17549e84 947 break;
31194731 948 case MIGRATION_STATUS_CANCELLED:
791e7c82 949 info->has_status = true;
17549e84 950 break;
5bb7910a 951 }
cde63fbe 952 info->status = s->state;
5bb7910a
AL
953}
954
4a84214e
PX
955/**
956 * @migration_caps_check - check capability validity
957 *
958 * @cap_list: old capability list, array of bool
959 * @params: new capabilities to be applied soon
960 * @errp: set *errp if the check failed, with reason
961 *
962 * Returns true if check passed, otherwise false.
963 */
964static bool migrate_caps_check(bool *cap_list,
965 MigrationCapabilityStatusList *params,
966 Error **errp)
00458433 967{
00458433 968 MigrationCapabilityStatusList *cap;
4a84214e 969 bool old_postcopy_cap;
d7651f15 970 MigrationIncomingState *mis = migration_incoming_get_current();
00458433 971
4a84214e 972 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
00458433
OW
973
974 for (cap = params; cap; cap = cap->next) {
4a84214e
PX
975 cap_list[cap->value->capability] = cap->value->state;
976 }
977
ed1701c6 978#ifndef CONFIG_LIVE_BLOCK_MIGRATION
4a84214e
PX
979 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
980 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
981 "block migration");
982 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
983 return false;
00458433 984 }
4a84214e 985#endif
53dd370c 986
7e934f5b
ZC
987#ifndef CONFIG_REPLICATION
988 if (cap_list[MIGRATION_CAPABILITY_X_COLO]) {
989 error_setg(errp, "QEMU compiled without replication module"
990 " can't enable COLO");
991 error_append_hint(errp, "Please enable replication before COLO.\n");
992 return false;
993 }
994#endif
995
4a84214e
PX
996 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
997 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
53dd370c
DDAG
998 /* The decompression threads asynchronously write into RAM
999 * rather than use the atomic copies needed to avoid
1000 * userfaulting. It should be possible to fix the decompression
1001 * threads for compatibility in future.
1002 */
4a84214e
PX
1003 error_setg(errp, "Postcopy is not currently compatible "
1004 "with compression");
1005 return false;
53dd370c 1006 }
4a84214e 1007
096631bd
DDAG
1008 /* This check is reasonably expensive, so only when it's being
1009 * set the first time, also it's only the destination that needs
1010 * special support.
1011 */
1012 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
d7651f15 1013 !postcopy_ram_supported_by_host(mis)) {
096631bd
DDAG
1014 /* postcopy_ram_supported_by_host will have emitted a more
1015 * detailed message
1016 */
4a84214e
PX
1017 error_setg(errp, "Postcopy is not supported");
1018 return false;
096631bd 1019 }
18269069
YK
1020
1021 if (cap_list[MIGRATION_CAPABILITY_X_IGNORE_SHARED]) {
1022 error_setg(errp, "Postcopy is not compatible with ignore-shared");
1023 return false;
1024 }
53dd370c 1025 }
4a84214e
PX
1026
1027 return true;
1028}
1029
65ace060
AP
1030static void fill_destination_migration_info(MigrationInfo *info)
1031{
1032 MigrationIncomingState *mis = migration_incoming_get_current();
1033
9aca82ba
JQ
1034 if (mis->socket_address_list) {
1035 info->has_socket_address = true;
1036 info->socket_address =
1037 QAPI_CLONE(SocketAddressList, mis->socket_address_list);
1038 }
1039
65ace060
AP
1040 switch (mis->state) {
1041 case MIGRATION_STATUS_NONE:
1042 return;
1043 break;
1044 case MIGRATION_STATUS_SETUP:
1045 case MIGRATION_STATUS_CANCELLING:
1046 case MIGRATION_STATUS_CANCELLED:
1047 case MIGRATION_STATUS_ACTIVE:
1048 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
3c9928d9
PX
1049 case MIGRATION_STATUS_POSTCOPY_PAUSED:
1050 case MIGRATION_STATUS_POSTCOPY_RECOVER:
65ace060
AP
1051 case MIGRATION_STATUS_FAILED:
1052 case MIGRATION_STATUS_COLO:
1053 info->has_status = true;
1054 break;
1055 case MIGRATION_STATUS_COMPLETED:
1056 info->has_status = true;
1057 fill_destination_postcopy_migration_info(info);
1058 break;
1059 }
1060 info->status = mis->state;
1061}
1062
1063MigrationInfo *qmp_query_migrate(Error **errp)
1064{
1065 MigrationInfo *info = g_malloc0(sizeof(*info));
1066
1067 fill_destination_migration_info(info);
1068 fill_source_migration_info(info);
1069
1070 return info;
1071}
1072
4a84214e
PX
1073void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
1074 Error **errp)
1075{
1076 MigrationState *s = migrate_get_current();
1077 MigrationCapabilityStatusList *cap;
dd0ee30c 1078 bool cap_list[MIGRATION_CAPABILITY__MAX];
4a84214e
PX
1079
1080 if (migration_is_setup_or_active(s->state)) {
1081 error_setg(errp, QERR_MIGRATION_ACTIVE);
1082 return;
1083 }
1084
dd0ee30c
PX
1085 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
1086 if (!migrate_caps_check(cap_list, params, errp)) {
4a84214e
PX
1087 return;
1088 }
1089
1090 for (cap = params; cap; cap = cap->next) {
1091 s->enabled_capabilities[cap->value->capability] = cap->value->state;
1092 }
00458433
OW
1093}
1094
16d063bc
PX
1095/*
1096 * Check whether the parameters are valid. Error will be put into errp
1097 * (if provided). Return true if valid, otherwise false.
1098 */
1099static bool migrate_params_check(MigrationParameters *params, Error **errp)
85de8323 1100{
7f375e04 1101 if (params->has_compress_level &&
741d4086 1102 (params->compress_level > 9)) {
c6bd8c70
MA
1103 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
1104 "is invalid, it should be in the range of 0 to 9");
16d063bc 1105 return false;
85de8323 1106 }
16d063bc 1107
741d4086 1108 if (params->has_compress_threads && (params->compress_threads < 1)) {
c6bd8c70
MA
1109 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1110 "compress_threads",
1111 "is invalid, it should be in the range of 1 to 255");
16d063bc 1112 return false;
85de8323 1113 }
16d063bc 1114
741d4086 1115 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
c6bd8c70
MA
1116 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1117 "decompress_threads",
1118 "is invalid, it should be in the range of 1 to 255");
16d063bc 1119 return false;
85de8323 1120 }
16d063bc 1121
7f375e04
EB
1122 if (params->has_cpu_throttle_initial &&
1123 (params->cpu_throttle_initial < 1 ||
1124 params->cpu_throttle_initial > 99)) {
1626fee3 1125 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 1126 "cpu_throttle_initial",
1626fee3 1127 "an integer in the range of 1 to 99");
16d063bc 1128 return false;
1626fee3 1129 }
16d063bc 1130
7f375e04
EB
1131 if (params->has_cpu_throttle_increment &&
1132 (params->cpu_throttle_increment < 1 ||
1133 params->cpu_throttle_increment > 99)) {
1626fee3 1134 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
d85a31d1 1135 "cpu_throttle_increment",
1626fee3 1136 "an integer in the range of 1 to 99");
16d063bc 1137 return false;
1626fee3 1138 }
16d063bc 1139
741d4086 1140 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
2ff30257
AA
1141 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
1142 " range of 0 to %zu bytes/second", SIZE_MAX);
16d063bc 1143 return false;
2ff30257 1144 }
16d063bc 1145
2ff30257 1146 if (params->has_downtime_limit &&
741d4086 1147 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
87c9cc1c
DHB
1148 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1149 "the range of 0 to %d milliseconds",
1150 MAX_MIGRATE_DOWNTIME);
16d063bc 1151 return false;
2ff30257 1152 }
16d063bc 1153
741d4086
JQ
1154 /* x_checkpoint_delay is now always positive */
1155
cbfd6c95 1156 if (params->has_multifd_channels && (params->multifd_channels < 1)) {
4075fb1c
JQ
1157 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1158 "multifd_channels",
1159 "is invalid, it should be in the range of 1 to 255");
1160 return false;
1161 }
16d063bc 1162
73af8dd8
JQ
1163 if (params->has_xbzrle_cache_size &&
1164 (params->xbzrle_cache_size < qemu_target_page_size() ||
1165 !is_power_of_2(params->xbzrle_cache_size))) {
1166 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1167 "xbzrle_cache_size",
1168 "is invalid, it should be bigger than target page size"
1169 " and a power of two");
1170 return false;
1171 }
1172
4cbc9c7f
LQ
1173 if (params->has_max_cpu_throttle &&
1174 (params->max_cpu_throttle < params->cpu_throttle_initial ||
1175 params->max_cpu_throttle > 99)) {
1176 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1177 "max_cpu_throttle",
1178 "an integer in the range of cpu_throttle_initial to 99");
1179 return false;
1180 }
1181
ee3d96ba
DDAG
1182 if (params->has_announce_initial &&
1183 params->announce_initial > 100000) {
1184 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1185 "announce_initial",
1186 "is invalid, it must be less than 100000 ms");
1187 return false;
1188 }
1189 if (params->has_announce_max &&
1190 params->announce_max > 100000) {
1191 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1192 "announce_max",
1193 "is invalid, it must be less than 100000 ms");
1194 return false;
1195 }
1196 if (params->has_announce_rounds &&
1197 params->announce_rounds > 1000) {
1198 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1199 "announce_rounds",
1200 "is invalid, it must be in the range of 0 to 1000");
1201 return false;
1202 }
1203 if (params->has_announce_step &&
1204 (params->announce_step < 1 ||
1205 params->announce_step > 10000)) {
1206 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
1207 "announce_step",
1208 "is invalid, it must be in the range of 1 to 10000 ms");
1209 return false;
1210 }
16d063bc
PX
1211 return true;
1212}
1213
1bda8b3c
MA
1214static void migrate_params_test_apply(MigrateSetParameters *params,
1215 MigrationParameters *dest)
1216{
1217 *dest = migrate_get_current()->parameters;
1218
1219 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1220
1221 if (params->has_compress_level) {
1222 dest->compress_level = params->compress_level;
1223 }
1224
1225 if (params->has_compress_threads) {
1226 dest->compress_threads = params->compress_threads;
1227 }
1228
1d58872a
XG
1229 if (params->has_compress_wait_thread) {
1230 dest->compress_wait_thread = params->compress_wait_thread;
1231 }
1232
1bda8b3c
MA
1233 if (params->has_decompress_threads) {
1234 dest->decompress_threads = params->decompress_threads;
1235 }
1236
1237 if (params->has_cpu_throttle_initial) {
1238 dest->cpu_throttle_initial = params->cpu_throttle_initial;
1239 }
1240
1241 if (params->has_cpu_throttle_increment) {
1242 dest->cpu_throttle_increment = params->cpu_throttle_increment;
1243 }
1244
1245 if (params->has_tls_creds) {
01fa5598
MA
1246 assert(params->tls_creds->type == QTYPE_QSTRING);
1247 dest->tls_creds = g_strdup(params->tls_creds->u.s);
1bda8b3c
MA
1248 }
1249
1250 if (params->has_tls_hostname) {
01fa5598
MA
1251 assert(params->tls_hostname->type == QTYPE_QSTRING);
1252 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
1bda8b3c
MA
1253 }
1254
1255 if (params->has_max_bandwidth) {
1256 dest->max_bandwidth = params->max_bandwidth;
1257 }
1258
1259 if (params->has_downtime_limit) {
1260 dest->downtime_limit = params->downtime_limit;
1261 }
1262
1263 if (params->has_x_checkpoint_delay) {
1264 dest->x_checkpoint_delay = params->x_checkpoint_delay;
1265 }
1266
1267 if (params->has_block_incremental) {
1268 dest->block_incremental = params->block_incremental;
1269 }
cbfd6c95
JQ
1270 if (params->has_multifd_channels) {
1271 dest->multifd_channels = params->multifd_channels;
5e7577a1 1272 }
73af8dd8
JQ
1273 if (params->has_xbzrle_cache_size) {
1274 dest->xbzrle_cache_size = params->xbzrle_cache_size;
1275 }
7e555c6c
DDAG
1276 if (params->has_max_postcopy_bandwidth) {
1277 dest->max_postcopy_bandwidth = params->max_postcopy_bandwidth;
1278 }
4cbc9c7f
LQ
1279 if (params->has_max_cpu_throttle) {
1280 dest->max_cpu_throttle = params->max_cpu_throttle;
1281 }
ee3d96ba
DDAG
1282 if (params->has_announce_initial) {
1283 dest->announce_initial = params->announce_initial;
1284 }
1285 if (params->has_announce_max) {
1286 dest->announce_max = params->announce_max;
1287 }
1288 if (params->has_announce_rounds) {
1289 dest->announce_rounds = params->announce_rounds;
1290 }
1291 if (params->has_announce_step) {
1292 dest->announce_step = params->announce_step;
1293 }
1bda8b3c
MA
1294}
1295
73af8dd8 1296static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
16d063bc
PX
1297{
1298 MigrationState *s = migrate_get_current();
1299
e87fae4c
MA
1300 /* TODO use QAPI_CLONE() instead of duplicating it inline */
1301
7f375e04
EB
1302 if (params->has_compress_level) {
1303 s->parameters.compress_level = params->compress_level;
85de8323 1304 }
476c72aa 1305
7f375e04
EB
1306 if (params->has_compress_threads) {
1307 s->parameters.compress_threads = params->compress_threads;
85de8323 1308 }
476c72aa 1309
1d58872a
XG
1310 if (params->has_compress_wait_thread) {
1311 s->parameters.compress_wait_thread = params->compress_wait_thread;
1312 }
1313
7f375e04
EB
1314 if (params->has_decompress_threads) {
1315 s->parameters.decompress_threads = params->decompress_threads;
85de8323 1316 }
476c72aa 1317
7f375e04
EB
1318 if (params->has_cpu_throttle_initial) {
1319 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
1626fee3 1320 }
476c72aa 1321
7f375e04
EB
1322 if (params->has_cpu_throttle_increment) {
1323 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
1626fee3 1324 }
476c72aa 1325
7f375e04 1326 if (params->has_tls_creds) {
69ef1f36 1327 g_free(s->parameters.tls_creds);
01fa5598
MA
1328 assert(params->tls_creds->type == QTYPE_QSTRING);
1329 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
69ef1f36 1330 }
476c72aa 1331
7f375e04 1332 if (params->has_tls_hostname) {
69ef1f36 1333 g_free(s->parameters.tls_hostname);
01fa5598
MA
1334 assert(params->tls_hostname->type == QTYPE_QSTRING);
1335 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
69ef1f36 1336 }
476c72aa 1337
d2f1d29b
DB
1338 if (params->has_tls_authz) {
1339 g_free(s->parameters.tls_authz);
1340 assert(params->tls_authz->type == QTYPE_QSTRING);
1341 s->parameters.tls_authz = g_strdup(params->tls_authz->u.s);
1342 }
1343
2ff30257
AA
1344 if (params->has_max_bandwidth) {
1345 s->parameters.max_bandwidth = params->max_bandwidth;
c38c1c14 1346 if (s->to_dst_file && !migration_in_postcopy()) {
2ff30257
AA
1347 qemu_file_set_rate_limit(s->to_dst_file,
1348 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1349 }
1350 }
476c72aa 1351
2ff30257
AA
1352 if (params->has_downtime_limit) {
1353 s->parameters.downtime_limit = params->downtime_limit;
1354 }
68b53591
HZ
1355
1356 if (params->has_x_checkpoint_delay) {
1357 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
479125d5
HZ
1358 if (migration_in_colo_state()) {
1359 colo_checkpoint_notify(s);
1360 }
68b53591 1361 }
476c72aa 1362
2833c59b
JQ
1363 if (params->has_block_incremental) {
1364 s->parameters.block_incremental = params->block_incremental;
1365 }
cbfd6c95
JQ
1366 if (params->has_multifd_channels) {
1367 s->parameters.multifd_channels = params->multifd_channels;
4075fb1c 1368 }
73af8dd8
JQ
1369 if (params->has_xbzrle_cache_size) {
1370 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1371 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1372 }
7e555c6c
DDAG
1373 if (params->has_max_postcopy_bandwidth) {
1374 s->parameters.max_postcopy_bandwidth = params->max_postcopy_bandwidth;
c38c1c14
DDAG
1375 if (s->to_dst_file && migration_in_postcopy()) {
1376 qemu_file_set_rate_limit(s->to_dst_file,
1377 s->parameters.max_postcopy_bandwidth / XFER_LIMIT_RATIO);
1378 }
7e555c6c 1379 }
4cbc9c7f
LQ
1380 if (params->has_max_cpu_throttle) {
1381 s->parameters.max_cpu_throttle = params->max_cpu_throttle;
1382 }
ee3d96ba
DDAG
1383 if (params->has_announce_initial) {
1384 s->parameters.announce_initial = params->announce_initial;
1385 }
1386 if (params->has_announce_max) {
1387 s->parameters.announce_max = params->announce_max;
1388 }
1389 if (params->has_announce_rounds) {
1390 s->parameters.announce_rounds = params->announce_rounds;
1391 }
1392 if (params->has_announce_step) {
1393 s->parameters.announce_step = params->announce_step;
1394 }
85de8323
LL
1395}
1396
1bda8b3c 1397void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
476c72aa 1398{
1bda8b3c
MA
1399 MigrationParameters tmp;
1400
01fa5598
MA
1401 /* TODO Rewrite "" to null instead */
1402 if (params->has_tls_creds
1403 && params->tls_creds->type == QTYPE_QNULL) {
cb3e7f08 1404 qobject_unref(params->tls_creds->u.n);
01fa5598
MA
1405 params->tls_creds->type = QTYPE_QSTRING;
1406 params->tls_creds->u.s = strdup("");
1407 }
1408 /* TODO Rewrite "" to null instead */
1409 if (params->has_tls_hostname
1410 && params->tls_hostname->type == QTYPE_QNULL) {
cb3e7f08 1411 qobject_unref(params->tls_hostname->u.n);
01fa5598
MA
1412 params->tls_hostname->type = QTYPE_QSTRING;
1413 params->tls_hostname->u.s = strdup("");
1414 }
1415
1bda8b3c
MA
1416 migrate_params_test_apply(params, &tmp);
1417
1418 if (!migrate_params_check(&tmp, errp)) {
476c72aa
PX
1419 /* Invalid parameter */
1420 return;
1421 }
1422
73af8dd8 1423 migrate_params_apply(params, errp);
476c72aa
PX
1424}
1425
2594f56d 1426
4886a1bc
DDAG
1427void qmp_migrate_start_postcopy(Error **errp)
1428{
1429 MigrationState *s = migrate_get_current();
1430
16b0fd32 1431 if (!migrate_postcopy()) {
a54d340b 1432 error_setg(errp, "Enable postcopy with migrate_set_capability before"
4886a1bc
DDAG
1433 " the start of migration");
1434 return;
1435 }
1436
1437 if (s->state == MIGRATION_STATUS_NONE) {
1438 error_setg(errp, "Postcopy must be started after migration has been"
1439 " started");
1440 return;
1441 }
1442 /*
1443 * we don't error if migration has finished since that would be racy
1444 * with issuing this command.
1445 */
1446 atomic_set(&s->start_postcopy, true);
1447}
1448
065e2813
AL
1449/* shared migration helpers */
1450
48781e5b 1451void migrate_set_state(int *state, int old_state, int new_state)
51cf4c1a 1452{
a31fedee 1453 assert(new_state < MIGRATION_STATUS__MAX);
48781e5b 1454 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
a31fedee 1455 trace_migrate_set_state(MigrationStatus_str(new_state));
b05dc723 1456 migrate_generate_event(new_state);
51cf4c1a
Z
1457 }
1458}
1459
4e4a3d3a
PX
1460static MigrationCapabilityStatusList *migrate_cap_add(
1461 MigrationCapabilityStatusList *list,
1462 MigrationCapability index,
1463 bool state)
2833c59b
JQ
1464{
1465 MigrationCapabilityStatusList *cap;
1466
1467 cap = g_new0(MigrationCapabilityStatusList, 1);
1468 cap->value = g_new0(MigrationCapabilityStatus, 1);
4e4a3d3a
PX
1469 cap->value->capability = index;
1470 cap->value->state = state;
1471 cap->next = list;
1472
1473 return cap;
1474}
1475
1476void migrate_set_block_enabled(bool value, Error **errp)
1477{
1478 MigrationCapabilityStatusList *cap;
1479
1480 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
2833c59b
JQ
1481 qmp_migrate_set_capabilities(cap, errp);
1482 qapi_free_MigrationCapabilityStatusList(cap);
1483}
1484
1485static void migrate_set_block_incremental(MigrationState *s, bool value)
1486{
1487 s->parameters.block_incremental = value;
1488}
1489
1490static void block_cleanup_parameters(MigrationState *s)
1491{
1492 if (s->must_remove_block_options) {
1493 /* setting to false can never fail */
1494 migrate_set_block_enabled(false, &error_abort);
1495 migrate_set_block_incremental(s, false);
1496 s->must_remove_block_options = false;
1497 }
1498}
1499
fd392cfa 1500static void migrate_fd_cleanup(MigrationState *s)
065e2813 1501{
bb1fadc4
PB
1502 qemu_bh_delete(s->cleanup_bh);
1503 s->cleanup_bh = NULL;
1504
0ceccd85
PX
1505 qemu_savevm_state_cleanup();
1506
89a02a9f 1507 if (s->to_dst_file) {
62df066f 1508 QEMUFile *tmp;
f986c3d2 1509
9013dca5 1510 trace_migrate_fd_cleanup();
404a7c05 1511 qemu_mutex_unlock_iothread();
1d34e4bf
DDAG
1512 if (s->migration_thread_running) {
1513 qemu_thread_join(&s->thread);
1514 s->migration_thread_running = false;
1515 }
404a7c05
PB
1516 qemu_mutex_lock_iothread();
1517
1398b2e3 1518 multifd_save_cleanup();
62df066f
PX
1519 qemu_mutex_lock(&s->qemu_file_lock);
1520 tmp = s->to_dst_file;
89a02a9f 1521 s->to_dst_file = NULL;
62df066f
PX
1522 qemu_mutex_unlock(&s->qemu_file_lock);
1523 /*
1524 * Close the file handle without the lock to make sure the
1525 * critical section won't block for long.
1526 */
1527 qemu_fclose(tmp);
065e2813
AL
1528 }
1529
9ec055ae
DDAG
1530 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1531 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
7a2c1721 1532
94f5a437 1533 if (s->state == MIGRATION_STATUS_CANCELLING) {
48781e5b 1534 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
94f5a437 1535 MIGRATION_STATUS_CANCELLED);
7a2c1721 1536 }
a3fa1d78 1537
87db1a7d
JQ
1538 if (s->error) {
1539 /* It is used on info migrate. We can't free it */
1540 error_report_err(error_copy(s->error));
1541 }
a3fa1d78 1542 notifier_list_notify(&migration_state_notifiers, s);
2833c59b 1543 block_cleanup_parameters(s);
065e2813
AL
1544}
1545
fd392cfa
YK
1546static void migrate_fd_cleanup_schedule(MigrationState *s)
1547{
1548 /*
1549 * Ref the state for bh, because it may be called when
1550 * there're already no other refs
1551 */
1552 object_ref(OBJECT(s));
1553 qemu_bh_schedule(s->cleanup_bh);
1554}
1555
1556static void migrate_fd_cleanup_bh(void *opaque)
1557{
1558 MigrationState *s = opaque;
1559 migrate_fd_cleanup(s);
1560 object_unref(OBJECT(s));
1561}
1562
87db1a7d
JQ
1563void migrate_set_error(MigrationState *s, const Error *error)
1564{
1565 qemu_mutex_lock(&s->error_mutex);
1566 if (!s->error) {
1567 s->error = error_copy(error);
1568 }
1569 qemu_mutex_unlock(&s->error_mutex);
1570}
1571
d59ce6f3 1572void migrate_fd_error(MigrationState *s, const Error *error)
065e2813 1573{
25174055 1574 trace_migrate_fd_error(error_get_pretty(error));
89a02a9f 1575 assert(s->to_dst_file == NULL);
48781e5b
HZ
1576 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1577 MIGRATION_STATUS_FAILED);
87db1a7d 1578 migrate_set_error(s, error);
458cf28e
JQ
1579}
1580
0edda1c4 1581static void migrate_fd_cancel(MigrationState *s)
065e2813 1582{
6f2b811a 1583 int old_state ;
89a02a9f 1584 QEMUFile *f = migrate_get_current()->to_dst_file;
9013dca5 1585 trace_migrate_fd_cancel();
065e2813 1586
70b20477
DDAG
1587 if (s->rp_state.from_dst_file) {
1588 /* shutdown the rp socket, so causing the rp thread to shutdown */
1589 qemu_file_shutdown(s->rp_state.from_dst_file);
1590 }
1591
6f2b811a
Z
1592 do {
1593 old_state = s->state;
f6844b99 1594 if (!migration_is_setup_or_active(old_state)) {
6f2b811a
Z
1595 break;
1596 }
a7b36b48
DDAG
1597 /* If the migration is paused, kick it out of the pause */
1598 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1599 qemu_sem_post(&s->pause_sem);
1600 }
48781e5b 1601 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
31194731 1602 } while (s->state != MIGRATION_STATUS_CANCELLING);
a26ba26e
DDAG
1603
1604 /*
1605 * If we're unlucky the migration code might be stuck somewhere in a
1606 * send/write while the network has failed and is waiting to timeout;
1607 * if we've got shutdown(2) available then we can force it to quit.
1608 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1609 * called in a bh, so there is no race against this cancel.
1610 */
31194731 1611 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
a26ba26e
DDAG
1612 qemu_file_shutdown(f);
1613 }
1d2acc31
HZ
1614 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1615 Error *local_err = NULL;
1616
1617 bdrv_invalidate_cache_all(&local_err);
1618 if (local_err) {
1619 error_report_err(local_err);
1620 } else {
1621 s->block_inactive = false;
1622 }
1623 }
065e2813
AL
1624}
1625
99a0db9b
GH
1626void add_migration_state_change_notifier(Notifier *notify)
1627{
1628 notifier_list_add(&migration_state_notifiers, notify);
1629}
1630
1631void remove_migration_state_change_notifier(Notifier *notify)
1632{
31552529 1633 notifier_remove(notify);
99a0db9b
GH
1634}
1635
02edd2e7 1636bool migration_in_setup(MigrationState *s)
afe2df69 1637{
31194731 1638 return s->state == MIGRATION_STATUS_SETUP;
afe2df69
GH
1639}
1640
7073693b 1641bool migration_has_finished(MigrationState *s)
99a0db9b 1642{
31194731 1643 return s->state == MIGRATION_STATUS_COMPLETED;
99a0db9b 1644}
0edda1c4 1645
afe2df69
GH
1646bool migration_has_failed(MigrationState *s)
1647{
31194731
HZ
1648 return (s->state == MIGRATION_STATUS_CANCELLED ||
1649 s->state == MIGRATION_STATUS_FAILED);
afe2df69
GH
1650}
1651
5727309d 1652bool migration_in_postcopy(void)
9ec055ae 1653{
5727309d
JQ
1654 MigrationState *s = migrate_get_current();
1655
9ec055ae
DDAG
1656 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1657}
1658
b82fc321
DDAG
1659bool migration_in_postcopy_after_devices(MigrationState *s)
1660{
5727309d 1661 return migration_in_postcopy() && s->postcopy_after_devices;
b82fc321
DDAG
1662}
1663
fab35005 1664bool migration_is_idle(void)
fe44dc91 1665{
daff7f0b
MA
1666 MigrationState *s = current_migration;
1667
1668 if (!s) {
1669 return true;
1670 }
fe44dc91
AA
1671
1672 switch (s->state) {
1673 case MIGRATION_STATUS_NONE:
1674 case MIGRATION_STATUS_CANCELLED:
1675 case MIGRATION_STATUS_COMPLETED:
1676 case MIGRATION_STATUS_FAILED:
1677 return true;
1678 case MIGRATION_STATUS_SETUP:
1679 case MIGRATION_STATUS_CANCELLING:
1680 case MIGRATION_STATUS_ACTIVE:
1681 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1682 case MIGRATION_STATUS_COLO:
31e06077
DDAG
1683 case MIGRATION_STATUS_PRE_SWITCHOVER:
1684 case MIGRATION_STATUS_DEVICE:
fe44dc91
AA
1685 return false;
1686 case MIGRATION_STATUS__MAX:
1687 g_assert_not_reached();
1688 }
1689
1690 return false;
1691}
1692
3e0c8050 1693void migrate_init(MigrationState *s)
0edda1c4 1694{
389775d1
DDAG
1695 /*
1696 * Reinitialise all migration state, except
1697 * parameters/capabilities that the user set, and
1698 * locks.
1699 */
1700 s->bytes_xfer = 0;
389775d1 1701 s->cleanup_bh = 0;
89a02a9f 1702 s->to_dst_file = NULL;
389775d1 1703 s->state = MIGRATION_STATUS_NONE;
389775d1
DDAG
1704 s->rp_state.from_dst_file = NULL;
1705 s->rp_state.error = false;
1706 s->mbps = 0.0;
aecbfe9c 1707 s->pages_per_second = 0.0;
389775d1
DDAG
1708 s->downtime = 0;
1709 s->expected_downtime = 0;
389775d1 1710 s->setup_time = 0;
389775d1 1711 s->start_postcopy = false;
b82fc321 1712 s->postcopy_after_devices = false;
389775d1 1713 s->migration_thread_running = false;
d59ce6f3
DB
1714 error_free(s->error);
1715 s->error = NULL;
389775d1 1716
48781e5b 1717 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
0edda1c4 1718
4af246a3
PX
1719 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1720 s->total_time = 0;
7287cbd4 1721 s->vm_was_running = false;
b15df1ae
PX
1722 s->iteration_initial_bytes = 0;
1723 s->threshold_size = 0;
0edda1c4 1724}
cab30143 1725
fa2756b7
AL
1726static GSList *migration_blockers;
1727
fe44dc91 1728int migrate_add_blocker(Error *reason, Error **errp)
fa2756b7 1729{
811f8652 1730 if (only_migratable) {
4b576648
MA
1731 error_propagate_prepend(errp, error_copy(reason),
1732 "disallowing migration blocker "
b6eca81e 1733 "(--only-migratable) for: ");
b67b8c3a
AA
1734 return -EACCES;
1735 }
1736
fab35005 1737 if (migration_is_idle()) {
fe44dc91
AA
1738 migration_blockers = g_slist_prepend(migration_blockers, reason);
1739 return 0;
1740 }
1741
4b576648
MA
1742 error_propagate_prepend(errp, error_copy(reason),
1743 "disallowing migration blocker "
1744 "(migration in progress) for: ");
fe44dc91 1745 return -EBUSY;
fa2756b7
AL
1746}
1747
1748void migrate_del_blocker(Error *reason)
1749{
1750 migration_blockers = g_slist_remove(migration_blockers, reason);
1751}
1752
bf1ae1f4
DDAG
1753void qmp_migrate_incoming(const char *uri, Error **errp)
1754{
1755 Error *local_err = NULL;
4debb5f5 1756 static bool once = true;
bf1ae1f4
DDAG
1757
1758 if (!deferred_incoming) {
4debb5f5 1759 error_setg(errp, "For use with '-incoming defer'");
bf1ae1f4
DDAG
1760 return;
1761 }
4debb5f5
DDAG
1762 if (!once) {
1763 error_setg(errp, "The incoming migration has already been started");
1764 }
bf1ae1f4
DDAG
1765
1766 qemu_start_incoming_migration(uri, &local_err);
1767
1768 if (local_err) {
1769 error_propagate(errp, local_err);
1770 return;
1771 }
1772
4debb5f5 1773 once = false;
bf1ae1f4
DDAG
1774}
1775
02affd41
PX
1776void qmp_migrate_recover(const char *uri, Error **errp)
1777{
1778 MigrationIncomingState *mis = migration_incoming_get_current();
1779
1780 if (mis->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1781 error_setg(errp, "Migrate recover can only be run "
1782 "when postcopy is paused.");
1783 return;
1784 }
1785
1786 if (atomic_cmpxchg(&mis->postcopy_recover_triggered,
1787 false, true) == true) {
1788 error_setg(errp, "Migrate recovery is triggered already");
1789 return;
1790 }
1791
1792 /*
1793 * Note that this call will never start a real migration; it will
1794 * only re-setup the migration stream and poke existing migration
1795 * to continue using that newly established channel.
1796 */
1797 qemu_start_incoming_migration(uri, errp);
1798}
1799
bfbf89c2
PX
1800void qmp_migrate_pause(Error **errp)
1801{
1802 MigrationState *ms = migrate_get_current();
1803 MigrationIncomingState *mis = migration_incoming_get_current();
1804 int ret;
1805
1806 if (ms->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1807 /* Source side, during postcopy */
1808 qemu_mutex_lock(&ms->qemu_file_lock);
1809 ret = qemu_file_shutdown(ms->to_dst_file);
1810 qemu_mutex_unlock(&ms->qemu_file_lock);
1811 if (ret) {
1812 error_setg(errp, "Failed to pause source migration");
1813 }
1814 return;
1815 }
1816
1817 if (mis->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1818 ret = qemu_file_shutdown(mis->from_src_file);
1819 if (ret) {
1820 error_setg(errp, "Failed to pause destination migration");
1821 }
1822 return;
1823 }
1824
1825 error_setg(errp, "migrate-pause is currently only supported "
1826 "during postcopy-active state");
1827}
1828
24f3902b
GK
1829bool migration_is_blocked(Error **errp)
1830{
1831 if (qemu_savevm_state_blocked(errp)) {
1832 return true;
1833 }
1834
1835 if (migration_blockers) {
250561e1 1836 error_propagate(errp, error_copy(migration_blockers->data));
24f3902b
GK
1837 return true;
1838 }
1839
1840 return false;
1841}
1842
d3e35b8f
PX
1843/* Returns true if continue to migrate, or false if error detected */
1844static bool migrate_prepare(MigrationState *s, bool blk, bool blk_inc,
1845 bool resume, Error **errp)
cab30143 1846{
be7059cd 1847 Error *local_err = NULL;
d3e35b8f
PX
1848
1849 if (resume) {
1850 if (s->state != MIGRATION_STATUS_POSTCOPY_PAUSED) {
1851 error_setg(errp, "Cannot resume if there is no "
1852 "paused migration");
1853 return false;
1854 }
97ca211c
PX
1855
1856 /*
1857 * Postcopy recovery won't work well with release-ram
1858 * capability since release-ram will drop the page buffer as
1859 * long as the page is put into the send buffer. So if there
1860 * is a network failure happened, any page buffers that have
1861 * not yet reached the destination VM but have already been
1862 * sent from the source VM will be lost forever. Let's refuse
1863 * the client from resuming such a postcopy migration.
1864 * Luckily release-ram was designed to only be used when src
1865 * and destination VMs are on the same host, so it should be
1866 * fine.
1867 */
1868 if (migrate_release_ram()) {
1869 error_setg(errp, "Postcopy recovery cannot work "
1870 "when release-ram capability is set");
1871 return false;
1872 }
1873
d3e35b8f
PX
1874 /* This is a resume, skip init status */
1875 return true;
1876 }
cab30143 1877
f6844b99 1878 if (migration_is_setup_or_active(s->state) ||
0b827d5e
HZ
1879 s->state == MIGRATION_STATUS_CANCELLING ||
1880 s->state == MIGRATION_STATUS_COLO) {
c6bd8c70 1881 error_setg(errp, QERR_MIGRATION_ACTIVE);
d3e35b8f 1882 return false;
cab30143 1883 }
d3e35b8f 1884
ca99993a
DDAG
1885 if (runstate_check(RUN_STATE_INMIGRATE)) {
1886 error_setg(errp, "Guest is waiting for an incoming migration");
d3e35b8f 1887 return false;
ca99993a
DDAG
1888 }
1889
24f3902b 1890 if (migration_is_blocked(errp)) {
d3e35b8f 1891 return false;
fa2756b7
AL
1892 }
1893
d3e35b8f 1894 if (blk || blk_inc) {
2833c59b
JQ
1895 if (migrate_use_block() || migrate_use_block_incremental()) {
1896 error_setg(errp, "Command options are incompatible with "
1897 "current migration capabilities");
d3e35b8f 1898 return false;
2833c59b
JQ
1899 }
1900 migrate_set_block_enabled(true, &local_err);
1901 if (local_err) {
1902 error_propagate(errp, local_err);
d3e35b8f 1903 return false;
2833c59b
JQ
1904 }
1905 s->must_remove_block_options = true;
1906 }
1907
d3e35b8f 1908 if (blk_inc) {
2833c59b
JQ
1909 migrate_set_block_incremental(s, true);
1910 }
1911
3e0c8050 1912 migrate_init(s);
cab30143 1913
d3e35b8f
PX
1914 return true;
1915}
1916
1917void qmp_migrate(const char *uri, bool has_blk, bool blk,
1918 bool has_inc, bool inc, bool has_detach, bool detach,
1919 bool has_resume, bool resume, Error **errp)
1920{
1921 Error *local_err = NULL;
1922 MigrationState *s = migrate_get_current();
1923 const char *p;
1924
1925 if (!migrate_prepare(s, has_blk && blk, has_inc && inc,
1926 has_resume && resume, errp)) {
1927 /* Error detected, put into errp */
1928 return;
1929 }
1930
cab30143 1931 if (strstart(uri, "tcp:", &p)) {
f37afb5a 1932 tcp_start_outgoing_migration(s, p, &local_err);
2da776db 1933#ifdef CONFIG_RDMA
41310c68 1934 } else if (strstart(uri, "rdma:", &p)) {
2da776db
MH
1935 rdma_start_outgoing_migration(s, p, &local_err);
1936#endif
cab30143 1937 } else if (strstart(uri, "exec:", &p)) {
f37afb5a 1938 exec_start_outgoing_migration(s, p, &local_err);
cab30143 1939 } else if (strstart(uri, "unix:", &p)) {
f37afb5a 1940 unix_start_outgoing_migration(s, p, &local_err);
cab30143 1941 } else if (strstart(uri, "fd:", &p)) {
f37afb5a 1942 fd_start_outgoing_migration(s, p, &local_err);
99a0db9b 1943 } else {
c6bd8c70
MA
1944 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1945 "a valid migration protocol");
48781e5b
HZ
1946 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1947 MIGRATION_STATUS_FAILED);
09576e74 1948 block_cleanup_parameters(s);
e1c37d0e 1949 return;
cab30143
JQ
1950 }
1951
f37afb5a 1952 if (local_err) {
d59ce6f3 1953 migrate_fd_error(s, local_err);
f37afb5a 1954 error_propagate(errp, local_err);
e1c37d0e 1955 return;
1299c631 1956 }
cab30143
JQ
1957}
1958
6cdedb07 1959void qmp_migrate_cancel(Error **errp)
cab30143 1960{
17549e84 1961 migrate_fd_cancel(migrate_get_current());
cab30143
JQ
1962}
1963
89cfc02c
DDAG
1964void qmp_migrate_continue(MigrationStatus state, Error **errp)
1965{
1966 MigrationState *s = migrate_get_current();
1967 if (s->state != state) {
1968 error_setg(errp, "Migration not in expected state: %s",
1969 MigrationStatus_str(s->state));
1970 return;
1971 }
1972 qemu_sem_post(&s->pause_sem);
1973}
1974
9e1ba4cc
OW
1975void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1976{
73af8dd8
JQ
1977 MigrateSetParameters p = {
1978 .has_xbzrle_cache_size = true,
1979 .xbzrle_cache_size = value,
1980 };
c91e681a 1981
73af8dd8 1982 qmp_migrate_set_parameters(&p, errp);
9e1ba4cc
OW
1983}
1984
1985int64_t qmp_query_migrate_cache_size(Error **errp)
1986{
1987 return migrate_xbzrle_cache_size();
1988}
1989
3dc85383 1990void qmp_migrate_set_speed(int64_t value, Error **errp)
cab30143 1991{
1bda8b3c 1992 MigrateSetParameters p = {
2ff30257
AA
1993 .has_max_bandwidth = true,
1994 .max_bandwidth = value,
1995 };
cab30143 1996
2ff30257 1997 qmp_migrate_set_parameters(&p, errp);
cab30143
JQ
1998}
1999
4f0a993b 2000void qmp_migrate_set_downtime(double value, Error **errp)
cab30143 2001{
87c9cc1c
DHB
2002 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
2003 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
2004 "the range of 0 to %d seconds",
2005 MAX_MIGRATE_DOWNTIME_SECONDS);
2006 return;
2007 }
2008
2ff30257
AA
2009 value *= 1000; /* Convert to milliseconds */
2010 value = MAX(0, MIN(INT64_MAX, value));
2011
1bda8b3c 2012 MigrateSetParameters p = {
2ff30257
AA
2013 .has_downtime_limit = true,
2014 .downtime_limit = value,
2015 };
2016
2017 qmp_migrate_set_parameters(&p, errp);
99a0db9b 2018}
17ad9b35 2019
53f09a10
PB
2020bool migrate_release_ram(void)
2021{
2022 MigrationState *s;
2023
2024 s = migrate_get_current();
2025
2026 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
2027}
2028
53dd370c
DDAG
2029bool migrate_postcopy_ram(void)
2030{
2031 MigrationState *s;
2032
2033 s = migrate_get_current();
2034
32c3db5b 2035 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
53dd370c
DDAG
2036}
2037
58110f0a
VSO
2038bool migrate_postcopy(void)
2039{
dd6bb914 2040 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
58110f0a
VSO
2041}
2042
bde1e2ec
CV
2043bool migrate_auto_converge(void)
2044{
2045 MigrationState *s;
2046
2047 s = migrate_get_current();
2048
2049 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
2050}
2051
323004a3
PL
2052bool migrate_zero_blocks(void)
2053{
2054 MigrationState *s;
2055
2056 s = migrate_get_current();
2057
2058 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
2059}
2060
f22f928e
AP
2061bool migrate_postcopy_blocktime(void)
2062{
2063 MigrationState *s;
2064
2065 s = migrate_get_current();
2066
2067 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
2068}
2069
8706d2d5
LL
2070bool migrate_use_compression(void)
2071{
dde4e694
LL
2072 MigrationState *s;
2073
2074 s = migrate_get_current();
2075
2076 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
8706d2d5
LL
2077}
2078
2079int migrate_compress_level(void)
2080{
2081 MigrationState *s;
2082
2083 s = migrate_get_current();
2084
2594f56d 2085 return s->parameters.compress_level;
8706d2d5
LL
2086}
2087
2088int migrate_compress_threads(void)
2089{
2090 MigrationState *s;
2091
2092 s = migrate_get_current();
2093
2594f56d 2094 return s->parameters.compress_threads;
8706d2d5
LL
2095}
2096
1d58872a
XG
2097int migrate_compress_wait_thread(void)
2098{
2099 MigrationState *s;
2100
2101 s = migrate_get_current();
2102
2103 return s->parameters.compress_wait_thread;
2104}
2105
3fcb38c2
LL
2106int migrate_decompress_threads(void)
2107{
2108 MigrationState *s;
2109
2110 s = migrate_get_current();
2111
2594f56d 2112 return s->parameters.decompress_threads;
3fcb38c2
LL
2113}
2114
55efc8c2
VSO
2115bool migrate_dirty_bitmaps(void)
2116{
2117 MigrationState *s;
2118
2119 s = migrate_get_current();
2120
2121 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
2122}
2123
18269069
YK
2124bool migrate_ignore_shared(void)
2125{
2126 MigrationState *s;
2127
2128 s = migrate_get_current();
2129
2130 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_IGNORE_SHARED];
2131}
2132
b05dc723
JQ
2133bool migrate_use_events(void)
2134{
2135 MigrationState *s;
2136
2137 s = migrate_get_current();
2138
2139 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
2140}
2141
30126bbf
JQ
2142bool migrate_use_multifd(void)
2143{
2144 MigrationState *s;
2145
2146 s = migrate_get_current();
2147
cbfd6c95 2148 return s->enabled_capabilities[MIGRATION_CAPABILITY_MULTIFD];
30126bbf
JQ
2149}
2150
93fbd031
DDAG
2151bool migrate_pause_before_switchover(void)
2152{
2153 MigrationState *s;
2154
2155 s = migrate_get_current();
2156
2157 return s->enabled_capabilities[
2158 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
2159}
2160
4075fb1c
JQ
2161int migrate_multifd_channels(void)
2162{
2163 MigrationState *s;
2164
2165 s = migrate_get_current();
2166
cbfd6c95 2167 return s->parameters.multifd_channels;
4075fb1c
JQ
2168}
2169
17ad9b35
OW
2170int migrate_use_xbzrle(void)
2171{
2172 MigrationState *s;
2173
2174 s = migrate_get_current();
2175
2176 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
2177}
2178
2179int64_t migrate_xbzrle_cache_size(void)
2180{
2181 MigrationState *s;
2182
2183 s = migrate_get_current();
2184
73af8dd8 2185 return s->parameters.xbzrle_cache_size;
17ad9b35 2186}
0d82d0e8 2187
7e555c6c
DDAG
2188static int64_t migrate_max_postcopy_bandwidth(void)
2189{
2190 MigrationState *s;
2191
2192 s = migrate_get_current();
2193
2194 return s->parameters.max_postcopy_bandwidth;
2195}
2196
2833c59b
JQ
2197bool migrate_use_block(void)
2198{
2199 MigrationState *s;
2200
2201 s = migrate_get_current();
2202
2203 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
2204}
2205
c788ada8
PX
2206bool migrate_use_return_path(void)
2207{
2208 MigrationState *s;
2209
2210 s = migrate_get_current();
2211
2212 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
2213}
2214
2833c59b
JQ
2215bool migrate_use_block_incremental(void)
2216{
2217 MigrationState *s;
2218
2219 s = migrate_get_current();
2220
2221 return s->parameters.block_incremental;
2222}
2223
70b20477
DDAG
2224/* migration thread support */
2225/*
2226 * Something bad happened to the RP stream, mark an error
2227 * The caller shall print or trace something to indicate why
2228 */
2229static void mark_source_rp_bad(MigrationState *s)
2230{
2231 s->rp_state.error = true;
2232}
2233
2234static struct rp_cmd_args {
2235 ssize_t len; /* -1 = variable */
2236 const char *name;
2237} rp_cmd_args[] = {
2238 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
2239 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
2240 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1e2d90eb
DDAG
2241 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
2242 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
a335debb 2243 [MIG_RP_MSG_RECV_BITMAP] = { .len = -1, .name = "RECV_BITMAP" },
13955b89 2244 [MIG_RP_MSG_RESUME_ACK] = { .len = 4, .name = "RESUME_ACK" },
70b20477
DDAG
2245 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
2246};
2247
1e2d90eb
DDAG
2248/*
2249 * Process a request for pages received on the return path,
2250 * We're allowed to send more than requested (e.g. to round to our page size)
2251 * and we don't need to send pages that have already been sent.
2252 */
2253static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
2254 ram_addr_t start, size_t len)
2255{
6c595cde
DDAG
2256 long our_host_ps = getpagesize();
2257
1e2d90eb 2258 trace_migrate_handle_rp_req_pages(rbname, start, len);
6c595cde
DDAG
2259
2260 /*
2261 * Since we currently insist on matching page sizes, just sanity check
2262 * we're being asked for whole host pages.
2263 */
2264 if (start & (our_host_ps-1) ||
2265 (len & (our_host_ps-1))) {
2266 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
2267 " len: %zd", __func__, start, len);
2268 mark_source_rp_bad(ms);
2269 return;
2270 }
2271
96506894 2272 if (ram_save_queue_pages(rbname, start, len)) {
6c595cde
DDAG
2273 mark_source_rp_bad(ms);
2274 }
1e2d90eb
DDAG
2275}
2276
14b1742e
PX
2277/* Return true to retry, false to quit */
2278static bool postcopy_pause_return_path_thread(MigrationState *s)
2279{
2280 trace_postcopy_pause_return_path();
2281
2282 qemu_sem_wait(&s->postcopy_pause_rp_sem);
2283
2284 trace_postcopy_pause_return_path_continued();
2285
2286 return true;
2287}
2288
a335debb
PX
2289static int migrate_handle_rp_recv_bitmap(MigrationState *s, char *block_name)
2290{
2291 RAMBlock *block = qemu_ram_block_by_name(block_name);
2292
2293 if (!block) {
2294 error_report("%s: invalid block name '%s'", __func__, block_name);
2295 return -EINVAL;
2296 }
2297
2298 /* Fetch the received bitmap and refresh the dirty bitmap */
2299 return ram_dirty_bitmap_reload(s, block);
2300}
2301
13955b89
PX
2302static int migrate_handle_rp_resume_ack(MigrationState *s, uint32_t value)
2303{
2304 trace_source_return_path_thread_resume_ack(value);
2305
2306 if (value != MIGRATION_RESUME_ACK_VALUE) {
2307 error_report("%s: illegal resume_ack value %"PRIu32,
2308 __func__, value);
2309 return -1;
2310 }
2311
2312 /* Now both sides are active. */
2313 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_RECOVER,
2314 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2315
94190696
PX
2316 /* Notify send thread that time to continue send pages */
2317 qemu_sem_post(&s->rp_state.rp_sem);
13955b89
PX
2318
2319 return 0;
2320}
2321
70b20477
DDAG
2322/*
2323 * Handles messages sent on the return path towards the source VM
2324 *
2325 */
2326static void *source_return_path_thread(void *opaque)
2327{
2328 MigrationState *ms = opaque;
2329 QEMUFile *rp = ms->rp_state.from_dst_file;
2330 uint16_t header_len, header_type;
568b01ca 2331 uint8_t buf[512];
70b20477 2332 uint32_t tmp32, sibling_error;
1e2d90eb
DDAG
2333 ram_addr_t start = 0; /* =0 to silence warning */
2334 size_t len = 0, expected_len;
70b20477
DDAG
2335 int res;
2336
2337 trace_source_return_path_thread_entry();
74637e6f 2338 rcu_register_thread();
14b1742e
PX
2339
2340retry:
70b20477
DDAG
2341 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
2342 migration_is_setup_or_active(ms->state)) {
2343 trace_source_return_path_thread_loop_top();
2344 header_type = qemu_get_be16(rp);
2345 header_len = qemu_get_be16(rp);
2346
7a9ddfbf
PX
2347 if (qemu_file_get_error(rp)) {
2348 mark_source_rp_bad(ms);
2349 goto out;
2350 }
2351
70b20477
DDAG
2352 if (header_type >= MIG_RP_MSG_MAX ||
2353 header_type == MIG_RP_MSG_INVALID) {
2354 error_report("RP: Received invalid message 0x%04x length 0x%04x",
2355 header_type, header_len);
2356 mark_source_rp_bad(ms);
2357 goto out;
2358 }
2359
2360 if ((rp_cmd_args[header_type].len != -1 &&
2361 header_len != rp_cmd_args[header_type].len) ||
568b01ca 2362 header_len > sizeof(buf)) {
70b20477
DDAG
2363 error_report("RP: Received '%s' message (0x%04x) with"
2364 "incorrect length %d expecting %zu",
2365 rp_cmd_args[header_type].name, header_type, header_len,
2366 (size_t)rp_cmd_args[header_type].len);
2367 mark_source_rp_bad(ms);
2368 goto out;
2369 }
2370
2371 /* We know we've got a valid header by this point */
2372 res = qemu_get_buffer(rp, buf, header_len);
2373 if (res != header_len) {
2374 error_report("RP: Failed reading data for message 0x%04x"
2375 " read %d expected %d",
2376 header_type, res, header_len);
2377 mark_source_rp_bad(ms);
2378 goto out;
2379 }
2380
2381 /* OK, we have the message and the data */
2382 switch (header_type) {
2383 case MIG_RP_MSG_SHUT:
4d885131 2384 sibling_error = ldl_be_p(buf);
70b20477
DDAG
2385 trace_source_return_path_thread_shut(sibling_error);
2386 if (sibling_error) {
2387 error_report("RP: Sibling indicated error %d", sibling_error);
2388 mark_source_rp_bad(ms);
2389 }
2390 /*
2391 * We'll let the main thread deal with closing the RP
2392 * we could do a shutdown(2) on it, but we're the only user
2393 * anyway, so there's nothing gained.
2394 */
2395 goto out;
2396
2397 case MIG_RP_MSG_PONG:
4d885131 2398 tmp32 = ldl_be_p(buf);
70b20477
DDAG
2399 trace_source_return_path_thread_pong(tmp32);
2400 break;
2401
1e2d90eb 2402 case MIG_RP_MSG_REQ_PAGES:
4d885131
PM
2403 start = ldq_be_p(buf);
2404 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2405 migrate_handle_rp_req_pages(ms, NULL, start, len);
2406 break;
2407
2408 case MIG_RP_MSG_REQ_PAGES_ID:
2409 expected_len = 12 + 1; /* header + termination */
2410
2411 if (header_len >= expected_len) {
4d885131
PM
2412 start = ldq_be_p(buf);
2413 len = ldl_be_p(buf + 8);
1e2d90eb
DDAG
2414 /* Now we expect an idstr */
2415 tmp32 = buf[12]; /* Length of the following idstr */
2416 buf[13 + tmp32] = '\0';
2417 expected_len += tmp32;
2418 }
2419 if (header_len != expected_len) {
2420 error_report("RP: Req_Page_id with length %d expecting %zd",
2421 header_len, expected_len);
2422 mark_source_rp_bad(ms);
2423 goto out;
2424 }
2425 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
2426 break;
2427
a335debb
PX
2428 case MIG_RP_MSG_RECV_BITMAP:
2429 if (header_len < 1) {
2430 error_report("%s: missing block name", __func__);
2431 mark_source_rp_bad(ms);
2432 goto out;
2433 }
2434 /* Format: len (1B) + idstr (<255B). This ends the idstr. */
2435 buf[buf[0] + 1] = '\0';
2436 if (migrate_handle_rp_recv_bitmap(ms, (char *)(buf + 1))) {
2437 mark_source_rp_bad(ms);
2438 goto out;
2439 }
2440 break;
2441
13955b89
PX
2442 case MIG_RP_MSG_RESUME_ACK:
2443 tmp32 = ldl_be_p(buf);
2444 if (migrate_handle_rp_resume_ack(ms, tmp32)) {
2445 mark_source_rp_bad(ms);
2446 goto out;
2447 }
2448 break;
2449
70b20477
DDAG
2450 default:
2451 break;
2452 }
2453 }
14b1742e
PX
2454
2455out:
2456 res = qemu_file_get_error(rp);
2457 if (res) {
2458 if (res == -EIO) {
2459 /*
2460 * Maybe there is something we can do: it looks like a
2461 * network down issue, and we pause for a recovery.
2462 */
2463 if (postcopy_pause_return_path_thread(ms)) {
2464 /* Reload rp, reset the rest */
0284a2a8
MAL
2465 if (rp != ms->rp_state.from_dst_file) {
2466 qemu_fclose(rp);
2467 rp = ms->rp_state.from_dst_file;
2468 }
14b1742e
PX
2469 ms->rp_state.error = false;
2470 goto retry;
2471 }
2472 }
2473
70b20477
DDAG
2474 trace_source_return_path_thread_bad_end();
2475 mark_source_rp_bad(ms);
2476 }
2477
2478 trace_source_return_path_thread_end();
70b20477
DDAG
2479 ms->rp_state.from_dst_file = NULL;
2480 qemu_fclose(rp);
74637e6f 2481 rcu_unregister_thread();
70b20477
DDAG
2482 return NULL;
2483}
2484
d3e35b8f
PX
2485static int open_return_path_on_source(MigrationState *ms,
2486 bool create_thread)
70b20477
DDAG
2487{
2488
89a02a9f 2489 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
70b20477
DDAG
2490 if (!ms->rp_state.from_dst_file) {
2491 return -1;
2492 }
2493
2494 trace_open_return_path_on_source();
d3e35b8f
PX
2495
2496 if (!create_thread) {
2497 /* We're done */
2498 return 0;
2499 }
2500
70b20477
DDAG
2501 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
2502 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
2503
2504 trace_open_return_path_on_source_continue();
2505
2506 return 0;
2507}
2508
70b20477
DDAG
2509/* Returns 0 if the RP was ok, otherwise there was an error on the RP */
2510static int await_return_path_close_on_source(MigrationState *ms)
2511{
2512 /*
2513 * If this is a normal exit then the destination will send a SHUT and the
2514 * rp_thread will exit, however if there's an error we need to cause
2515 * it to exit.
2516 */
89a02a9f 2517 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
70b20477
DDAG
2518 /*
2519 * shutdown(2), if we have it, will cause it to unblock if it's stuck
2520 * waiting for the destination.
2521 */
2522 qemu_file_shutdown(ms->rp_state.from_dst_file);
2523 mark_source_rp_bad(ms);
2524 }
2525 trace_await_return_path_close_on_source_joining();
2526 qemu_thread_join(&ms->rp_state.rp_thread);
2527 trace_await_return_path_close_on_source_close();
2528 return ms->rp_state.error;
2529}
2530
1d34e4bf
DDAG
2531/*
2532 * Switch from normal iteration to postcopy
2533 * Returns non-0 on error
2534 */
7287cbd4 2535static int postcopy_start(MigrationState *ms)
1d34e4bf
DDAG
2536{
2537 int ret;
61b67d47
DB
2538 QIOChannelBuffer *bioc;
2539 QEMUFile *fb;
1d34e4bf 2540 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
7e555c6c 2541 int64_t bandwidth = migrate_max_postcopy_bandwidth();
ef8d6488 2542 bool restart_block = false;
0331c8ca
DDAG
2543 int cur_state = MIGRATION_STATUS_ACTIVE;
2544 if (!migrate_pause_before_switchover()) {
2545 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
2546 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2547 }
1d34e4bf
DDAG
2548
2549 trace_postcopy_start();
2550 qemu_mutex_lock_iothread();
2551 trace_postcopy_start_set_run();
2552
fb064112 2553 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
1d34e4bf
DDAG
2554 global_state_store();
2555 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
76b1c7fe
KW
2556 if (ret < 0) {
2557 goto fail;
2558 }
1d34e4bf 2559
0331c8ca
DDAG
2560 ret = migration_maybe_pause(ms, &cur_state,
2561 MIGRATION_STATUS_POSTCOPY_ACTIVE);
2562 if (ret < 0) {
2563 goto fail;
2564 }
2565
76b1c7fe 2566 ret = bdrv_inactivate_all();
1d34e4bf
DDAG
2567 if (ret < 0) {
2568 goto fail;
2569 }
ef8d6488 2570 restart_block = true;
1d34e4bf 2571
1c0d249d
DDAG
2572 /*
2573 * Cause any non-postcopiable, but iterative devices to
2574 * send out their final data.
2575 */
a1fbe750 2576 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1c0d249d 2577
1d34e4bf
DDAG
2578 /*
2579 * in Finish migrate and with the io-lock held everything should
2580 * be quiet, but we've potentially still got dirty pages and we
2581 * need to tell the destination to throw any pages it's already received
2582 * that are dirty
2583 */
58110f0a
VSO
2584 if (migrate_postcopy_ram()) {
2585 if (ram_postcopy_send_discard_bitmap(ms)) {
2586 error_report("postcopy send discard bitmap failed");
2587 goto fail;
2588 }
1d34e4bf
DDAG
2589 }
2590
2591 /*
2592 * send rest of state - note things that are doing postcopy
2593 * will notice we're in POSTCOPY_ACTIVE and not actually
2594 * wrap their state up here
2595 */
7e555c6c
DDAG
2596 /* 0 max-postcopy-bandwidth means unlimited */
2597 if (!bandwidth) {
2598 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
2599 } else {
2600 qemu_file_set_rate_limit(ms->to_dst_file, bandwidth / XFER_LIMIT_RATIO);
2601 }
58110f0a
VSO
2602 if (migrate_postcopy_ram()) {
2603 /* Ping just for debugging, helps line traces up */
2604 qemu_savevm_send_ping(ms->to_dst_file, 2);
2605 }
1d34e4bf
DDAG
2606
2607 /*
2608 * While loading the device state we may trigger page transfer
2609 * requests and the fd must be free to process those, and thus
2610 * the destination must read the whole device state off the fd before
2611 * it starts processing it. Unfortunately the ad-hoc migration format
2612 * doesn't allow the destination to know the size to read without fully
2613 * parsing it through each devices load-state code (especially the open
2614 * coded devices that use get/put).
2615 * So we wrap the device state up in a package with a length at the start;
2616 * to do this we use a qemu_buf to hold the whole of the device state.
2617 */
61b67d47 2618 bioc = qio_channel_buffer_new(4096);
6f01f136 2619 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
61b67d47
DB
2620 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2621 object_unref(OBJECT(bioc));
1d34e4bf 2622
c76201ab
DDAG
2623 /*
2624 * Make sure the receiver can get incoming pages before we send the rest
2625 * of the state
2626 */
2627 qemu_savevm_send_postcopy_listen(fb);
2628
a1fbe750 2629 qemu_savevm_state_complete_precopy(fb, false, false);
58110f0a
VSO
2630 if (migrate_postcopy_ram()) {
2631 qemu_savevm_send_ping(fb, 3);
2632 }
1d34e4bf
DDAG
2633
2634 qemu_savevm_send_postcopy_run(fb);
2635
2636 /* <><> end of stuff going into the package */
1d34e4bf 2637
ef8d6488
DDAG
2638 /* Last point of recovery; as soon as we send the package the destination
2639 * can open devices and potentially start running.
2640 * Lets just check again we've not got any errors.
2641 */
2642 ret = qemu_file_get_error(ms->to_dst_file);
2643 if (ret) {
2644 error_report("postcopy_start: Migration stream errored (pre package)");
2645 goto fail_closefb;
2646 }
2647
2648 restart_block = false;
2649
1d34e4bf 2650 /* Now send that blob */
61b67d47 2651 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
1d34e4bf
DDAG
2652 goto fail_closefb;
2653 }
2654 qemu_fclose(fb);
b82fc321
DDAG
2655
2656 /* Send a notify to give a chance for anything that needs to happen
2657 * at the transition to postcopy and after the device state; in particular
2658 * spice needs to trigger a transition now
2659 */
2660 ms->postcopy_after_devices = true;
2661 notifier_list_notify(&migration_state_notifiers, ms);
2662
1d34e4bf
DDAG
2663 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2664
2665 qemu_mutex_unlock_iothread();
2666
58110f0a
VSO
2667 if (migrate_postcopy_ram()) {
2668 /*
2669 * Although this ping is just for debug, it could potentially be
2670 * used for getting a better measurement of downtime at the source.
2671 */
2672 qemu_savevm_send_ping(ms->to_dst_file, 4);
2673 }
1d34e4bf 2674
ced1c616
PB
2675 if (migrate_release_ram()) {
2676 ram_postcopy_migrated_memory_release(ms);
2677 }
2678
89a02a9f 2679 ret = qemu_file_get_error(ms->to_dst_file);
1d34e4bf
DDAG
2680 if (ret) {
2681 error_report("postcopy_start: Migration stream errored");
48781e5b 2682 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf
DDAG
2683 MIGRATION_STATUS_FAILED);
2684 }
2685
2686 return ret;
2687
2688fail_closefb:
2689 qemu_fclose(fb);
2690fail:
48781e5b 2691 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1d34e4bf 2692 MIGRATION_STATUS_FAILED);
ef8d6488
DDAG
2693 if (restart_block) {
2694 /* A failure happened early enough that we know the destination hasn't
2695 * accessed block devices, so we're safe to recover.
2696 */
2697 Error *local_err = NULL;
2698
2699 bdrv_invalidate_cache_all(&local_err);
2700 if (local_err) {
2701 error_report_err(local_err);
2702 }
2703 }
1d34e4bf
DDAG
2704 qemu_mutex_unlock_iothread();
2705 return -1;
2706}
2707
e91d8951
DDAG
2708/**
2709 * migration_maybe_pause: Pause if required to by
2710 * migrate_pause_before_switchover called with the iothread locked
2711 * Returns: 0 on success
2712 */
0331c8ca
DDAG
2713static int migration_maybe_pause(MigrationState *s,
2714 int *current_active_state,
2715 int new_state)
e91d8951
DDAG
2716{
2717 if (!migrate_pause_before_switchover()) {
2718 return 0;
2719 }
2720
2721 /* Since leaving this state is not atomic with posting the semaphore
2722 * it's possible that someone could have issued multiple migrate_continue
2723 * and the semaphore is incorrectly positive at this point;
2724 * the docs say it's undefined to reinit a semaphore that's already
2725 * init'd, so use timedwait to eat up any existing posts.
2726 */
2727 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2728 /* This block intentionally left blank */
2729 }
2730
2731 qemu_mutex_unlock_iothread();
2732 migrate_set_state(&s->state, *current_active_state,
2733 MIGRATION_STATUS_PRE_SWITCHOVER);
2734 qemu_sem_wait(&s->pause_sem);
2735 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
0331c8ca
DDAG
2736 new_state);
2737 *current_active_state = new_state;
e91d8951
DDAG
2738 qemu_mutex_lock_iothread();
2739
0331c8ca 2740 return s->state == new_state ? 0 : -EINVAL;
e91d8951
DDAG
2741}
2742
09f6c85e
DDAG
2743/**
2744 * migration_completion: Used by migration_thread when there's not much left.
2745 * The caller 'breaks' the loop when this returns.
2746 *
2747 * @s: Current migration state
09f6c85e 2748 */
2ad87305 2749static void migration_completion(MigrationState *s)
09f6c85e
DDAG
2750{
2751 int ret;
2ad87305 2752 int current_active_state = s->state;
09f6c85e 2753
b10ac0c4
DDAG
2754 if (s->state == MIGRATION_STATUS_ACTIVE) {
2755 qemu_mutex_lock_iothread();
64909f97 2756 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
fb064112 2757 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
7287cbd4 2758 s->vm_was_running = runstate_is_running();
b10ac0c4
DDAG
2759 ret = global_state_store();
2760
2761 if (!ret) {
a1fbe750 2762 bool inactivate = !migrate_colo_enabled();
b10ac0c4 2763 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
e91d8951 2764 if (ret >= 0) {
0331c8ca
DDAG
2765 ret = migration_maybe_pause(s, &current_active_state,
2766 MIGRATION_STATUS_DEVICE);
e91d8951 2767 }
f07fa4cb
KW
2768 if (ret >= 0) {
2769 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
a1fbe750
FZ
2770 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2771 inactivate);
f07fa4cb 2772 }
a1fbe750
FZ
2773 if (inactivate && ret >= 0) {
2774 s->block_inactive = true;
b10ac0c4
DDAG
2775 }
2776 }
2777 qemu_mutex_unlock_iothread();
09f6c85e 2778
b10ac0c4
DDAG
2779 if (ret < 0) {
2780 goto fail;
09f6c85e 2781 }
b10ac0c4
DDAG
2782 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2783 trace_migration_completion_postcopy_end();
2784
89a02a9f 2785 qemu_savevm_state_complete_postcopy(s->to_dst_file);
b10ac0c4 2786 trace_migration_completion_postcopy_end_after_complete();
09f6c85e 2787 }
09f6c85e 2788
b10ac0c4
DDAG
2789 /*
2790 * If rp was opened we must clean up the thread before
2791 * cleaning everything else up (since if there are no failures
2792 * it will wait for the destination to send it's status in
2793 * a SHUT command).
b10ac0c4 2794 */
0425dc97 2795 if (s->rp_state.from_dst_file) {
b10ac0c4 2796 int rp_error;
0425dc97 2797 trace_migration_return_path_end_before();
b10ac0c4 2798 rp_error = await_return_path_close_on_source(s);
0425dc97 2799 trace_migration_return_path_end_after(rp_error);
b10ac0c4 2800 if (rp_error) {
fe904ea8 2801 goto fail_invalidate;
b10ac0c4 2802 }
09f6c85e
DDAG
2803 }
2804
89a02a9f 2805 if (qemu_file_get_error(s->to_dst_file)) {
09f6c85e 2806 trace_migration_completion_file_err();
fe904ea8 2807 goto fail_invalidate;
09f6c85e
DDAG
2808 }
2809
0b827d5e
HZ
2810 if (!migrate_colo_enabled()) {
2811 migrate_set_state(&s->state, current_active_state,
2812 MIGRATION_STATUS_COMPLETED);
2813 }
2814
09f6c85e
DDAG
2815 return;
2816
fe904ea8
GK
2817fail_invalidate:
2818 /* If not doing postcopy, vm_start() will be called: let's regain
2819 * control on images.
2820 */
6039dd5b
DDAG
2821 if (s->state == MIGRATION_STATUS_ACTIVE ||
2822 s->state == MIGRATION_STATUS_DEVICE) {
fe904ea8
GK
2823 Error *local_err = NULL;
2824
1d2acc31 2825 qemu_mutex_lock_iothread();
fe904ea8
GK
2826 bdrv_invalidate_cache_all(&local_err);
2827 if (local_err) {
2828 error_report_err(local_err);
1d2acc31
HZ
2829 } else {
2830 s->block_inactive = false;
fe904ea8 2831 }
1d2acc31 2832 qemu_mutex_unlock_iothread();
fe904ea8
GK
2833 }
2834
09f6c85e 2835fail:
48781e5b
HZ
2836 migrate_set_state(&s->state, current_active_state,
2837 MIGRATION_STATUS_FAILED);
09f6c85e
DDAG
2838}
2839
35a6ed4f
HZ
2840bool migrate_colo_enabled(void)
2841{
2842 MigrationState *s = migrate_get_current();
2843 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2844}
2845
b23c2ade
PX
2846typedef enum MigThrError {
2847 /* No error detected */
2848 MIG_THR_ERR_NONE = 0,
2849 /* Detected error, but resumed successfully */
2850 MIG_THR_ERR_RECOVERED = 1,
2851 /* Detected fatal error, need to exit */
2852 MIG_THR_ERR_FATAL = 2,
2853} MigThrError;
2854
94190696
PX
2855static int postcopy_resume_handshake(MigrationState *s)
2856{
2857 qemu_savevm_send_postcopy_resume(s->to_dst_file);
2858
2859 while (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2860 qemu_sem_wait(&s->rp_state.rp_sem);
2861 }
2862
2863 if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2864 return 0;
2865 }
2866
2867 return -1;
2868}
2869
135b87b4
PX
2870/* Return zero if success, or <0 for error */
2871static int postcopy_do_resume(MigrationState *s)
2872{
d1b8eadb
PX
2873 int ret;
2874
2875 /*
2876 * Call all the resume_prepare() hooks, so that modules can be
2877 * ready for the migration resume.
2878 */
2879 ret = qemu_savevm_state_resume_prepare(s);
2880 if (ret) {
2881 error_report("%s: resume_prepare() failure detected: %d",
2882 __func__, ret);
2883 return ret;
2884 }
2885
2886 /*
94190696
PX
2887 * Last handshake with destination on the resume (destination will
2888 * switch to postcopy-active afterwards)
d1b8eadb 2889 */
94190696
PX
2890 ret = postcopy_resume_handshake(s);
2891 if (ret) {
2892 error_report("%s: handshake failed: %d", __func__, ret);
2893 return ret;
2894 }
d1b8eadb 2895
135b87b4
PX
2896 return 0;
2897}
2898
b23c2ade
PX
2899/*
2900 * We don't return until we are in a safe state to continue current
2901 * postcopy migration. Returns MIG_THR_ERR_RECOVERED if recovered, or
2902 * MIG_THR_ERR_FATAL if unrecovery failure happened.
2903 */
2904static MigThrError postcopy_pause(MigrationState *s)
2905{
2906 assert(s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
b23c2ade 2907
135b87b4 2908 while (true) {
62df066f
PX
2909 QEMUFile *file;
2910
135b87b4
PX
2911 migrate_set_state(&s->state, s->state,
2912 MIGRATION_STATUS_POSTCOPY_PAUSED);
b23c2ade 2913
135b87b4
PX
2914 /* Current channel is possibly broken. Release it. */
2915 assert(s->to_dst_file);
62df066f
PX
2916 qemu_mutex_lock(&s->qemu_file_lock);
2917 file = s->to_dst_file;
135b87b4 2918 s->to_dst_file = NULL;
62df066f
PX
2919 qemu_mutex_unlock(&s->qemu_file_lock);
2920
2921 qemu_file_shutdown(file);
2922 qemu_fclose(file);
b23c2ade 2923
135b87b4
PX
2924 error_report("Detected IO failure for postcopy. "
2925 "Migration paused.");
b23c2ade 2926
135b87b4
PX
2927 /*
2928 * We wait until things fixed up. Then someone will setup the
2929 * status back for us.
2930 */
2931 while (s->state == MIGRATION_STATUS_POSTCOPY_PAUSED) {
2932 qemu_sem_wait(&s->postcopy_pause_sem);
2933 }
2934
2935 if (s->state == MIGRATION_STATUS_POSTCOPY_RECOVER) {
2936 /* Woken up by a recover procedure. Give it a shot */
b23c2ade 2937
135b87b4
PX
2938 /*
2939 * Firstly, let's wake up the return path now, with a new
2940 * return path channel.
2941 */
2942 qemu_sem_post(&s->postcopy_pause_rp_sem);
2943
2944 /* Do the resume logic */
2945 if (postcopy_do_resume(s) == 0) {
2946 /* Let's continue! */
2947 trace_postcopy_pause_continued();
2948 return MIG_THR_ERR_RECOVERED;
2949 } else {
2950 /*
2951 * Something wrong happened during the recovery, let's
2952 * pause again. Pause is always better than throwing
2953 * data away.
2954 */
2955 continue;
2956 }
2957 } else {
2958 /* This is not right... Time to quit. */
2959 return MIG_THR_ERR_FATAL;
2960 }
2961 }
b23c2ade
PX
2962}
2963
2964static MigThrError migration_detect_error(MigrationState *s)
2965{
2966 int ret;
c3c5eae6
DDAG
2967 int state = s->state;
2968
2969 if (state == MIGRATION_STATUS_CANCELLING ||
2970 state == MIGRATION_STATUS_CANCELLED) {
2971 /* End the migration, but don't set the state to failed */
2972 return MIG_THR_ERR_FATAL;
2973 }
b23c2ade
PX
2974
2975 /* Try to detect any file errors */
2976 ret = qemu_file_get_error(s->to_dst_file);
2977
2978 if (!ret) {
2979 /* Everything is fine */
2980 return MIG_THR_ERR_NONE;
2981 }
2982
c3c5eae6 2983 if (state == MIGRATION_STATUS_POSTCOPY_ACTIVE && ret == -EIO) {
b23c2ade
PX
2984 /*
2985 * For postcopy, we allow the network to be down for a
2986 * while. After that, it can be continued by a
2987 * recovery phase.
2988 */
2989 return postcopy_pause(s);
2990 } else {
2991 /*
2992 * For precopy (or postcopy with error outside IO), we fail
2993 * with no time.
2994 */
c3c5eae6 2995 migrate_set_state(&s->state, state, MIGRATION_STATUS_FAILED);
b23c2ade
PX
2996 trace_migration_thread_file_err();
2997
2998 /* Time to stop the migration, now. */
2999 return MIG_THR_ERR_FATAL;
3000 }
3001}
3002
0c8f0efd
JQ
3003/* How many bytes have we transferred since the beggining of the migration */
3004static uint64_t migration_total_bytes(MigrationState *s)
3005{
b9ee2f7d 3006 return qemu_ftell(s->to_dst_file) + ram_counters.multifd_bytes;
0c8f0efd
JQ
3007}
3008
cf011f08
PX
3009static void migration_calculate_complete(MigrationState *s)
3010{
0c8f0efd 3011 uint64_t bytes = migration_total_bytes(s);
cf011f08 3012 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
6cde6fbe 3013 int64_t transfer_time;
cf011f08
PX
3014
3015 s->total_time = end_time - s->start_time;
3016 if (!s->downtime) {
3017 /*
3018 * It's still not set, so we are precopy migration. For
3019 * postcopy, downtime is calculated during postcopy_start().
3020 */
3021 s->downtime = end_time - s->downtime_start;
3022 }
3023
6cde6fbe
JQ
3024 transfer_time = s->total_time - s->setup_time;
3025 if (transfer_time) {
3026 s->mbps = ((double) bytes * 8.0) / transfer_time / 1000;
cf011f08
PX
3027 }
3028}
3029
b15df1ae
PX
3030static void migration_update_counters(MigrationState *s,
3031 int64_t current_time)
3032{
aecbfe9c 3033 uint64_t transferred, transferred_pages, time_spent;
0c8f0efd 3034 uint64_t current_bytes; /* bytes transferred since the beginning */
b15df1ae
PX
3035 double bandwidth;
3036
3037 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
3038 return;
3039 }
3040
0c8f0efd
JQ
3041 current_bytes = migration_total_bytes(s);
3042 transferred = current_bytes - s->iteration_initial_bytes;
b15df1ae
PX
3043 time_spent = current_time - s->iteration_start_time;
3044 bandwidth = (double)transferred / time_spent;
0781c1ed 3045 s->threshold_size = bandwidth * s->parameters.downtime_limit;
b15df1ae
PX
3046
3047 s->mbps = (((double) transferred * 8.0) /
3048 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
3049
aecbfe9c
XG
3050 transferred_pages = ram_get_total_transferred_pages() -
3051 s->iteration_initial_pages;
3052 s->pages_per_second = (double) transferred_pages /
3053 (((double) time_spent / 1000.0));
3054
b15df1ae
PX
3055 /*
3056 * if we haven't sent anything, we don't want to
3057 * recalculate. 10000 is a small enough number for our purposes
3058 */
3059 if (ram_counters.dirty_pages_rate && transferred > 10000) {
650af890 3060 s->expected_downtime = ram_counters.remaining / bandwidth;
b15df1ae
PX
3061 }
3062
3063 qemu_file_reset_rate_limit(s->to_dst_file);
3064
3065 s->iteration_start_time = current_time;
0c8f0efd 3066 s->iteration_initial_bytes = current_bytes;
aecbfe9c 3067 s->iteration_initial_pages = ram_get_total_transferred_pages();
b15df1ae
PX
3068
3069 trace_migrate_transferred(transferred, time_spent,
0781c1ed 3070 bandwidth, s->threshold_size);
b15df1ae
PX
3071}
3072
2ad87305
PX
3073/* Migration thread iteration status */
3074typedef enum {
3075 MIG_ITERATE_RESUME, /* Resume current iteration */
3076 MIG_ITERATE_SKIP, /* Skip current iteration */
3077 MIG_ITERATE_BREAK, /* Break the loop */
3078} MigIterateState;
3079
3080/*
3081 * Return true if continue to the next iteration directly, false
3082 * otherwise.
3083 */
3084static MigIterateState migration_iteration_run(MigrationState *s)
3085{
47995026 3086 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2ad87305
PX
3087 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
3088
47995026
VSO
3089 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
3090 &pend_compat, &pend_post);
3091 pending_size = pend_pre + pend_compat + pend_post;
2ad87305
PX
3092
3093 trace_migrate_pending(pending_size, s->threshold_size,
47995026 3094 pend_pre, pend_compat, pend_post);
2ad87305
PX
3095
3096 if (pending_size && pending_size >= s->threshold_size) {
3097 /* Still a significant amount to transfer */
3098 if (migrate_postcopy() && !in_postcopy &&
47995026 3099 pend_pre <= s->threshold_size &&
2ad87305
PX
3100 atomic_read(&s->start_postcopy)) {
3101 if (postcopy_start(s)) {
3102 error_report("%s: postcopy failed to start", __func__);
3103 }
3104 return MIG_ITERATE_SKIP;
3105 }
3106 /* Just another iteration step */
3107 qemu_savevm_state_iterate(s->to_dst_file,
3108 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
3109 } else {
3110 trace_migration_thread_low_pending(pending_size);
3111 migration_completion(s);
3112 return MIG_ITERATE_BREAK;
3113 }
3114
3115 return MIG_ITERATE_RESUME;
3116}
3117
199aa6d4
PX
3118static void migration_iteration_finish(MigrationState *s)
3119{
3120 /* If we enabled cpu throttling for auto-converge, turn it off. */
3121 cpu_throttle_stop();
3122
3123 qemu_mutex_lock_iothread();
3124 switch (s->state) {
3125 case MIGRATION_STATUS_COMPLETED:
3126 migration_calculate_complete(s);
3127 runstate_set(RUN_STATE_POSTMIGRATE);
3128 break;
3129
3130 case MIGRATION_STATUS_ACTIVE:
3131 /*
3132 * We should really assert here, but since it's during
3133 * migration, let's try to reduce the usage of assertions.
3134 */
3135 if (!migrate_colo_enabled()) {
3136 error_report("%s: critical error: calling COLO code without "
3137 "COLO enabled", __func__);
3138 }
3139 migrate_start_colo_process(s);
3140 /*
3141 * Fixme: we will run VM in COLO no matter its old running state.
3142 * After exited COLO, we will keep running.
3143 */
3144 s->vm_was_running = true;
3145 /* Fallthrough */
3146 case MIGRATION_STATUS_FAILED:
3147 case MIGRATION_STATUS_CANCELLED:
57225e5f 3148 case MIGRATION_STATUS_CANCELLING:
199aa6d4
PX
3149 if (s->vm_was_running) {
3150 vm_start();
3151 } else {
3152 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
3153 runstate_set(RUN_STATE_POSTMIGRATE);
3154 }
3155 }
3156 break;
3157
3158 default:
3159 /* Should not reach here, but if so, forgive the VM. */
3160 error_report("%s: Unknown ending state %d", __func__, s->state);
3161 break;
3162 }
fd392cfa 3163 migrate_fd_cleanup_schedule(s);
199aa6d4
PX
3164 qemu_mutex_unlock_iothread();
3165}
3166
ad767bed
DDAG
3167void migration_make_urgent_request(void)
3168{
3169 qemu_sem_post(&migrate_get_current()->rate_limit_sem);
3170}
3171
3172void migration_consume_urgent_request(void)
3173{
3174 qemu_sem_wait(&migrate_get_current()->rate_limit_sem);
3175}
3176
70b20477
DDAG
3177/*
3178 * Master migration thread on the source VM.
3179 * It drives the migration and pumps the data down the outgoing channel.
3180 */
5f496a1b 3181static void *migration_thread(void *opaque)
0d82d0e8 3182{
9848a404 3183 MigrationState *s = opaque;
bc72ad67 3184 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
b23c2ade 3185 MigThrError thr_error;
ad767bed 3186 bool urgent = false;
76f5933a 3187
ab28bd23
PB
3188 rcu_register_thread();
3189
892ae715 3190 object_ref(OBJECT(s));
b15df1ae
PX
3191 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3192
89a02a9f 3193 qemu_savevm_state_header(s->to_dst_file);
1d34e4bf 3194
62a02658
PX
3195 /*
3196 * If we opened the return path, we need to make sure dst has it
3197 * opened as well.
3198 */
3199 if (s->rp_state.from_dst_file) {
1d34e4bf 3200 /* Now tell the dest that it should open its end so it can reply */
89a02a9f 3201 qemu_savevm_send_open_return_path(s->to_dst_file);
1d34e4bf
DDAG
3202
3203 /* And do a ping that will make stuff easier to debug */
89a02a9f 3204 qemu_savevm_send_ping(s->to_dst_file, 1);
0425dc97 3205 }
1d34e4bf 3206
58110f0a 3207 if (migrate_postcopy()) {
1d34e4bf
DDAG
3208 /*
3209 * Tell the destination that we *might* want to do postcopy later;
3210 * if the other end can't do postcopy it should fail now, nice and
3211 * early.
3212 */
89a02a9f 3213 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1d34e4bf
DDAG
3214 }
3215
aad555c2
ZC
3216 if (migrate_colo_enabled()) {
3217 /* Notify migration destination that we enable COLO */
3218 qemu_savevm_send_colo_enable(s->to_dst_file);
3219 }
3220
9907e842 3221 qemu_savevm_state_setup(s->to_dst_file);
0d82d0e8 3222
bc72ad67 3223 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
48781e5b
HZ
3224 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3225 MIGRATION_STATUS_ACTIVE);
29ae8a41 3226
9ec055ae
DDAG
3227 trace_migration_thread_setup_complete();
3228
3229 while (s->state == MIGRATION_STATUS_ACTIVE ||
3230 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
a3e879cd 3231 int64_t current_time;
0d82d0e8 3232
ad767bed 3233 if (urgent || !qemu_file_rate_limit(s->to_dst_file)) {
2ad87305
PX
3234 MigIterateState iter_state = migration_iteration_run(s);
3235 if (iter_state == MIG_ITERATE_SKIP) {
3236 continue;
3237 } else if (iter_state == MIG_ITERATE_BREAK) {
09f6c85e 3238 break;
c369f40d
JQ
3239 }
3240 }
f4410a5d 3241
b23c2ade
PX
3242 /*
3243 * Try to detect any kind of failures, and see whether we
3244 * should stop the migration now.
3245 */
3246 thr_error = migration_detect_error(s);
3247 if (thr_error == MIG_THR_ERR_FATAL) {
3248 /* Stop migration */
fd45ee2c 3249 break;
b23c2ade
PX
3250 } else if (thr_error == MIG_THR_ERR_RECOVERED) {
3251 /*
3252 * Just recovered from a e.g. network failure, reset all
3253 * the local variables. This is important to avoid
3254 * breaking transferred_bytes and bandwidth calculation
3255 */
3256 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
3257 s->iteration_initial_bytes = 0;
fd45ee2c 3258 }
b15df1ae 3259
bc72ad67 3260 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
0d82d0e8 3261
b15df1ae
PX
3262 migration_update_counters(s, current_time);
3263
ad767bed 3264 urgent = false;
89a02a9f 3265 if (qemu_file_rate_limit(s->to_dst_file)) {
ad767bed
DDAG
3266 /* Wait for a delay to do rate limiting OR
3267 * something urgent to post the semaphore.
3268 */
3269 int ms = s->iteration_start_time + BUFFER_DELAY - current_time;
3270 trace_migration_thread_ratelimit_pre(ms);
3271 if (qemu_sem_timedwait(&s->rate_limit_sem, ms) == 0) {
3272 /* We were worken by one or more urgent things but
3273 * the timedwait will have consumed one of them.
3274 * The service routine for the urgent wake will dec
3275 * the semaphore itself for each item it consumes,
3276 * so add this one we just eat back.
3277 */
3278 qemu_sem_post(&s->rate_limit_sem);
3279 urgent = true;
3280 }
3281 trace_migration_thread_ratelimit_post(urgent);
0d82d0e8 3282 }
a3fa1d78
PB
3283 }
3284
1d34e4bf 3285 trace_migration_thread_after_loop();
199aa6d4 3286 migration_iteration_finish(s);
892ae715 3287 object_unref(OBJECT(s));
ab28bd23 3288 rcu_unregister_thread();
0d82d0e8
JQ
3289 return NULL;
3290}
3291
cce8040b 3292void migrate_fd_connect(MigrationState *s, Error *error_in)
0d82d0e8 3293{
d3e35b8f
PX
3294 int64_t rate_limit;
3295 bool resume = s->state == MIGRATION_STATUS_POSTCOPY_PAUSED;
3296
2ff30257 3297 s->expected_downtime = s->parameters.downtime_limit;
fd392cfa 3298 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup_bh, s);
cce8040b
DDAG
3299 if (error_in) {
3300 migrate_fd_error(s, error_in);
3301 migrate_fd_cleanup(s);
3302 return;
3303 }
0d82d0e8 3304
d3e35b8f
PX
3305 if (resume) {
3306 /* This is a resumed migration */
3307 rate_limit = INT64_MAX;
3308 } else {
3309 /* This is a fresh new migration */
3310 rate_limit = s->parameters.max_bandwidth / XFER_LIMIT_RATIO;
442773ce 3311
d3e35b8f
PX
3312 /* Notify before starting migration thread */
3313 notifier_list_notify(&migration_state_notifiers, s);
3314 }
3315
3316 qemu_file_set_rate_limit(s->to_dst_file, rate_limit);
3317 qemu_file_set_blocking(s->to_dst_file, true);
9287ac27 3318
1d34e4bf 3319 /*
c788ada8
PX
3320 * Open the return path. For postcopy, it is used exclusively. For
3321 * precopy, only if user specified "return-path" capability would
3322 * QEMU uses the return path.
1d34e4bf 3323 */
c788ada8 3324 if (migrate_postcopy_ram() || migrate_use_return_path()) {
d3e35b8f 3325 if (open_return_path_on_source(s, !resume)) {
1d34e4bf 3326 error_report("Unable to open return-path for postcopy");
d3e35b8f 3327 migrate_set_state(&s->state, s->state, MIGRATION_STATUS_FAILED);
1d34e4bf
DDAG
3328 migrate_fd_cleanup(s);
3329 return;
3330 }
3331 }
3332
d3e35b8f 3333 if (resume) {
135b87b4
PX
3334 /* Wakeup the main migration thread to do the recovery */
3335 migrate_set_state(&s->state, MIGRATION_STATUS_POSTCOPY_PAUSED,
3336 MIGRATION_STATUS_POSTCOPY_RECOVER);
3337 qemu_sem_post(&s->postcopy_pause_sem);
d3e35b8f
PX
3338 return;
3339 }
3340
f986c3d2
JQ
3341 if (multifd_save_setup() != 0) {
3342 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
3343 MIGRATION_STATUS_FAILED);
3344 migrate_fd_cleanup(s);
3345 return;
3346 }
009fad7f 3347 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
bb1fadc4 3348 QEMU_THREAD_JOINABLE);
1d34e4bf 3349 s->migration_thread_running = true;
0d82d0e8 3350}
093e3c42 3351
9d18af93
PX
3352void migration_global_dump(Monitor *mon)
3353{
3354 MigrationState *ms = migrate_get_current();
3355
6f0f6428
JQ
3356 monitor_printf(mon, "globals:\n");
3357 monitor_printf(mon, "store-global-state: %s\n",
3358 ms->store_global_state ? "on" : "off");
3359 monitor_printf(mon, "only-migratable: %s\n",
811f8652 3360 only_migratable ? "on" : "off");
6f0f6428
JQ
3361 monitor_printf(mon, "send-configuration: %s\n",
3362 ms->send_configuration ? "on" : "off");
3363 monitor_printf(mon, "send-section-footer: %s\n",
3364 ms->send_section_footer ? "on" : "off");
f548222c
XG
3365 monitor_printf(mon, "decompress-error-check: %s\n",
3366 ms->decompress_error_check ? "on" : "off");
002cad6b
PX
3367 monitor_printf(mon, "clear-bitmap-shift: %u\n",
3368 ms->clear_bitmap_shift);
9d18af93
PX
3369}
3370
20814758
PX
3371#define DEFINE_PROP_MIG_CAP(name, x) \
3372 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
3373
5272298c
PX
3374static Property migration_properties[] = {
3375 DEFINE_PROP_BOOL("store-global-state", MigrationState,
3376 store_global_state, true),
71dd4c1a
PX
3377 DEFINE_PROP_BOOL("send-configuration", MigrationState,
3378 send_configuration, true),
15c38503
PX
3379 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
3380 send_section_footer, true),
f548222c
XG
3381 DEFINE_PROP_BOOL("decompress-error-check", MigrationState,
3382 decompress_error_check, true),
002cad6b
PX
3383 DEFINE_PROP_UINT8("x-clear-bitmap-shift", MigrationState,
3384 clear_bitmap_shift, CLEAR_BITMAP_SHIFT_DEFAULT),
89632faf
PX
3385
3386 /* Migration parameters */
741d4086 3387 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
89632faf
PX
3388 parameters.compress_level,
3389 DEFAULT_MIGRATE_COMPRESS_LEVEL),
741d4086 3390 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
89632faf
PX
3391 parameters.compress_threads,
3392 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
1d58872a
XG
3393 DEFINE_PROP_BOOL("x-compress-wait-thread", MigrationState,
3394 parameters.compress_wait_thread, true),
741d4086 3395 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
89632faf
PX
3396 parameters.decompress_threads,
3397 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
741d4086 3398 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
89632faf
PX
3399 parameters.cpu_throttle_initial,
3400 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
741d4086 3401 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
89632faf
PX
3402 parameters.cpu_throttle_increment,
3403 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
741d4086 3404 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
89632faf 3405 parameters.max_bandwidth, MAX_THROTTLE),
741d4086 3406 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
89632faf
PX
3407 parameters.downtime_limit,
3408 DEFAULT_MIGRATE_SET_DOWNTIME),
741d4086 3409 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
89632faf
PX
3410 parameters.x_checkpoint_delay,
3411 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
cbfd6c95
JQ
3412 DEFINE_PROP_UINT8("multifd-channels", MigrationState,
3413 parameters.multifd_channels,
4075fb1c 3414 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
73af8dd8
JQ
3415 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
3416 parameters.xbzrle_cache_size,
3417 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
7e555c6c
DDAG
3418 DEFINE_PROP_SIZE("max-postcopy-bandwidth", MigrationState,
3419 parameters.max_postcopy_bandwidth,
3420 DEFAULT_MIGRATE_MAX_POSTCOPY_BANDWIDTH),
4cbc9c7f
LQ
3421 DEFINE_PROP_UINT8("max-cpu-throttle", MigrationState,
3422 parameters.max_cpu_throttle,
3423 DEFAULT_MIGRATE_MAX_CPU_THROTTLE),
ee3d96ba
DDAG
3424 DEFINE_PROP_SIZE("announce-initial", MigrationState,
3425 parameters.announce_initial,
3426 DEFAULT_MIGRATE_ANNOUNCE_INITIAL),
3427 DEFINE_PROP_SIZE("announce-max", MigrationState,
3428 parameters.announce_max,
3429 DEFAULT_MIGRATE_ANNOUNCE_MAX),
3430 DEFINE_PROP_SIZE("announce-rounds", MigrationState,
3431 parameters.announce_rounds,
3432 DEFAULT_MIGRATE_ANNOUNCE_ROUNDS),
3433 DEFINE_PROP_SIZE("announce-step", MigrationState,
3434 parameters.announce_step,
3435 DEFAULT_MIGRATE_ANNOUNCE_STEP),
20814758
PX
3436
3437 /* Migration capabilities */
3438 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
3439 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
3440 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
3441 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
3442 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
3443 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
3444 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
3445 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
3446 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
3447 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
3448 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
cbfd6c95 3449 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_MULTIFD),
20814758 3450
5272298c
PX
3451 DEFINE_PROP_END_OF_LIST(),
3452};
3453
e5cb7e76
PX
3454static void migration_class_init(ObjectClass *klass, void *data)
3455{
3456 DeviceClass *dc = DEVICE_CLASS(klass);
3457
3458 dc->user_creatable = false;
5272298c 3459 dc->props = migration_properties;
e5cb7e76
PX
3460}
3461
b91bf5e4
MAL
3462static void migration_instance_finalize(Object *obj)
3463{
3464 MigrationState *ms = MIGRATION_OBJ(obj);
3465 MigrationParameters *params = &ms->parameters;
3466
87db1a7d 3467 qemu_mutex_destroy(&ms->error_mutex);
62df066f 3468 qemu_mutex_destroy(&ms->qemu_file_lock);
b91bf5e4
MAL
3469 g_free(params->tls_hostname);
3470 g_free(params->tls_creds);
ad767bed 3471 qemu_sem_destroy(&ms->rate_limit_sem);
e91d8951 3472 qemu_sem_destroy(&ms->pause_sem);
b23c2ade 3473 qemu_sem_destroy(&ms->postcopy_pause_sem);
14b1742e 3474 qemu_sem_destroy(&ms->postcopy_pause_rp_sem);
edd090c7 3475 qemu_sem_destroy(&ms->rp_state.rp_sem);
ab105cc1 3476 error_free(ms->error);
b91bf5e4
MAL
3477}
3478
e5cb7e76
PX
3479static void migration_instance_init(Object *obj)
3480{
3481 MigrationState *ms = MIGRATION_OBJ(obj);
8b0b29dc 3482 MigrationParameters *params = &ms->parameters;
e5cb7e76
PX
3483
3484 ms->state = MIGRATION_STATUS_NONE;
e5cb7e76 3485 ms->mbps = -1;
aecbfe9c 3486 ms->pages_per_second = -1;
e91d8951 3487 qemu_sem_init(&ms->pause_sem, 0);
87db1a7d 3488 qemu_mutex_init(&ms->error_mutex);
8b0b29dc
PX
3489
3490 params->tls_hostname = g_strdup("");
3491 params->tls_creds = g_strdup("");
3492
3493 /* Set has_* up only for parameter checks */
3494 params->has_compress_level = true;
3495 params->has_compress_threads = true;
3496 params->has_decompress_threads = true;
3497 params->has_cpu_throttle_initial = true;
3498 params->has_cpu_throttle_increment = true;
3499 params->has_max_bandwidth = true;
3500 params->has_downtime_limit = true;
3501 params->has_x_checkpoint_delay = true;
3502 params->has_block_incremental = true;
cbfd6c95 3503 params->has_multifd_channels = true;
73af8dd8 3504 params->has_xbzrle_cache_size = true;
7e555c6c 3505 params->has_max_postcopy_bandwidth = true;
4cbc9c7f 3506 params->has_max_cpu_throttle = true;
ee3d96ba
DDAG
3507 params->has_announce_initial = true;
3508 params->has_announce_max = true;
3509 params->has_announce_rounds = true;
3510 params->has_announce_step = true;
b23c2ade
PX
3511
3512 qemu_sem_init(&ms->postcopy_pause_sem, 0);
14b1742e 3513 qemu_sem_init(&ms->postcopy_pause_rp_sem, 0);
edd090c7 3514 qemu_sem_init(&ms->rp_state.rp_sem, 0);
ad767bed 3515 qemu_sem_init(&ms->rate_limit_sem, 0);
62df066f 3516 qemu_mutex_init(&ms->qemu_file_lock);
8b0b29dc
PX
3517}
3518
3519/*
3520 * Return true if check pass, false otherwise. Error will be put
3521 * inside errp if provided.
3522 */
3523static bool migration_object_check(MigrationState *ms, Error **errp)
3524{
6b19a7d9
PX
3525 MigrationCapabilityStatusList *head = NULL;
3526 /* Assuming all off */
3527 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
3528 int i;
3529
8b0b29dc
PX
3530 if (!migrate_params_check(&ms->parameters, errp)) {
3531 return false;
3532 }
3533
6b19a7d9
PX
3534 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
3535 if (ms->enabled_capabilities[i]) {
3536 head = migrate_cap_add(head, i, true);
3537 }
3538 }
3539
3540 ret = migrate_caps_check(cap_list, head, errp);
3541
3542 /* It works with head == NULL */
3543 qapi_free_MigrationCapabilityStatusList(head);
3544
3545 return ret;
e5cb7e76
PX
3546}
3547
3548static const TypeInfo migration_type = {
3549 .name = TYPE_MIGRATION,
01f6e14c 3550 /*
c8d3ff38
PX
3551 * NOTE: TYPE_MIGRATION is not really a device, as the object is
3552 * not created using qdev_create(), it is not attached to the qdev
3553 * device tree, and it is never realized.
3554 *
3555 * TODO: Make this TYPE_OBJECT once QOM provides something like
3556 * TYPE_DEVICE's "-global" properties.
01f6e14c 3557 */
e5cb7e76
PX
3558 .parent = TYPE_DEVICE,
3559 .class_init = migration_class_init,
3560 .class_size = sizeof(MigrationClass),
3561 .instance_size = sizeof(MigrationState),
3562 .instance_init = migration_instance_init,
b91bf5e4 3563 .instance_finalize = migration_instance_finalize,
e5cb7e76
PX
3564};
3565
3566static void register_migration_types(void)
3567{
3568 type_register_static(&migration_type);
3569}
3570
3571type_init(register_migration_types);