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