]> Git Repo - qemu.git/blob - migration/migration.c
block: Fix .bdrv_open flags
[qemu.git] / migration / migration.c
1 /*
2  * QEMU live migration
3  *
4  * Copyright IBM, Corp. 2008
5  *
6  * Authors:
7  *  Anthony Liguori   <[email protected]>
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
1426     if (ret < 0) {
1427         goto fail;
1428     }
1429
1430     /*
1431      * Cause any non-postcopiable, but iterative devices to
1432      * send out their final data.
1433      */
1434     qemu_savevm_state_complete_precopy(ms->file, true);
1435
1436     /*
1437      * in Finish migrate and with the io-lock held everything should
1438      * be quiet, but we've potentially still got dirty pages and we
1439      * need to tell the destination to throw any pages it's already received
1440      * that are dirty
1441      */
1442     if (ram_postcopy_send_discard_bitmap(ms)) {
1443         error_report("postcopy send discard bitmap failed");
1444         goto fail;
1445     }
1446
1447     /*
1448      * send rest of state - note things that are doing postcopy
1449      * will notice we're in POSTCOPY_ACTIVE and not actually
1450      * wrap their state up here
1451      */
1452     qemu_file_set_rate_limit(ms->file, INT64_MAX);
1453     /* Ping just for debugging, helps line traces up */
1454     qemu_savevm_send_ping(ms->file, 2);
1455
1456     /*
1457      * While loading the device state we may trigger page transfer
1458      * requests and the fd must be free to process those, and thus
1459      * the destination must read the whole device state off the fd before
1460      * it starts processing it.  Unfortunately the ad-hoc migration format
1461      * doesn't allow the destination to know the size to read without fully
1462      * parsing it through each devices load-state code (especially the open
1463      * coded devices that use get/put).
1464      * So we wrap the device state up in a package with a length at the start;
1465      * to do this we use a qemu_buf to hold the whole of the device state.
1466      */
1467     QEMUFile *fb = qemu_bufopen("w", NULL);
1468     if (!fb) {
1469         error_report("Failed to create buffered file");
1470         goto fail;
1471     }
1472
1473     /*
1474      * Make sure the receiver can get incoming pages before we send the rest
1475      * of the state
1476      */
1477     qemu_savevm_send_postcopy_listen(fb);
1478
1479     qemu_savevm_state_complete_precopy(fb, false);
1480     qemu_savevm_send_ping(fb, 3);
1481
1482     qemu_savevm_send_postcopy_run(fb);
1483
1484     /* <><> end of stuff going into the package */
1485     qsb = qemu_buf_get(fb);
1486
1487     /* Now send that blob */
1488     if (qemu_savevm_send_packaged(ms->file, qsb)) {
1489         goto fail_closefb;
1490     }
1491     qemu_fclose(fb);
1492     ms->downtime =  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1493
1494     qemu_mutex_unlock_iothread();
1495
1496     /*
1497      * Although this ping is just for debug, it could potentially be
1498      * used for getting a better measurement of downtime at the source.
1499      */
1500     qemu_savevm_send_ping(ms->file, 4);
1501
1502     ret = qemu_file_get_error(ms->file);
1503     if (ret) {
1504         error_report("postcopy_start: Migration stream errored");
1505         migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1506                               MIGRATION_STATUS_FAILED);
1507     }
1508
1509     return ret;
1510
1511 fail_closefb:
1512     qemu_fclose(fb);
1513 fail:
1514     migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1515                           MIGRATION_STATUS_FAILED);
1516     qemu_mutex_unlock_iothread();
1517     return -1;
1518 }
1519
1520 /**
1521  * migration_completion: Used by migration_thread when there's not much left.
1522  *   The caller 'breaks' the loop when this returns.
1523  *
1524  * @s: Current migration state
1525  * @current_active_state: The migration state we expect to be in
1526  * @*old_vm_running: Pointer to old_vm_running flag
1527  * @*start_time: Pointer to time to update
1528  */
1529 static void migration_completion(MigrationState *s, int current_active_state,
1530                                  bool *old_vm_running,
1531                                  int64_t *start_time)
1532 {
1533     int ret;
1534
1535     if (s->state == MIGRATION_STATUS_ACTIVE) {
1536         qemu_mutex_lock_iothread();
1537         *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1538         qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1539         *old_vm_running = runstate_is_running();
1540         ret = global_state_store();
1541
1542         if (!ret) {
1543             ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1544             if (ret >= 0) {
1545                 qemu_file_set_rate_limit(s->file, INT64_MAX);
1546                 qemu_savevm_state_complete_precopy(s->file, false);
1547             }
1548         }
1549         qemu_mutex_unlock_iothread();
1550
1551         if (ret < 0) {
1552             goto fail;
1553         }
1554     } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1555         trace_migration_completion_postcopy_end();
1556
1557         qemu_savevm_state_complete_postcopy(s->file);
1558         trace_migration_completion_postcopy_end_after_complete();
1559     }
1560
1561     /*
1562      * If rp was opened we must clean up the thread before
1563      * cleaning everything else up (since if there are no failures
1564      * it will wait for the destination to send it's status in
1565      * a SHUT command).
1566      * Postcopy opens rp if enabled (even if it's not avtivated)
1567      */
1568     if (migrate_postcopy_ram()) {
1569         int rp_error;
1570         trace_migration_completion_postcopy_end_before_rp();
1571         rp_error = await_return_path_close_on_source(s);
1572         trace_migration_completion_postcopy_end_after_rp(rp_error);
1573         if (rp_error) {
1574             goto fail;
1575         }
1576     }
1577
1578     if (qemu_file_get_error(s->file)) {
1579         trace_migration_completion_file_err();
1580         goto fail;
1581     }
1582
1583     migrate_set_state(&s->state, current_active_state,
1584                       MIGRATION_STATUS_COMPLETED);
1585     return;
1586
1587 fail:
1588     migrate_set_state(&s->state, current_active_state,
1589                       MIGRATION_STATUS_FAILED);
1590 }
1591
1592 /*
1593  * Master migration thread on the source VM.
1594  * It drives the migration and pumps the data down the outgoing channel.
1595  */
1596 static void *migration_thread(void *opaque)
1597 {
1598     MigrationState *s = opaque;
1599     /* Used by the bandwidth calcs, updated later */
1600     int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1601     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
1602     int64_t initial_bytes = 0;
1603     int64_t max_size = 0;
1604     int64_t start_time = initial_time;
1605     int64_t end_time;
1606     bool old_vm_running = false;
1607     bool entered_postcopy = false;
1608     /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1609     enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
1610
1611     rcu_register_thread();
1612
1613     qemu_savevm_state_header(s->file);
1614
1615     if (migrate_postcopy_ram()) {
1616         /* Now tell the dest that it should open its end so it can reply */
1617         qemu_savevm_send_open_return_path(s->file);
1618
1619         /* And do a ping that will make stuff easier to debug */
1620         qemu_savevm_send_ping(s->file, 1);
1621
1622         /*
1623          * Tell the destination that we *might* want to do postcopy later;
1624          * if the other end can't do postcopy it should fail now, nice and
1625          * early.
1626          */
1627         qemu_savevm_send_postcopy_advise(s->file);
1628     }
1629
1630     qemu_savevm_state_begin(s->file, &s->params);
1631
1632     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
1633     current_active_state = MIGRATION_STATUS_ACTIVE;
1634     migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1635                       MIGRATION_STATUS_ACTIVE);
1636
1637     trace_migration_thread_setup_complete();
1638
1639     while (s->state == MIGRATION_STATUS_ACTIVE ||
1640            s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1641         int64_t current_time;
1642         uint64_t pending_size;
1643
1644         if (!qemu_file_rate_limit(s->file)) {
1645             uint64_t pend_post, pend_nonpost;
1646
1647             qemu_savevm_state_pending(s->file, max_size, &pend_nonpost,
1648                                       &pend_post);
1649             pending_size = pend_nonpost + pend_post;
1650             trace_migrate_pending(pending_size, max_size,
1651                                   pend_post, pend_nonpost);
1652             if (pending_size && pending_size >= max_size) {
1653                 /* Still a significant amount to transfer */
1654
1655                 if (migrate_postcopy_ram() &&
1656                     s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
1657                     pend_nonpost <= max_size &&
1658                     atomic_read(&s->start_postcopy)) {
1659
1660                     if (!postcopy_start(s, &old_vm_running)) {
1661                         current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1662                         entered_postcopy = true;
1663                     }
1664
1665                     continue;
1666                 }
1667                 /* Just another iteration step */
1668                 qemu_savevm_state_iterate(s->file, entered_postcopy);
1669             } else {
1670                 trace_migration_thread_low_pending(pending_size);
1671                 migration_completion(s, current_active_state,
1672                                      &old_vm_running, &start_time);
1673                 break;
1674             }
1675         }
1676
1677         if (qemu_file_get_error(s->file)) {
1678             migrate_set_state(&s->state, current_active_state,
1679                               MIGRATION_STATUS_FAILED);
1680             trace_migration_thread_file_err();
1681             break;
1682         }
1683         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1684         if (current_time >= initial_time + BUFFER_DELAY) {
1685             uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
1686             uint64_t time_spent = current_time - initial_time;
1687             double bandwidth = (double)transferred_bytes / time_spent;
1688             max_size = bandwidth * migrate_max_downtime() / 1000000;
1689
1690             s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1691                     ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1692
1693             trace_migrate_transferred(transferred_bytes, time_spent,
1694                                       bandwidth, max_size);
1695             /* if we haven't sent anything, we don't want to recalculate
1696                10000 is a small enough number for our purposes */
1697             if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1698                 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1699             }
1700
1701             qemu_file_reset_rate_limit(s->file);
1702             initial_time = current_time;
1703             initial_bytes = qemu_ftell(s->file);
1704         }
1705         if (qemu_file_rate_limit(s->file)) {
1706             /* usleep expects microseconds */
1707             g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1708         }
1709     }
1710
1711     trace_migration_thread_after_loop();
1712     /* If we enabled cpu throttling for auto-converge, turn it off. */
1713     cpu_throttle_stop();
1714     end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1715
1716     qemu_mutex_lock_iothread();
1717     qemu_savevm_state_cleanup();
1718     if (s->state == MIGRATION_STATUS_COMPLETED) {
1719         uint64_t transferred_bytes = qemu_ftell(s->file);
1720         s->total_time = end_time - s->total_time;
1721         if (!entered_postcopy) {
1722             s->downtime = end_time - start_time;
1723         }
1724         if (s->total_time) {
1725             s->mbps = (((double) transferred_bytes * 8.0) /
1726                        ((double) s->total_time)) / 1000;
1727         }
1728         runstate_set(RUN_STATE_POSTMIGRATE);
1729     } else {
1730         if (old_vm_running && !entered_postcopy) {
1731             vm_start();
1732         }
1733     }
1734     qemu_bh_schedule(s->cleanup_bh);
1735     qemu_mutex_unlock_iothread();
1736
1737     rcu_unregister_thread();
1738     return NULL;
1739 }
1740
1741 void migrate_fd_connect(MigrationState *s)
1742 {
1743     /* This is a best 1st approximation. ns to ms */
1744     s->expected_downtime = max_downtime/1000000;
1745     s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1746
1747     qemu_file_set_rate_limit(s->file,
1748                              s->bandwidth_limit / XFER_LIMIT_RATIO);
1749
1750     /* Notify before starting migration thread */
1751     notifier_list_notify(&migration_state_notifiers, s);
1752
1753     /*
1754      * Open the return path; currently for postcopy but other things might
1755      * also want it.
1756      */
1757     if (migrate_postcopy_ram()) {
1758         if (open_return_path_on_source(s)) {
1759             error_report("Unable to open return-path for postcopy");
1760             migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1761                               MIGRATION_STATUS_FAILED);
1762             migrate_fd_cleanup(s);
1763             return;
1764         }
1765     }
1766
1767     migrate_compress_threads_create();
1768     qemu_thread_create(&s->thread, "migration", migration_thread, s,
1769                        QEMU_THREAD_JOINABLE);
1770     s->migration_thread_running = true;
1771 }
1772
1773 PostcopyState  postcopy_state_get(void)
1774 {
1775     return atomic_mb_read(&incoming_postcopy_state);
1776 }
1777
1778 /* Set the state and return the old state */
1779 PostcopyState postcopy_state_set(PostcopyState new_state)
1780 {
1781     return atomic_xchg(&incoming_postcopy_state, new_state);
1782 }
1783
This page took 0.121132 seconds and 4 git commands to generate.