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