xref: /openbmc/qemu/migration/migration.c (revision d341d9f3)
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-common.h"
17 #include "qemu/error-report.h"
18 #include "qemu/main-loop.h"
19 #include "migration/migration.h"
20 #include "migration/qemu-file.h"
21 #include "sysemu/sysemu.h"
22 #include "block/block.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qapi/util.h"
25 #include "qemu/sockets.h"
26 #include "qemu/rcu.h"
27 #include "migration/block.h"
28 #include "migration/postcopy-ram.h"
29 #include "qemu/thread.h"
30 #include "qmp-commands.h"
31 #include "trace.h"
32 #include "qapi-event.h"
33 #include "qom/cpu.h"
34 #include "exec/memory.h"
35 #include "exec/address-spaces.h"
36 
37 #define MAX_THROTTLE  (32 << 20)      /* Migration transfer speed throttling */
38 
39 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
40  * data. */
41 #define BUFFER_DELAY     100
42 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
43 
44 /* Default compression thread count */
45 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
46 /* Default decompression thread count, usually decompression is at
47  * least 4 times as fast as compression.*/
48 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
49 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
50 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
51 /* Define default autoconverge cpu throttle migration parameters */
52 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL 20
53 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT 10
54 
55 /* Migration XBZRLE default cache size */
56 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
57 
58 static NotifierList migration_state_notifiers =
59     NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
60 
61 static bool deferred_incoming;
62 
63 /*
64  * Current state of incoming postcopy; note this is not part of
65  * MigrationIncomingState since it's state is used during cleanup
66  * at the end as MIS is being freed.
67  */
68 static PostcopyState incoming_postcopy_state;
69 
70 /* When we add fault tolerance, we could have several
71    migrations at once.  For now we don't need to add
72    dynamic creation of migration */
73 
74 /* For outgoing */
75 MigrationState *migrate_get_current(void)
76 {
77     static bool once;
78     static MigrationState current_migration = {
79         .state = MIGRATION_STATUS_NONE,
80         .bandwidth_limit = MAX_THROTTLE,
81         .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
82         .mbps = -1,
83         .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
84                 DEFAULT_MIGRATE_COMPRESS_LEVEL,
85         .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
86                 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
87         .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
88                 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
89         .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
90                 DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL,
91         .parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
92                 DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT,
93     };
94 
95     if (!once) {
96         qemu_mutex_init(&current_migration.src_page_req_mutex);
97         once = true;
98     }
99     return &current_migration;
100 }
101 
102 /* For incoming */
103 static MigrationIncomingState *mis_current;
104 
105 MigrationIncomingState *migration_incoming_get_current(void)
106 {
107     return mis_current;
108 }
109 
110 MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
111 {
112     mis_current = g_new0(MigrationIncomingState, 1);
113     mis_current->from_src_file = f;
114     mis_current->state = MIGRATION_STATUS_NONE;
115     QLIST_INIT(&mis_current->loadvm_handlers);
116     qemu_mutex_init(&mis_current->rp_mutex);
117     qemu_event_init(&mis_current->main_thread_load_event, false);
118 
119     return mis_current;
120 }
121 
122 void migration_incoming_state_destroy(void)
123 {
124     qemu_event_destroy(&mis_current->main_thread_load_event);
125     loadvm_free_handlers(mis_current);
126     g_free(mis_current);
127     mis_current = NULL;
128 }
129 
130 
131 typedef struct {
132     bool optional;
133     uint32_t size;
134     uint8_t runstate[100];
135     RunState state;
136     bool received;
137 } GlobalState;
138 
139 static GlobalState global_state;
140 
141 int global_state_store(void)
142 {
143     if (!runstate_store((char *)global_state.runstate,
144                         sizeof(global_state.runstate))) {
145         error_report("runstate name too big: %s", global_state.runstate);
146         trace_migrate_state_too_big();
147         return -EINVAL;
148     }
149     return 0;
150 }
151 
152 void global_state_store_running(void)
153 {
154     const char *state = RunState_lookup[RUN_STATE_RUNNING];
155     strncpy((char *)global_state.runstate,
156            state, sizeof(global_state.runstate));
157 }
158 
159 static bool global_state_received(void)
160 {
161     return global_state.received;
162 }
163 
164 static RunState global_state_get_runstate(void)
165 {
166     return global_state.state;
167 }
168 
169 void global_state_set_optional(void)
170 {
171     global_state.optional = true;
172 }
173 
174 static bool global_state_needed(void *opaque)
175 {
176     GlobalState *s = opaque;
177     char *runstate = (char *)s->runstate;
178 
179     /* If it is not optional, it is mandatory */
180 
181     if (s->optional == false) {
182         return true;
183     }
184 
185     /* If state is running or paused, it is not needed */
186 
187     if (strcmp(runstate, "running") == 0 ||
188         strcmp(runstate, "paused") == 0) {
189         return false;
190     }
191 
192     /* for any other state it is needed */
193     return true;
194 }
195 
196 static int global_state_post_load(void *opaque, int version_id)
197 {
198     GlobalState *s = opaque;
199     Error *local_err = NULL;
200     int r;
201     char *runstate = (char *)s->runstate;
202 
203     s->received = true;
204     trace_migrate_global_state_post_load(runstate);
205 
206     r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE__MAX,
207                                 -1, &local_err);
208 
209     if (r == -1) {
210         if (local_err) {
211             error_report_err(local_err);
212         }
213         return -EINVAL;
214     }
215     s->state = r;
216 
217     return 0;
218 }
219 
220 static void global_state_pre_save(void *opaque)
221 {
222     GlobalState *s = opaque;
223 
224     trace_migrate_global_state_pre_save((char *)s->runstate);
225     s->size = strlen((char *)s->runstate) + 1;
226 }
227 
228 static const VMStateDescription vmstate_globalstate = {
229     .name = "globalstate",
230     .version_id = 1,
231     .minimum_version_id = 1,
232     .post_load = global_state_post_load,
233     .pre_save = global_state_pre_save,
234     .needed = global_state_needed,
235     .fields = (VMStateField[]) {
236         VMSTATE_UINT32(size, GlobalState),
237         VMSTATE_BUFFER(runstate, GlobalState),
238         VMSTATE_END_OF_LIST()
239     },
240 };
241 
242 void register_global_state(void)
243 {
244     /* We would use it independently that we receive it */
245     strcpy((char *)&global_state.runstate, "");
246     global_state.received = false;
247     vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
248 }
249 
250 static void migrate_generate_event(int new_state)
251 {
252     if (migrate_use_events()) {
253         qapi_event_send_migration(new_state, &error_abort);
254     }
255 }
256 
257 /*
258  * Called on -incoming with a defer: uri.
259  * The migration can be started later after any parameters have been
260  * changed.
261  */
262 static void deferred_incoming_migration(Error **errp)
263 {
264     if (deferred_incoming) {
265         error_setg(errp, "Incoming migration already deferred");
266     }
267     deferred_incoming = true;
268 }
269 
270 /* Request a range of pages from the source VM at the given
271  * start address.
272  *   rbname: Name of the RAMBlock to request the page in, if NULL it's the same
273  *           as the last request (a name must have been given previously)
274  *   Start: Address offset within the RB
275  *   Len: Length in bytes required - must be a multiple of pagesize
276  */
277 void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
278                                ram_addr_t start, size_t len)
279 {
280     uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname upto 256 */
281     size_t msglen = 12; /* start + len */
282 
283     *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
284     *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
285 
286     if (rbname) {
287         int rbname_len = strlen(rbname);
288         assert(rbname_len < 256);
289 
290         bufc[msglen++] = rbname_len;
291         memcpy(bufc + msglen, rbname, rbname_len);
292         msglen += rbname_len;
293         migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES_ID, msglen, bufc);
294     } else {
295         migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES, msglen, bufc);
296     }
297 }
298 
299 void qemu_start_incoming_migration(const char *uri, Error **errp)
300 {
301     const char *p;
302 
303     qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
304     if (!strcmp(uri, "defer")) {
305         deferred_incoming_migration(errp);
306     } else if (strstart(uri, "tcp:", &p)) {
307         tcp_start_incoming_migration(p, errp);
308 #ifdef CONFIG_RDMA
309     } else if (strstart(uri, "rdma:", &p)) {
310         rdma_start_incoming_migration(p, errp);
311 #endif
312 #if !defined(WIN32)
313     } else if (strstart(uri, "exec:", &p)) {
314         exec_start_incoming_migration(p, errp);
315     } else if (strstart(uri, "unix:", &p)) {
316         unix_start_incoming_migration(p, errp);
317     } else if (strstart(uri, "fd:", &p)) {
318         fd_start_incoming_migration(p, errp);
319 #endif
320     } else {
321         error_setg(errp, "unknown migration protocol: %s", uri);
322     }
323 }
324 
325 static void process_incoming_migration_co(void *opaque)
326 {
327     QEMUFile *f = opaque;
328     Error *local_err = NULL;
329     MigrationIncomingState *mis;
330     PostcopyState ps;
331     int ret;
332 
333     mis = migration_incoming_state_new(f);
334     postcopy_state_set(POSTCOPY_INCOMING_NONE);
335     migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
336                       MIGRATION_STATUS_ACTIVE);
337     ret = qemu_loadvm_state(f);
338 
339     ps = postcopy_state_get();
340     trace_process_incoming_migration_co_end(ret, ps);
341     if (ps != POSTCOPY_INCOMING_NONE) {
342         if (ps == POSTCOPY_INCOMING_ADVISE) {
343             /*
344              * Where a migration had postcopy enabled (and thus went to advise)
345              * but managed to complete within the precopy period, we can use
346              * the normal exit.
347              */
348             postcopy_ram_incoming_cleanup(mis);
349         } else if (ret >= 0) {
350             /*
351              * Postcopy was started, cleanup should happen at the end of the
352              * postcopy thread.
353              */
354             trace_process_incoming_migration_co_postcopy_end_main();
355             return;
356         }
357         /* Else if something went wrong then just fall out of the normal exit */
358     }
359 
360     qemu_fclose(f);
361     free_xbzrle_decoded_buf();
362 
363     if (ret < 0) {
364         migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
365                           MIGRATION_STATUS_FAILED);
366         error_report("load of migration failed: %s", strerror(-ret));
367         migrate_decompress_threads_join();
368         exit(EXIT_FAILURE);
369     }
370 
371     /* Make sure all file formats flush their mutable metadata */
372     bdrv_invalidate_cache_all(&local_err);
373     if (local_err) {
374         migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
375                           MIGRATION_STATUS_FAILED);
376         error_report_err(local_err);
377         migrate_decompress_threads_join();
378         exit(EXIT_FAILURE);
379     }
380 
381     /*
382      * This must happen after all error conditions are dealt with and
383      * we're sure the VM is going to be running on this host.
384      */
385     qemu_announce_self();
386 
387     /* If global state section was not received or we are in running
388        state, we need to obey autostart. Any other state is set with
389        runstate_set. */
390 
391     if (!global_state_received() ||
392         global_state_get_runstate() == RUN_STATE_RUNNING) {
393         if (autostart) {
394             vm_start();
395         } else {
396             runstate_set(RUN_STATE_PAUSED);
397         }
398     } else {
399         runstate_set(global_state_get_runstate());
400     }
401     migrate_decompress_threads_join();
402     /*
403      * This must happen after any state changes since as soon as an external
404      * observer sees this event they might start to prod at the VM assuming
405      * it's ready to use.
406      */
407     migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
408                       MIGRATION_STATUS_COMPLETED);
409     migration_incoming_state_destroy();
410 }
411 
412 void process_incoming_migration(QEMUFile *f)
413 {
414     Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
415     int fd = qemu_get_fd(f);
416 
417     assert(fd != -1);
418     migrate_decompress_threads_create();
419     qemu_set_nonblock(fd);
420     qemu_coroutine_enter(co, f);
421 }
422 
423 /*
424  * Send a message on the return channel back to the source
425  * of the migration.
426  */
427 void migrate_send_rp_message(MigrationIncomingState *mis,
428                              enum mig_rp_message_type message_type,
429                              uint16_t len, void *data)
430 {
431     trace_migrate_send_rp_message((int)message_type, len);
432     qemu_mutex_lock(&mis->rp_mutex);
433     qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
434     qemu_put_be16(mis->to_src_file, len);
435     qemu_put_buffer(mis->to_src_file, data, len);
436     qemu_fflush(mis->to_src_file);
437     qemu_mutex_unlock(&mis->rp_mutex);
438 }
439 
440 /*
441  * Send a 'SHUT' message on the return channel with the given value
442  * to indicate that we've finished with the RP.  Non-0 value indicates
443  * error.
444  */
445 void migrate_send_rp_shut(MigrationIncomingState *mis,
446                           uint32_t value)
447 {
448     uint32_t buf;
449 
450     buf = cpu_to_be32(value);
451     migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
452 }
453 
454 /*
455  * Send a 'PONG' message on the return channel with the given value
456  * (normally in response to a 'PING')
457  */
458 void migrate_send_rp_pong(MigrationIncomingState *mis,
459                           uint32_t value)
460 {
461     uint32_t buf;
462 
463     buf = cpu_to_be32(value);
464     migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
465 }
466 
467 /* amount of nanoseconds we are willing to wait for migration to be down.
468  * the choice of nanoseconds is because it is the maximum resolution that
469  * get_clock() can achieve. It is an internal measure. All user-visible
470  * units must be in seconds */
471 static uint64_t max_downtime = 300000000;
472 
473 uint64_t migrate_max_downtime(void)
474 {
475     return max_downtime;
476 }
477 
478 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
479 {
480     MigrationCapabilityStatusList *head = NULL;
481     MigrationCapabilityStatusList *caps;
482     MigrationState *s = migrate_get_current();
483     int i;
484 
485     caps = NULL; /* silence compiler warning */
486     for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
487         if (head == NULL) {
488             head = g_malloc0(sizeof(*caps));
489             caps = head;
490         } else {
491             caps->next = g_malloc0(sizeof(*caps));
492             caps = caps->next;
493         }
494         caps->value =
495             g_malloc(sizeof(*caps->value));
496         caps->value->capability = i;
497         caps->value->state = s->enabled_capabilities[i];
498     }
499 
500     return head;
501 }
502 
503 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
504 {
505     MigrationParameters *params;
506     MigrationState *s = migrate_get_current();
507 
508     params = g_malloc0(sizeof(*params));
509     params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
510     params->compress_threads =
511             s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
512     params->decompress_threads =
513             s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
514     params->x_cpu_throttle_initial =
515             s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL];
516     params->x_cpu_throttle_increment =
517             s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT];
518 
519     return params;
520 }
521 
522 /*
523  * Return true if we're already in the middle of a migration
524  * (i.e. any of the active or setup states)
525  */
526 static bool migration_is_setup_or_active(int state)
527 {
528     switch (state) {
529     case MIGRATION_STATUS_ACTIVE:
530     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
531     case MIGRATION_STATUS_SETUP:
532         return true;
533 
534     default:
535         return false;
536 
537     }
538 }
539 
540 static void get_xbzrle_cache_stats(MigrationInfo *info)
541 {
542     if (migrate_use_xbzrle()) {
543         info->has_xbzrle_cache = true;
544         info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
545         info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
546         info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
547         info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
548         info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
549         info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
550         info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
551     }
552 }
553 
554 MigrationInfo *qmp_query_migrate(Error **errp)
555 {
556     MigrationInfo *info = g_malloc0(sizeof(*info));
557     MigrationState *s = migrate_get_current();
558 
559     switch (s->state) {
560     case MIGRATION_STATUS_NONE:
561         /* no migration has happened ever */
562         break;
563     case MIGRATION_STATUS_SETUP:
564         info->has_status = true;
565         info->has_total_time = false;
566         break;
567     case MIGRATION_STATUS_ACTIVE:
568     case MIGRATION_STATUS_CANCELLING:
569         info->has_status = true;
570         info->has_total_time = true;
571         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
572             - s->total_time;
573         info->has_expected_downtime = true;
574         info->expected_downtime = s->expected_downtime;
575         info->has_setup_time = true;
576         info->setup_time = s->setup_time;
577 
578         info->has_ram = true;
579         info->ram = g_malloc0(sizeof(*info->ram));
580         info->ram->transferred = ram_bytes_transferred();
581         info->ram->remaining = ram_bytes_remaining();
582         info->ram->total = ram_bytes_total();
583         info->ram->duplicate = dup_mig_pages_transferred();
584         info->ram->skipped = skipped_mig_pages_transferred();
585         info->ram->normal = norm_mig_pages_transferred();
586         info->ram->normal_bytes = norm_mig_bytes_transferred();
587         info->ram->dirty_pages_rate = s->dirty_pages_rate;
588         info->ram->mbps = s->mbps;
589         info->ram->dirty_sync_count = s->dirty_sync_count;
590 
591         if (blk_mig_active()) {
592             info->has_disk = true;
593             info->disk = g_malloc0(sizeof(*info->disk));
594             info->disk->transferred = blk_mig_bytes_transferred();
595             info->disk->remaining = blk_mig_bytes_remaining();
596             info->disk->total = blk_mig_bytes_total();
597         }
598 
599         if (cpu_throttle_active()) {
600             info->has_x_cpu_throttle_percentage = true;
601             info->x_cpu_throttle_percentage = cpu_throttle_get_percentage();
602         }
603 
604         get_xbzrle_cache_stats(info);
605         break;
606     case MIGRATION_STATUS_POSTCOPY_ACTIVE:
607         /* Mostly the same as active; TODO add some postcopy stats */
608         info->has_status = true;
609         info->has_total_time = true;
610         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
611             - s->total_time;
612         info->has_expected_downtime = true;
613         info->expected_downtime = s->expected_downtime;
614         info->has_setup_time = true;
615         info->setup_time = s->setup_time;
616 
617         info->has_ram = true;
618         info->ram = g_malloc0(sizeof(*info->ram));
619         info->ram->transferred = ram_bytes_transferred();
620         info->ram->remaining = ram_bytes_remaining();
621         info->ram->total = ram_bytes_total();
622         info->ram->duplicate = dup_mig_pages_transferred();
623         info->ram->skipped = skipped_mig_pages_transferred();
624         info->ram->normal = norm_mig_pages_transferred();
625         info->ram->normal_bytes = norm_mig_bytes_transferred();
626         info->ram->dirty_pages_rate = s->dirty_pages_rate;
627         info->ram->mbps = s->mbps;
628 
629         if (blk_mig_active()) {
630             info->has_disk = true;
631             info->disk = g_malloc0(sizeof(*info->disk));
632             info->disk->transferred = blk_mig_bytes_transferred();
633             info->disk->remaining = blk_mig_bytes_remaining();
634             info->disk->total = blk_mig_bytes_total();
635         }
636 
637         get_xbzrle_cache_stats(info);
638         break;
639     case MIGRATION_STATUS_COMPLETED:
640         get_xbzrle_cache_stats(info);
641 
642         info->has_status = true;
643         info->has_total_time = true;
644         info->total_time = s->total_time;
645         info->has_downtime = true;
646         info->downtime = s->downtime;
647         info->has_setup_time = true;
648         info->setup_time = s->setup_time;
649 
650         info->has_ram = true;
651         info->ram = g_malloc0(sizeof(*info->ram));
652         info->ram->transferred = ram_bytes_transferred();
653         info->ram->remaining = 0;
654         info->ram->total = ram_bytes_total();
655         info->ram->duplicate = dup_mig_pages_transferred();
656         info->ram->skipped = skipped_mig_pages_transferred();
657         info->ram->normal = norm_mig_pages_transferred();
658         info->ram->normal_bytes = norm_mig_bytes_transferred();
659         info->ram->mbps = s->mbps;
660         info->ram->dirty_sync_count = s->dirty_sync_count;
661         break;
662     case MIGRATION_STATUS_FAILED:
663         info->has_status = true;
664         break;
665     case MIGRATION_STATUS_CANCELLED:
666         info->has_status = true;
667         break;
668     }
669     info->status = s->state;
670 
671     return info;
672 }
673 
674 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
675                                   Error **errp)
676 {
677     MigrationState *s = migrate_get_current();
678     MigrationCapabilityStatusList *cap;
679 
680     if (migration_is_setup_or_active(s->state)) {
681         error_setg(errp, QERR_MIGRATION_ACTIVE);
682         return;
683     }
684 
685     for (cap = params; cap; cap = cap->next) {
686         s->enabled_capabilities[cap->value->capability] = cap->value->state;
687     }
688 
689     if (migrate_postcopy_ram()) {
690         if (migrate_use_compression()) {
691             /* The decompression threads asynchronously write into RAM
692              * rather than use the atomic copies needed to avoid
693              * userfaulting.  It should be possible to fix the decompression
694              * threads for compatibility in future.
695              */
696             error_report("Postcopy is not currently compatible with "
697                          "compression");
698             s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM] =
699                 false;
700         }
701     }
702 }
703 
704 void qmp_migrate_set_parameters(bool has_compress_level,
705                                 int64_t compress_level,
706                                 bool has_compress_threads,
707                                 int64_t compress_threads,
708                                 bool has_decompress_threads,
709                                 int64_t decompress_threads,
710                                 bool has_x_cpu_throttle_initial,
711                                 int64_t x_cpu_throttle_initial,
712                                 bool has_x_cpu_throttle_increment,
713                                 int64_t x_cpu_throttle_increment, Error **errp)
714 {
715     MigrationState *s = migrate_get_current();
716 
717     if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
718         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
719                    "is invalid, it should be in the range of 0 to 9");
720         return;
721     }
722     if (has_compress_threads &&
723             (compress_threads < 1 || compress_threads > 255)) {
724         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
725                    "compress_threads",
726                    "is invalid, it should be in the range of 1 to 255");
727         return;
728     }
729     if (has_decompress_threads &&
730             (decompress_threads < 1 || decompress_threads > 255)) {
731         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
732                    "decompress_threads",
733                    "is invalid, it should be in the range of 1 to 255");
734         return;
735     }
736     if (has_x_cpu_throttle_initial &&
737             (x_cpu_throttle_initial < 1 || x_cpu_throttle_initial > 99)) {
738         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
739                    "x_cpu_throttle_initial",
740                    "an integer in the range of 1 to 99");
741     }
742     if (has_x_cpu_throttle_increment &&
743             (x_cpu_throttle_increment < 1 || x_cpu_throttle_increment > 99)) {
744         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
745                    "x_cpu_throttle_increment",
746                    "an integer in the range of 1 to 99");
747     }
748 
749     if (has_compress_level) {
750         s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
751     }
752     if (has_compress_threads) {
753         s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
754     }
755     if (has_decompress_threads) {
756         s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
757                                                     decompress_threads;
758     }
759     if (has_x_cpu_throttle_initial) {
760         s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
761                                                     x_cpu_throttle_initial;
762     }
763 
764     if (has_x_cpu_throttle_increment) {
765         s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
766                                                     x_cpu_throttle_increment;
767     }
768 }
769 
770 void qmp_migrate_start_postcopy(Error **errp)
771 {
772     MigrationState *s = migrate_get_current();
773 
774     if (!migrate_postcopy_ram()) {
775         error_setg(errp, "Enable postcopy with migrate_set_capability before"
776                          " the start of migration");
777         return;
778     }
779 
780     if (s->state == MIGRATION_STATUS_NONE) {
781         error_setg(errp, "Postcopy must be started after migration has been"
782                          " started");
783         return;
784     }
785     /*
786      * we don't error if migration has finished since that would be racy
787      * with issuing this command.
788      */
789     atomic_set(&s->start_postcopy, true);
790 }
791 
792 /* shared migration helpers */
793 
794 void migrate_set_state(int *state, int old_state, int new_state)
795 {
796     if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
797         trace_migrate_set_state(new_state);
798         migrate_generate_event(new_state);
799     }
800 }
801 
802 static void migrate_fd_cleanup(void *opaque)
803 {
804     MigrationState *s = opaque;
805 
806     qemu_bh_delete(s->cleanup_bh);
807     s->cleanup_bh = NULL;
808 
809     flush_page_queue(s);
810 
811     if (s->file) {
812         trace_migrate_fd_cleanup();
813         qemu_mutex_unlock_iothread();
814         if (s->migration_thread_running) {
815             qemu_thread_join(&s->thread);
816             s->migration_thread_running = false;
817         }
818         qemu_mutex_lock_iothread();
819 
820         migrate_compress_threads_join();
821         qemu_fclose(s->file);
822         s->file = NULL;
823     }
824 
825     assert((s->state != MIGRATION_STATUS_ACTIVE) &&
826            (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
827 
828     if (s->state == MIGRATION_STATUS_CANCELLING) {
829         migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
830                           MIGRATION_STATUS_CANCELLED);
831     }
832 
833     notifier_list_notify(&migration_state_notifiers, s);
834 }
835 
836 void migrate_fd_error(MigrationState *s)
837 {
838     trace_migrate_fd_error();
839     assert(s->file == NULL);
840     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
841                       MIGRATION_STATUS_FAILED);
842     notifier_list_notify(&migration_state_notifiers, s);
843 }
844 
845 static void migrate_fd_cancel(MigrationState *s)
846 {
847     int old_state ;
848     QEMUFile *f = migrate_get_current()->file;
849     trace_migrate_fd_cancel();
850 
851     if (s->rp_state.from_dst_file) {
852         /* shutdown the rp socket, so causing the rp thread to shutdown */
853         qemu_file_shutdown(s->rp_state.from_dst_file);
854     }
855 
856     do {
857         old_state = s->state;
858         if (!migration_is_setup_or_active(old_state)) {
859             break;
860         }
861         migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
862     } while (s->state != MIGRATION_STATUS_CANCELLING);
863 
864     /*
865      * If we're unlucky the migration code might be stuck somewhere in a
866      * send/write while the network has failed and is waiting to timeout;
867      * if we've got shutdown(2) available then we can force it to quit.
868      * The outgoing qemu file gets closed in migrate_fd_cleanup that is
869      * called in a bh, so there is no race against this cancel.
870      */
871     if (s->state == MIGRATION_STATUS_CANCELLING && f) {
872         qemu_file_shutdown(f);
873     }
874 }
875 
876 void add_migration_state_change_notifier(Notifier *notify)
877 {
878     notifier_list_add(&migration_state_notifiers, notify);
879 }
880 
881 void remove_migration_state_change_notifier(Notifier *notify)
882 {
883     notifier_remove(notify);
884 }
885 
886 bool migration_in_setup(MigrationState *s)
887 {
888     return s->state == MIGRATION_STATUS_SETUP;
889 }
890 
891 bool migration_has_finished(MigrationState *s)
892 {
893     return s->state == MIGRATION_STATUS_COMPLETED;
894 }
895 
896 bool migration_has_failed(MigrationState *s)
897 {
898     return (s->state == MIGRATION_STATUS_CANCELLED ||
899             s->state == MIGRATION_STATUS_FAILED);
900 }
901 
902 bool migration_in_postcopy(MigrationState *s)
903 {
904     return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
905 }
906 
907 MigrationState *migrate_init(const MigrationParams *params)
908 {
909     MigrationState *s = migrate_get_current();
910 
911     /*
912      * Reinitialise all migration state, except
913      * parameters/capabilities that the user set, and
914      * locks.
915      */
916     s->bytes_xfer = 0;
917     s->xfer_limit = 0;
918     s->cleanup_bh = 0;
919     s->file = NULL;
920     s->state = MIGRATION_STATUS_NONE;
921     s->params = *params;
922     s->rp_state.from_dst_file = NULL;
923     s->rp_state.error = false;
924     s->mbps = 0.0;
925     s->downtime = 0;
926     s->expected_downtime = 0;
927     s->dirty_pages_rate = 0;
928     s->dirty_bytes_rate = 0;
929     s->setup_time = 0;
930     s->dirty_sync_count = 0;
931     s->start_postcopy = false;
932     s->migration_thread_running = false;
933     s->last_req_rb = NULL;
934 
935     migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
936 
937     QSIMPLEQ_INIT(&s->src_page_requests);
938 
939     s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
940     return s;
941 }
942 
943 static GSList *migration_blockers;
944 
945 void migrate_add_blocker(Error *reason)
946 {
947     migration_blockers = g_slist_prepend(migration_blockers, reason);
948 }
949 
950 void migrate_del_blocker(Error *reason)
951 {
952     migration_blockers = g_slist_remove(migration_blockers, reason);
953 }
954 
955 void qmp_migrate_incoming(const char *uri, Error **errp)
956 {
957     Error *local_err = NULL;
958     static bool once = true;
959 
960     if (!deferred_incoming) {
961         error_setg(errp, "For use with '-incoming defer'");
962         return;
963     }
964     if (!once) {
965         error_setg(errp, "The incoming migration has already been started");
966     }
967 
968     qemu_start_incoming_migration(uri, &local_err);
969 
970     if (local_err) {
971         error_propagate(errp, local_err);
972         return;
973     }
974 
975     once = false;
976 }
977 
978 void qmp_migrate(const char *uri, bool has_blk, bool blk,
979                  bool has_inc, bool inc, bool has_detach, bool detach,
980                  Error **errp)
981 {
982     Error *local_err = NULL;
983     MigrationState *s = migrate_get_current();
984     MigrationParams params;
985     const char *p;
986 
987     params.blk = has_blk && blk;
988     params.shared = has_inc && inc;
989 
990     if (migration_is_setup_or_active(s->state) ||
991         s->state == MIGRATION_STATUS_CANCELLING) {
992         error_setg(errp, QERR_MIGRATION_ACTIVE);
993         return;
994     }
995     if (runstate_check(RUN_STATE_INMIGRATE)) {
996         error_setg(errp, "Guest is waiting for an incoming migration");
997         return;
998     }
999 
1000     if (qemu_savevm_state_blocked(errp)) {
1001         return;
1002     }
1003 
1004     if (migration_blockers) {
1005         *errp = error_copy(migration_blockers->data);
1006         return;
1007     }
1008 
1009     /* We are starting a new migration, so we want to start in a clean
1010        state.  This change is only needed if previous migration
1011        failed/was cancelled.  We don't use migrate_set_state() because
1012        we are setting the initial state, not changing it. */
1013     s->state = MIGRATION_STATUS_NONE;
1014 
1015     s = migrate_init(&params);
1016 
1017     if (strstart(uri, "tcp:", &p)) {
1018         tcp_start_outgoing_migration(s, p, &local_err);
1019 #ifdef CONFIG_RDMA
1020     } else if (strstart(uri, "rdma:", &p)) {
1021         rdma_start_outgoing_migration(s, p, &local_err);
1022 #endif
1023 #if !defined(WIN32)
1024     } else if (strstart(uri, "exec:", &p)) {
1025         exec_start_outgoing_migration(s, p, &local_err);
1026     } else if (strstart(uri, "unix:", &p)) {
1027         unix_start_outgoing_migration(s, p, &local_err);
1028     } else if (strstart(uri, "fd:", &p)) {
1029         fd_start_outgoing_migration(s, p, &local_err);
1030 #endif
1031     } else {
1032         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1033                    "a valid migration protocol");
1034         migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1035                           MIGRATION_STATUS_FAILED);
1036         return;
1037     }
1038 
1039     if (local_err) {
1040         migrate_fd_error(s);
1041         error_propagate(errp, local_err);
1042         return;
1043     }
1044 }
1045 
1046 void qmp_migrate_cancel(Error **errp)
1047 {
1048     migrate_fd_cancel(migrate_get_current());
1049 }
1050 
1051 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1052 {
1053     MigrationState *s = migrate_get_current();
1054     int64_t new_size;
1055 
1056     /* Check for truncation */
1057     if (value != (size_t)value) {
1058         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1059                    "exceeding address space");
1060         return;
1061     }
1062 
1063     /* Cache should not be larger than guest ram size */
1064     if (value > ram_bytes_total()) {
1065         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1066                    "exceeds guest ram size ");
1067         return;
1068     }
1069 
1070     new_size = xbzrle_cache_resize(value);
1071     if (new_size < 0) {
1072         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1073                    "is smaller than page size");
1074         return;
1075     }
1076 
1077     s->xbzrle_cache_size = new_size;
1078 }
1079 
1080 int64_t qmp_query_migrate_cache_size(Error **errp)
1081 {
1082     return migrate_xbzrle_cache_size();
1083 }
1084 
1085 void qmp_migrate_set_speed(int64_t value, Error **errp)
1086 {
1087     MigrationState *s;
1088 
1089     if (value < 0) {
1090         value = 0;
1091     }
1092     if (value > SIZE_MAX) {
1093         value = SIZE_MAX;
1094     }
1095 
1096     s = migrate_get_current();
1097     s->bandwidth_limit = value;
1098     if (s->file) {
1099         qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
1100     }
1101 }
1102 
1103 void qmp_migrate_set_downtime(double value, Error **errp)
1104 {
1105     value *= 1e9;
1106     value = MAX(0, MIN(UINT64_MAX, value));
1107     max_downtime = (uint64_t)value;
1108 }
1109 
1110 bool migrate_postcopy_ram(void)
1111 {
1112     MigrationState *s;
1113 
1114     s = migrate_get_current();
1115 
1116     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM];
1117 }
1118 
1119 bool migrate_auto_converge(void)
1120 {
1121     MigrationState *s;
1122 
1123     s = migrate_get_current();
1124 
1125     return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1126 }
1127 
1128 bool migrate_zero_blocks(void)
1129 {
1130     MigrationState *s;
1131 
1132     s = migrate_get_current();
1133 
1134     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1135 }
1136 
1137 bool migrate_use_compression(void)
1138 {
1139     MigrationState *s;
1140 
1141     s = migrate_get_current();
1142 
1143     return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1144 }
1145 
1146 int migrate_compress_level(void)
1147 {
1148     MigrationState *s;
1149 
1150     s = migrate_get_current();
1151 
1152     return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
1153 }
1154 
1155 int migrate_compress_threads(void)
1156 {
1157     MigrationState *s;
1158 
1159     s = migrate_get_current();
1160 
1161     return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
1162 }
1163 
1164 int migrate_decompress_threads(void)
1165 {
1166     MigrationState *s;
1167 
1168     s = migrate_get_current();
1169 
1170     return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1171 }
1172 
1173 bool migrate_use_events(void)
1174 {
1175     MigrationState *s;
1176 
1177     s = migrate_get_current();
1178 
1179     return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1180 }
1181 
1182 int migrate_use_xbzrle(void)
1183 {
1184     MigrationState *s;
1185 
1186     s = migrate_get_current();
1187 
1188     return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1189 }
1190 
1191 int64_t migrate_xbzrle_cache_size(void)
1192 {
1193     MigrationState *s;
1194 
1195     s = migrate_get_current();
1196 
1197     return s->xbzrle_cache_size;
1198 }
1199 
1200 /* migration thread support */
1201 /*
1202  * Something bad happened to the RP stream, mark an error
1203  * The caller shall print or trace something to indicate why
1204  */
1205 static void mark_source_rp_bad(MigrationState *s)
1206 {
1207     s->rp_state.error = true;
1208 }
1209 
1210 static struct rp_cmd_args {
1211     ssize_t     len; /* -1 = variable */
1212     const char *name;
1213 } rp_cmd_args[] = {
1214     [MIG_RP_MSG_INVALID]        = { .len = -1, .name = "INVALID" },
1215     [MIG_RP_MSG_SHUT]           = { .len =  4, .name = "SHUT" },
1216     [MIG_RP_MSG_PONG]           = { .len =  4, .name = "PONG" },
1217     [MIG_RP_MSG_REQ_PAGES]      = { .len = 12, .name = "REQ_PAGES" },
1218     [MIG_RP_MSG_REQ_PAGES_ID]   = { .len = -1, .name = "REQ_PAGES_ID" },
1219     [MIG_RP_MSG_MAX]            = { .len = -1, .name = "MAX" },
1220 };
1221 
1222 /*
1223  * Process a request for pages received on the return path,
1224  * We're allowed to send more than requested (e.g. to round to our page size)
1225  * and we don't need to send pages that have already been sent.
1226  */
1227 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1228                                        ram_addr_t start, size_t len)
1229 {
1230     long our_host_ps = getpagesize();
1231 
1232     trace_migrate_handle_rp_req_pages(rbname, start, len);
1233 
1234     /*
1235      * Since we currently insist on matching page sizes, just sanity check
1236      * we're being asked for whole host pages.
1237      */
1238     if (start & (our_host_ps-1) ||
1239        (len & (our_host_ps-1))) {
1240         error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1241                      " len: %zd", __func__, start, len);
1242         mark_source_rp_bad(ms);
1243         return;
1244     }
1245 
1246     if (ram_save_queue_pages(ms, rbname, start, len)) {
1247         mark_source_rp_bad(ms);
1248     }
1249 }
1250 
1251 /*
1252  * Handles messages sent on the return path towards the source VM
1253  *
1254  */
1255 static void *source_return_path_thread(void *opaque)
1256 {
1257     MigrationState *ms = opaque;
1258     QEMUFile *rp = ms->rp_state.from_dst_file;
1259     uint16_t header_len, header_type;
1260     const int max_len = 512;
1261     uint8_t buf[max_len];
1262     uint32_t tmp32, sibling_error;
1263     ram_addr_t start = 0; /* =0 to silence warning */
1264     size_t  len = 0, expected_len;
1265     int res;
1266 
1267     trace_source_return_path_thread_entry();
1268     while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1269            migration_is_setup_or_active(ms->state)) {
1270         trace_source_return_path_thread_loop_top();
1271         header_type = qemu_get_be16(rp);
1272         header_len = qemu_get_be16(rp);
1273 
1274         if (header_type >= MIG_RP_MSG_MAX ||
1275             header_type == MIG_RP_MSG_INVALID) {
1276             error_report("RP: Received invalid message 0x%04x length 0x%04x",
1277                     header_type, header_len);
1278             mark_source_rp_bad(ms);
1279             goto out;
1280         }
1281 
1282         if ((rp_cmd_args[header_type].len != -1 &&
1283             header_len != rp_cmd_args[header_type].len) ||
1284             header_len > max_len) {
1285             error_report("RP: Received '%s' message (0x%04x) with"
1286                     "incorrect length %d expecting %zu",
1287                     rp_cmd_args[header_type].name, header_type, header_len,
1288                     (size_t)rp_cmd_args[header_type].len);
1289             mark_source_rp_bad(ms);
1290             goto out;
1291         }
1292 
1293         /* We know we've got a valid header by this point */
1294         res = qemu_get_buffer(rp, buf, header_len);
1295         if (res != header_len) {
1296             error_report("RP: Failed reading data for message 0x%04x"
1297                          " read %d expected %d",
1298                          header_type, res, header_len);
1299             mark_source_rp_bad(ms);
1300             goto out;
1301         }
1302 
1303         /* OK, we have the message and the data */
1304         switch (header_type) {
1305         case MIG_RP_MSG_SHUT:
1306             sibling_error = be32_to_cpup((uint32_t *)buf);
1307             trace_source_return_path_thread_shut(sibling_error);
1308             if (sibling_error) {
1309                 error_report("RP: Sibling indicated error %d", sibling_error);
1310                 mark_source_rp_bad(ms);
1311             }
1312             /*
1313              * We'll let the main thread deal with closing the RP
1314              * we could do a shutdown(2) on it, but we're the only user
1315              * anyway, so there's nothing gained.
1316              */
1317             goto out;
1318 
1319         case MIG_RP_MSG_PONG:
1320             tmp32 = be32_to_cpup((uint32_t *)buf);
1321             trace_source_return_path_thread_pong(tmp32);
1322             break;
1323 
1324         case MIG_RP_MSG_REQ_PAGES:
1325             start = be64_to_cpup((uint64_t *)buf);
1326             len = be32_to_cpup((uint32_t *)(buf + 8));
1327             migrate_handle_rp_req_pages(ms, NULL, start, len);
1328             break;
1329 
1330         case MIG_RP_MSG_REQ_PAGES_ID:
1331             expected_len = 12 + 1; /* header + termination */
1332 
1333             if (header_len >= expected_len) {
1334                 start = be64_to_cpup((uint64_t *)buf);
1335                 len = be32_to_cpup((uint32_t *)(buf + 8));
1336                 /* Now we expect an idstr */
1337                 tmp32 = buf[12]; /* Length of the following idstr */
1338                 buf[13 + tmp32] = '\0';
1339                 expected_len += tmp32;
1340             }
1341             if (header_len != expected_len) {
1342                 error_report("RP: Req_Page_id with length %d expecting %zd",
1343                         header_len, expected_len);
1344                 mark_source_rp_bad(ms);
1345                 goto out;
1346             }
1347             migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1348             break;
1349 
1350         default:
1351             break;
1352         }
1353     }
1354     if (qemu_file_get_error(rp)) {
1355         trace_source_return_path_thread_bad_end();
1356         mark_source_rp_bad(ms);
1357     }
1358 
1359     trace_source_return_path_thread_end();
1360 out:
1361     ms->rp_state.from_dst_file = NULL;
1362     qemu_fclose(rp);
1363     return NULL;
1364 }
1365 
1366 static int open_return_path_on_source(MigrationState *ms)
1367 {
1368 
1369     ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->file);
1370     if (!ms->rp_state.from_dst_file) {
1371         return -1;
1372     }
1373 
1374     trace_open_return_path_on_source();
1375     qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1376                        source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1377 
1378     trace_open_return_path_on_source_continue();
1379 
1380     return 0;
1381 }
1382 
1383 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1384 static int await_return_path_close_on_source(MigrationState *ms)
1385 {
1386     /*
1387      * If this is a normal exit then the destination will send a SHUT and the
1388      * rp_thread will exit, however if there's an error we need to cause
1389      * it to exit.
1390      */
1391     if (qemu_file_get_error(ms->file) && ms->rp_state.from_dst_file) {
1392         /*
1393          * shutdown(2), if we have it, will cause it to unblock if it's stuck
1394          * waiting for the destination.
1395          */
1396         qemu_file_shutdown(ms->rp_state.from_dst_file);
1397         mark_source_rp_bad(ms);
1398     }
1399     trace_await_return_path_close_on_source_joining();
1400     qemu_thread_join(&ms->rp_state.rp_thread);
1401     trace_await_return_path_close_on_source_close();
1402     return ms->rp_state.error;
1403 }
1404 
1405 /*
1406  * Switch from normal iteration to postcopy
1407  * Returns non-0 on error
1408  */
1409 static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1410 {
1411     int ret;
1412     const QEMUSizedBuffer *qsb;
1413     int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1414     migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1415                       MIGRATION_STATUS_POSTCOPY_ACTIVE);
1416 
1417     trace_postcopy_start();
1418     qemu_mutex_lock_iothread();
1419     trace_postcopy_start_set_run();
1420 
1421     qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1422     *old_vm_running = runstate_is_running();
1423     global_state_store();
1424     ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1425     if (ret < 0) {
1426         goto fail;
1427     }
1428 
1429     ret = bdrv_inactivate_all();
1430     if (ret < 0) {
1431         goto fail;
1432     }
1433 
1434     /*
1435      * Cause any non-postcopiable, but iterative devices to
1436      * send out their final data.
1437      */
1438     qemu_savevm_state_complete_precopy(ms->file, true);
1439 
1440     /*
1441      * in Finish migrate and with the io-lock held everything should
1442      * be quiet, but we've potentially still got dirty pages and we
1443      * need to tell the destination to throw any pages it's already received
1444      * that are dirty
1445      */
1446     if (ram_postcopy_send_discard_bitmap(ms)) {
1447         error_report("postcopy send discard bitmap failed");
1448         goto fail;
1449     }
1450 
1451     /*
1452      * send rest of state - note things that are doing postcopy
1453      * will notice we're in POSTCOPY_ACTIVE and not actually
1454      * wrap their state up here
1455      */
1456     qemu_file_set_rate_limit(ms->file, INT64_MAX);
1457     /* Ping just for debugging, helps line traces up */
1458     qemu_savevm_send_ping(ms->file, 2);
1459 
1460     /*
1461      * While loading the device state we may trigger page transfer
1462      * requests and the fd must be free to process those, and thus
1463      * the destination must read the whole device state off the fd before
1464      * it starts processing it.  Unfortunately the ad-hoc migration format
1465      * doesn't allow the destination to know the size to read without fully
1466      * parsing it through each devices load-state code (especially the open
1467      * coded devices that use get/put).
1468      * So we wrap the device state up in a package with a length at the start;
1469      * to do this we use a qemu_buf to hold the whole of the device state.
1470      */
1471     QEMUFile *fb = qemu_bufopen("w", NULL);
1472     if (!fb) {
1473         error_report("Failed to create buffered file");
1474         goto fail;
1475     }
1476 
1477     /*
1478      * Make sure the receiver can get incoming pages before we send the rest
1479      * of the state
1480      */
1481     qemu_savevm_send_postcopy_listen(fb);
1482 
1483     qemu_savevm_state_complete_precopy(fb, false);
1484     qemu_savevm_send_ping(fb, 3);
1485 
1486     qemu_savevm_send_postcopy_run(fb);
1487 
1488     /* <><> end of stuff going into the package */
1489     qsb = qemu_buf_get(fb);
1490 
1491     /* Now send that blob */
1492     if (qemu_savevm_send_packaged(ms->file, qsb)) {
1493         goto fail_closefb;
1494     }
1495     qemu_fclose(fb);
1496     ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1497 
1498     qemu_mutex_unlock_iothread();
1499 
1500     /*
1501      * Although this ping is just for debug, it could potentially be
1502      * used for getting a better measurement of downtime at the source.
1503      */
1504     qemu_savevm_send_ping(ms->file, 4);
1505 
1506     ret = qemu_file_get_error(ms->file);
1507     if (ret) {
1508         error_report("postcopy_start: Migration stream errored");
1509         migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1510                               MIGRATION_STATUS_FAILED);
1511     }
1512 
1513     return ret;
1514 
1515 fail_closefb:
1516     qemu_fclose(fb);
1517 fail:
1518     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1519                           MIGRATION_STATUS_FAILED);
1520     qemu_mutex_unlock_iothread();
1521     return -1;
1522 }
1523 
1524 /**
1525  * migration_completion: Used by migration_thread when there's not much left.
1526  *   The caller 'breaks' the loop when this returns.
1527  *
1528  * @s: Current migration state
1529  * @current_active_state: The migration state we expect to be in
1530  * @*old_vm_running: Pointer to old_vm_running flag
1531  * @*start_time: Pointer to time to update
1532  */
1533 static void migration_completion(MigrationState *s, int current_active_state,
1534                                  bool *old_vm_running,
1535                                  int64_t *start_time)
1536 {
1537     int ret;
1538 
1539     if (s->state == MIGRATION_STATUS_ACTIVE) {
1540         qemu_mutex_lock_iothread();
1541         *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1542         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1543         *old_vm_running = runstate_is_running();
1544         ret = global_state_store();
1545 
1546         if (!ret) {
1547             ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1548             if (ret >= 0) {
1549                 ret = bdrv_inactivate_all();
1550             }
1551             if (ret >= 0) {
1552                 qemu_file_set_rate_limit(s->file, INT64_MAX);
1553                 qemu_savevm_state_complete_precopy(s->file, false);
1554             }
1555         }
1556         qemu_mutex_unlock_iothread();
1557 
1558         if (ret < 0) {
1559             goto fail;
1560         }
1561     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1562         trace_migration_completion_postcopy_end();
1563 
1564         qemu_savevm_state_complete_postcopy(s->file);
1565         trace_migration_completion_postcopy_end_after_complete();
1566     }
1567 
1568     /*
1569      * If rp was opened we must clean up the thread before
1570      * cleaning everything else up (since if there are no failures
1571      * it will wait for the destination to send it's status in
1572      * a SHUT command).
1573      * Postcopy opens rp if enabled (even if it's not avtivated)
1574      */
1575     if (migrate_postcopy_ram()) {
1576         int rp_error;
1577         trace_migration_completion_postcopy_end_before_rp();
1578         rp_error = await_return_path_close_on_source(s);
1579         trace_migration_completion_postcopy_end_after_rp(rp_error);
1580         if (rp_error) {
1581             goto fail;
1582         }
1583     }
1584 
1585     if (qemu_file_get_error(s->file)) {
1586         trace_migration_completion_file_err();
1587         goto fail;
1588     }
1589 
1590     migrate_set_state(&s->state, current_active_state,
1591                       MIGRATION_STATUS_COMPLETED);
1592     return;
1593 
1594 fail:
1595     migrate_set_state(&s->state, current_active_state,
1596                       MIGRATION_STATUS_FAILED);
1597 }
1598 
1599 /*
1600  * Master migration thread on the source VM.
1601  * It drives the migration and pumps the data down the outgoing channel.
1602  */
1603 static void *migration_thread(void *opaque)
1604 {
1605     MigrationState *s = opaque;
1606     /* Used by the bandwidth calcs, updated later */
1607     int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1608     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
1609     int64_t initial_bytes = 0;
1610     int64_t max_size = 0;
1611     int64_t start_time = initial_time;
1612     int64_t end_time;
1613     bool old_vm_running = false;
1614     bool entered_postcopy = false;
1615     /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1616     enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
1617 
1618     rcu_register_thread();
1619 
1620     qemu_savevm_state_header(s->file);
1621 
1622     if (migrate_postcopy_ram()) {
1623         /* Now tell the dest that it should open its end so it can reply */
1624         qemu_savevm_send_open_return_path(s->file);
1625 
1626         /* And do a ping that will make stuff easier to debug */
1627         qemu_savevm_send_ping(s->file, 1);
1628 
1629         /*
1630          * Tell the destination that we *might* want to do postcopy later;
1631          * if the other end can't do postcopy it should fail now, nice and
1632          * early.
1633          */
1634         qemu_savevm_send_postcopy_advise(s->file);
1635     }
1636 
1637     qemu_savevm_state_begin(s->file, &s->params);
1638 
1639     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
1640     current_active_state = MIGRATION_STATUS_ACTIVE;
1641     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1642                       MIGRATION_STATUS_ACTIVE);
1643 
1644     trace_migration_thread_setup_complete();
1645 
1646     while (s->state == MIGRATION_STATUS_ACTIVE ||
1647            s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1648         int64_t current_time;
1649         uint64_t pending_size;
1650 
1651         if (!qemu_file_rate_limit(s->file)) {
1652             uint64_t pend_post, pend_nonpost;
1653 
1654             qemu_savevm_state_pending(s->file, max_size, &pend_nonpost,
1655                                       &pend_post);
1656             pending_size = pend_nonpost + pend_post;
1657             trace_migrate_pending(pending_size, max_size,
1658                                   pend_post, pend_nonpost);
1659             if (pending_size && pending_size >= max_size) {
1660                 /* Still a significant amount to transfer */
1661 
1662                 if (migrate_postcopy_ram() &&
1663                     s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
1664                     pend_nonpost <= max_size &&
1665                     atomic_read(&s->start_postcopy)) {
1666 
1667                     if (!postcopy_start(s, &old_vm_running)) {
1668                         current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1669                         entered_postcopy = true;
1670                     }
1671 
1672                     continue;
1673                 }
1674                 /* Just another iteration step */
1675                 qemu_savevm_state_iterate(s->file, entered_postcopy);
1676             } else {
1677                 trace_migration_thread_low_pending(pending_size);
1678                 migration_completion(s, current_active_state,
1679                                      &old_vm_running, &start_time);
1680                 break;
1681             }
1682         }
1683 
1684         if (qemu_file_get_error(s->file)) {
1685             migrate_set_state(&s->state, current_active_state,
1686                               MIGRATION_STATUS_FAILED);
1687             trace_migration_thread_file_err();
1688             break;
1689         }
1690         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1691         if (current_time >= initial_time + BUFFER_DELAY) {
1692             uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
1693             uint64_t time_spent = current_time - initial_time;
1694             double bandwidth = (double)transferred_bytes / time_spent;
1695             max_size = bandwidth * migrate_max_downtime() / 1000000;
1696 
1697             s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1698                     ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1699 
1700             trace_migrate_transferred(transferred_bytes, time_spent,
1701                                       bandwidth, max_size);
1702             /* if we haven't sent anything, we don't want to recalculate
1703                10000 is a small enough number for our purposes */
1704             if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1705                 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1706             }
1707 
1708             qemu_file_reset_rate_limit(s->file);
1709             initial_time = current_time;
1710             initial_bytes = qemu_ftell(s->file);
1711         }
1712         if (qemu_file_rate_limit(s->file)) {
1713             /* usleep expects microseconds */
1714             g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1715         }
1716     }
1717 
1718     trace_migration_thread_after_loop();
1719     /* If we enabled cpu throttling for auto-converge, turn it off. */
1720     cpu_throttle_stop();
1721     end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1722 
1723     qemu_mutex_lock_iothread();
1724     qemu_savevm_state_cleanup();
1725     if (s->state == MIGRATION_STATUS_COMPLETED) {
1726         uint64_t transferred_bytes = qemu_ftell(s->file);
1727         s->total_time = end_time - s->total_time;
1728         if (!entered_postcopy) {
1729             s->downtime = end_time - start_time;
1730         }
1731         if (s->total_time) {
1732             s->mbps = (((double) transferred_bytes * 8.0) /
1733                        ((double) s->total_time)) / 1000;
1734         }
1735         runstate_set(RUN_STATE_POSTMIGRATE);
1736     } else {
1737         if (old_vm_running && !entered_postcopy) {
1738             vm_start();
1739         }
1740     }
1741     qemu_bh_schedule(s->cleanup_bh);
1742     qemu_mutex_unlock_iothread();
1743 
1744     rcu_unregister_thread();
1745     return NULL;
1746 }
1747 
1748 void migrate_fd_connect(MigrationState *s)
1749 {
1750     /* This is a best 1st approximation. ns to ms */
1751     s->expected_downtime = max_downtime/1000000;
1752     s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1753 
1754     qemu_file_set_rate_limit(s->file,
1755                              s->bandwidth_limit / XFER_LIMIT_RATIO);
1756 
1757     /* Notify before starting migration thread */
1758     notifier_list_notify(&migration_state_notifiers, s);
1759 
1760     /*
1761      * Open the return path; currently for postcopy but other things might
1762      * also want it.
1763      */
1764     if (migrate_postcopy_ram()) {
1765         if (open_return_path_on_source(s)) {
1766             error_report("Unable to open return-path for postcopy");
1767             migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1768                               MIGRATION_STATUS_FAILED);
1769             migrate_fd_cleanup(s);
1770             return;
1771         }
1772     }
1773 
1774     migrate_compress_threads_create();
1775     qemu_thread_create(&s->thread, "migration", migration_thread, s,
1776                        QEMU_THREAD_JOINABLE);
1777     s->migration_thread_running = true;
1778 }
1779 
1780 PostcopyState  postcopy_state_get(void)
1781 {
1782     return atomic_mb_read(&incoming_postcopy_state);
1783 }
1784 
1785 /* Set the state and return the old state */
1786 PostcopyState postcopy_state_set(PostcopyState new_state)
1787 {
1788     return atomic_xchg(&incoming_postcopy_state, new_state);
1789 }
1790 
1791