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