migration: do cleanup operation after completion
[kvmfornfv.git] / qemu / migration / migration.c
1 /*
2  * QEMU live migration
3  *
4  * Copyright IBM, Corp. 2008
5  *
6  * Authors:
7  *  Anthony Liguori   <aliguori@us.ibm.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2.  See
10  * the COPYING file in the top-level directory.
11  *
12  * Contributions after 2012-01-13 are licensed under the terms of the
13  * GNU GPL, version 2 or (at your option) any later version.
14  */
15
16 #include "qemu-common.h"
17 #include "qemu/error-report.h"
18 #include "qemu/main-loop.h"
19 #include "migration/migration.h"
20 #include "migration/qemu-file.h"
21 #include "sysemu/sysemu.h"
22 #include "block/block.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/sockets.h"
25 #include "qemu/rcu.h"
26 #include "migration/block.h"
27 #include "qemu/thread.h"
28 #include "qmp-commands.h"
29 #include "trace.h"
30 #include "qapi/util.h"
31 #include "qapi-event.h"
32
33 #define MAX_THROTTLE  (32 << 20)      /* Migration speed throttling */
34
35 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
36  * data. */
37 #define BUFFER_DELAY     100
38 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
39
40 /* Default compression thread count */
41 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
42 /* Default decompression thread count, usually decompression is at
43  * least 4 times as fast as compression.*/
44 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
45 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
46 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
47
48 /* Migration XBZRLE default cache size */
49 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
50
51 static NotifierList migration_state_notifiers =
52     NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
53
54 static bool deferred_incoming;
55
56 /* When we add fault tolerance, we could have several
57    migrations at once.  For now we don't need to add
58    dynamic creation of migration */
59
60 /* For outgoing */
61 MigrationState *migrate_get_current(void)
62 {
63     static MigrationState current_migration = {
64         .state = MIGRATION_STATUS_NONE,
65         .bandwidth_limit = MAX_THROTTLE,
66         .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
67         .mbps = -1,
68         .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
69                 DEFAULT_MIGRATE_COMPRESS_LEVEL,
70         .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
71                 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
72         .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
73                 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
74     };
75
76     return &current_migration;
77 }
78
79 /* For incoming */
80 static MigrationIncomingState *mis_current;
81
82 MigrationIncomingState *migration_incoming_get_current(void)
83 {
84     return mis_current;
85 }
86
87 MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
88 {
89     mis_current = g_malloc0(sizeof(MigrationIncomingState));
90     mis_current->file = f;
91     QLIST_INIT(&mis_current->loadvm_handlers);
92
93     return mis_current;
94 }
95
96 void migration_incoming_state_destroy(void)
97 {
98     loadvm_free_handlers(mis_current);
99     g_free(mis_current);
100     mis_current = NULL;
101 }
102
103
104 typedef struct {
105     bool optional;
106     uint32_t size;
107     uint8_t runstate[100];
108     RunState state;
109     bool received;
110 } GlobalState;
111
112 static GlobalState global_state;
113
114 int global_state_store(void)
115 {
116     if (!runstate_store((char *)global_state.runstate,
117                         sizeof(global_state.runstate))) {
118         error_report("runstate name too big: %s", global_state.runstate);
119         trace_migrate_state_too_big();
120         return -EINVAL;
121     }
122     return 0;
123 }
124
125 void global_state_store_running(void)
126 {
127     const char *state = RunState_lookup[RUN_STATE_RUNNING];
128     strncpy((char *)global_state.runstate,
129            state, sizeof(global_state.runstate));
130 }
131
132 static bool global_state_received(void)
133 {
134     return global_state.received;
135 }
136
137 static RunState global_state_get_runstate(void)
138 {
139     return global_state.state;
140 }
141
142 void global_state_set_optional(void)
143 {
144     global_state.optional = true;
145 }
146
147 static bool global_state_needed(void *opaque)
148 {
149     GlobalState *s = opaque;
150     char *runstate = (char *)s->runstate;
151
152     /* If it is not optional, it is mandatory */
153
154     if (s->optional == false) {
155         return true;
156     }
157
158     /* If state is running or paused, it is not needed */
159
160     if (strcmp(runstate, "running") == 0 ||
161         strcmp(runstate, "paused") == 0) {
162         return false;
163     }
164
165     /* for any other state it is needed */
166     return true;
167 }
168
169 static int global_state_post_load(void *opaque, int version_id)
170 {
171     GlobalState *s = opaque;
172     Error *local_err = NULL;
173     int r;
174     char *runstate = (char *)s->runstate;
175
176     s->received = true;
177     trace_migrate_global_state_post_load(runstate);
178
179     r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE_MAX,
180                                 -1, &local_err);
181
182     if (r == -1) {
183         if (local_err) {
184             error_report_err(local_err);
185         }
186         return -EINVAL;
187     }
188     s->state = r;
189
190     return 0;
191 }
192
193 static void global_state_pre_save(void *opaque)
194 {
195     GlobalState *s = opaque;
196
197     trace_migrate_global_state_pre_save((char *)s->runstate);
198     s->size = strlen((char *)s->runstate) + 1;
199 }
200
201 static const VMStateDescription vmstate_globalstate = {
202     .name = "globalstate",
203     .version_id = 1,
204     .minimum_version_id = 1,
205     .post_load = global_state_post_load,
206     .pre_save = global_state_pre_save,
207     .needed = global_state_needed,
208     .fields = (VMStateField[]) {
209         VMSTATE_UINT32(size, GlobalState),
210         VMSTATE_BUFFER(runstate, GlobalState),
211         VMSTATE_END_OF_LIST()
212     },
213 };
214
215 void register_global_state(void)
216 {
217     /* We would use it independently that we receive it */
218     strcpy((char *)&global_state.runstate, "");
219     global_state.received = false;
220     vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
221 }
222
223 static void migrate_generate_event(int new_state)
224 {
225     if (migrate_use_events()) {
226         qapi_event_send_migration(new_state, &error_abort);
227     }
228 }
229
230 /*
231  * Called on -incoming with a defer: uri.
232  * The migration can be started later after any parameters have been
233  * changed.
234  */
235 static void deferred_incoming_migration(Error **errp)
236 {
237     if (deferred_incoming) {
238         error_setg(errp, "Incoming migration already deferred");
239     }
240     deferred_incoming = true;
241 }
242
243 void qemu_start_incoming_migration(const char *uri, Error **errp)
244 {
245     const char *p;
246
247     qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
248     if (!strcmp(uri, "defer")) {
249         deferred_incoming_migration(errp);
250     } else if (strstart(uri, "tcp:", &p)) {
251         tcp_start_incoming_migration(p, errp);
252 #ifdef CONFIG_RDMA
253     } else if (strstart(uri, "rdma:", &p)) {
254         rdma_start_incoming_migration(p, errp);
255 #endif
256 #if !defined(WIN32)
257     } else if (strstart(uri, "exec:", &p)) {
258         exec_start_incoming_migration(p, errp);
259     } else if (strstart(uri, "unix:", &p)) {
260         unix_start_incoming_migration(p, errp);
261     } else if (strstart(uri, "fd:", &p)) {
262         fd_start_incoming_migration(p, errp);
263 #endif
264     } else {
265         error_setg(errp, "unknown migration protocol: %s", uri);
266     }
267 }
268
269 static void process_incoming_migration_co(void *opaque)
270 {
271     QEMUFile *f = opaque;
272     Error *local_err = NULL;
273     int ret;
274
275     migration_incoming_state_new(f);
276     migrate_generate_event(MIGRATION_STATUS_ACTIVE);
277     ret = qemu_loadvm_state(f);
278
279     qemu_fclose(f);
280     free_xbzrle_decoded_buf();
281     migration_incoming_state_destroy();
282
283     if (ret < 0) {
284         migrate_generate_event(MIGRATION_STATUS_FAILED);
285         error_report("load of migration failed: %s", strerror(-ret));
286         migrate_decompress_threads_join();
287         exit(EXIT_FAILURE);
288     }
289     migrate_generate_event(MIGRATION_STATUS_COMPLETED);
290     qemu_announce_self();
291
292     /* Make sure all file formats flush their mutable metadata */
293     bdrv_invalidate_cache_all(&local_err);
294     if (local_err) {
295         error_report_err(local_err);
296         migrate_decompress_threads_join();
297         exit(EXIT_FAILURE);
298     }
299
300     /* If global state section was not received or we are in running
301        state, we need to obey autostart. Any other state is set with
302        runstate_set. */
303
304     if (!global_state_received() ||
305         global_state_get_runstate() == RUN_STATE_RUNNING) {
306         if (autostart) {
307             vm_start();
308         } else {
309             runstate_set(RUN_STATE_PAUSED);
310         }
311     } else {
312         runstate_set(global_state_get_runstate());
313     }
314     migrate_decompress_threads_join();
315 }
316
317 void process_incoming_migration(QEMUFile *f)
318 {
319     Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
320     int fd = qemu_get_fd(f);
321
322     assert(fd != -1);
323     migrate_decompress_threads_create();
324     qemu_set_nonblock(fd);
325     qemu_coroutine_enter(co, f);
326 }
327
328 /* amount of nanoseconds we are willing to wait for migration to be down.
329  * the choice of nanoseconds is because it is the maximum resolution that
330  * get_clock() can achieve. It is an internal measure. All user-visible
331  * units must be in seconds */
332 static uint64_t max_downtime = 300000000;
333
334 uint64_t migrate_max_downtime(void)
335 {
336     return max_downtime;
337 }
338
339 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
340 {
341     MigrationCapabilityStatusList *head = NULL;
342     MigrationCapabilityStatusList *caps;
343     MigrationState *s = migrate_get_current();
344     int i;
345
346     caps = NULL; /* silence compiler warning */
347     for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
348         if (head == NULL) {
349             head = g_malloc0(sizeof(*caps));
350             caps = head;
351         } else {
352             caps->next = g_malloc0(sizeof(*caps));
353             caps = caps->next;
354         }
355         caps->value =
356             g_malloc(sizeof(*caps->value));
357         caps->value->capability = i;
358         caps->value->state = s->enabled_capabilities[i];
359     }
360
361     return head;
362 }
363
364 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
365 {
366     MigrationParameters *params;
367     MigrationState *s = migrate_get_current();
368
369     params = g_malloc0(sizeof(*params));
370     params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
371     params->compress_threads =
372             s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
373     params->decompress_threads =
374             s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
375
376     return params;
377 }
378
379 static void get_xbzrle_cache_stats(MigrationInfo *info)
380 {
381     if (migrate_use_xbzrle()) {
382         info->has_xbzrle_cache = true;
383         info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
384         info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
385         info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
386         info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
387         info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
388         info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
389         info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
390     }
391 }
392
393 MigrationInfo *qmp_query_migrate(Error **errp)
394 {
395     MigrationInfo *info = g_malloc0(sizeof(*info));
396     MigrationState *s = migrate_get_current();
397
398     switch (s->state) {
399     case MIGRATION_STATUS_NONE:
400         /* no migration has happened ever */
401         break;
402     case MIGRATION_STATUS_SETUP:
403         info->has_status = true;
404         info->has_total_time = false;
405         break;
406     case MIGRATION_STATUS_ACTIVE:
407     case MIGRATION_STATUS_CANCELLING:
408         info->has_status = true;
409         info->has_total_time = true;
410         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
411             - s->total_time;
412         info->has_expected_downtime = true;
413         info->expected_downtime = s->expected_downtime;
414         info->has_setup_time = true;
415         info->setup_time = s->setup_time;
416
417         info->has_ram = true;
418         info->ram = g_malloc0(sizeof(*info->ram));
419         info->ram->transferred = ram_bytes_transferred();
420         info->ram->remaining = ram_bytes_remaining();
421         info->ram->total = ram_bytes_total();
422         info->ram->duplicate = dup_mig_pages_transferred();
423         info->ram->skipped = skipped_mig_pages_transferred();
424         info->ram->normal = norm_mig_pages_transferred();
425         info->ram->normal_bytes = norm_mig_bytes_transferred();
426         info->ram->dirty_pages_rate = s->dirty_pages_rate;
427         info->ram->mbps = s->mbps;
428         info->ram->dirty_sync_count = s->dirty_sync_count;
429
430         if (blk_mig_active()) {
431             info->has_disk = true;
432             info->disk = g_malloc0(sizeof(*info->disk));
433             info->disk->transferred = blk_mig_bytes_transferred();
434             info->disk->remaining = blk_mig_bytes_remaining();
435             info->disk->total = blk_mig_bytes_total();
436         }
437
438         get_xbzrle_cache_stats(info);
439         break;
440     case MIGRATION_STATUS_COMPLETED:
441         get_xbzrle_cache_stats(info);
442
443         info->has_status = true;
444         info->has_total_time = true;
445         info->total_time = s->total_time;
446         info->has_downtime = true;
447         info->downtime = s->downtime;
448         info->has_setup_time = true;
449         info->setup_time = s->setup_time;
450
451         info->has_ram = true;
452         info->ram = g_malloc0(sizeof(*info->ram));
453         info->ram->transferred = ram_bytes_transferred();
454         info->ram->remaining = 0;
455         info->ram->total = ram_bytes_total();
456         info->ram->duplicate = dup_mig_pages_transferred();
457         info->ram->skipped = skipped_mig_pages_transferred();
458         info->ram->normal = norm_mig_pages_transferred();
459         info->ram->normal_bytes = norm_mig_bytes_transferred();
460         info->ram->mbps = s->mbps;
461         info->ram->dirty_sync_count = s->dirty_sync_count;
462         break;
463     case MIGRATION_STATUS_FAILED:
464         info->has_status = true;
465         break;
466     case MIGRATION_STATUS_CANCELLED:
467         info->has_status = true;
468         break;
469     }
470     info->status = s->state;
471
472     return info;
473 }
474
475 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
476                                   Error **errp)
477 {
478     MigrationState *s = migrate_get_current();
479     MigrationCapabilityStatusList *cap;
480
481     if (s->state == MIGRATION_STATUS_ACTIVE ||
482         s->state == MIGRATION_STATUS_SETUP) {
483         error_setg(errp, QERR_MIGRATION_ACTIVE);
484         return;
485     }
486
487     for (cap = params; cap; cap = cap->next) {
488         s->enabled_capabilities[cap->value->capability] = cap->value->state;
489     }
490 }
491
492 void qmp_migrate_set_parameters(bool has_compress_level,
493                                 int64_t compress_level,
494                                 bool has_compress_threads,
495                                 int64_t compress_threads,
496                                 bool has_decompress_threads,
497                                 int64_t decompress_threads, Error **errp)
498 {
499     MigrationState *s = migrate_get_current();
500
501     if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
502         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
503                    "is invalid, it should be in the range of 0 to 9");
504         return;
505     }
506     if (has_compress_threads &&
507             (compress_threads < 1 || compress_threads > 255)) {
508         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
509                    "compress_threads",
510                    "is invalid, it should be in the range of 1 to 255");
511         return;
512     }
513     if (has_decompress_threads &&
514             (decompress_threads < 1 || decompress_threads > 255)) {
515         error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
516                    "decompress_threads",
517                    "is invalid, it should be in the range of 1 to 255");
518         return;
519     }
520
521     if (has_compress_level) {
522         s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
523     }
524     if (has_compress_threads) {
525         s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
526     }
527     if (has_decompress_threads) {
528         s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
529                                                     decompress_threads;
530     }
531 }
532
533 /* shared migration helpers */
534
535 static void migrate_set_state(MigrationState *s, int old_state, int new_state)
536 {
537     if (atomic_cmpxchg(&s->state, old_state, new_state) == old_state) {
538         trace_migrate_set_state(new_state);
539         migrate_generate_event(new_state);
540     }
541 }
542
543 static void migrate_fd_cleanup(void *opaque)
544 {
545     MigrationState *s = opaque;
546
547     qemu_bh_delete(s->cleanup_bh);
548     s->cleanup_bh = NULL;
549
550     if (s->file) {
551         trace_migrate_fd_cleanup();
552         qemu_mutex_unlock_iothread();
553         qemu_thread_join(&s->thread);
554         qemu_mutex_lock_iothread();
555
556         migrate_compress_threads_join();
557         qemu_fclose(s->file);
558         s->file = NULL;
559     }
560
561     assert(s->state != MIGRATION_STATUS_ACTIVE);
562
563     if (s->state == MIGRATION_STATUS_CANCELLING) {
564         migrate_set_state(s, MIGRATION_STATUS_CANCELLING,
565                           MIGRATION_STATUS_CANCELLED);
566     }
567
568     notifier_list_notify(&migration_state_notifiers, s);
569 }
570
571 void migrate_fd_error(MigrationState *s)
572 {
573     trace_migrate_fd_error();
574     assert(s->file == NULL);
575     migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
576     notifier_list_notify(&migration_state_notifiers, s);
577 }
578
579 static void migrate_fd_cancel(MigrationState *s)
580 {
581     int old_state ;
582     QEMUFile *f = migrate_get_current()->file;
583     trace_migrate_fd_cancel();
584
585     do {
586         old_state = s->state;
587         if (old_state != MIGRATION_STATUS_SETUP &&
588             old_state != MIGRATION_STATUS_ACTIVE) {
589             break;
590         }
591         migrate_set_state(s, old_state, MIGRATION_STATUS_CANCELLING);
592     } while (s->state != MIGRATION_STATUS_CANCELLING);
593
594     /*
595      * If we're unlucky the migration code might be stuck somewhere in a
596      * send/write while the network has failed and is waiting to timeout;
597      * if we've got shutdown(2) available then we can force it to quit.
598      * The outgoing qemu file gets closed in migrate_fd_cleanup that is
599      * called in a bh, so there is no race against this cancel.
600      */
601     if (s->state == MIGRATION_STATUS_CANCELLING && f) {
602         qemu_file_shutdown(f);
603     }
604 }
605
606 void add_migration_state_change_notifier(Notifier *notify)
607 {
608     notifier_list_add(&migration_state_notifiers, notify);
609 }
610
611 void remove_migration_state_change_notifier(Notifier *notify)
612 {
613     notifier_remove(notify);
614 }
615
616 bool migration_in_setup(MigrationState *s)
617 {
618     return s->state == MIGRATION_STATUS_SETUP;
619 }
620
621 bool migration_has_finished(MigrationState *s)
622 {
623     return s->state == MIGRATION_STATUS_COMPLETED;
624 }
625
626 bool migration_has_failed(MigrationState *s)
627 {
628     return (s->state == MIGRATION_STATUS_CANCELLED ||
629             s->state == MIGRATION_STATUS_FAILED);
630 }
631
632 static MigrationState *migrate_init(const MigrationParams *params)
633 {
634     MigrationState *s = migrate_get_current();
635     int64_t bandwidth_limit = s->bandwidth_limit;
636     bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
637     int64_t xbzrle_cache_size = s->xbzrle_cache_size;
638     int compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
639     int compress_thread_count =
640             s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
641     int decompress_thread_count =
642             s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
643
644     memcpy(enabled_capabilities, s->enabled_capabilities,
645            sizeof(enabled_capabilities));
646
647     memset(s, 0, sizeof(*s));
648     s->params = *params;
649     memcpy(s->enabled_capabilities, enabled_capabilities,
650            sizeof(enabled_capabilities));
651     s->xbzrle_cache_size = xbzrle_cache_size;
652
653     s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
654     s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
655                compress_thread_count;
656     s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
657                decompress_thread_count;
658     s->bandwidth_limit = bandwidth_limit;
659     migrate_set_state(s, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
660
661     s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
662     return s;
663 }
664
665 static GSList *migration_blockers;
666
667 void migrate_add_blocker(Error *reason)
668 {
669     migration_blockers = g_slist_prepend(migration_blockers, reason);
670 }
671
672 void migrate_del_blocker(Error *reason)
673 {
674     migration_blockers = g_slist_remove(migration_blockers, reason);
675 }
676
677 void qmp_migrate_incoming(const char *uri, Error **errp)
678 {
679     Error *local_err = NULL;
680     static bool once = true;
681
682     if (!deferred_incoming) {
683         error_setg(errp, "For use with '-incoming defer'");
684         return;
685     }
686     if (!once) {
687         error_setg(errp, "The incoming migration has already been started");
688     }
689
690     qemu_start_incoming_migration(uri, &local_err);
691
692     if (local_err) {
693         error_propagate(errp, local_err);
694         return;
695     }
696
697     once = false;
698 }
699
700 void qmp_migrate(const char *uri, bool has_blk, bool blk,
701                  bool has_inc, bool inc, bool has_detach, bool detach,
702                  Error **errp)
703 {
704     Error *local_err = NULL;
705     MigrationState *s = migrate_get_current();
706     MigrationParams params;
707     const char *p;
708
709     params.blk = has_blk && blk;
710     params.shared = has_inc && inc;
711
712     if (s->state == MIGRATION_STATUS_ACTIVE ||
713         s->state == MIGRATION_STATUS_SETUP ||
714         s->state == MIGRATION_STATUS_CANCELLING) {
715         error_setg(errp, QERR_MIGRATION_ACTIVE);
716         return;
717     }
718     if (runstate_check(RUN_STATE_INMIGRATE)) {
719         error_setg(errp, "Guest is waiting for an incoming migration");
720         return;
721     }
722
723     if (qemu_savevm_state_blocked(errp)) {
724         return;
725     }
726
727     if (migration_blockers) {
728         *errp = error_copy(migration_blockers->data);
729         return;
730     }
731
732     /* We are starting a new migration, so we want to start in a clean
733        state.  This change is only needed if previous migration
734        failed/was cancelled.  We don't use migrate_set_state() because
735        we are setting the initial state, not changing it. */
736     s->state = MIGRATION_STATUS_NONE;
737
738     s = migrate_init(&params);
739
740     if (strstart(uri, "tcp:", &p)) {
741         tcp_start_outgoing_migration(s, p, &local_err);
742 #ifdef CONFIG_RDMA
743     } else if (strstart(uri, "rdma:", &p)) {
744         rdma_start_outgoing_migration(s, p, &local_err);
745 #endif
746 #if !defined(WIN32)
747     } else if (strstart(uri, "exec:", &p)) {
748         exec_start_outgoing_migration(s, p, &local_err);
749     } else if (strstart(uri, "unix:", &p)) {
750         unix_start_outgoing_migration(s, p, &local_err);
751     } else if (strstart(uri, "fd:", &p)) {
752         fd_start_outgoing_migration(s, p, &local_err);
753 #endif
754     } else {
755         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
756                    "a valid migration protocol");
757         migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_FAILED);
758         return;
759     }
760
761     if (local_err) {
762         migrate_fd_error(s);
763         error_propagate(errp, local_err);
764         return;
765     }
766 }
767
768 void qmp_migrate_cancel(Error **errp)
769 {
770     migrate_fd_cancel(migrate_get_current());
771 }
772
773 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
774 {
775     MigrationState *s = migrate_get_current();
776     int64_t new_size;
777
778     /* Check for truncation */
779     if (value != (size_t)value) {
780         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
781                    "exceeding address space");
782         return;
783     }
784
785     /* Cache should not be larger than guest ram size */
786     if (value > ram_bytes_total()) {
787         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
788                    "exceeds guest ram size ");
789         return;
790     }
791
792     new_size = xbzrle_cache_resize(value);
793     if (new_size < 0) {
794         error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
795                    "is smaller than page size");
796         return;
797     }
798
799     s->xbzrle_cache_size = new_size;
800 }
801
802 int64_t qmp_query_migrate_cache_size(Error **errp)
803 {
804     return migrate_xbzrle_cache_size();
805 }
806
807 void qmp_migrate_set_speed(int64_t value, Error **errp)
808 {
809     MigrationState *s;
810
811     if (value < 0) {
812         value = 0;
813     }
814     if (value > SIZE_MAX) {
815         value = SIZE_MAX;
816     }
817
818     s = migrate_get_current();
819     s->bandwidth_limit = value;
820     if (s->file) {
821         qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
822     }
823 }
824
825 void qmp_migrate_set_downtime(double value, Error **errp)
826 {
827     value *= 1e9;
828     value = MAX(0, MIN(UINT64_MAX, value));
829     max_downtime = (uint64_t)value;
830 }
831
832 bool migrate_auto_converge(void)
833 {
834     MigrationState *s;
835
836     s = migrate_get_current();
837
838     return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
839 }
840
841 bool migrate_zero_blocks(void)
842 {
843     MigrationState *s;
844
845     s = migrate_get_current();
846
847     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
848 }
849
850 bool migrate_use_compression(void)
851 {
852     MigrationState *s;
853
854     s = migrate_get_current();
855
856     return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
857 }
858
859 int migrate_compress_level(void)
860 {
861     MigrationState *s;
862
863     s = migrate_get_current();
864
865     return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
866 }
867
868 int migrate_compress_threads(void)
869 {
870     MigrationState *s;
871
872     s = migrate_get_current();
873
874     return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
875 }
876
877 int migrate_decompress_threads(void)
878 {
879     MigrationState *s;
880
881     s = migrate_get_current();
882
883     return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
884 }
885
886 bool migrate_use_events(void)
887 {
888     MigrationState *s;
889
890     s = migrate_get_current();
891
892     return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
893 }
894
895 int migrate_use_xbzrle(void)
896 {
897     MigrationState *s;
898
899     s = migrate_get_current();
900
901     return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
902 }
903
904 int64_t migrate_xbzrle_cache_size(void)
905 {
906     MigrationState *s;
907
908     s = migrate_get_current();
909
910     return s->xbzrle_cache_size;
911 }
912
913 /* migration thread support */
914
915 static void *migration_thread(void *opaque)
916 {
917     MigrationState *s = opaque;
918     int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
919     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
920     int64_t initial_bytes = 0;
921     int64_t max_size = 0;
922     int64_t start_time = initial_time;
923     int64_t end_time;
924     bool old_vm_running = false;
925
926     rcu_register_thread();
927
928     qemu_savevm_state_header(s->file);
929     qemu_savevm_state_begin(s->file, &s->params);
930
931     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
932     migrate_set_state(s, MIGRATION_STATUS_SETUP, MIGRATION_STATUS_ACTIVE);
933
934     while (s->state == MIGRATION_STATUS_ACTIVE) {
935         int64_t current_time;
936         uint64_t pending_size;
937
938         if (!qemu_file_rate_limit(s->file)) {
939             pending_size = qemu_savevm_state_pending(s->file, max_size);
940             trace_migrate_pending(pending_size, max_size);
941             if (pending_size && pending_size >= max_size) {
942                 qemu_savevm_state_iterate(s->file);
943             } else {
944                 int ret;
945
946                 qemu_mutex_lock_iothread();
947                 start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
948                 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
949                 old_vm_running = runstate_is_running();
950
951                 ret = global_state_store();
952                 if (!ret) {
953                     ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
954                     if (ret >= 0) {
955                         qemu_file_set_rate_limit(s->file, INT64_MAX);
956                         qemu_savevm_state_complete(s->file);
957                     }
958                 }
959                 qemu_mutex_unlock_iothread();
960
961                 if (ret < 0) {
962                     migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
963                                       MIGRATION_STATUS_FAILED);
964                     break;
965                 }
966
967                 if (!qemu_file_get_error(s->file)) {
968                     migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
969                                       MIGRATION_STATUS_COMPLETED);
970                     break;
971                 }
972             }
973         }
974
975         if (qemu_file_get_error(s->file)) {
976             migrate_set_state(s, MIGRATION_STATUS_ACTIVE,
977                               MIGRATION_STATUS_FAILED);
978             break;
979         }
980         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
981         if (current_time >= initial_time + BUFFER_DELAY) {
982             uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
983             uint64_t time_spent = current_time - initial_time;
984             double bandwidth = transferred_bytes / time_spent;
985             max_size = bandwidth * migrate_max_downtime() / 1000000;
986
987             s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
988                     ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
989
990             trace_migrate_transferred(transferred_bytes, time_spent,
991                                       bandwidth, max_size);
992             /* if we haven't sent anything, we don't want to recalculate
993                10000 is a small enough number for our purposes */
994             if (s->dirty_bytes_rate && transferred_bytes > 10000) {
995                 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
996             }
997
998             qemu_file_reset_rate_limit(s->file);
999             initial_time = current_time;
1000             initial_bytes = qemu_ftell(s->file);
1001         }
1002         if (qemu_file_rate_limit(s->file)) {
1003             /* usleep expects microseconds */
1004             g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1005         }
1006     }
1007
1008     end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1009
1010     qemu_mutex_lock_iothread();
1011     qemu_savevm_state_cancel();
1012     if (s->state == MIGRATION_STATUS_COMPLETED) {
1013         uint64_t transferred_bytes = qemu_ftell(s->file);
1014         s->total_time = end_time - s->total_time;
1015         s->downtime = end_time - start_time;
1016         if (s->total_time) {
1017             s->mbps = (((double) transferred_bytes * 8.0) /
1018                        ((double) s->total_time)) / 1000;
1019         }
1020         runstate_set(RUN_STATE_POSTMIGRATE);
1021     } else {
1022         if (old_vm_running) {
1023             vm_start();
1024         }
1025     }
1026     qemu_bh_schedule(s->cleanup_bh);
1027     qemu_mutex_unlock_iothread();
1028
1029     rcu_unregister_thread();
1030     return NULL;
1031 }
1032
1033 void migrate_fd_connect(MigrationState *s)
1034 {
1035     /* This is a best 1st approximation. ns to ms */
1036     s->expected_downtime = max_downtime/1000000;
1037     s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1038
1039     qemu_file_set_rate_limit(s->file,
1040                              s->bandwidth_limit / XFER_LIMIT_RATIO);
1041
1042     /* Notify before starting migration thread */
1043     notifier_list_notify(&migration_state_notifiers, s);
1044
1045     migrate_compress_threads_create();
1046     qemu_thread_create(&s->thread, "migration", migration_thread, s,
1047                        QEMU_THREAD_JOINABLE);
1048 }