4 * Copyright IBM, Corp. 2008
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
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.
16 #include "qemu/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "qemu/main-loop.h"
20 #include "migration/migration.h"
21 #include "migration/qemu-file.h"
22 #include "sysemu/sysemu.h"
23 #include "block/block.h"
24 #include "qapi/qmp/qerror.h"
25 #include "qapi/util.h"
26 #include "qemu/sockets.h"
28 #include "migration/block.h"
29 #include "migration/postcopy-ram.h"
30 #include "qemu/thread.h"
31 #include "qmp-commands.h"
33 #include "qapi-event.h"
35 #include "exec/memory.h"
36 #include "exec/address-spaces.h"
38 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
40 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
42 #define BUFFER_DELAY 100
43 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
45 /* Default compression thread count */
46 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
47 /* Default decompression thread count, usually decompression is at
48 * least 4 times as fast as compression.*/
49 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
50 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
51 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
52 /* Define default autoconverge cpu throttle migration parameters */
53 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
54 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
56 /* Migration XBZRLE default cache size */
57 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
59 static NotifierList migration_state_notifiers
=
60 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
62 static bool deferred_incoming
;
65 * Current state of incoming postcopy; note this is not part of
66 * MigrationIncomingState since it's state is used during cleanup
67 * at the end as MIS is being freed.
69 static PostcopyState incoming_postcopy_state
;
71 /* When we add fault tolerance, we could have several
72 migrations at once. For now we don't need to add
73 dynamic creation of migration */
76 MigrationState
*migrate_get_current(void)
79 static MigrationState current_migration
= {
80 .state
= MIGRATION_STATUS_NONE
,
81 .bandwidth_limit
= MAX_THROTTLE
,
82 .xbzrle_cache_size
= DEFAULT_MIGRATE_CACHE_SIZE
,
84 .parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
] =
85 DEFAULT_MIGRATE_COMPRESS_LEVEL
,
86 .parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
] =
87 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT
,
88 .parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
] =
89 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT
,
90 .parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL
] =
91 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL
,
92 .parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT
] =
93 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT
,
97 qemu_mutex_init(¤t_migration
.src_page_req_mutex
);
100 return ¤t_migration
;
104 static MigrationIncomingState
*mis_current
;
106 MigrationIncomingState
*migration_incoming_get_current(void)
111 MigrationIncomingState
*migration_incoming_state_new(QEMUFile
* f
)
113 mis_current
= g_new0(MigrationIncomingState
, 1);
114 mis_current
->from_src_file
= f
;
115 mis_current
->state
= MIGRATION_STATUS_NONE
;
116 QLIST_INIT(&mis_current
->loadvm_handlers
);
117 qemu_mutex_init(&mis_current
->rp_mutex
);
118 qemu_event_init(&mis_current
->main_thread_load_event
, false);
123 void migration_incoming_state_destroy(void)
125 qemu_event_destroy(&mis_current
->main_thread_load_event
);
126 loadvm_free_handlers(mis_current
);
135 uint8_t runstate
[100];
140 static GlobalState global_state
;
142 int global_state_store(void)
144 if (!runstate_store((char *)global_state
.runstate
,
145 sizeof(global_state
.runstate
))) {
146 error_report("runstate name too big: %s", global_state
.runstate
);
147 trace_migrate_state_too_big();
153 void global_state_store_running(void)
155 const char *state
= RunState_lookup
[RUN_STATE_RUNNING
];
156 strncpy((char *)global_state
.runstate
,
157 state
, sizeof(global_state
.runstate
));
160 static bool global_state_received(void)
162 return global_state
.received
;
165 static RunState
global_state_get_runstate(void)
167 return global_state
.state
;
170 void global_state_set_optional(void)
172 global_state
.optional
= true;
175 static bool global_state_needed(void *opaque
)
177 GlobalState
*s
= opaque
;
178 char *runstate
= (char *)s
->runstate
;
180 /* If it is not optional, it is mandatory */
182 if (s
->optional
== false) {
186 /* If state is running or paused, it is not needed */
188 if (strcmp(runstate
, "running") == 0 ||
189 strcmp(runstate
, "paused") == 0) {
193 /* for any other state it is needed */
197 static int global_state_post_load(void *opaque
, int version_id
)
199 GlobalState
*s
= opaque
;
200 Error
*local_err
= NULL
;
202 char *runstate
= (char *)s
->runstate
;
205 trace_migrate_global_state_post_load(runstate
);
207 r
= qapi_enum_parse(RunState_lookup
, runstate
, RUN_STATE__MAX
,
212 error_report_err(local_err
);
221 static void global_state_pre_save(void *opaque
)
223 GlobalState
*s
= opaque
;
225 trace_migrate_global_state_pre_save((char *)s
->runstate
);
226 s
->size
= strlen((char *)s
->runstate
) + 1;
229 static const VMStateDescription vmstate_globalstate
= {
230 .name
= "globalstate",
232 .minimum_version_id
= 1,
233 .post_load
= global_state_post_load
,
234 .pre_save
= global_state_pre_save
,
235 .needed
= global_state_needed
,
236 .fields
= (VMStateField
[]) {
237 VMSTATE_UINT32(size
, GlobalState
),
238 VMSTATE_BUFFER(runstate
, GlobalState
),
239 VMSTATE_END_OF_LIST()
243 void register_global_state(void)
245 /* We would use it independently that we receive it */
246 strcpy((char *)&global_state
.runstate
, "");
247 global_state
.received
= false;
248 vmstate_register(NULL
, 0, &vmstate_globalstate
, &global_state
);
251 static void migrate_generate_event(int new_state
)
253 if (migrate_use_events()) {
254 qapi_event_send_migration(new_state
, &error_abort
);
259 * Called on -incoming with a defer: uri.
260 * The migration can be started later after any parameters have been
263 static void deferred_incoming_migration(Error
**errp
)
265 if (deferred_incoming
) {
266 error_setg(errp
, "Incoming migration already deferred");
268 deferred_incoming
= true;
271 /* Request a range of pages from the source VM at the given
273 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
274 * as the last request (a name must have been given previously)
275 * Start: Address offset within the RB
276 * Len: Length in bytes required - must be a multiple of pagesize
278 void migrate_send_rp_req_pages(MigrationIncomingState
*mis
, const char *rbname
,
279 ram_addr_t start
, size_t len
)
281 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
282 size_t msglen
= 12; /* start + len */
284 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
285 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
288 int rbname_len
= strlen(rbname
);
289 assert(rbname_len
< 256);
291 bufc
[msglen
++] = rbname_len
;
292 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
293 msglen
+= rbname_len
;
294 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES_ID
, msglen
, bufc
);
296 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES
, msglen
, bufc
);
300 void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
304 qapi_event_send_migration(MIGRATION_STATUS_SETUP
, &error_abort
);
305 if (!strcmp(uri
, "defer")) {
306 deferred_incoming_migration(errp
);
307 } else if (strstart(uri
, "tcp:", &p
)) {
308 tcp_start_incoming_migration(p
, errp
);
310 } else if (strstart(uri
, "rdma:", &p
)) {
311 rdma_start_incoming_migration(p
, errp
);
314 } else if (strstart(uri
, "exec:", &p
)) {
315 exec_start_incoming_migration(p
, errp
);
316 } else if (strstart(uri
, "unix:", &p
)) {
317 unix_start_incoming_migration(p
, errp
);
318 } else if (strstart(uri
, "fd:", &p
)) {
319 fd_start_incoming_migration(p
, errp
);
322 error_setg(errp
, "unknown migration protocol: %s", uri
);
326 static void process_incoming_migration_bh(void *opaque
)
328 Error
*local_err
= NULL
;
329 MigrationIncomingState
*mis
= opaque
;
331 /* Make sure all file formats flush their mutable metadata */
332 bdrv_invalidate_cache_all(&local_err
);
334 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
335 MIGRATION_STATUS_FAILED
);
336 error_report_err(local_err
);
337 migrate_decompress_threads_join();
342 * This must happen after all error conditions are dealt with and
343 * we're sure the VM is going to be running on this host.
345 qemu_announce_self();
347 /* If global state section was not received or we are in running
348 state, we need to obey autostart. Any other state is set with
351 if (!global_state_received() ||
352 global_state_get_runstate() == RUN_STATE_RUNNING
) {
356 runstate_set(RUN_STATE_PAUSED
);
359 runstate_set(global_state_get_runstate());
361 migrate_decompress_threads_join();
363 * This must happen after any state changes since as soon as an external
364 * observer sees this event they might start to prod at the VM assuming
367 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
368 MIGRATION_STATUS_COMPLETED
);
369 qemu_bh_delete(mis
->bh
);
370 migration_incoming_state_destroy();
373 static void process_incoming_migration_co(void *opaque
)
375 QEMUFile
*f
= opaque
;
376 MigrationIncomingState
*mis
;
380 mis
= migration_incoming_state_new(f
);
381 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
382 migrate_set_state(&mis
->state
, MIGRATION_STATUS_NONE
,
383 MIGRATION_STATUS_ACTIVE
);
384 ret
= qemu_loadvm_state(f
);
386 ps
= postcopy_state_get();
387 trace_process_incoming_migration_co_end(ret
, ps
);
388 if (ps
!= POSTCOPY_INCOMING_NONE
) {
389 if (ps
== POSTCOPY_INCOMING_ADVISE
) {
391 * Where a migration had postcopy enabled (and thus went to advise)
392 * but managed to complete within the precopy period, we can use
395 postcopy_ram_incoming_cleanup(mis
);
396 } else if (ret
>= 0) {
398 * Postcopy was started, cleanup should happen at the end of the
401 trace_process_incoming_migration_co_postcopy_end_main();
404 /* Else if something went wrong then just fall out of the normal exit */
408 free_xbzrle_decoded_buf();
411 migrate_set_state(&mis
->state
, MIGRATION_STATUS_ACTIVE
,
412 MIGRATION_STATUS_FAILED
);
413 error_report("load of migration failed: %s", strerror(-ret
));
414 migrate_decompress_threads_join();
418 mis
->bh
= qemu_bh_new(process_incoming_migration_bh
, mis
);
419 qemu_bh_schedule(mis
->bh
);
422 void process_incoming_migration(QEMUFile
*f
)
424 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
);
426 migrate_decompress_threads_create();
427 qemu_file_set_blocking(f
, false);
428 qemu_coroutine_enter(co
, f
);
432 * Send a message on the return channel back to the source
435 void migrate_send_rp_message(MigrationIncomingState
*mis
,
436 enum mig_rp_message_type message_type
,
437 uint16_t len
, void *data
)
439 trace_migrate_send_rp_message((int)message_type
, len
);
440 qemu_mutex_lock(&mis
->rp_mutex
);
441 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
442 qemu_put_be16(mis
->to_src_file
, len
);
443 qemu_put_buffer(mis
->to_src_file
, data
, len
);
444 qemu_fflush(mis
->to_src_file
);
445 qemu_mutex_unlock(&mis
->rp_mutex
);
449 * Send a 'SHUT' message on the return channel with the given value
450 * to indicate that we've finished with the RP. Non-0 value indicates
453 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
458 buf
= cpu_to_be32(value
);
459 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
463 * Send a 'PONG' message on the return channel with the given value
464 * (normally in response to a 'PING')
466 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
471 buf
= cpu_to_be32(value
);
472 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
475 /* amount of nanoseconds we are willing to wait for migration to be down.
476 * the choice of nanoseconds is because it is the maximum resolution that
477 * get_clock() can achieve. It is an internal measure. All user-visible
478 * units must be in seconds */
479 static uint64_t max_downtime
= 300000000;
481 uint64_t migrate_max_downtime(void)
486 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
488 MigrationCapabilityStatusList
*head
= NULL
;
489 MigrationCapabilityStatusList
*caps
;
490 MigrationState
*s
= migrate_get_current();
493 caps
= NULL
; /* silence compiler warning */
494 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
496 head
= g_malloc0(sizeof(*caps
));
499 caps
->next
= g_malloc0(sizeof(*caps
));
503 g_malloc(sizeof(*caps
->value
));
504 caps
->value
->capability
= i
;
505 caps
->value
->state
= s
->enabled_capabilities
[i
];
511 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
513 MigrationParameters
*params
;
514 MigrationState
*s
= migrate_get_current();
516 params
= g_malloc0(sizeof(*params
));
517 params
->compress_level
= s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
];
518 params
->compress_threads
=
519 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
];
520 params
->decompress_threads
=
521 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
];
522 params
->cpu_throttle_initial
=
523 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL
];
524 params
->cpu_throttle_increment
=
525 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT
];
531 * Return true if we're already in the middle of a migration
532 * (i.e. any of the active or setup states)
534 static bool migration_is_setup_or_active(int state
)
537 case MIGRATION_STATUS_ACTIVE
:
538 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
539 case MIGRATION_STATUS_SETUP
:
548 static void get_xbzrle_cache_stats(MigrationInfo
*info
)
550 if (migrate_use_xbzrle()) {
551 info
->has_xbzrle_cache
= true;
552 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
553 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
554 info
->xbzrle_cache
->bytes
= xbzrle_mig_bytes_transferred();
555 info
->xbzrle_cache
->pages
= xbzrle_mig_pages_transferred();
556 info
->xbzrle_cache
->cache_miss
= xbzrle_mig_pages_cache_miss();
557 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_mig_cache_miss_rate();
558 info
->xbzrle_cache
->overflow
= xbzrle_mig_pages_overflow();
562 MigrationInfo
*qmp_query_migrate(Error
**errp
)
564 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
565 MigrationState
*s
= migrate_get_current();
568 case MIGRATION_STATUS_NONE
:
569 /* no migration has happened ever */
571 case MIGRATION_STATUS_SETUP
:
572 info
->has_status
= true;
573 info
->has_total_time
= false;
575 case MIGRATION_STATUS_ACTIVE
:
576 case MIGRATION_STATUS_CANCELLING
:
577 info
->has_status
= true;
578 info
->has_total_time
= true;
579 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
581 info
->has_expected_downtime
= true;
582 info
->expected_downtime
= s
->expected_downtime
;
583 info
->has_setup_time
= true;
584 info
->setup_time
= s
->setup_time
;
586 info
->has_ram
= true;
587 info
->ram
= g_malloc0(sizeof(*info
->ram
));
588 info
->ram
->transferred
= ram_bytes_transferred();
589 info
->ram
->remaining
= ram_bytes_remaining();
590 info
->ram
->total
= ram_bytes_total();
591 info
->ram
->duplicate
= dup_mig_pages_transferred();
592 info
->ram
->skipped
= skipped_mig_pages_transferred();
593 info
->ram
->normal
= norm_mig_pages_transferred();
594 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
595 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
596 info
->ram
->mbps
= s
->mbps
;
597 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
599 if (blk_mig_active()) {
600 info
->has_disk
= true;
601 info
->disk
= g_malloc0(sizeof(*info
->disk
));
602 info
->disk
->transferred
= blk_mig_bytes_transferred();
603 info
->disk
->remaining
= blk_mig_bytes_remaining();
604 info
->disk
->total
= blk_mig_bytes_total();
607 if (cpu_throttle_active()) {
608 info
->has_cpu_throttle_percentage
= true;
609 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
612 get_xbzrle_cache_stats(info
);
614 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
615 /* Mostly the same as active; TODO add some postcopy stats */
616 info
->has_status
= true;
617 info
->has_total_time
= true;
618 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
620 info
->has_expected_downtime
= true;
621 info
->expected_downtime
= s
->expected_downtime
;
622 info
->has_setup_time
= true;
623 info
->setup_time
= s
->setup_time
;
625 info
->has_ram
= true;
626 info
->ram
= g_malloc0(sizeof(*info
->ram
));
627 info
->ram
->transferred
= ram_bytes_transferred();
628 info
->ram
->remaining
= ram_bytes_remaining();
629 info
->ram
->total
= ram_bytes_total();
630 info
->ram
->duplicate
= dup_mig_pages_transferred();
631 info
->ram
->skipped
= skipped_mig_pages_transferred();
632 info
->ram
->normal
= norm_mig_pages_transferred();
633 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
634 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
635 info
->ram
->mbps
= s
->mbps
;
636 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
638 if (blk_mig_active()) {
639 info
->has_disk
= true;
640 info
->disk
= g_malloc0(sizeof(*info
->disk
));
641 info
->disk
->transferred
= blk_mig_bytes_transferred();
642 info
->disk
->remaining
= blk_mig_bytes_remaining();
643 info
->disk
->total
= blk_mig_bytes_total();
646 get_xbzrle_cache_stats(info
);
648 case MIGRATION_STATUS_COMPLETED
:
649 get_xbzrle_cache_stats(info
);
651 info
->has_status
= true;
652 info
->has_total_time
= true;
653 info
->total_time
= s
->total_time
;
654 info
->has_downtime
= true;
655 info
->downtime
= s
->downtime
;
656 info
->has_setup_time
= true;
657 info
->setup_time
= s
->setup_time
;
659 info
->has_ram
= true;
660 info
->ram
= g_malloc0(sizeof(*info
->ram
));
661 info
->ram
->transferred
= ram_bytes_transferred();
662 info
->ram
->remaining
= 0;
663 info
->ram
->total
= ram_bytes_total();
664 info
->ram
->duplicate
= dup_mig_pages_transferred();
665 info
->ram
->skipped
= skipped_mig_pages_transferred();
666 info
->ram
->normal
= norm_mig_pages_transferred();
667 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
668 info
->ram
->mbps
= s
->mbps
;
669 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
671 case MIGRATION_STATUS_FAILED
:
672 info
->has_status
= true;
674 case MIGRATION_STATUS_CANCELLED
:
675 info
->has_status
= true;
678 info
->status
= s
->state
;
683 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
686 MigrationState
*s
= migrate_get_current();
687 MigrationCapabilityStatusList
*cap
;
689 if (migration_is_setup_or_active(s
->state
)) {
690 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
694 for (cap
= params
; cap
; cap
= cap
->next
) {
695 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
698 if (migrate_postcopy_ram()) {
699 if (migrate_use_compression()) {
700 /* The decompression threads asynchronously write into RAM
701 * rather than use the atomic copies needed to avoid
702 * userfaulting. It should be possible to fix the decompression
703 * threads for compatibility in future.
705 error_report("Postcopy is not currently compatible with "
707 s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
] =
713 void qmp_migrate_set_parameters(bool has_compress_level
,
714 int64_t compress_level
,
715 bool has_compress_threads
,
716 int64_t compress_threads
,
717 bool has_decompress_threads
,
718 int64_t decompress_threads
,
719 bool has_cpu_throttle_initial
,
720 int64_t cpu_throttle_initial
,
721 bool has_cpu_throttle_increment
,
722 int64_t cpu_throttle_increment
, Error
**errp
)
724 MigrationState
*s
= migrate_get_current();
726 if (has_compress_level
&& (compress_level
< 0 || compress_level
> 9)) {
727 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
728 "is invalid, it should be in the range of 0 to 9");
731 if (has_compress_threads
&&
732 (compress_threads
< 1 || compress_threads
> 255)) {
733 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
735 "is invalid, it should be in the range of 1 to 255");
738 if (has_decompress_threads
&&
739 (decompress_threads
< 1 || decompress_threads
> 255)) {
740 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
741 "decompress_threads",
742 "is invalid, it should be in the range of 1 to 255");
745 if (has_cpu_throttle_initial
&&
746 (cpu_throttle_initial
< 1 || cpu_throttle_initial
> 99)) {
747 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
748 "cpu_throttle_initial",
749 "an integer in the range of 1 to 99");
751 if (has_cpu_throttle_increment
&&
752 (cpu_throttle_increment
< 1 || cpu_throttle_increment
> 99)) {
753 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
754 "cpu_throttle_increment",
755 "an integer in the range of 1 to 99");
758 if (has_compress_level
) {
759 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
] = compress_level
;
761 if (has_compress_threads
) {
762 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
] = compress_threads
;
764 if (has_decompress_threads
) {
765 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
] =
768 if (has_cpu_throttle_initial
) {
769 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL
] =
770 cpu_throttle_initial
;
773 if (has_cpu_throttle_increment
) {
774 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT
] =
775 cpu_throttle_increment
;
779 void qmp_migrate_start_postcopy(Error
**errp
)
781 MigrationState
*s
= migrate_get_current();
783 if (!migrate_postcopy_ram()) {
784 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
785 " the start of migration");
789 if (s
->state
== MIGRATION_STATUS_NONE
) {
790 error_setg(errp
, "Postcopy must be started after migration has been"
795 * we don't error if migration has finished since that would be racy
796 * with issuing this command.
798 atomic_set(&s
->start_postcopy
, true);
801 /* shared migration helpers */
803 void migrate_set_state(int *state
, int old_state
, int new_state
)
805 if (atomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
806 trace_migrate_set_state(new_state
);
807 migrate_generate_event(new_state
);
811 static void migrate_fd_cleanup(void *opaque
)
813 MigrationState
*s
= opaque
;
815 qemu_bh_delete(s
->cleanup_bh
);
816 s
->cleanup_bh
= NULL
;
820 if (s
->to_dst_file
) {
821 trace_migrate_fd_cleanup();
822 qemu_mutex_unlock_iothread();
823 if (s
->migration_thread_running
) {
824 qemu_thread_join(&s
->thread
);
825 s
->migration_thread_running
= false;
827 qemu_mutex_lock_iothread();
829 migrate_compress_threads_join();
830 qemu_fclose(s
->to_dst_file
);
831 s
->to_dst_file
= NULL
;
834 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
835 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
837 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
838 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
839 MIGRATION_STATUS_CANCELLED
);
842 notifier_list_notify(&migration_state_notifiers
, s
);
845 void migrate_fd_error(MigrationState
*s
)
847 trace_migrate_fd_error();
848 assert(s
->to_dst_file
== NULL
);
849 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
850 MIGRATION_STATUS_FAILED
);
851 notifier_list_notify(&migration_state_notifiers
, s
);
854 static void migrate_fd_cancel(MigrationState
*s
)
857 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
858 trace_migrate_fd_cancel();
860 if (s
->rp_state
.from_dst_file
) {
861 /* shutdown the rp socket, so causing the rp thread to shutdown */
862 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
866 old_state
= s
->state
;
867 if (!migration_is_setup_or_active(old_state
)) {
870 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
871 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
874 * If we're unlucky the migration code might be stuck somewhere in a
875 * send/write while the network has failed and is waiting to timeout;
876 * if we've got shutdown(2) available then we can force it to quit.
877 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
878 * called in a bh, so there is no race against this cancel.
880 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
881 qemu_file_shutdown(f
);
885 void add_migration_state_change_notifier(Notifier
*notify
)
887 notifier_list_add(&migration_state_notifiers
, notify
);
890 void remove_migration_state_change_notifier(Notifier
*notify
)
892 notifier_remove(notify
);
895 bool migration_in_setup(MigrationState
*s
)
897 return s
->state
== MIGRATION_STATUS_SETUP
;
900 bool migration_has_finished(MigrationState
*s
)
902 return s
->state
== MIGRATION_STATUS_COMPLETED
;
905 bool migration_has_failed(MigrationState
*s
)
907 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
908 s
->state
== MIGRATION_STATUS_FAILED
);
911 bool migration_in_postcopy(MigrationState
*s
)
913 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
916 bool migration_in_postcopy_after_devices(MigrationState
*s
)
918 return migration_in_postcopy(s
) && s
->postcopy_after_devices
;
921 MigrationState
*migrate_init(const MigrationParams
*params
)
923 MigrationState
*s
= migrate_get_current();
926 * Reinitialise all migration state, except
927 * parameters/capabilities that the user set, and
933 s
->to_dst_file
= NULL
;
934 s
->state
= MIGRATION_STATUS_NONE
;
936 s
->rp_state
.from_dst_file
= NULL
;
937 s
->rp_state
.error
= false;
940 s
->expected_downtime
= 0;
941 s
->dirty_pages_rate
= 0;
942 s
->dirty_bytes_rate
= 0;
944 s
->dirty_sync_count
= 0;
945 s
->start_postcopy
= false;
946 s
->postcopy_after_devices
= false;
947 s
->migration_thread_running
= false;
948 s
->last_req_rb
= NULL
;
950 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
952 QSIMPLEQ_INIT(&s
->src_page_requests
);
954 s
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
958 static GSList
*migration_blockers
;
960 void migrate_add_blocker(Error
*reason
)
962 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
965 void migrate_del_blocker(Error
*reason
)
967 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
970 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
972 Error
*local_err
= NULL
;
973 static bool once
= true;
975 if (!deferred_incoming
) {
976 error_setg(errp
, "For use with '-incoming defer'");
980 error_setg(errp
, "The incoming migration has already been started");
983 qemu_start_incoming_migration(uri
, &local_err
);
986 error_propagate(errp
, local_err
);
993 bool migration_is_blocked(Error
**errp
)
995 if (qemu_savevm_state_blocked(errp
)) {
999 if (migration_blockers
) {
1000 *errp
= error_copy(migration_blockers
->data
);
1007 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1008 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1011 Error
*local_err
= NULL
;
1012 MigrationState
*s
= migrate_get_current();
1013 MigrationParams params
;
1016 params
.blk
= has_blk
&& blk
;
1017 params
.shared
= has_inc
&& inc
;
1019 if (migration_is_setup_or_active(s
->state
) ||
1020 s
->state
== MIGRATION_STATUS_CANCELLING
) {
1021 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1024 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1025 error_setg(errp
, "Guest is waiting for an incoming migration");
1029 if (migration_is_blocked(errp
)) {
1033 s
= migrate_init(¶ms
);
1035 if (strstart(uri
, "tcp:", &p
)) {
1036 tcp_start_outgoing_migration(s
, p
, &local_err
);
1038 } else if (strstart(uri
, "rdma:", &p
)) {
1039 rdma_start_outgoing_migration(s
, p
, &local_err
);
1042 } else if (strstart(uri
, "exec:", &p
)) {
1043 exec_start_outgoing_migration(s
, p
, &local_err
);
1044 } else if (strstart(uri
, "unix:", &p
)) {
1045 unix_start_outgoing_migration(s
, p
, &local_err
);
1046 } else if (strstart(uri
, "fd:", &p
)) {
1047 fd_start_outgoing_migration(s
, p
, &local_err
);
1050 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1051 "a valid migration protocol");
1052 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1053 MIGRATION_STATUS_FAILED
);
1058 migrate_fd_error(s
);
1059 error_propagate(errp
, local_err
);
1064 void qmp_migrate_cancel(Error
**errp
)
1066 migrate_fd_cancel(migrate_get_current());
1069 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1071 MigrationState
*s
= migrate_get_current();
1074 /* Check for truncation */
1075 if (value
!= (size_t)value
) {
1076 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1077 "exceeding address space");
1081 /* Cache should not be larger than guest ram size */
1082 if (value
> ram_bytes_total()) {
1083 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1084 "exceeds guest ram size ");
1088 new_size
= xbzrle_cache_resize(value
);
1090 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1091 "is smaller than page size");
1095 s
->xbzrle_cache_size
= new_size
;
1098 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1100 return migrate_xbzrle_cache_size();
1103 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1110 if (value
> SIZE_MAX
) {
1114 s
= migrate_get_current();
1115 s
->bandwidth_limit
= value
;
1116 if (s
->to_dst_file
) {
1117 qemu_file_set_rate_limit(s
->to_dst_file
,
1118 s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1122 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1125 value
= MAX(0, MIN(UINT64_MAX
, value
));
1126 max_downtime
= (uint64_t)value
;
1129 bool migrate_postcopy_ram(void)
1133 s
= migrate_get_current();
1135 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
1138 bool migrate_auto_converge(void)
1142 s
= migrate_get_current();
1144 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1147 bool migrate_zero_blocks(void)
1151 s
= migrate_get_current();
1153 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1156 bool migrate_use_compression(void)
1160 s
= migrate_get_current();
1162 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1165 int migrate_compress_level(void)
1169 s
= migrate_get_current();
1171 return s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
];
1174 int migrate_compress_threads(void)
1178 s
= migrate_get_current();
1180 return s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
];
1183 int migrate_decompress_threads(void)
1187 s
= migrate_get_current();
1189 return s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
];
1192 bool migrate_use_events(void)
1196 s
= migrate_get_current();
1198 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1201 int migrate_use_xbzrle(void)
1205 s
= migrate_get_current();
1207 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1210 int64_t migrate_xbzrle_cache_size(void)
1214 s
= migrate_get_current();
1216 return s
->xbzrle_cache_size
;
1219 /* migration thread support */
1221 * Something bad happened to the RP stream, mark an error
1222 * The caller shall print or trace something to indicate why
1224 static void mark_source_rp_bad(MigrationState
*s
)
1226 s
->rp_state
.error
= true;
1229 static struct rp_cmd_args
{
1230 ssize_t len
; /* -1 = variable */
1233 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1234 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1235 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1236 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1237 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1238 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1242 * Process a request for pages received on the return path,
1243 * We're allowed to send more than requested (e.g. to round to our page size)
1244 * and we don't need to send pages that have already been sent.
1246 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1247 ram_addr_t start
, size_t len
)
1249 long our_host_ps
= getpagesize();
1251 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1254 * Since we currently insist on matching page sizes, just sanity check
1255 * we're being asked for whole host pages.
1257 if (start
& (our_host_ps
-1) ||
1258 (len
& (our_host_ps
-1))) {
1259 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1260 " len: %zd", __func__
, start
, len
);
1261 mark_source_rp_bad(ms
);
1265 if (ram_save_queue_pages(ms
, rbname
, start
, len
)) {
1266 mark_source_rp_bad(ms
);
1271 * Handles messages sent on the return path towards the source VM
1274 static void *source_return_path_thread(void *opaque
)
1276 MigrationState
*ms
= opaque
;
1277 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1278 uint16_t header_len
, header_type
;
1280 uint32_t tmp32
, sibling_error
;
1281 ram_addr_t start
= 0; /* =0 to silence warning */
1282 size_t len
= 0, expected_len
;
1285 trace_source_return_path_thread_entry();
1286 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1287 migration_is_setup_or_active(ms
->state
)) {
1288 trace_source_return_path_thread_loop_top();
1289 header_type
= qemu_get_be16(rp
);
1290 header_len
= qemu_get_be16(rp
);
1292 if (header_type
>= MIG_RP_MSG_MAX
||
1293 header_type
== MIG_RP_MSG_INVALID
) {
1294 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1295 header_type
, header_len
);
1296 mark_source_rp_bad(ms
);
1300 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1301 header_len
!= rp_cmd_args
[header_type
].len
) ||
1302 header_len
> sizeof(buf
)) {
1303 error_report("RP: Received '%s' message (0x%04x) with"
1304 "incorrect length %d expecting %zu",
1305 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1306 (size_t)rp_cmd_args
[header_type
].len
);
1307 mark_source_rp_bad(ms
);
1311 /* We know we've got a valid header by this point */
1312 res
= qemu_get_buffer(rp
, buf
, header_len
);
1313 if (res
!= header_len
) {
1314 error_report("RP: Failed reading data for message 0x%04x"
1315 " read %d expected %d",
1316 header_type
, res
, header_len
);
1317 mark_source_rp_bad(ms
);
1321 /* OK, we have the message and the data */
1322 switch (header_type
) {
1323 case MIG_RP_MSG_SHUT
:
1324 sibling_error
= be32_to_cpup((uint32_t *)buf
);
1325 trace_source_return_path_thread_shut(sibling_error
);
1326 if (sibling_error
) {
1327 error_report("RP: Sibling indicated error %d", sibling_error
);
1328 mark_source_rp_bad(ms
);
1331 * We'll let the main thread deal with closing the RP
1332 * we could do a shutdown(2) on it, but we're the only user
1333 * anyway, so there's nothing gained.
1337 case MIG_RP_MSG_PONG
:
1338 tmp32
= be32_to_cpup((uint32_t *)buf
);
1339 trace_source_return_path_thread_pong(tmp32
);
1342 case MIG_RP_MSG_REQ_PAGES
:
1343 start
= be64_to_cpup((uint64_t *)buf
);
1344 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1345 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1348 case MIG_RP_MSG_REQ_PAGES_ID
:
1349 expected_len
= 12 + 1; /* header + termination */
1351 if (header_len
>= expected_len
) {
1352 start
= be64_to_cpup((uint64_t *)buf
);
1353 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1354 /* Now we expect an idstr */
1355 tmp32
= buf
[12]; /* Length of the following idstr */
1356 buf
[13 + tmp32
] = '\0';
1357 expected_len
+= tmp32
;
1359 if (header_len
!= expected_len
) {
1360 error_report("RP: Req_Page_id with length %d expecting %zd",
1361 header_len
, expected_len
);
1362 mark_source_rp_bad(ms
);
1365 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1372 if (qemu_file_get_error(rp
)) {
1373 trace_source_return_path_thread_bad_end();
1374 mark_source_rp_bad(ms
);
1377 trace_source_return_path_thread_end();
1379 ms
->rp_state
.from_dst_file
= NULL
;
1384 static int open_return_path_on_source(MigrationState
*ms
)
1387 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
1388 if (!ms
->rp_state
.from_dst_file
) {
1392 trace_open_return_path_on_source();
1393 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
1394 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
1396 trace_open_return_path_on_source_continue();
1401 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1402 static int await_return_path_close_on_source(MigrationState
*ms
)
1405 * If this is a normal exit then the destination will send a SHUT and the
1406 * rp_thread will exit, however if there's an error we need to cause
1409 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
1411 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1412 * waiting for the destination.
1414 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
1415 mark_source_rp_bad(ms
);
1417 trace_await_return_path_close_on_source_joining();
1418 qemu_thread_join(&ms
->rp_state
.rp_thread
);
1419 trace_await_return_path_close_on_source_close();
1420 return ms
->rp_state
.error
;
1424 * Switch from normal iteration to postcopy
1425 * Returns non-0 on error
1427 static int postcopy_start(MigrationState
*ms
, bool *old_vm_running
)
1430 const QEMUSizedBuffer
*qsb
;
1431 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1432 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
1433 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1435 trace_postcopy_start();
1436 qemu_mutex_lock_iothread();
1437 trace_postcopy_start_set_run();
1439 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1440 *old_vm_running
= runstate_is_running();
1441 global_state_store();
1442 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1447 ret
= bdrv_inactivate_all();
1453 * Cause any non-postcopiable, but iterative devices to
1454 * send out their final data.
1456 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true);
1459 * in Finish migrate and with the io-lock held everything should
1460 * be quiet, but we've potentially still got dirty pages and we
1461 * need to tell the destination to throw any pages it's already received
1464 if (ram_postcopy_send_discard_bitmap(ms
)) {
1465 error_report("postcopy send discard bitmap failed");
1470 * send rest of state - note things that are doing postcopy
1471 * will notice we're in POSTCOPY_ACTIVE and not actually
1472 * wrap their state up here
1474 qemu_file_set_rate_limit(ms
->to_dst_file
, INT64_MAX
);
1475 /* Ping just for debugging, helps line traces up */
1476 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
1479 * While loading the device state we may trigger page transfer
1480 * requests and the fd must be free to process those, and thus
1481 * the destination must read the whole device state off the fd before
1482 * it starts processing it. Unfortunately the ad-hoc migration format
1483 * doesn't allow the destination to know the size to read without fully
1484 * parsing it through each devices load-state code (especially the open
1485 * coded devices that use get/put).
1486 * So we wrap the device state up in a package with a length at the start;
1487 * to do this we use a qemu_buf to hold the whole of the device state.
1489 QEMUFile
*fb
= qemu_bufopen("w", NULL
);
1491 error_report("Failed to create buffered file");
1496 * Make sure the receiver can get incoming pages before we send the rest
1499 qemu_savevm_send_postcopy_listen(fb
);
1501 qemu_savevm_state_complete_precopy(fb
, false);
1502 qemu_savevm_send_ping(fb
, 3);
1504 qemu_savevm_send_postcopy_run(fb
);
1506 /* <><> end of stuff going into the package */
1507 qsb
= qemu_buf_get(fb
);
1509 /* Now send that blob */
1510 if (qemu_savevm_send_packaged(ms
->to_dst_file
, qsb
)) {
1515 /* Send a notify to give a chance for anything that needs to happen
1516 * at the transition to postcopy and after the device state; in particular
1517 * spice needs to trigger a transition now
1519 ms
->postcopy_after_devices
= true;
1520 notifier_list_notify(&migration_state_notifiers
, ms
);
1522 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
1524 qemu_mutex_unlock_iothread();
1527 * Although this ping is just for debug, it could potentially be
1528 * used for getting a better measurement of downtime at the source.
1530 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
1532 ret
= qemu_file_get_error(ms
->to_dst_file
);
1534 error_report("postcopy_start: Migration stream errored");
1535 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1536 MIGRATION_STATUS_FAILED
);
1544 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1545 MIGRATION_STATUS_FAILED
);
1546 qemu_mutex_unlock_iothread();
1551 * migration_completion: Used by migration_thread when there's not much left.
1552 * The caller 'breaks' the loop when this returns.
1554 * @s: Current migration state
1555 * @current_active_state: The migration state we expect to be in
1556 * @*old_vm_running: Pointer to old_vm_running flag
1557 * @*start_time: Pointer to time to update
1559 static void migration_completion(MigrationState
*s
, int current_active_state
,
1560 bool *old_vm_running
,
1561 int64_t *start_time
)
1565 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1566 qemu_mutex_lock_iothread();
1567 *start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1568 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1569 *old_vm_running
= runstate_is_running();
1570 ret
= global_state_store();
1573 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1575 ret
= bdrv_inactivate_all();
1578 qemu_file_set_rate_limit(s
->to_dst_file
, INT64_MAX
);
1579 qemu_savevm_state_complete_precopy(s
->to_dst_file
, false);
1582 qemu_mutex_unlock_iothread();
1587 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1588 trace_migration_completion_postcopy_end();
1590 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
1591 trace_migration_completion_postcopy_end_after_complete();
1595 * If rp was opened we must clean up the thread before
1596 * cleaning everything else up (since if there are no failures
1597 * it will wait for the destination to send it's status in
1599 * Postcopy opens rp if enabled (even if it's not avtivated)
1601 if (migrate_postcopy_ram()) {
1603 trace_migration_completion_postcopy_end_before_rp();
1604 rp_error
= await_return_path_close_on_source(s
);
1605 trace_migration_completion_postcopy_end_after_rp(rp_error
);
1607 goto fail_invalidate
;
1611 if (qemu_file_get_error(s
->to_dst_file
)) {
1612 trace_migration_completion_file_err();
1613 goto fail_invalidate
;
1616 migrate_set_state(&s
->state
, current_active_state
,
1617 MIGRATION_STATUS_COMPLETED
);
1621 /* If not doing postcopy, vm_start() will be called: let's regain
1622 * control on images.
1624 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1625 Error
*local_err
= NULL
;
1627 bdrv_invalidate_cache_all(&local_err
);
1629 error_report_err(local_err
);
1634 migrate_set_state(&s
->state
, current_active_state
,
1635 MIGRATION_STATUS_FAILED
);
1639 * Master migration thread on the source VM.
1640 * It drives the migration and pumps the data down the outgoing channel.
1642 static void *migration_thread(void *opaque
)
1644 MigrationState
*s
= opaque
;
1645 /* Used by the bandwidth calcs, updated later */
1646 int64_t initial_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1647 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
1648 int64_t initial_bytes
= 0;
1649 int64_t max_size
= 0;
1650 int64_t start_time
= initial_time
;
1652 bool old_vm_running
= false;
1653 bool entered_postcopy
= false;
1654 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1655 enum MigrationStatus current_active_state
= MIGRATION_STATUS_ACTIVE
;
1657 rcu_register_thread();
1659 qemu_savevm_state_header(s
->to_dst_file
);
1661 if (migrate_postcopy_ram()) {
1662 /* Now tell the dest that it should open its end so it can reply */
1663 qemu_savevm_send_open_return_path(s
->to_dst_file
);
1665 /* And do a ping that will make stuff easier to debug */
1666 qemu_savevm_send_ping(s
->to_dst_file
, 1);
1669 * Tell the destination that we *might* want to do postcopy later;
1670 * if the other end can't do postcopy it should fail now, nice and
1673 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
1676 qemu_savevm_state_begin(s
->to_dst_file
, &s
->params
);
1678 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
1679 current_active_state
= MIGRATION_STATUS_ACTIVE
;
1680 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1681 MIGRATION_STATUS_ACTIVE
);
1683 trace_migration_thread_setup_complete();
1685 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
1686 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1687 int64_t current_time
;
1688 uint64_t pending_size
;
1690 if (!qemu_file_rate_limit(s
->to_dst_file
)) {
1691 uint64_t pend_post
, pend_nonpost
;
1693 qemu_savevm_state_pending(s
->to_dst_file
, max_size
, &pend_nonpost
,
1695 pending_size
= pend_nonpost
+ pend_post
;
1696 trace_migrate_pending(pending_size
, max_size
,
1697 pend_post
, pend_nonpost
);
1698 if (pending_size
&& pending_size
>= max_size
) {
1699 /* Still a significant amount to transfer */
1701 if (migrate_postcopy_ram() &&
1702 s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
&&
1703 pend_nonpost
<= max_size
&&
1704 atomic_read(&s
->start_postcopy
)) {
1706 if (!postcopy_start(s
, &old_vm_running
)) {
1707 current_active_state
= MIGRATION_STATUS_POSTCOPY_ACTIVE
;
1708 entered_postcopy
= true;
1713 /* Just another iteration step */
1714 qemu_savevm_state_iterate(s
->to_dst_file
, entered_postcopy
);
1716 trace_migration_thread_low_pending(pending_size
);
1717 migration_completion(s
, current_active_state
,
1718 &old_vm_running
, &start_time
);
1723 if (qemu_file_get_error(s
->to_dst_file
)) {
1724 migrate_set_state(&s
->state
, current_active_state
,
1725 MIGRATION_STATUS_FAILED
);
1726 trace_migration_thread_file_err();
1729 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1730 if (current_time
>= initial_time
+ BUFFER_DELAY
) {
1731 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
) -
1733 uint64_t time_spent
= current_time
- initial_time
;
1734 double bandwidth
= (double)transferred_bytes
/ time_spent
;
1735 max_size
= bandwidth
* migrate_max_downtime() / 1000000;
1737 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1738 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
1740 trace_migrate_transferred(transferred_bytes
, time_spent
,
1741 bandwidth
, max_size
);
1742 /* if we haven't sent anything, we don't want to recalculate
1743 10000 is a small enough number for our purposes */
1744 if (s
->dirty_bytes_rate
&& transferred_bytes
> 10000) {
1745 s
->expected_downtime
= s
->dirty_bytes_rate
/ bandwidth
;
1748 qemu_file_reset_rate_limit(s
->to_dst_file
);
1749 initial_time
= current_time
;
1750 initial_bytes
= qemu_ftell(s
->to_dst_file
);
1752 if (qemu_file_rate_limit(s
->to_dst_file
)) {
1753 /* usleep expects microseconds */
1754 g_usleep((initial_time
+ BUFFER_DELAY
- current_time
)*1000);
1758 trace_migration_thread_after_loop();
1759 /* If we enabled cpu throttling for auto-converge, turn it off. */
1760 cpu_throttle_stop();
1761 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1763 qemu_mutex_lock_iothread();
1764 qemu_savevm_state_cleanup();
1765 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1766 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
);
1767 s
->total_time
= end_time
- s
->total_time
;
1768 if (!entered_postcopy
) {
1769 s
->downtime
= end_time
- start_time
;
1771 if (s
->total_time
) {
1772 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1773 ((double) s
->total_time
)) / 1000;
1775 runstate_set(RUN_STATE_POSTMIGRATE
);
1777 if (old_vm_running
&& !entered_postcopy
) {
1781 qemu_bh_schedule(s
->cleanup_bh
);
1782 qemu_mutex_unlock_iothread();
1784 rcu_unregister_thread();
1788 void migrate_fd_connect(MigrationState
*s
)
1790 /* This is a best 1st approximation. ns to ms */
1791 s
->expected_downtime
= max_downtime
/1000000;
1792 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
1794 qemu_file_set_blocking(s
->to_dst_file
, true);
1795 qemu_file_set_rate_limit(s
->to_dst_file
,
1796 s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1798 /* Notify before starting migration thread */
1799 notifier_list_notify(&migration_state_notifiers
, s
);
1802 * Open the return path; currently for postcopy but other things might
1805 if (migrate_postcopy_ram()) {
1806 if (open_return_path_on_source(s
)) {
1807 error_report("Unable to open return-path for postcopy");
1808 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1809 MIGRATION_STATUS_FAILED
);
1810 migrate_fd_cleanup(s
);
1815 migrate_compress_threads_create();
1816 qemu_thread_create(&s
->thread
, "migration", migration_thread
, s
,
1817 QEMU_THREAD_JOINABLE
);
1818 s
->migration_thread_running
= true;
1821 PostcopyState
postcopy_state_get(void)
1823 return atomic_mb_read(&incoming_postcopy_state
);
1826 /* Set the state and return the old state */
1827 PostcopyState
postcopy_state_set(PostcopyState new_state
)
1829 return atomic_xchg(&incoming_postcopy_state
, new_state
);