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