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