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