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
);
425 int fd
= qemu_get_fd(f
);
428 migrate_decompress_threads_create();
429 qemu_set_nonblock(fd
);
430 qemu_coroutine_enter(co
, f
);
434 * Send a message on the return channel back to the source
437 void migrate_send_rp_message(MigrationIncomingState
*mis
,
438 enum mig_rp_message_type message_type
,
439 uint16_t len
, void *data
)
441 trace_migrate_send_rp_message((int)message_type
, len
);
442 qemu_mutex_lock(&mis
->rp_mutex
);
443 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
444 qemu_put_be16(mis
->to_src_file
, len
);
445 qemu_put_buffer(mis
->to_src_file
, data
, len
);
446 qemu_fflush(mis
->to_src_file
);
447 qemu_mutex_unlock(&mis
->rp_mutex
);
451 * Send a 'SHUT' message on the return channel with the given value
452 * to indicate that we've finished with the RP. Non-0 value indicates
455 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
460 buf
= cpu_to_be32(value
);
461 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
465 * Send a 'PONG' message on the return channel with the given value
466 * (normally in response to a 'PING')
468 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
473 buf
= cpu_to_be32(value
);
474 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
477 /* amount of nanoseconds we are willing to wait for migration to be down.
478 * the choice of nanoseconds is because it is the maximum resolution that
479 * get_clock() can achieve. It is an internal measure. All user-visible
480 * units must be in seconds */
481 static uint64_t max_downtime
= 300000000;
483 uint64_t migrate_max_downtime(void)
488 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
490 MigrationCapabilityStatusList
*head
= NULL
;
491 MigrationCapabilityStatusList
*caps
;
492 MigrationState
*s
= migrate_get_current();
495 caps
= NULL
; /* silence compiler warning */
496 for (i
= 0; i
< MIGRATION_CAPABILITY__MAX
; i
++) {
498 head
= g_malloc0(sizeof(*caps
));
501 caps
->next
= g_malloc0(sizeof(*caps
));
505 g_malloc(sizeof(*caps
->value
));
506 caps
->value
->capability
= i
;
507 caps
->value
->state
= s
->enabled_capabilities
[i
];
513 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
515 MigrationParameters
*params
;
516 MigrationState
*s
= migrate_get_current();
518 params
= g_malloc0(sizeof(*params
));
519 params
->compress_level
= s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
];
520 params
->compress_threads
=
521 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
];
522 params
->decompress_threads
=
523 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
];
524 params
->cpu_throttle_initial
=
525 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL
];
526 params
->cpu_throttle_increment
=
527 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT
];
533 * Return true if we're already in the middle of a migration
534 * (i.e. any of the active or setup states)
536 static bool migration_is_setup_or_active(int state
)
539 case MIGRATION_STATUS_ACTIVE
:
540 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
541 case MIGRATION_STATUS_SETUP
:
550 static void get_xbzrle_cache_stats(MigrationInfo
*info
)
552 if (migrate_use_xbzrle()) {
553 info
->has_xbzrle_cache
= true;
554 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
555 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
556 info
->xbzrle_cache
->bytes
= xbzrle_mig_bytes_transferred();
557 info
->xbzrle_cache
->pages
= xbzrle_mig_pages_transferred();
558 info
->xbzrle_cache
->cache_miss
= xbzrle_mig_pages_cache_miss();
559 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_mig_cache_miss_rate();
560 info
->xbzrle_cache
->overflow
= xbzrle_mig_pages_overflow();
564 MigrationInfo
*qmp_query_migrate(Error
**errp
)
566 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
567 MigrationState
*s
= migrate_get_current();
570 case MIGRATION_STATUS_NONE
:
571 /* no migration has happened ever */
573 case MIGRATION_STATUS_SETUP
:
574 info
->has_status
= true;
575 info
->has_total_time
= false;
577 case MIGRATION_STATUS_ACTIVE
:
578 case MIGRATION_STATUS_CANCELLING
:
579 info
->has_status
= true;
580 info
->has_total_time
= true;
581 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
583 info
->has_expected_downtime
= true;
584 info
->expected_downtime
= s
->expected_downtime
;
585 info
->has_setup_time
= true;
586 info
->setup_time
= s
->setup_time
;
588 info
->has_ram
= true;
589 info
->ram
= g_malloc0(sizeof(*info
->ram
));
590 info
->ram
->transferred
= ram_bytes_transferred();
591 info
->ram
->remaining
= ram_bytes_remaining();
592 info
->ram
->total
= ram_bytes_total();
593 info
->ram
->duplicate
= dup_mig_pages_transferred();
594 info
->ram
->skipped
= skipped_mig_pages_transferred();
595 info
->ram
->normal
= norm_mig_pages_transferred();
596 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
597 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
598 info
->ram
->mbps
= s
->mbps
;
599 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
601 if (blk_mig_active()) {
602 info
->has_disk
= true;
603 info
->disk
= g_malloc0(sizeof(*info
->disk
));
604 info
->disk
->transferred
= blk_mig_bytes_transferred();
605 info
->disk
->remaining
= blk_mig_bytes_remaining();
606 info
->disk
->total
= blk_mig_bytes_total();
609 if (cpu_throttle_active()) {
610 info
->has_cpu_throttle_percentage
= true;
611 info
->cpu_throttle_percentage
= cpu_throttle_get_percentage();
614 get_xbzrle_cache_stats(info
);
616 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
617 /* Mostly the same as active; TODO add some postcopy stats */
618 info
->has_status
= true;
619 info
->has_total_time
= true;
620 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
622 info
->has_expected_downtime
= true;
623 info
->expected_downtime
= s
->expected_downtime
;
624 info
->has_setup_time
= true;
625 info
->setup_time
= s
->setup_time
;
627 info
->has_ram
= true;
628 info
->ram
= g_malloc0(sizeof(*info
->ram
));
629 info
->ram
->transferred
= ram_bytes_transferred();
630 info
->ram
->remaining
= ram_bytes_remaining();
631 info
->ram
->total
= ram_bytes_total();
632 info
->ram
->duplicate
= dup_mig_pages_transferred();
633 info
->ram
->skipped
= skipped_mig_pages_transferred();
634 info
->ram
->normal
= norm_mig_pages_transferred();
635 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
636 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
637 info
->ram
->mbps
= s
->mbps
;
638 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
640 if (blk_mig_active()) {
641 info
->has_disk
= true;
642 info
->disk
= g_malloc0(sizeof(*info
->disk
));
643 info
->disk
->transferred
= blk_mig_bytes_transferred();
644 info
->disk
->remaining
= blk_mig_bytes_remaining();
645 info
->disk
->total
= blk_mig_bytes_total();
648 get_xbzrle_cache_stats(info
);
650 case MIGRATION_STATUS_COMPLETED
:
651 get_xbzrle_cache_stats(info
);
653 info
->has_status
= true;
654 info
->has_total_time
= true;
655 info
->total_time
= s
->total_time
;
656 info
->has_downtime
= true;
657 info
->downtime
= s
->downtime
;
658 info
->has_setup_time
= true;
659 info
->setup_time
= s
->setup_time
;
661 info
->has_ram
= true;
662 info
->ram
= g_malloc0(sizeof(*info
->ram
));
663 info
->ram
->transferred
= ram_bytes_transferred();
664 info
->ram
->remaining
= 0;
665 info
->ram
->total
= ram_bytes_total();
666 info
->ram
->duplicate
= dup_mig_pages_transferred();
667 info
->ram
->skipped
= skipped_mig_pages_transferred();
668 info
->ram
->normal
= norm_mig_pages_transferred();
669 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
670 info
->ram
->mbps
= s
->mbps
;
671 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
673 case MIGRATION_STATUS_FAILED
:
674 info
->has_status
= true;
676 case MIGRATION_STATUS_CANCELLED
:
677 info
->has_status
= true;
680 info
->status
= s
->state
;
685 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
688 MigrationState
*s
= migrate_get_current();
689 MigrationCapabilityStatusList
*cap
;
691 if (migration_is_setup_or_active(s
->state
)) {
692 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
696 for (cap
= params
; cap
; cap
= cap
->next
) {
697 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
700 if (migrate_postcopy_ram()) {
701 if (migrate_use_compression()) {
702 /* The decompression threads asynchronously write into RAM
703 * rather than use the atomic copies needed to avoid
704 * userfaulting. It should be possible to fix the decompression
705 * threads for compatibility in future.
707 error_report("Postcopy is not currently compatible with "
709 s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
] =
715 void qmp_migrate_set_parameters(bool has_compress_level
,
716 int64_t compress_level
,
717 bool has_compress_threads
,
718 int64_t compress_threads
,
719 bool has_decompress_threads
,
720 int64_t decompress_threads
,
721 bool has_cpu_throttle_initial
,
722 int64_t cpu_throttle_initial
,
723 bool has_cpu_throttle_increment
,
724 int64_t cpu_throttle_increment
, Error
**errp
)
726 MigrationState
*s
= migrate_get_current();
728 if (has_compress_level
&& (compress_level
< 0 || compress_level
> 9)) {
729 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
730 "is invalid, it should be in the range of 0 to 9");
733 if (has_compress_threads
&&
734 (compress_threads
< 1 || compress_threads
> 255)) {
735 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
737 "is invalid, it should be in the range of 1 to 255");
740 if (has_decompress_threads
&&
741 (decompress_threads
< 1 || decompress_threads
> 255)) {
742 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
743 "decompress_threads",
744 "is invalid, it should be in the range of 1 to 255");
747 if (has_cpu_throttle_initial
&&
748 (cpu_throttle_initial
< 1 || cpu_throttle_initial
> 99)) {
749 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
750 "cpu_throttle_initial",
751 "an integer in the range of 1 to 99");
753 if (has_cpu_throttle_increment
&&
754 (cpu_throttle_increment
< 1 || cpu_throttle_increment
> 99)) {
755 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
756 "cpu_throttle_increment",
757 "an integer in the range of 1 to 99");
760 if (has_compress_level
) {
761 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
] = compress_level
;
763 if (has_compress_threads
) {
764 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
] = compress_threads
;
766 if (has_decompress_threads
) {
767 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
] =
770 if (has_cpu_throttle_initial
) {
771 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL
] =
772 cpu_throttle_initial
;
775 if (has_cpu_throttle_increment
) {
776 s
->parameters
[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT
] =
777 cpu_throttle_increment
;
781 void qmp_migrate_start_postcopy(Error
**errp
)
783 MigrationState
*s
= migrate_get_current();
785 if (!migrate_postcopy_ram()) {
786 error_setg(errp
, "Enable postcopy with migrate_set_capability before"
787 " the start of migration");
791 if (s
->state
== MIGRATION_STATUS_NONE
) {
792 error_setg(errp
, "Postcopy must be started after migration has been"
797 * we don't error if migration has finished since that would be racy
798 * with issuing this command.
800 atomic_set(&s
->start_postcopy
, true);
803 /* shared migration helpers */
805 void migrate_set_state(int *state
, int old_state
, int new_state
)
807 if (atomic_cmpxchg(state
, old_state
, new_state
) == old_state
) {
808 trace_migrate_set_state(new_state
);
809 migrate_generate_event(new_state
);
813 static void migrate_fd_cleanup(void *opaque
)
815 MigrationState
*s
= opaque
;
817 qemu_bh_delete(s
->cleanup_bh
);
818 s
->cleanup_bh
= NULL
;
822 if (s
->to_dst_file
) {
823 trace_migrate_fd_cleanup();
824 qemu_mutex_unlock_iothread();
825 if (s
->migration_thread_running
) {
826 qemu_thread_join(&s
->thread
);
827 s
->migration_thread_running
= false;
829 qemu_mutex_lock_iothread();
831 migrate_compress_threads_join();
832 qemu_fclose(s
->to_dst_file
);
833 s
->to_dst_file
= NULL
;
836 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
837 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
839 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
840 migrate_set_state(&s
->state
, MIGRATION_STATUS_CANCELLING
,
841 MIGRATION_STATUS_CANCELLED
);
844 notifier_list_notify(&migration_state_notifiers
, s
);
847 void migrate_fd_error(MigrationState
*s
)
849 trace_migrate_fd_error();
850 assert(s
->to_dst_file
== NULL
);
851 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
852 MIGRATION_STATUS_FAILED
);
853 notifier_list_notify(&migration_state_notifiers
, s
);
856 static void migrate_fd_cancel(MigrationState
*s
)
859 QEMUFile
*f
= migrate_get_current()->to_dst_file
;
860 trace_migrate_fd_cancel();
862 if (s
->rp_state
.from_dst_file
) {
863 /* shutdown the rp socket, so causing the rp thread to shutdown */
864 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
868 old_state
= s
->state
;
869 if (!migration_is_setup_or_active(old_state
)) {
872 migrate_set_state(&s
->state
, old_state
, MIGRATION_STATUS_CANCELLING
);
873 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
876 * If we're unlucky the migration code might be stuck somewhere in a
877 * send/write while the network has failed and is waiting to timeout;
878 * if we've got shutdown(2) available then we can force it to quit.
879 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
880 * called in a bh, so there is no race against this cancel.
882 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
883 qemu_file_shutdown(f
);
887 void add_migration_state_change_notifier(Notifier
*notify
)
889 notifier_list_add(&migration_state_notifiers
, notify
);
892 void remove_migration_state_change_notifier(Notifier
*notify
)
894 notifier_remove(notify
);
897 bool migration_in_setup(MigrationState
*s
)
899 return s
->state
== MIGRATION_STATUS_SETUP
;
902 bool migration_has_finished(MigrationState
*s
)
904 return s
->state
== MIGRATION_STATUS_COMPLETED
;
907 bool migration_has_failed(MigrationState
*s
)
909 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
910 s
->state
== MIGRATION_STATUS_FAILED
);
913 bool migration_in_postcopy(MigrationState
*s
)
915 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
918 bool migration_in_postcopy_after_devices(MigrationState
*s
)
920 return migration_in_postcopy(s
) && s
->postcopy_after_devices
;
923 MigrationState
*migrate_init(const MigrationParams
*params
)
925 MigrationState
*s
= migrate_get_current();
928 * Reinitialise all migration state, except
929 * parameters/capabilities that the user set, and
935 s
->to_dst_file
= NULL
;
936 s
->state
= MIGRATION_STATUS_NONE
;
938 s
->rp_state
.from_dst_file
= NULL
;
939 s
->rp_state
.error
= false;
942 s
->expected_downtime
= 0;
943 s
->dirty_pages_rate
= 0;
944 s
->dirty_bytes_rate
= 0;
946 s
->dirty_sync_count
= 0;
947 s
->start_postcopy
= false;
948 s
->postcopy_after_devices
= false;
949 s
->migration_thread_running
= false;
950 s
->last_req_rb
= NULL
;
952 migrate_set_state(&s
->state
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
954 QSIMPLEQ_INIT(&s
->src_page_requests
);
956 s
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
960 static GSList
*migration_blockers
;
962 void migrate_add_blocker(Error
*reason
)
964 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
967 void migrate_del_blocker(Error
*reason
)
969 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
972 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
974 Error
*local_err
= NULL
;
975 static bool once
= true;
977 if (!deferred_incoming
) {
978 error_setg(errp
, "For use with '-incoming defer'");
982 error_setg(errp
, "The incoming migration has already been started");
985 qemu_start_incoming_migration(uri
, &local_err
);
988 error_propagate(errp
, local_err
);
995 bool migration_is_blocked(Error
**errp
)
997 if (qemu_savevm_state_blocked(errp
)) {
1001 if (migration_blockers
) {
1002 *errp
= error_copy(migration_blockers
->data
);
1009 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
1010 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
1013 Error
*local_err
= NULL
;
1014 MigrationState
*s
= migrate_get_current();
1015 MigrationParams params
;
1018 params
.blk
= has_blk
&& blk
;
1019 params
.shared
= has_inc
&& inc
;
1021 if (migration_is_setup_or_active(s
->state
) ||
1022 s
->state
== MIGRATION_STATUS_CANCELLING
) {
1023 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
1026 if (runstate_check(RUN_STATE_INMIGRATE
)) {
1027 error_setg(errp
, "Guest is waiting for an incoming migration");
1031 if (migration_is_blocked(errp
)) {
1035 s
= migrate_init(¶ms
);
1037 if (strstart(uri
, "tcp:", &p
)) {
1038 tcp_start_outgoing_migration(s
, p
, &local_err
);
1040 } else if (strstart(uri
, "rdma:", &p
)) {
1041 rdma_start_outgoing_migration(s
, p
, &local_err
);
1044 } else if (strstart(uri
, "exec:", &p
)) {
1045 exec_start_outgoing_migration(s
, p
, &local_err
);
1046 } else if (strstart(uri
, "unix:", &p
)) {
1047 unix_start_outgoing_migration(s
, p
, &local_err
);
1048 } else if (strstart(uri
, "fd:", &p
)) {
1049 fd_start_outgoing_migration(s
, p
, &local_err
);
1052 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1053 "a valid migration protocol");
1054 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1055 MIGRATION_STATUS_FAILED
);
1060 migrate_fd_error(s
);
1061 error_propagate(errp
, local_err
);
1066 void qmp_migrate_cancel(Error
**errp
)
1068 migrate_fd_cancel(migrate_get_current());
1071 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1073 MigrationState
*s
= migrate_get_current();
1076 /* Check for truncation */
1077 if (value
!= (size_t)value
) {
1078 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1079 "exceeding address space");
1083 /* Cache should not be larger than guest ram size */
1084 if (value
> ram_bytes_total()) {
1085 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1086 "exceeds guest ram size ");
1090 new_size
= xbzrle_cache_resize(value
);
1092 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1093 "is smaller than page size");
1097 s
->xbzrle_cache_size
= new_size
;
1100 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1102 return migrate_xbzrle_cache_size();
1105 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1112 if (value
> SIZE_MAX
) {
1116 s
= migrate_get_current();
1117 s
->bandwidth_limit
= value
;
1118 if (s
->to_dst_file
) {
1119 qemu_file_set_rate_limit(s
->to_dst_file
,
1120 s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1124 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1127 value
= MAX(0, MIN(UINT64_MAX
, value
));
1128 max_downtime
= (uint64_t)value
;
1131 bool migrate_postcopy_ram(void)
1135 s
= migrate_get_current();
1137 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_POSTCOPY_RAM
];
1140 bool migrate_auto_converge(void)
1144 s
= migrate_get_current();
1146 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1149 bool migrate_zero_blocks(void)
1153 s
= migrate_get_current();
1155 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1158 bool migrate_use_compression(void)
1162 s
= migrate_get_current();
1164 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1167 int migrate_compress_level(void)
1171 s
= migrate_get_current();
1173 return s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
];
1176 int migrate_compress_threads(void)
1180 s
= migrate_get_current();
1182 return s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
];
1185 int migrate_decompress_threads(void)
1189 s
= migrate_get_current();
1191 return s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
];
1194 bool migrate_use_events(void)
1198 s
= migrate_get_current();
1200 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1203 int migrate_use_xbzrle(void)
1207 s
= migrate_get_current();
1209 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1212 int64_t migrate_xbzrle_cache_size(void)
1216 s
= migrate_get_current();
1218 return s
->xbzrle_cache_size
;
1221 /* migration thread support */
1223 * Something bad happened to the RP stream, mark an error
1224 * The caller shall print or trace something to indicate why
1226 static void mark_source_rp_bad(MigrationState
*s
)
1228 s
->rp_state
.error
= true;
1231 static struct rp_cmd_args
{
1232 ssize_t len
; /* -1 = variable */
1235 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1236 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1237 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1238 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1239 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1240 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1244 * Process a request for pages received on the return path,
1245 * We're allowed to send more than requested (e.g. to round to our page size)
1246 * and we don't need to send pages that have already been sent.
1248 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1249 ram_addr_t start
, size_t len
)
1251 long our_host_ps
= getpagesize();
1253 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1256 * Since we currently insist on matching page sizes, just sanity check
1257 * we're being asked for whole host pages.
1259 if (start
& (our_host_ps
-1) ||
1260 (len
& (our_host_ps
-1))) {
1261 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1262 " len: %zd", __func__
, start
, len
);
1263 mark_source_rp_bad(ms
);
1267 if (ram_save_queue_pages(ms
, rbname
, start
, len
)) {
1268 mark_source_rp_bad(ms
);
1273 * Handles messages sent on the return path towards the source VM
1276 static void *source_return_path_thread(void *opaque
)
1278 MigrationState
*ms
= opaque
;
1279 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1280 uint16_t header_len
, header_type
;
1282 uint32_t tmp32
, sibling_error
;
1283 ram_addr_t start
= 0; /* =0 to silence warning */
1284 size_t len
= 0, expected_len
;
1287 trace_source_return_path_thread_entry();
1288 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1289 migration_is_setup_or_active(ms
->state
)) {
1290 trace_source_return_path_thread_loop_top();
1291 header_type
= qemu_get_be16(rp
);
1292 header_len
= qemu_get_be16(rp
);
1294 if (header_type
>= MIG_RP_MSG_MAX
||
1295 header_type
== MIG_RP_MSG_INVALID
) {
1296 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1297 header_type
, header_len
);
1298 mark_source_rp_bad(ms
);
1302 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1303 header_len
!= rp_cmd_args
[header_type
].len
) ||
1304 header_len
> sizeof(buf
)) {
1305 error_report("RP: Received '%s' message (0x%04x) with"
1306 "incorrect length %d expecting %zu",
1307 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1308 (size_t)rp_cmd_args
[header_type
].len
);
1309 mark_source_rp_bad(ms
);
1313 /* We know we've got a valid header by this point */
1314 res
= qemu_get_buffer(rp
, buf
, header_len
);
1315 if (res
!= header_len
) {
1316 error_report("RP: Failed reading data for message 0x%04x"
1317 " read %d expected %d",
1318 header_type
, res
, header_len
);
1319 mark_source_rp_bad(ms
);
1323 /* OK, we have the message and the data */
1324 switch (header_type
) {
1325 case MIG_RP_MSG_SHUT
:
1326 sibling_error
= be32_to_cpup((uint32_t *)buf
);
1327 trace_source_return_path_thread_shut(sibling_error
);
1328 if (sibling_error
) {
1329 error_report("RP: Sibling indicated error %d", sibling_error
);
1330 mark_source_rp_bad(ms
);
1333 * We'll let the main thread deal with closing the RP
1334 * we could do a shutdown(2) on it, but we're the only user
1335 * anyway, so there's nothing gained.
1339 case MIG_RP_MSG_PONG
:
1340 tmp32
= be32_to_cpup((uint32_t *)buf
);
1341 trace_source_return_path_thread_pong(tmp32
);
1344 case MIG_RP_MSG_REQ_PAGES
:
1345 start
= be64_to_cpup((uint64_t *)buf
);
1346 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1347 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1350 case MIG_RP_MSG_REQ_PAGES_ID
:
1351 expected_len
= 12 + 1; /* header + termination */
1353 if (header_len
>= expected_len
) {
1354 start
= be64_to_cpup((uint64_t *)buf
);
1355 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1356 /* Now we expect an idstr */
1357 tmp32
= buf
[12]; /* Length of the following idstr */
1358 buf
[13 + tmp32
] = '\0';
1359 expected_len
+= tmp32
;
1361 if (header_len
!= expected_len
) {
1362 error_report("RP: Req_Page_id with length %d expecting %zd",
1363 header_len
, expected_len
);
1364 mark_source_rp_bad(ms
);
1367 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1374 if (qemu_file_get_error(rp
)) {
1375 trace_source_return_path_thread_bad_end();
1376 mark_source_rp_bad(ms
);
1379 trace_source_return_path_thread_end();
1381 ms
->rp_state
.from_dst_file
= NULL
;
1386 static int open_return_path_on_source(MigrationState
*ms
)
1389 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->to_dst_file
);
1390 if (!ms
->rp_state
.from_dst_file
) {
1394 trace_open_return_path_on_source();
1395 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
1396 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
1398 trace_open_return_path_on_source_continue();
1403 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1404 static int await_return_path_close_on_source(MigrationState
*ms
)
1407 * If this is a normal exit then the destination will send a SHUT and the
1408 * rp_thread will exit, however if there's an error we need to cause
1411 if (qemu_file_get_error(ms
->to_dst_file
) && ms
->rp_state
.from_dst_file
) {
1413 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1414 * waiting for the destination.
1416 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
1417 mark_source_rp_bad(ms
);
1419 trace_await_return_path_close_on_source_joining();
1420 qemu_thread_join(&ms
->rp_state
.rp_thread
);
1421 trace_await_return_path_close_on_source_close();
1422 return ms
->rp_state
.error
;
1426 * Switch from normal iteration to postcopy
1427 * Returns non-0 on error
1429 static int postcopy_start(MigrationState
*ms
, bool *old_vm_running
)
1432 const QEMUSizedBuffer
*qsb
;
1433 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1434 migrate_set_state(&ms
->state
, MIGRATION_STATUS_ACTIVE
,
1435 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1437 trace_postcopy_start();
1438 qemu_mutex_lock_iothread();
1439 trace_postcopy_start_set_run();
1441 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1442 *old_vm_running
= runstate_is_running();
1443 global_state_store();
1444 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1449 ret
= bdrv_inactivate_all();
1455 * Cause any non-postcopiable, but iterative devices to
1456 * send out their final data.
1458 qemu_savevm_state_complete_precopy(ms
->to_dst_file
, true);
1461 * in Finish migrate and with the io-lock held everything should
1462 * be quiet, but we've potentially still got dirty pages and we
1463 * need to tell the destination to throw any pages it's already received
1466 if (ram_postcopy_send_discard_bitmap(ms
)) {
1467 error_report("postcopy send discard bitmap failed");
1472 * send rest of state - note things that are doing postcopy
1473 * will notice we're in POSTCOPY_ACTIVE and not actually
1474 * wrap their state up here
1476 qemu_file_set_rate_limit(ms
->to_dst_file
, INT64_MAX
);
1477 /* Ping just for debugging, helps line traces up */
1478 qemu_savevm_send_ping(ms
->to_dst_file
, 2);
1481 * While loading the device state we may trigger page transfer
1482 * requests and the fd must be free to process those, and thus
1483 * the destination must read the whole device state off the fd before
1484 * it starts processing it. Unfortunately the ad-hoc migration format
1485 * doesn't allow the destination to know the size to read without fully
1486 * parsing it through each devices load-state code (especially the open
1487 * coded devices that use get/put).
1488 * So we wrap the device state up in a package with a length at the start;
1489 * to do this we use a qemu_buf to hold the whole of the device state.
1491 QEMUFile
*fb
= qemu_bufopen("w", NULL
);
1493 error_report("Failed to create buffered file");
1498 * Make sure the receiver can get incoming pages before we send the rest
1501 qemu_savevm_send_postcopy_listen(fb
);
1503 qemu_savevm_state_complete_precopy(fb
, false);
1504 qemu_savevm_send_ping(fb
, 3);
1506 qemu_savevm_send_postcopy_run(fb
);
1508 /* <><> end of stuff going into the package */
1509 qsb
= qemu_buf_get(fb
);
1511 /* Now send that blob */
1512 if (qemu_savevm_send_packaged(ms
->to_dst_file
, qsb
)) {
1517 /* Send a notify to give a chance for anything that needs to happen
1518 * at the transition to postcopy and after the device state; in particular
1519 * spice needs to trigger a transition now
1521 ms
->postcopy_after_devices
= true;
1522 notifier_list_notify(&migration_state_notifiers
, ms
);
1524 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
1526 qemu_mutex_unlock_iothread();
1529 * Although this ping is just for debug, it could potentially be
1530 * used for getting a better measurement of downtime at the source.
1532 qemu_savevm_send_ping(ms
->to_dst_file
, 4);
1534 ret
= qemu_file_get_error(ms
->to_dst_file
);
1536 error_report("postcopy_start: Migration stream errored");
1537 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1538 MIGRATION_STATUS_FAILED
);
1546 migrate_set_state(&ms
->state
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1547 MIGRATION_STATUS_FAILED
);
1548 qemu_mutex_unlock_iothread();
1553 * migration_completion: Used by migration_thread when there's not much left.
1554 * The caller 'breaks' the loop when this returns.
1556 * @s: Current migration state
1557 * @current_active_state: The migration state we expect to be in
1558 * @*old_vm_running: Pointer to old_vm_running flag
1559 * @*start_time: Pointer to time to update
1561 static void migration_completion(MigrationState
*s
, int current_active_state
,
1562 bool *old_vm_running
,
1563 int64_t *start_time
)
1567 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1568 qemu_mutex_lock_iothread();
1569 *start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1570 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1571 *old_vm_running
= runstate_is_running();
1572 ret
= global_state_store();
1575 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1577 ret
= bdrv_inactivate_all();
1580 qemu_file_set_rate_limit(s
->to_dst_file
, INT64_MAX
);
1581 qemu_savevm_state_complete_precopy(s
->to_dst_file
, false);
1584 qemu_mutex_unlock_iothread();
1589 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1590 trace_migration_completion_postcopy_end();
1592 qemu_savevm_state_complete_postcopy(s
->to_dst_file
);
1593 trace_migration_completion_postcopy_end_after_complete();
1597 * If rp was opened we must clean up the thread before
1598 * cleaning everything else up (since if there are no failures
1599 * it will wait for the destination to send it's status in
1601 * Postcopy opens rp if enabled (even if it's not avtivated)
1603 if (migrate_postcopy_ram()) {
1605 trace_migration_completion_postcopy_end_before_rp();
1606 rp_error
= await_return_path_close_on_source(s
);
1607 trace_migration_completion_postcopy_end_after_rp(rp_error
);
1609 goto fail_invalidate
;
1613 if (qemu_file_get_error(s
->to_dst_file
)) {
1614 trace_migration_completion_file_err();
1615 goto fail_invalidate
;
1618 migrate_set_state(&s
->state
, current_active_state
,
1619 MIGRATION_STATUS_COMPLETED
);
1623 /* If not doing postcopy, vm_start() will be called: let's regain
1624 * control on images.
1626 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1627 Error
*local_err
= NULL
;
1629 bdrv_invalidate_cache_all(&local_err
);
1631 error_report_err(local_err
);
1636 migrate_set_state(&s
->state
, current_active_state
,
1637 MIGRATION_STATUS_FAILED
);
1641 * Master migration thread on the source VM.
1642 * It drives the migration and pumps the data down the outgoing channel.
1644 static void *migration_thread(void *opaque
)
1646 MigrationState
*s
= opaque
;
1647 /* Used by the bandwidth calcs, updated later */
1648 int64_t initial_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1649 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
1650 int64_t initial_bytes
= 0;
1651 int64_t max_size
= 0;
1652 int64_t start_time
= initial_time
;
1654 bool old_vm_running
= false;
1655 bool entered_postcopy
= false;
1656 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1657 enum MigrationStatus current_active_state
= MIGRATION_STATUS_ACTIVE
;
1659 rcu_register_thread();
1661 qemu_savevm_state_header(s
->to_dst_file
);
1663 if (migrate_postcopy_ram()) {
1664 /* Now tell the dest that it should open its end so it can reply */
1665 qemu_savevm_send_open_return_path(s
->to_dst_file
);
1667 /* And do a ping that will make stuff easier to debug */
1668 qemu_savevm_send_ping(s
->to_dst_file
, 1);
1671 * Tell the destination that we *might* want to do postcopy later;
1672 * if the other end can't do postcopy it should fail now, nice and
1675 qemu_savevm_send_postcopy_advise(s
->to_dst_file
);
1678 qemu_savevm_state_begin(s
->to_dst_file
, &s
->params
);
1680 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
1681 current_active_state
= MIGRATION_STATUS_ACTIVE
;
1682 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1683 MIGRATION_STATUS_ACTIVE
);
1685 trace_migration_thread_setup_complete();
1687 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
1688 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1689 int64_t current_time
;
1690 uint64_t pending_size
;
1692 if (!qemu_file_rate_limit(s
->to_dst_file
)) {
1693 uint64_t pend_post
, pend_nonpost
;
1695 qemu_savevm_state_pending(s
->to_dst_file
, max_size
, &pend_nonpost
,
1697 pending_size
= pend_nonpost
+ pend_post
;
1698 trace_migrate_pending(pending_size
, max_size
,
1699 pend_post
, pend_nonpost
);
1700 if (pending_size
&& pending_size
>= max_size
) {
1701 /* Still a significant amount to transfer */
1703 if (migrate_postcopy_ram() &&
1704 s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
&&
1705 pend_nonpost
<= max_size
&&
1706 atomic_read(&s
->start_postcopy
)) {
1708 if (!postcopy_start(s
, &old_vm_running
)) {
1709 current_active_state
= MIGRATION_STATUS_POSTCOPY_ACTIVE
;
1710 entered_postcopy
= true;
1715 /* Just another iteration step */
1716 qemu_savevm_state_iterate(s
->to_dst_file
, entered_postcopy
);
1718 trace_migration_thread_low_pending(pending_size
);
1719 migration_completion(s
, current_active_state
,
1720 &old_vm_running
, &start_time
);
1725 if (qemu_file_get_error(s
->to_dst_file
)) {
1726 migrate_set_state(&s
->state
, current_active_state
,
1727 MIGRATION_STATUS_FAILED
);
1728 trace_migration_thread_file_err();
1731 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1732 if (current_time
>= initial_time
+ BUFFER_DELAY
) {
1733 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
) -
1735 uint64_t time_spent
= current_time
- initial_time
;
1736 double bandwidth
= (double)transferred_bytes
/ time_spent
;
1737 max_size
= bandwidth
* migrate_max_downtime() / 1000000;
1739 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1740 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0;
1742 trace_migrate_transferred(transferred_bytes
, time_spent
,
1743 bandwidth
, max_size
);
1744 /* if we haven't sent anything, we don't want to recalculate
1745 10000 is a small enough number for our purposes */
1746 if (s
->dirty_bytes_rate
&& transferred_bytes
> 10000) {
1747 s
->expected_downtime
= s
->dirty_bytes_rate
/ bandwidth
;
1750 qemu_file_reset_rate_limit(s
->to_dst_file
);
1751 initial_time
= current_time
;
1752 initial_bytes
= qemu_ftell(s
->to_dst_file
);
1754 if (qemu_file_rate_limit(s
->to_dst_file
)) {
1755 /* usleep expects microseconds */
1756 g_usleep((initial_time
+ BUFFER_DELAY
- current_time
)*1000);
1760 trace_migration_thread_after_loop();
1761 /* If we enabled cpu throttling for auto-converge, turn it off. */
1762 cpu_throttle_stop();
1763 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1765 qemu_mutex_lock_iothread();
1766 qemu_savevm_state_cleanup();
1767 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1768 uint64_t transferred_bytes
= qemu_ftell(s
->to_dst_file
);
1769 s
->total_time
= end_time
- s
->total_time
;
1770 if (!entered_postcopy
) {
1771 s
->downtime
= end_time
- start_time
;
1773 if (s
->total_time
) {
1774 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1775 ((double) s
->total_time
)) / 1000;
1777 runstate_set(RUN_STATE_POSTMIGRATE
);
1779 if (old_vm_running
&& !entered_postcopy
) {
1783 qemu_bh_schedule(s
->cleanup_bh
);
1784 qemu_mutex_unlock_iothread();
1786 rcu_unregister_thread();
1790 void migrate_fd_connect(MigrationState
*s
)
1792 /* This is a best 1st approximation. ns to ms */
1793 s
->expected_downtime
= max_downtime
/1000000;
1794 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
1796 qemu_file_set_rate_limit(s
->to_dst_file
,
1797 s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1799 /* Notify before starting migration thread */
1800 notifier_list_notify(&migration_state_notifiers
, s
);
1803 * Open the return path; currently for postcopy but other things might
1806 if (migrate_postcopy_ram()) {
1807 if (open_return_path_on_source(s
)) {
1808 error_report("Unable to open return-path for postcopy");
1809 migrate_set_state(&s
->state
, MIGRATION_STATUS_SETUP
,
1810 MIGRATION_STATUS_FAILED
);
1811 migrate_fd_cleanup(s
);
1816 migrate_compress_threads_create();
1817 qemu_thread_create(&s
->thread
, "migration", migration_thread
, s
,
1818 QEMU_THREAD_JOINABLE
);
1819 s
->migration_thread_running
= true;
1822 PostcopyState
postcopy_state_get(void)
1824 return atomic_mb_read(&incoming_postcopy_state
);
1827 /* Set the state and return the old state */
1828 PostcopyState
postcopy_state_set(PostcopyState new_state
)
1830 return atomic_xchg(&incoming_postcopy_state
, new_state
);