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