]> rtime.felk.cvut.cz Git - lisovros/qemu_apohw.git/blob - migration.c
Merge remote-tracking branch 'stefanha/block' into staging
[lisovros/qemu_apohw.git] / 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/main-loop.h"
18 #include "migration/migration.h"
19 #include "monitor/monitor.h"
20 #include "migration/qemu-file.h"
21 #include "sysemu/sysemu.h"
22 #include "block/block.h"
23 #include "qemu/sockets.h"
24 #include "migration/block.h"
25 #include "qemu/thread.h"
26 #include "qmp-commands.h"
27 #include "trace.h"
28
29 //#define DEBUG_MIGRATION
30
31 #ifdef DEBUG_MIGRATION
32 #define DPRINTF(fmt, ...) \
33     do { printf("migration: " fmt, ## __VA_ARGS__); } while (0)
34 #else
35 #define DPRINTF(fmt, ...) \
36     do { } while (0)
37 #endif
38
39 enum {
40     MIG_STATE_ERROR = -1,
41     MIG_STATE_NONE,
42     MIG_STATE_SETUP,
43     MIG_STATE_CANCELLED,
44     MIG_STATE_ACTIVE,
45     MIG_STATE_COMPLETED,
46 };
47
48 #define MAX_THROTTLE  (32 << 20)      /* Migration speed throttling */
49
50 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
51  * data. */
52 #define BUFFER_DELAY     100
53 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
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 /* When we add fault tolerance, we could have several
62    migrations at once.  For now we don't need to add
63    dynamic creation of migration */
64
65 MigrationState *migrate_get_current(void)
66 {
67     static MigrationState current_migration = {
68         .state = MIG_STATE_NONE,
69         .bandwidth_limit = MAX_THROTTLE,
70         .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
71         .mbps = -1,
72     };
73
74     return &current_migration;
75 }
76
77 void qemu_start_incoming_migration(const char *uri, Error **errp)
78 {
79     const char *p;
80
81     if (strstart(uri, "tcp:", &p))
82         tcp_start_incoming_migration(p, errp);
83 #ifdef CONFIG_RDMA
84     else if (strstart(uri, "x-rdma:", &p))
85         rdma_start_incoming_migration(p, errp);
86 #endif
87 #if !defined(WIN32)
88     else if (strstart(uri, "exec:", &p))
89         exec_start_incoming_migration(p, errp);
90     else if (strstart(uri, "unix:", &p))
91         unix_start_incoming_migration(p, errp);
92     else if (strstart(uri, "fd:", &p))
93         fd_start_incoming_migration(p, errp);
94 #endif
95     else {
96         error_setg(errp, "unknown migration protocol: %s", uri);
97     }
98 }
99
100 static void process_incoming_migration_co(void *opaque)
101 {
102     QEMUFile *f = opaque;
103     int ret;
104
105     ret = qemu_loadvm_state(f);
106     qemu_fclose(f);
107     if (ret < 0) {
108         fprintf(stderr, "load of migration failed\n");
109         exit(EXIT_FAILURE);
110     }
111     qemu_announce_self();
112     DPRINTF("successfully loaded vm state\n");
113
114     bdrv_clear_incoming_migration_all();
115     /* Make sure all file formats flush their mutable metadata */
116     bdrv_invalidate_cache_all();
117
118     if (autostart) {
119         vm_start();
120     } else {
121         runstate_set(RUN_STATE_PAUSED);
122     }
123 }
124
125 void process_incoming_migration(QEMUFile *f)
126 {
127     Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
128     int fd = qemu_get_fd(f);
129
130     assert(fd != -1);
131     qemu_set_nonblock(fd);
132     qemu_coroutine_enter(co, f);
133 }
134
135 /* amount of nanoseconds we are willing to wait for migration to be down.
136  * the choice of nanoseconds is because it is the maximum resolution that
137  * get_clock() can achieve. It is an internal measure. All user-visible
138  * units must be in seconds */
139 static uint64_t max_downtime = 30000000;
140
141 uint64_t migrate_max_downtime(void)
142 {
143     return max_downtime;
144 }
145
146 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
147 {
148     MigrationCapabilityStatusList *head = NULL;
149     MigrationCapabilityStatusList *caps;
150     MigrationState *s = migrate_get_current();
151     int i;
152
153     caps = NULL; /* silence compiler warning */
154     for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
155         if (head == NULL) {
156             head = g_malloc0(sizeof(*caps));
157             caps = head;
158         } else {
159             caps->next = g_malloc0(sizeof(*caps));
160             caps = caps->next;
161         }
162         caps->value =
163             g_malloc(sizeof(*caps->value));
164         caps->value->capability = i;
165         caps->value->state = s->enabled_capabilities[i];
166     }
167
168     return head;
169 }
170
171 static void get_xbzrle_cache_stats(MigrationInfo *info)
172 {
173     if (migrate_use_xbzrle()) {
174         info->has_xbzrle_cache = true;
175         info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
176         info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
177         info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
178         info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
179         info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
180         info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
181     }
182 }
183
184 MigrationInfo *qmp_query_migrate(Error **errp)
185 {
186     MigrationInfo *info = g_malloc0(sizeof(*info));
187     MigrationState *s = migrate_get_current();
188
189     switch (s->state) {
190     case MIG_STATE_NONE:
191         /* no migration has happened ever */
192         break;
193     case MIG_STATE_SETUP:
194         info->has_status = true;
195         info->status = g_strdup("setup");
196         info->has_total_time = false;
197         break;
198     case MIG_STATE_ACTIVE:
199         info->has_status = true;
200         info->status = g_strdup("active");
201         info->has_total_time = true;
202         info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
203             - s->total_time;
204         info->has_expected_downtime = true;
205         info->expected_downtime = s->expected_downtime;
206         info->has_setup_time = true;
207         info->setup_time = s->setup_time;
208
209         info->has_ram = true;
210         info->ram = g_malloc0(sizeof(*info->ram));
211         info->ram->transferred = ram_bytes_transferred();
212         info->ram->remaining = ram_bytes_remaining();
213         info->ram->total = ram_bytes_total();
214         info->ram->duplicate = dup_mig_pages_transferred();
215         info->ram->skipped = skipped_mig_pages_transferred();
216         info->ram->normal = norm_mig_pages_transferred();
217         info->ram->normal_bytes = norm_mig_bytes_transferred();
218         info->ram->dirty_pages_rate = s->dirty_pages_rate;
219         info->ram->mbps = s->mbps;
220
221         if (blk_mig_active()) {
222             info->has_disk = true;
223             info->disk = g_malloc0(sizeof(*info->disk));
224             info->disk->transferred = blk_mig_bytes_transferred();
225             info->disk->remaining = blk_mig_bytes_remaining();
226             info->disk->total = blk_mig_bytes_total();
227         }
228
229         get_xbzrle_cache_stats(info);
230         break;
231     case MIG_STATE_COMPLETED:
232         get_xbzrle_cache_stats(info);
233
234         info->has_status = true;
235         info->status = g_strdup("completed");
236         info->has_total_time = true;
237         info->total_time = s->total_time;
238         info->has_downtime = true;
239         info->downtime = s->downtime;
240         info->has_setup_time = true;
241         info->setup_time = s->setup_time;
242
243         info->has_ram = true;
244         info->ram = g_malloc0(sizeof(*info->ram));
245         info->ram->transferred = ram_bytes_transferred();
246         info->ram->remaining = 0;
247         info->ram->total = ram_bytes_total();
248         info->ram->duplicate = dup_mig_pages_transferred();
249         info->ram->skipped = skipped_mig_pages_transferred();
250         info->ram->normal = norm_mig_pages_transferred();
251         info->ram->normal_bytes = norm_mig_bytes_transferred();
252         info->ram->mbps = s->mbps;
253         break;
254     case MIG_STATE_ERROR:
255         info->has_status = true;
256         info->status = g_strdup("failed");
257         break;
258     case MIG_STATE_CANCELLED:
259         info->has_status = true;
260         info->status = g_strdup("cancelled");
261         break;
262     }
263
264     return info;
265 }
266
267 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
268                                   Error **errp)
269 {
270     MigrationState *s = migrate_get_current();
271     MigrationCapabilityStatusList *cap;
272
273     if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP) {
274         error_set(errp, QERR_MIGRATION_ACTIVE);
275         return;
276     }
277
278     for (cap = params; cap; cap = cap->next) {
279         s->enabled_capabilities[cap->value->capability] = cap->value->state;
280     }
281 }
282
283 /* shared migration helpers */
284
285 static void migrate_fd_cleanup(void *opaque)
286 {
287     MigrationState *s = opaque;
288
289     qemu_bh_delete(s->cleanup_bh);
290     s->cleanup_bh = NULL;
291
292     if (s->file) {
293         DPRINTF("closing file\n");
294         qemu_mutex_unlock_iothread();
295         qemu_thread_join(&s->thread);
296         qemu_mutex_lock_iothread();
297
298         qemu_fclose(s->file);
299         s->file = NULL;
300     }
301
302     assert(s->state != MIG_STATE_ACTIVE);
303
304     if (s->state != MIG_STATE_COMPLETED) {
305         qemu_savevm_state_cancel();
306     }
307
308     notifier_list_notify(&migration_state_notifiers, s);
309 }
310
311 static void migrate_set_state(MigrationState *s, int old_state, int new_state)
312 {
313     if (atomic_cmpxchg(&s->state, old_state, new_state) == new_state) {
314         trace_migrate_set_state(new_state);
315     }
316 }
317
318 void migrate_fd_error(MigrationState *s)
319 {
320     DPRINTF("setting error state\n");
321     assert(s->file == NULL);
322     s->state = MIG_STATE_ERROR;
323     trace_migrate_set_state(MIG_STATE_ERROR);
324     notifier_list_notify(&migration_state_notifiers, s);
325 }
326
327 static void migrate_fd_cancel(MigrationState *s)
328 {
329     DPRINTF("cancelling migration\n");
330
331     migrate_set_state(s, s->state, MIG_STATE_CANCELLED);
332 }
333
334 void add_migration_state_change_notifier(Notifier *notify)
335 {
336     notifier_list_add(&migration_state_notifiers, notify);
337 }
338
339 void remove_migration_state_change_notifier(Notifier *notify)
340 {
341     notifier_remove(notify);
342 }
343
344 bool migration_in_setup(MigrationState *s)
345 {
346     return s->state == MIG_STATE_SETUP;
347 }
348
349 bool migration_has_finished(MigrationState *s)
350 {
351     return s->state == MIG_STATE_COMPLETED;
352 }
353
354 bool migration_has_failed(MigrationState *s)
355 {
356     return (s->state == MIG_STATE_CANCELLED ||
357             s->state == MIG_STATE_ERROR);
358 }
359
360 static MigrationState *migrate_init(const MigrationParams *params)
361 {
362     MigrationState *s = migrate_get_current();
363     int64_t bandwidth_limit = s->bandwidth_limit;
364     bool enabled_capabilities[MIGRATION_CAPABILITY_MAX];
365     int64_t xbzrle_cache_size = s->xbzrle_cache_size;
366
367     memcpy(enabled_capabilities, s->enabled_capabilities,
368            sizeof(enabled_capabilities));
369
370     memset(s, 0, sizeof(*s));
371     s->params = *params;
372     memcpy(s->enabled_capabilities, enabled_capabilities,
373            sizeof(enabled_capabilities));
374     s->xbzrle_cache_size = xbzrle_cache_size;
375
376     s->bandwidth_limit = bandwidth_limit;
377     s->state = MIG_STATE_SETUP;
378     trace_migrate_set_state(MIG_STATE_SETUP);
379
380     s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
381     return s;
382 }
383
384 static GSList *migration_blockers;
385
386 void migrate_add_blocker(Error *reason)
387 {
388     migration_blockers = g_slist_prepend(migration_blockers, reason);
389 }
390
391 void migrate_del_blocker(Error *reason)
392 {
393     migration_blockers = g_slist_remove(migration_blockers, reason);
394 }
395
396 void qmp_migrate(const char *uri, bool has_blk, bool blk,
397                  bool has_inc, bool inc, bool has_detach, bool detach,
398                  Error **errp)
399 {
400     Error *local_err = NULL;
401     MigrationState *s = migrate_get_current();
402     MigrationParams params;
403     const char *p;
404
405     params.blk = has_blk && blk;
406     params.shared = has_inc && inc;
407
408     if (s->state == MIG_STATE_ACTIVE || s->state == MIG_STATE_SETUP) {
409         error_set(errp, QERR_MIGRATION_ACTIVE);
410         return;
411     }
412
413     if (qemu_savevm_state_blocked(errp)) {
414         return;
415     }
416
417     if (migration_blockers) {
418         *errp = error_copy(migration_blockers->data);
419         return;
420     }
421
422     s = migrate_init(&params);
423
424     if (strstart(uri, "tcp:", &p)) {
425         tcp_start_outgoing_migration(s, p, &local_err);
426 #ifdef CONFIG_RDMA
427     } else if (strstart(uri, "x-rdma:", &p)) {
428         rdma_start_outgoing_migration(s, p, &local_err);
429 #endif
430 #if !defined(WIN32)
431     } else if (strstart(uri, "exec:", &p)) {
432         exec_start_outgoing_migration(s, p, &local_err);
433     } else if (strstart(uri, "unix:", &p)) {
434         unix_start_outgoing_migration(s, p, &local_err);
435     } else if (strstart(uri, "fd:", &p)) {
436         fd_start_outgoing_migration(s, p, &local_err);
437 #endif
438     } else {
439         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "uri", "a valid migration protocol");
440         return;
441     }
442
443     if (local_err) {
444         migrate_fd_error(s);
445         error_propagate(errp, local_err);
446         return;
447     }
448 }
449
450 void qmp_migrate_cancel(Error **errp)
451 {
452     migrate_fd_cancel(migrate_get_current());
453 }
454
455 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
456 {
457     MigrationState *s = migrate_get_current();
458
459     /* Check for truncation */
460     if (value != (size_t)value) {
461         error_set(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
462                   "exceeding address space");
463         return;
464     }
465
466     s->xbzrle_cache_size = xbzrle_cache_resize(value);
467 }
468
469 int64_t qmp_query_migrate_cache_size(Error **errp)
470 {
471     return migrate_xbzrle_cache_size();
472 }
473
474 void qmp_migrate_set_speed(int64_t value, Error **errp)
475 {
476     MigrationState *s;
477
478     if (value < 0) {
479         value = 0;
480     }
481     if (value > SIZE_MAX) {
482         value = SIZE_MAX;
483     }
484
485     s = migrate_get_current();
486     s->bandwidth_limit = value;
487     if (s->file) {
488         qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
489     }
490 }
491
492 void qmp_migrate_set_downtime(double value, Error **errp)
493 {
494     value *= 1e9;
495     value = MAX(0, MIN(UINT64_MAX, value));
496     max_downtime = (uint64_t)value;
497 }
498
499 bool migrate_rdma_pin_all(void)
500 {
501     MigrationState *s;
502
503     s = migrate_get_current();
504
505     return s->enabled_capabilities[MIGRATION_CAPABILITY_X_RDMA_PIN_ALL];
506 }
507
508 bool migrate_auto_converge(void)
509 {
510     MigrationState *s;
511
512     s = migrate_get_current();
513
514     return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
515 }
516
517 bool migrate_zero_blocks(void)
518 {
519     MigrationState *s;
520
521     s = migrate_get_current();
522
523     return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
524 }
525
526 int migrate_use_xbzrle(void)
527 {
528     MigrationState *s;
529
530     s = migrate_get_current();
531
532     return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
533 }
534
535 int64_t migrate_xbzrle_cache_size(void)
536 {
537     MigrationState *s;
538
539     s = migrate_get_current();
540
541     return s->xbzrle_cache_size;
542 }
543
544 /* migration thread support */
545
546 static void *migration_thread(void *opaque)
547 {
548     MigrationState *s = opaque;
549     int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
550     int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
551     int64_t initial_bytes = 0;
552     int64_t max_size = 0;
553     int64_t start_time = initial_time;
554     bool old_vm_running = false;
555
556     DPRINTF("beginning savevm\n");
557     qemu_savevm_state_begin(s->file, &s->params);
558
559     s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
560     migrate_set_state(s, MIG_STATE_SETUP, MIG_STATE_ACTIVE);
561
562     DPRINTF("setup complete\n");
563
564     while (s->state == MIG_STATE_ACTIVE) {
565         int64_t current_time;
566         uint64_t pending_size;
567
568         if (!qemu_file_rate_limit(s->file)) {
569             DPRINTF("iterate\n");
570             pending_size = qemu_savevm_state_pending(s->file, max_size);
571             DPRINTF("pending size %" PRIu64 " max %" PRIu64 "\n",
572                     pending_size, max_size);
573             if (pending_size && pending_size >= max_size) {
574                 qemu_savevm_state_iterate(s->file);
575             } else {
576                 int ret;
577
578                 DPRINTF("done iterating\n");
579                 qemu_mutex_lock_iothread();
580                 start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
581                 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
582                 old_vm_running = runstate_is_running();
583
584                 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
585                 if (ret >= 0) {
586                     qemu_file_set_rate_limit(s->file, INT_MAX);
587                     qemu_savevm_state_complete(s->file);
588                 }
589                 qemu_mutex_unlock_iothread();
590
591                 if (ret < 0) {
592                     migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
593                     break;
594                 }
595
596                 if (!qemu_file_get_error(s->file)) {
597                     migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_COMPLETED);
598                     break;
599                 }
600             }
601         }
602
603         if (qemu_file_get_error(s->file)) {
604             migrate_set_state(s, MIG_STATE_ACTIVE, MIG_STATE_ERROR);
605             break;
606         }
607         current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
608         if (current_time >= initial_time + BUFFER_DELAY) {
609             uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;
610             uint64_t time_spent = current_time - initial_time;
611             double bandwidth = transferred_bytes / time_spent;
612             max_size = bandwidth * migrate_max_downtime() / 1000000;
613
614             s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
615                     ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
616
617             DPRINTF("transferred %" PRIu64 " time_spent %" PRIu64
618                     " bandwidth %g max_size %" PRId64 "\n",
619                     transferred_bytes, time_spent, bandwidth, max_size);
620             /* if we haven't sent anything, we don't want to recalculate
621                10000 is a small enough number for our purposes */
622             if (s->dirty_bytes_rate && transferred_bytes > 10000) {
623                 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
624             }
625
626             qemu_file_reset_rate_limit(s->file);
627             initial_time = current_time;
628             initial_bytes = qemu_ftell(s->file);
629         }
630         if (qemu_file_rate_limit(s->file)) {
631             /* usleep expects microseconds */
632             g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
633         }
634     }
635
636     qemu_mutex_lock_iothread();
637     if (s->state == MIG_STATE_COMPLETED) {
638         int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
639         s->total_time = end_time - s->total_time;
640         s->downtime = end_time - start_time;
641         runstate_set(RUN_STATE_POSTMIGRATE);
642     } else {
643         if (old_vm_running) {
644             vm_start();
645         }
646     }
647     qemu_bh_schedule(s->cleanup_bh);
648     qemu_mutex_unlock_iothread();
649
650     return NULL;
651 }
652
653 void migrate_fd_connect(MigrationState *s)
654 {
655     s->state = MIG_STATE_SETUP;
656     trace_migrate_set_state(MIG_STATE_SETUP);
657
658     /* This is a best 1st approximation. ns to ms */
659     s->expected_downtime = max_downtime/1000000;
660     s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
661
662     qemu_file_set_rate_limit(s->file,
663                              s->bandwidth_limit / XFER_LIMIT_RATIO);
664
665     /* Notify before starting migration thread */
666     notifier_list_notify(&migration_state_notifiers, s);
667
668     qemu_thread_create(&s->thread, migration_thread, s,
669                        QEMU_THREAD_JOINABLE);
670 }