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