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