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