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