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