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-common.h"
17 #include "qemu/error-report.h"
18 #include "qemu/main-loop.h"
19 #include "migration/migration.h"
20 #include "migration/qemu-file.h"
21 #include "sysemu/sysemu.h"
22 #include "block/block.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/sockets.h"
26 #include "migration/block.h"
27 #include "migration/postcopy-ram.h"
28 #include "qemu/thread.h"
29 #include "qmp-commands.h"
31 #include "qapi/util.h"
32 #include "qapi-event.h"
35 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
37 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
39 #define BUFFER_DELAY 100
40 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
42 /* Default compression thread count */
43 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
44 /* Default decompression thread count, usually decompression is at
45 * least 4 times as fast as compression.*/
46 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
47 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
48 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
49 /* Define default autoconverge cpu throttle migration parameters */
50 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL 20
51 #define DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT 10
53 /* Migration XBZRLE default cache size */
54 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
56 static NotifierList migration_state_notifiers
=
57 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers
);
59 static bool deferred_incoming
;
62 * Current state of incoming postcopy; note this is not part of
63 * MigrationIncomingState since it's state is used during cleanup
64 * at the end as MIS is being freed.
66 static PostcopyState incoming_postcopy_state
;
68 /* When we add fault tolerance, we could have several
69 migrations at once. For now we don't need to add
70 dynamic creation of migration */
73 MigrationState
*migrate_get_current(void)
75 static MigrationState current_migration
= {
76 .state
= MIGRATION_STATUS_NONE
,
77 .bandwidth_limit
= MAX_THROTTLE
,
78 .xbzrle_cache_size
= DEFAULT_MIGRATE_CACHE_SIZE
,
80 .parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
] =
81 DEFAULT_MIGRATE_COMPRESS_LEVEL
,
82 .parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
] =
83 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT
,
84 .parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
] =
85 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT
,
86 .parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL
] =
87 DEFAULT_MIGRATE_X_CPU_THROTTLE_INITIAL
,
88 .parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT
] =
89 DEFAULT_MIGRATE_X_CPU_THROTTLE_INCREMENT
,
92 return ¤t_migration
;
96 static MigrationIncomingState
*mis_current
;
98 MigrationIncomingState
*migration_incoming_get_current(void)
103 MigrationIncomingState
*migration_incoming_state_new(QEMUFile
* f
)
105 mis_current
= g_new0(MigrationIncomingState
, 1);
106 mis_current
->from_src_file
= f
;
107 QLIST_INIT(&mis_current
->loadvm_handlers
);
108 qemu_mutex_init(&mis_current
->rp_mutex
);
109 qemu_event_init(&mis_current
->main_thread_load_event
, false);
114 void migration_incoming_state_destroy(void)
116 qemu_event_destroy(&mis_current
->main_thread_load_event
);
117 loadvm_free_handlers(mis_current
);
126 uint8_t runstate
[100];
131 static GlobalState global_state
;
133 int global_state_store(void)
135 if (!runstate_store((char *)global_state
.runstate
,
136 sizeof(global_state
.runstate
))) {
137 error_report("runstate name too big: %s", global_state
.runstate
);
138 trace_migrate_state_too_big();
144 void global_state_store_running(void)
146 const char *state
= RunState_lookup
[RUN_STATE_RUNNING
];
147 strncpy((char *)global_state
.runstate
,
148 state
, sizeof(global_state
.runstate
));
151 static bool global_state_received(void)
153 return global_state
.received
;
156 static RunState
global_state_get_runstate(void)
158 return global_state
.state
;
161 void global_state_set_optional(void)
163 global_state
.optional
= true;
166 static bool global_state_needed(void *opaque
)
168 GlobalState
*s
= opaque
;
169 char *runstate
= (char *)s
->runstate
;
171 /* If it is not optional, it is mandatory */
173 if (s
->optional
== false) {
177 /* If state is running or paused, it is not needed */
179 if (strcmp(runstate
, "running") == 0 ||
180 strcmp(runstate
, "paused") == 0) {
184 /* for any other state it is needed */
188 static int global_state_post_load(void *opaque
, int version_id
)
190 GlobalState
*s
= opaque
;
191 Error
*local_err
= NULL
;
193 char *runstate
= (char *)s
->runstate
;
196 trace_migrate_global_state_post_load(runstate
);
198 r
= qapi_enum_parse(RunState_lookup
, runstate
, RUN_STATE_MAX
,
203 error_report_err(local_err
);
212 static void global_state_pre_save(void *opaque
)
214 GlobalState
*s
= opaque
;
216 trace_migrate_global_state_pre_save((char *)s
->runstate
);
217 s
->size
= strlen((char *)s
->runstate
) + 1;
220 static const VMStateDescription vmstate_globalstate
= {
221 .name
= "globalstate",
223 .minimum_version_id
= 1,
224 .post_load
= global_state_post_load
,
225 .pre_save
= global_state_pre_save
,
226 .needed
= global_state_needed
,
227 .fields
= (VMStateField
[]) {
228 VMSTATE_UINT32(size
, GlobalState
),
229 VMSTATE_BUFFER(runstate
, GlobalState
),
230 VMSTATE_END_OF_LIST()
234 void register_global_state(void)
236 /* We would use it independently that we receive it */
237 strcpy((char *)&global_state
.runstate
, "");
238 global_state
.received
= false;
239 vmstate_register(NULL
, 0, &vmstate_globalstate
, &global_state
);
242 static void migrate_generate_event(int new_state
)
244 if (migrate_use_events()) {
245 qapi_event_send_migration(new_state
, &error_abort
);
250 * Called on -incoming with a defer: uri.
251 * The migration can be started later after any parameters have been
254 static void deferred_incoming_migration(Error
**errp
)
256 if (deferred_incoming
) {
257 error_setg(errp
, "Incoming migration already deferred");
259 deferred_incoming
= true;
262 /* Request a range of pages from the source VM at the given
264 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
265 * as the last request (a name must have been given previously)
266 * Start: Address offset within the RB
267 * Len: Length in bytes required - must be a multiple of pagesize
269 void migrate_send_rp_req_pages(MigrationIncomingState
*mis
, const char *rbname
,
270 ram_addr_t start
, size_t len
)
272 uint8_t bufc
[12 + 1 + 255]; /* start (8), len (4), rbname upto 256 */
273 size_t msglen
= 12; /* start + len */
275 *(uint64_t *)bufc
= cpu_to_be64((uint64_t)start
);
276 *(uint32_t *)(bufc
+ 8) = cpu_to_be32((uint32_t)len
);
279 int rbname_len
= strlen(rbname
);
280 assert(rbname_len
< 256);
282 bufc
[msglen
++] = rbname_len
;
283 memcpy(bufc
+ msglen
, rbname
, rbname_len
);
284 msglen
+= rbname_len
;
285 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES_ID
, msglen
, bufc
);
287 migrate_send_rp_message(mis
, MIG_RP_MSG_REQ_PAGES
, msglen
, bufc
);
291 void qemu_start_incoming_migration(const char *uri
, Error
**errp
)
295 qapi_event_send_migration(MIGRATION_STATUS_SETUP
, &error_abort
);
296 if (!strcmp(uri
, "defer")) {
297 deferred_incoming_migration(errp
);
298 } else if (strstart(uri
, "tcp:", &p
)) {
299 tcp_start_incoming_migration(p
, errp
);
301 } else if (strstart(uri
, "rdma:", &p
)) {
302 rdma_start_incoming_migration(p
, errp
);
305 } else if (strstart(uri
, "exec:", &p
)) {
306 exec_start_incoming_migration(p
, errp
);
307 } else if (strstart(uri
, "unix:", &p
)) {
308 unix_start_incoming_migration(p
, errp
);
309 } else if (strstart(uri
, "fd:", &p
)) {
310 fd_start_incoming_migration(p
, errp
);
313 error_setg(errp
, "unknown migration protocol: %s", uri
);
317 static void process_incoming_migration_co(void *opaque
)
319 QEMUFile
*f
= opaque
;
320 Error
*local_err
= NULL
;
323 migration_incoming_state_new(f
);
324 postcopy_state_set(POSTCOPY_INCOMING_NONE
);
325 migrate_generate_event(MIGRATION_STATUS_ACTIVE
);
326 ret
= qemu_loadvm_state(f
);
329 free_xbzrle_decoded_buf();
330 migration_incoming_state_destroy();
333 migrate_generate_event(MIGRATION_STATUS_FAILED
);
334 error_report("load of migration failed: %s", strerror(-ret
));
335 migrate_decompress_threads_join();
339 /* Make sure all file formats flush their mutable metadata */
340 bdrv_invalidate_cache_all(&local_err
);
342 migrate_generate_event(MIGRATION_STATUS_FAILED
);
343 error_report_err(local_err
);
344 migrate_decompress_threads_join();
349 * This must happen after all error conditions are dealt with and
350 * we're sure the VM is going to be running on this host.
352 qemu_announce_self();
354 /* If global state section was not received or we are in running
355 state, we need to obey autostart. Any other state is set with
358 if (!global_state_received() ||
359 global_state_get_runstate() == RUN_STATE_RUNNING
) {
363 runstate_set(RUN_STATE_PAUSED
);
366 runstate_set(global_state_get_runstate());
368 migrate_decompress_threads_join();
370 * This must happen after any state changes since as soon as an external
371 * observer sees this event they might start to prod at the VM assuming
374 migrate_generate_event(MIGRATION_STATUS_COMPLETED
);
377 void process_incoming_migration(QEMUFile
*f
)
379 Coroutine
*co
= qemu_coroutine_create(process_incoming_migration_co
);
380 int fd
= qemu_get_fd(f
);
383 migrate_decompress_threads_create();
384 qemu_set_nonblock(fd
);
385 qemu_coroutine_enter(co
, f
);
389 * Send a message on the return channel back to the source
392 void migrate_send_rp_message(MigrationIncomingState
*mis
,
393 enum mig_rp_message_type message_type
,
394 uint16_t len
, void *data
)
396 trace_migrate_send_rp_message((int)message_type
, len
);
397 qemu_mutex_lock(&mis
->rp_mutex
);
398 qemu_put_be16(mis
->to_src_file
, (unsigned int)message_type
);
399 qemu_put_be16(mis
->to_src_file
, len
);
400 qemu_put_buffer(mis
->to_src_file
, data
, len
);
401 qemu_fflush(mis
->to_src_file
);
402 qemu_mutex_unlock(&mis
->rp_mutex
);
406 * Send a 'SHUT' message on the return channel with the given value
407 * to indicate that we've finished with the RP. Non-0 value indicates
410 void migrate_send_rp_shut(MigrationIncomingState
*mis
,
415 buf
= cpu_to_be32(value
);
416 migrate_send_rp_message(mis
, MIG_RP_MSG_SHUT
, sizeof(buf
), &buf
);
420 * Send a 'PONG' message on the return channel with the given value
421 * (normally in response to a 'PING')
423 void migrate_send_rp_pong(MigrationIncomingState
*mis
,
428 buf
= cpu_to_be32(value
);
429 migrate_send_rp_message(mis
, MIG_RP_MSG_PONG
, sizeof(buf
), &buf
);
432 /* amount of nanoseconds we are willing to wait for migration to be down.
433 * the choice of nanoseconds is because it is the maximum resolution that
434 * get_clock() can achieve. It is an internal measure. All user-visible
435 * units must be in seconds */
436 static uint64_t max_downtime
= 300000000;
438 uint64_t migrate_max_downtime(void)
443 MigrationCapabilityStatusList
*qmp_query_migrate_capabilities(Error
**errp
)
445 MigrationCapabilityStatusList
*head
= NULL
;
446 MigrationCapabilityStatusList
*caps
;
447 MigrationState
*s
= migrate_get_current();
450 caps
= NULL
; /* silence compiler warning */
451 for (i
= 0; i
< MIGRATION_CAPABILITY_MAX
; i
++) {
453 head
= g_malloc0(sizeof(*caps
));
456 caps
->next
= g_malloc0(sizeof(*caps
));
460 g_malloc(sizeof(*caps
->value
));
461 caps
->value
->capability
= i
;
462 caps
->value
->state
= s
->enabled_capabilities
[i
];
468 MigrationParameters
*qmp_query_migrate_parameters(Error
**errp
)
470 MigrationParameters
*params
;
471 MigrationState
*s
= migrate_get_current();
473 params
= g_malloc0(sizeof(*params
));
474 params
->compress_level
= s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
];
475 params
->compress_threads
=
476 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
];
477 params
->decompress_threads
=
478 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
];
479 params
->x_cpu_throttle_initial
=
480 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL
];
481 params
->x_cpu_throttle_increment
=
482 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT
];
488 * Return true if we're already in the middle of a migration
489 * (i.e. any of the active or setup states)
491 static bool migration_is_setup_or_active(int state
)
494 case MIGRATION_STATUS_ACTIVE
:
495 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
496 case MIGRATION_STATUS_SETUP
:
505 static void get_xbzrle_cache_stats(MigrationInfo
*info
)
507 if (migrate_use_xbzrle()) {
508 info
->has_xbzrle_cache
= true;
509 info
->xbzrle_cache
= g_malloc0(sizeof(*info
->xbzrle_cache
));
510 info
->xbzrle_cache
->cache_size
= migrate_xbzrle_cache_size();
511 info
->xbzrle_cache
->bytes
= xbzrle_mig_bytes_transferred();
512 info
->xbzrle_cache
->pages
= xbzrle_mig_pages_transferred();
513 info
->xbzrle_cache
->cache_miss
= xbzrle_mig_pages_cache_miss();
514 info
->xbzrle_cache
->cache_miss_rate
= xbzrle_mig_cache_miss_rate();
515 info
->xbzrle_cache
->overflow
= xbzrle_mig_pages_overflow();
519 MigrationInfo
*qmp_query_migrate(Error
**errp
)
521 MigrationInfo
*info
= g_malloc0(sizeof(*info
));
522 MigrationState
*s
= migrate_get_current();
525 case MIGRATION_STATUS_NONE
:
526 /* no migration has happened ever */
528 case MIGRATION_STATUS_SETUP
:
529 info
->has_status
= true;
530 info
->has_total_time
= false;
532 case MIGRATION_STATUS_ACTIVE
:
533 case MIGRATION_STATUS_CANCELLING
:
534 info
->has_status
= true;
535 info
->has_total_time
= true;
536 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
538 info
->has_expected_downtime
= true;
539 info
->expected_downtime
= s
->expected_downtime
;
540 info
->has_setup_time
= true;
541 info
->setup_time
= s
->setup_time
;
543 info
->has_ram
= true;
544 info
->ram
= g_malloc0(sizeof(*info
->ram
));
545 info
->ram
->transferred
= ram_bytes_transferred();
546 info
->ram
->remaining
= ram_bytes_remaining();
547 info
->ram
->total
= ram_bytes_total();
548 info
->ram
->duplicate
= dup_mig_pages_transferred();
549 info
->ram
->skipped
= skipped_mig_pages_transferred();
550 info
->ram
->normal
= norm_mig_pages_transferred();
551 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
552 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
553 info
->ram
->mbps
= s
->mbps
;
554 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
556 if (blk_mig_active()) {
557 info
->has_disk
= true;
558 info
->disk
= g_malloc0(sizeof(*info
->disk
));
559 info
->disk
->transferred
= blk_mig_bytes_transferred();
560 info
->disk
->remaining
= blk_mig_bytes_remaining();
561 info
->disk
->total
= blk_mig_bytes_total();
564 if (cpu_throttle_active()) {
565 info
->has_x_cpu_throttle_percentage
= true;
566 info
->x_cpu_throttle_percentage
= cpu_throttle_get_percentage();
569 get_xbzrle_cache_stats(info
);
571 case MIGRATION_STATUS_POSTCOPY_ACTIVE
:
572 /* Mostly the same as active; TODO add some postcopy stats */
573 info
->has_status
= true;
574 info
->has_total_time
= true;
575 info
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
)
577 info
->has_expected_downtime
= true;
578 info
->expected_downtime
= s
->expected_downtime
;
579 info
->has_setup_time
= true;
580 info
->setup_time
= s
->setup_time
;
582 info
->has_ram
= true;
583 info
->ram
= g_malloc0(sizeof(*info
->ram
));
584 info
->ram
->transferred
= ram_bytes_transferred();
585 info
->ram
->remaining
= ram_bytes_remaining();
586 info
->ram
->total
= ram_bytes_total();
587 info
->ram
->duplicate
= dup_mig_pages_transferred();
588 info
->ram
->skipped
= skipped_mig_pages_transferred();
589 info
->ram
->normal
= norm_mig_pages_transferred();
590 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
591 info
->ram
->dirty_pages_rate
= s
->dirty_pages_rate
;
592 info
->ram
->mbps
= s
->mbps
;
594 if (blk_mig_active()) {
595 info
->has_disk
= true;
596 info
->disk
= g_malloc0(sizeof(*info
->disk
));
597 info
->disk
->transferred
= blk_mig_bytes_transferred();
598 info
->disk
->remaining
= blk_mig_bytes_remaining();
599 info
->disk
->total
= blk_mig_bytes_total();
602 get_xbzrle_cache_stats(info
);
604 case MIGRATION_STATUS_COMPLETED
:
605 get_xbzrle_cache_stats(info
);
607 info
->has_status
= true;
608 info
->has_total_time
= true;
609 info
->total_time
= s
->total_time
;
610 info
->has_downtime
= true;
611 info
->downtime
= s
->downtime
;
612 info
->has_setup_time
= true;
613 info
->setup_time
= s
->setup_time
;
615 info
->has_ram
= true;
616 info
->ram
= g_malloc0(sizeof(*info
->ram
));
617 info
->ram
->transferred
= ram_bytes_transferred();
618 info
->ram
->remaining
= 0;
619 info
->ram
->total
= ram_bytes_total();
620 info
->ram
->duplicate
= dup_mig_pages_transferred();
621 info
->ram
->skipped
= skipped_mig_pages_transferred();
622 info
->ram
->normal
= norm_mig_pages_transferred();
623 info
->ram
->normal_bytes
= norm_mig_bytes_transferred();
624 info
->ram
->mbps
= s
->mbps
;
625 info
->ram
->dirty_sync_count
= s
->dirty_sync_count
;
627 case MIGRATION_STATUS_FAILED
:
628 info
->has_status
= true;
630 case MIGRATION_STATUS_CANCELLED
:
631 info
->has_status
= true;
634 info
->status
= s
->state
;
639 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList
*params
,
642 MigrationState
*s
= migrate_get_current();
643 MigrationCapabilityStatusList
*cap
;
645 if (migration_is_setup_or_active(s
->state
)) {
646 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
650 for (cap
= params
; cap
; cap
= cap
->next
) {
651 s
->enabled_capabilities
[cap
->value
->capability
] = cap
->value
->state
;
654 if (migrate_postcopy_ram()) {
655 if (migrate_use_compression()) {
656 /* The decompression threads asynchronously write into RAM
657 * rather than use the atomic copies needed to avoid
658 * userfaulting. It should be possible to fix the decompression
659 * threads for compatibility in future.
661 error_report("Postcopy is not currently compatible with "
663 s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_POSTCOPY_RAM
] =
669 void qmp_migrate_set_parameters(bool has_compress_level
,
670 int64_t compress_level
,
671 bool has_compress_threads
,
672 int64_t compress_threads
,
673 bool has_decompress_threads
,
674 int64_t decompress_threads
,
675 bool has_x_cpu_throttle_initial
,
676 int64_t x_cpu_throttle_initial
,
677 bool has_x_cpu_throttle_increment
,
678 int64_t x_cpu_throttle_increment
, Error
**errp
)
680 MigrationState
*s
= migrate_get_current();
682 if (has_compress_level
&& (compress_level
< 0 || compress_level
> 9)) {
683 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "compress_level",
684 "is invalid, it should be in the range of 0 to 9");
687 if (has_compress_threads
&&
688 (compress_threads
< 1 || compress_threads
> 255)) {
689 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
691 "is invalid, it should be in the range of 1 to 255");
694 if (has_decompress_threads
&&
695 (decompress_threads
< 1 || decompress_threads
> 255)) {
696 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
697 "decompress_threads",
698 "is invalid, it should be in the range of 1 to 255");
701 if (has_x_cpu_throttle_initial
&&
702 (x_cpu_throttle_initial
< 1 || x_cpu_throttle_initial
> 99)) {
703 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
704 "x_cpu_throttle_initial",
705 "an integer in the range of 1 to 99");
707 if (has_x_cpu_throttle_increment
&&
708 (x_cpu_throttle_increment
< 1 || x_cpu_throttle_increment
> 99)) {
709 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
,
710 "x_cpu_throttle_increment",
711 "an integer in the range of 1 to 99");
714 if (has_compress_level
) {
715 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
] = compress_level
;
717 if (has_compress_threads
) {
718 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
] = compress_threads
;
720 if (has_decompress_threads
) {
721 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
] =
724 if (has_x_cpu_throttle_initial
) {
725 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL
] =
726 x_cpu_throttle_initial
;
729 if (has_x_cpu_throttle_increment
) {
730 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT
] =
731 x_cpu_throttle_increment
;
735 void qmp_migrate_start_postcopy(Error
**errp
)
737 MigrationState
*s
= migrate_get_current();
739 if (!migrate_postcopy_ram()) {
740 error_setg(errp
, "Enable postcopy with migration_set_capability before"
741 " the start of migration");
745 if (s
->state
== MIGRATION_STATUS_NONE
) {
746 error_setg(errp
, "Postcopy must be started after migration has been"
751 * we don't error if migration has finished since that would be racy
752 * with issuing this command.
754 atomic_set(&s
->start_postcopy
, true);
757 /* shared migration helpers */
759 static void migrate_set_state(MigrationState
*s
, int old_state
, int new_state
)
761 if (atomic_cmpxchg(&s
->state
, old_state
, new_state
) == old_state
) {
762 trace_migrate_set_state(new_state
);
763 migrate_generate_event(new_state
);
767 static void migrate_fd_cleanup(void *opaque
)
769 MigrationState
*s
= opaque
;
771 qemu_bh_delete(s
->cleanup_bh
);
772 s
->cleanup_bh
= NULL
;
775 trace_migrate_fd_cleanup();
776 qemu_mutex_unlock_iothread();
777 if (s
->migration_thread_running
) {
778 qemu_thread_join(&s
->thread
);
779 s
->migration_thread_running
= false;
781 qemu_mutex_lock_iothread();
783 migrate_compress_threads_join();
784 qemu_fclose(s
->file
);
788 assert((s
->state
!= MIGRATION_STATUS_ACTIVE
) &&
789 (s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
));
791 if (s
->state
== MIGRATION_STATUS_CANCELLING
) {
792 migrate_set_state(s
, MIGRATION_STATUS_CANCELLING
,
793 MIGRATION_STATUS_CANCELLED
);
796 notifier_list_notify(&migration_state_notifiers
, s
);
799 void migrate_fd_error(MigrationState
*s
)
801 trace_migrate_fd_error();
802 assert(s
->file
== NULL
);
803 migrate_set_state(s
, MIGRATION_STATUS_SETUP
, MIGRATION_STATUS_FAILED
);
804 notifier_list_notify(&migration_state_notifiers
, s
);
807 static void migrate_fd_cancel(MigrationState
*s
)
810 QEMUFile
*f
= migrate_get_current()->file
;
811 trace_migrate_fd_cancel();
813 if (s
->rp_state
.from_dst_file
) {
814 /* shutdown the rp socket, so causing the rp thread to shutdown */
815 qemu_file_shutdown(s
->rp_state
.from_dst_file
);
819 old_state
= s
->state
;
820 if (!migration_is_setup_or_active(old_state
)) {
823 migrate_set_state(s
, old_state
, MIGRATION_STATUS_CANCELLING
);
824 } while (s
->state
!= MIGRATION_STATUS_CANCELLING
);
827 * If we're unlucky the migration code might be stuck somewhere in a
828 * send/write while the network has failed and is waiting to timeout;
829 * if we've got shutdown(2) available then we can force it to quit.
830 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
831 * called in a bh, so there is no race against this cancel.
833 if (s
->state
== MIGRATION_STATUS_CANCELLING
&& f
) {
834 qemu_file_shutdown(f
);
838 void add_migration_state_change_notifier(Notifier
*notify
)
840 notifier_list_add(&migration_state_notifiers
, notify
);
843 void remove_migration_state_change_notifier(Notifier
*notify
)
845 notifier_remove(notify
);
848 bool migration_in_setup(MigrationState
*s
)
850 return s
->state
== MIGRATION_STATUS_SETUP
;
853 bool migration_has_finished(MigrationState
*s
)
855 return s
->state
== MIGRATION_STATUS_COMPLETED
;
858 bool migration_has_failed(MigrationState
*s
)
860 return (s
->state
== MIGRATION_STATUS_CANCELLED
||
861 s
->state
== MIGRATION_STATUS_FAILED
);
864 bool migration_in_postcopy(MigrationState
*s
)
866 return (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
);
869 MigrationState
*migrate_init(const MigrationParams
*params
)
871 MigrationState
*s
= migrate_get_current();
872 int64_t bandwidth_limit
= s
->bandwidth_limit
;
873 bool enabled_capabilities
[MIGRATION_CAPABILITY_MAX
];
874 int64_t xbzrle_cache_size
= s
->xbzrle_cache_size
;
875 int compress_level
= s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
];
876 int compress_thread_count
=
877 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
];
878 int decompress_thread_count
=
879 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
];
880 int x_cpu_throttle_initial
=
881 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL
];
882 int x_cpu_throttle_increment
=
883 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT
];
885 memcpy(enabled_capabilities
, s
->enabled_capabilities
,
886 sizeof(enabled_capabilities
));
888 memset(s
, 0, sizeof(*s
));
890 memcpy(s
->enabled_capabilities
, enabled_capabilities
,
891 sizeof(enabled_capabilities
));
892 s
->xbzrle_cache_size
= xbzrle_cache_size
;
894 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
] = compress_level
;
895 s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
] =
896 compress_thread_count
;
897 s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
] =
898 decompress_thread_count
;
899 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL
] =
900 x_cpu_throttle_initial
;
901 s
->parameters
[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT
] =
902 x_cpu_throttle_increment
;
903 s
->bandwidth_limit
= bandwidth_limit
;
904 migrate_set_state(s
, MIGRATION_STATUS_NONE
, MIGRATION_STATUS_SETUP
);
906 s
->total_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
910 static GSList
*migration_blockers
;
912 void migrate_add_blocker(Error
*reason
)
914 migration_blockers
= g_slist_prepend(migration_blockers
, reason
);
917 void migrate_del_blocker(Error
*reason
)
919 migration_blockers
= g_slist_remove(migration_blockers
, reason
);
922 void qmp_migrate_incoming(const char *uri
, Error
**errp
)
924 Error
*local_err
= NULL
;
925 static bool once
= true;
927 if (!deferred_incoming
) {
928 error_setg(errp
, "For use with '-incoming defer'");
932 error_setg(errp
, "The incoming migration has already been started");
935 qemu_start_incoming_migration(uri
, &local_err
);
938 error_propagate(errp
, local_err
);
945 void qmp_migrate(const char *uri
, bool has_blk
, bool blk
,
946 bool has_inc
, bool inc
, bool has_detach
, bool detach
,
949 Error
*local_err
= NULL
;
950 MigrationState
*s
= migrate_get_current();
951 MigrationParams params
;
954 params
.blk
= has_blk
&& blk
;
955 params
.shared
= has_inc
&& inc
;
957 if (migration_is_setup_or_active(s
->state
) ||
958 s
->state
== MIGRATION_STATUS_CANCELLING
) {
959 error_setg(errp
, QERR_MIGRATION_ACTIVE
);
962 if (runstate_check(RUN_STATE_INMIGRATE
)) {
963 error_setg(errp
, "Guest is waiting for an incoming migration");
967 if (qemu_savevm_state_blocked(errp
)) {
971 if (migration_blockers
) {
972 *errp
= error_copy(migration_blockers
->data
);
976 /* We are starting a new migration, so we want to start in a clean
977 state. This change is only needed if previous migration
978 failed/was cancelled. We don't use migrate_set_state() because
979 we are setting the initial state, not changing it. */
980 s
->state
= MIGRATION_STATUS_NONE
;
982 s
= migrate_init(¶ms
);
984 if (strstart(uri
, "tcp:", &p
)) {
985 tcp_start_outgoing_migration(s
, p
, &local_err
);
987 } else if (strstart(uri
, "rdma:", &p
)) {
988 rdma_start_outgoing_migration(s
, p
, &local_err
);
991 } else if (strstart(uri
, "exec:", &p
)) {
992 exec_start_outgoing_migration(s
, p
, &local_err
);
993 } else if (strstart(uri
, "unix:", &p
)) {
994 unix_start_outgoing_migration(s
, p
, &local_err
);
995 } else if (strstart(uri
, "fd:", &p
)) {
996 fd_start_outgoing_migration(s
, p
, &local_err
);
999 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "uri",
1000 "a valid migration protocol");
1001 migrate_set_state(s
, MIGRATION_STATUS_SETUP
, MIGRATION_STATUS_FAILED
);
1006 migrate_fd_error(s
);
1007 error_propagate(errp
, local_err
);
1012 void qmp_migrate_cancel(Error
**errp
)
1014 migrate_fd_cancel(migrate_get_current());
1017 void qmp_migrate_set_cache_size(int64_t value
, Error
**errp
)
1019 MigrationState
*s
= migrate_get_current();
1022 /* Check for truncation */
1023 if (value
!= (size_t)value
) {
1024 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1025 "exceeding address space");
1029 /* Cache should not be larger than guest ram size */
1030 if (value
> ram_bytes_total()) {
1031 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1032 "exceeds guest ram size ");
1036 new_size
= xbzrle_cache_resize(value
);
1038 error_setg(errp
, QERR_INVALID_PARAMETER_VALUE
, "cache size",
1039 "is smaller than page size");
1043 s
->xbzrle_cache_size
= new_size
;
1046 int64_t qmp_query_migrate_cache_size(Error
**errp
)
1048 return migrate_xbzrle_cache_size();
1051 void qmp_migrate_set_speed(int64_t value
, Error
**errp
)
1058 if (value
> SIZE_MAX
) {
1062 s
= migrate_get_current();
1063 s
->bandwidth_limit
= value
;
1065 qemu_file_set_rate_limit(s
->file
, s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1069 void qmp_migrate_set_downtime(double value
, Error
**errp
)
1072 value
= MAX(0, MIN(UINT64_MAX
, value
));
1073 max_downtime
= (uint64_t)value
;
1076 bool migrate_postcopy_ram(void)
1080 s
= migrate_get_current();
1082 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_X_POSTCOPY_RAM
];
1085 bool migrate_auto_converge(void)
1089 s
= migrate_get_current();
1091 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_AUTO_CONVERGE
];
1094 bool migrate_zero_blocks(void)
1098 s
= migrate_get_current();
1100 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_ZERO_BLOCKS
];
1103 bool migrate_use_compression(void)
1107 s
= migrate_get_current();
1109 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_COMPRESS
];
1112 int migrate_compress_level(void)
1116 s
= migrate_get_current();
1118 return s
->parameters
[MIGRATION_PARAMETER_COMPRESS_LEVEL
];
1121 int migrate_compress_threads(void)
1125 s
= migrate_get_current();
1127 return s
->parameters
[MIGRATION_PARAMETER_COMPRESS_THREADS
];
1130 int migrate_decompress_threads(void)
1134 s
= migrate_get_current();
1136 return s
->parameters
[MIGRATION_PARAMETER_DECOMPRESS_THREADS
];
1139 bool migrate_use_events(void)
1143 s
= migrate_get_current();
1145 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_EVENTS
];
1148 int migrate_use_xbzrle(void)
1152 s
= migrate_get_current();
1154 return s
->enabled_capabilities
[MIGRATION_CAPABILITY_XBZRLE
];
1157 int64_t migrate_xbzrle_cache_size(void)
1161 s
= migrate_get_current();
1163 return s
->xbzrle_cache_size
;
1166 /* migration thread support */
1168 * Something bad happened to the RP stream, mark an error
1169 * The caller shall print or trace something to indicate why
1171 static void mark_source_rp_bad(MigrationState
*s
)
1173 s
->rp_state
.error
= true;
1176 static struct rp_cmd_args
{
1177 ssize_t len
; /* -1 = variable */
1180 [MIG_RP_MSG_INVALID
] = { .len
= -1, .name
= "INVALID" },
1181 [MIG_RP_MSG_SHUT
] = { .len
= 4, .name
= "SHUT" },
1182 [MIG_RP_MSG_PONG
] = { .len
= 4, .name
= "PONG" },
1183 [MIG_RP_MSG_REQ_PAGES
] = { .len
= 12, .name
= "REQ_PAGES" },
1184 [MIG_RP_MSG_REQ_PAGES_ID
] = { .len
= -1, .name
= "REQ_PAGES_ID" },
1185 [MIG_RP_MSG_MAX
] = { .len
= -1, .name
= "MAX" },
1189 * Process a request for pages received on the return path,
1190 * We're allowed to send more than requested (e.g. to round to our page size)
1191 * and we don't need to send pages that have already been sent.
1193 static void migrate_handle_rp_req_pages(MigrationState
*ms
, const char* rbname
,
1194 ram_addr_t start
, size_t len
)
1196 trace_migrate_handle_rp_req_pages(rbname
, start
, len
);
1200 * Handles messages sent on the return path towards the source VM
1203 static void *source_return_path_thread(void *opaque
)
1205 MigrationState
*ms
= opaque
;
1206 QEMUFile
*rp
= ms
->rp_state
.from_dst_file
;
1207 uint16_t header_len
, header_type
;
1208 const int max_len
= 512;
1209 uint8_t buf
[max_len
];
1210 uint32_t tmp32
, sibling_error
;
1211 ram_addr_t start
= 0; /* =0 to silence warning */
1212 size_t len
= 0, expected_len
;
1215 trace_source_return_path_thread_entry();
1216 while (!ms
->rp_state
.error
&& !qemu_file_get_error(rp
) &&
1217 migration_is_setup_or_active(ms
->state
)) {
1218 trace_source_return_path_thread_loop_top();
1219 header_type
= qemu_get_be16(rp
);
1220 header_len
= qemu_get_be16(rp
);
1222 if (header_type
>= MIG_RP_MSG_MAX
||
1223 header_type
== MIG_RP_MSG_INVALID
) {
1224 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1225 header_type
, header_len
);
1226 mark_source_rp_bad(ms
);
1230 if ((rp_cmd_args
[header_type
].len
!= -1 &&
1231 header_len
!= rp_cmd_args
[header_type
].len
) ||
1232 header_len
> max_len
) {
1233 error_report("RP: Received '%s' message (0x%04x) with"
1234 "incorrect length %d expecting %zu",
1235 rp_cmd_args
[header_type
].name
, header_type
, header_len
,
1236 (size_t)rp_cmd_args
[header_type
].len
);
1237 mark_source_rp_bad(ms
);
1241 /* We know we've got a valid header by this point */
1242 res
= qemu_get_buffer(rp
, buf
, header_len
);
1243 if (res
!= header_len
) {
1244 error_report("RP: Failed reading data for message 0x%04x"
1245 " read %d expected %d",
1246 header_type
, res
, header_len
);
1247 mark_source_rp_bad(ms
);
1251 /* OK, we have the message and the data */
1252 switch (header_type
) {
1253 case MIG_RP_MSG_SHUT
:
1254 sibling_error
= be32_to_cpup((uint32_t *)buf
);
1255 trace_source_return_path_thread_shut(sibling_error
);
1256 if (sibling_error
) {
1257 error_report("RP: Sibling indicated error %d", sibling_error
);
1258 mark_source_rp_bad(ms
);
1261 * We'll let the main thread deal with closing the RP
1262 * we could do a shutdown(2) on it, but we're the only user
1263 * anyway, so there's nothing gained.
1267 case MIG_RP_MSG_PONG
:
1268 tmp32
= be32_to_cpup((uint32_t *)buf
);
1269 trace_source_return_path_thread_pong(tmp32
);
1272 case MIG_RP_MSG_REQ_PAGES
:
1273 start
= be64_to_cpup((uint64_t *)buf
);
1274 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1275 migrate_handle_rp_req_pages(ms
, NULL
, start
, len
);
1278 case MIG_RP_MSG_REQ_PAGES_ID
:
1279 expected_len
= 12 + 1; /* header + termination */
1281 if (header_len
>= expected_len
) {
1282 start
= be64_to_cpup((uint64_t *)buf
);
1283 len
= be32_to_cpup((uint32_t *)(buf
+ 8));
1284 /* Now we expect an idstr */
1285 tmp32
= buf
[12]; /* Length of the following idstr */
1286 buf
[13 + tmp32
] = '\0';
1287 expected_len
+= tmp32
;
1289 if (header_len
!= expected_len
) {
1290 error_report("RP: Req_Page_id with length %d expecting %zd",
1291 header_len
, expected_len
);
1292 mark_source_rp_bad(ms
);
1295 migrate_handle_rp_req_pages(ms
, (char *)&buf
[13], start
, len
);
1302 if (rp
&& qemu_file_get_error(rp
)) {
1303 trace_source_return_path_thread_bad_end();
1304 mark_source_rp_bad(ms
);
1307 trace_source_return_path_thread_end();
1309 ms
->rp_state
.from_dst_file
= NULL
;
1314 static int open_return_path_on_source(MigrationState
*ms
)
1317 ms
->rp_state
.from_dst_file
= qemu_file_get_return_path(ms
->file
);
1318 if (!ms
->rp_state
.from_dst_file
) {
1322 trace_open_return_path_on_source();
1323 qemu_thread_create(&ms
->rp_state
.rp_thread
, "return path",
1324 source_return_path_thread
, ms
, QEMU_THREAD_JOINABLE
);
1326 trace_open_return_path_on_source_continue();
1331 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1332 static int await_return_path_close_on_source(MigrationState
*ms
)
1335 * If this is a normal exit then the destination will send a SHUT and the
1336 * rp_thread will exit, however if there's an error we need to cause
1339 if (qemu_file_get_error(ms
->file
) && ms
->rp_state
.from_dst_file
) {
1341 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1342 * waiting for the destination.
1344 qemu_file_shutdown(ms
->rp_state
.from_dst_file
);
1345 mark_source_rp_bad(ms
);
1347 trace_await_return_path_close_on_source_joining();
1348 qemu_thread_join(&ms
->rp_state
.rp_thread
);
1349 trace_await_return_path_close_on_source_close();
1350 return ms
->rp_state
.error
;
1354 * Switch from normal iteration to postcopy
1355 * Returns non-0 on error
1357 static int postcopy_start(MigrationState
*ms
, bool *old_vm_running
)
1360 const QEMUSizedBuffer
*qsb
;
1361 int64_t time_at_stop
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1362 migrate_set_state(ms
, MIGRATION_STATUS_ACTIVE
,
1363 MIGRATION_STATUS_POSTCOPY_ACTIVE
);
1365 trace_postcopy_start();
1366 qemu_mutex_lock_iothread();
1367 trace_postcopy_start_set_run();
1369 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1370 *old_vm_running
= runstate_is_running();
1371 global_state_store();
1372 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1379 * in Finish migrate and with the io-lock held everything should
1380 * be quiet, but we've potentially still got dirty pages and we
1381 * need to tell the destination to throw any pages it's already received
1384 if (ram_postcopy_send_discard_bitmap(ms
)) {
1385 error_report("postcopy send discard bitmap failed");
1390 * send rest of state - note things that are doing postcopy
1391 * will notice we're in POSTCOPY_ACTIVE and not actually
1392 * wrap their state up here
1394 qemu_file_set_rate_limit(ms
->file
, INT64_MAX
);
1395 /* Ping just for debugging, helps line traces up */
1396 qemu_savevm_send_ping(ms
->file
, 2);
1399 * While loading the device state we may trigger page transfer
1400 * requests and the fd must be free to process those, and thus
1401 * the destination must read the whole device state off the fd before
1402 * it starts processing it. Unfortunately the ad-hoc migration format
1403 * doesn't allow the destination to know the size to read without fully
1404 * parsing it through each devices load-state code (especially the open
1405 * coded devices that use get/put).
1406 * So we wrap the device state up in a package with a length at the start;
1407 * to do this we use a qemu_buf to hold the whole of the device state.
1409 QEMUFile
*fb
= qemu_bufopen("w", NULL
);
1411 error_report("Failed to create buffered file");
1415 qemu_savevm_state_complete_precopy(fb
);
1416 qemu_savevm_send_ping(fb
, 3);
1418 qemu_savevm_send_postcopy_run(fb
);
1420 /* <><> end of stuff going into the package */
1421 qsb
= qemu_buf_get(fb
);
1423 /* Now send that blob */
1424 if (qemu_savevm_send_packaged(ms
->file
, qsb
)) {
1428 ms
->downtime
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
) - time_at_stop
;
1430 qemu_mutex_unlock_iothread();
1433 * Although this ping is just for debug, it could potentially be
1434 * used for getting a better measurement of downtime at the source.
1436 qemu_savevm_send_ping(ms
->file
, 4);
1438 ret
= qemu_file_get_error(ms
->file
);
1440 error_report("postcopy_start: Migration stream errored");
1441 migrate_set_state(ms
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1442 MIGRATION_STATUS_FAILED
);
1450 migrate_set_state(ms
, MIGRATION_STATUS_POSTCOPY_ACTIVE
,
1451 MIGRATION_STATUS_FAILED
);
1452 qemu_mutex_unlock_iothread();
1457 * migration_completion: Used by migration_thread when there's not much left.
1458 * The caller 'breaks' the loop when this returns.
1460 * @s: Current migration state
1461 * @current_active_state: The migration state we expect to be in
1462 * @*old_vm_running: Pointer to old_vm_running flag
1463 * @*start_time: Pointer to time to update
1465 static void migration_completion(MigrationState
*s
, int current_active_state
,
1466 bool *old_vm_running
,
1467 int64_t *start_time
)
1471 if (s
->state
== MIGRATION_STATUS_ACTIVE
) {
1472 qemu_mutex_lock_iothread();
1473 *start_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1474 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER
);
1475 *old_vm_running
= runstate_is_running();
1476 ret
= global_state_store();
1479 ret
= vm_stop_force_state(RUN_STATE_FINISH_MIGRATE
);
1481 qemu_file_set_rate_limit(s
->file
, INT64_MAX
);
1482 qemu_savevm_state_complete_precopy(s
->file
);
1485 qemu_mutex_unlock_iothread();
1490 } else if (s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1491 trace_migration_completion_postcopy_end();
1493 qemu_savevm_state_complete_postcopy(s
->file
);
1494 trace_migration_completion_postcopy_end_after_complete();
1498 * If rp was opened we must clean up the thread before
1499 * cleaning everything else up (since if there are no failures
1500 * it will wait for the destination to send it's status in
1502 * Postcopy opens rp if enabled (even if it's not avtivated)
1504 if (migrate_postcopy_ram()) {
1506 trace_migration_completion_postcopy_end_before_rp();
1507 rp_error
= await_return_path_close_on_source(s
);
1508 trace_migration_completion_postcopy_end_after_rp(rp_error
);
1514 if (qemu_file_get_error(s
->file
)) {
1515 trace_migration_completion_file_err();
1519 migrate_set_state(s
, current_active_state
, MIGRATION_STATUS_COMPLETED
);
1523 migrate_set_state(s
, current_active_state
, MIGRATION_STATUS_FAILED
);
1527 * Master migration thread on the source VM.
1528 * It drives the migration and pumps the data down the outgoing channel.
1530 static void *migration_thread(void *opaque
)
1532 MigrationState
*s
= opaque
;
1533 /* Used by the bandwidth calcs, updated later */
1534 int64_t initial_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1535 int64_t setup_start
= qemu_clock_get_ms(QEMU_CLOCK_HOST
);
1536 int64_t initial_bytes
= 0;
1537 int64_t max_size
= 0;
1538 int64_t start_time
= initial_time
;
1540 bool old_vm_running
= false;
1541 bool entered_postcopy
= false;
1542 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1543 enum MigrationStatus current_active_state
= MIGRATION_STATUS_ACTIVE
;
1545 rcu_register_thread();
1547 qemu_savevm_state_header(s
->file
);
1549 if (migrate_postcopy_ram()) {
1550 /* Now tell the dest that it should open its end so it can reply */
1551 qemu_savevm_send_open_return_path(s
->file
);
1553 /* And do a ping that will make stuff easier to debug */
1554 qemu_savevm_send_ping(s
->file
, 1);
1557 * Tell the destination that we *might* want to do postcopy later;
1558 * if the other end can't do postcopy it should fail now, nice and
1561 qemu_savevm_send_postcopy_advise(s
->file
);
1564 qemu_savevm_state_begin(s
->file
, &s
->params
);
1566 s
->setup_time
= qemu_clock_get_ms(QEMU_CLOCK_HOST
) - setup_start
;
1567 current_active_state
= MIGRATION_STATUS_ACTIVE
;
1568 migrate_set_state(s
, MIGRATION_STATUS_SETUP
, MIGRATION_STATUS_ACTIVE
);
1570 trace_migration_thread_setup_complete();
1572 while (s
->state
== MIGRATION_STATUS_ACTIVE
||
1573 s
->state
== MIGRATION_STATUS_POSTCOPY_ACTIVE
) {
1574 int64_t current_time
;
1575 uint64_t pending_size
;
1577 if (!qemu_file_rate_limit(s
->file
)) {
1578 uint64_t pend_post
, pend_nonpost
;
1580 qemu_savevm_state_pending(s
->file
, max_size
, &pend_nonpost
,
1582 pending_size
= pend_nonpost
+ pend_post
;
1583 trace_migrate_pending(pending_size
, max_size
,
1584 pend_post
, pend_nonpost
);
1585 if (pending_size
&& pending_size
>= max_size
) {
1586 /* Still a significant amount to transfer */
1588 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1589 if (migrate_postcopy_ram() &&
1590 s
->state
!= MIGRATION_STATUS_POSTCOPY_ACTIVE
&&
1591 pend_nonpost
<= max_size
&&
1592 atomic_read(&s
->start_postcopy
)) {
1594 if (!postcopy_start(s
, &old_vm_running
)) {
1595 current_active_state
= MIGRATION_STATUS_POSTCOPY_ACTIVE
;
1596 entered_postcopy
= true;
1601 /* Just another iteration step */
1602 qemu_savevm_state_iterate(s
->file
);
1604 trace_migration_thread_low_pending(pending_size
);
1605 migration_completion(s
, current_active_state
,
1606 &old_vm_running
, &start_time
);
1611 if (qemu_file_get_error(s
->file
)) {
1612 migrate_set_state(s
, current_active_state
, MIGRATION_STATUS_FAILED
);
1613 trace_migration_thread_file_err();
1616 current_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1617 if (current_time
>= initial_time
+ BUFFER_DELAY
) {
1618 uint64_t transferred_bytes
= qemu_ftell(s
->file
) - initial_bytes
;
1619 uint64_t time_spent
= current_time
- initial_time
;
1620 double bandwidth
= transferred_bytes
/ time_spent
;
1621 max_size
= bandwidth
* migrate_max_downtime() / 1000000;
1623 s
->mbps
= time_spent
? (((double) transferred_bytes
* 8.0) /
1624 ((double) time_spent
/ 1000.0)) / 1000.0 / 1000.0 : -1;
1626 trace_migrate_transferred(transferred_bytes
, time_spent
,
1627 bandwidth
, max_size
);
1628 /* if we haven't sent anything, we don't want to recalculate
1629 10000 is a small enough number for our purposes */
1630 if (s
->dirty_bytes_rate
&& transferred_bytes
> 10000) {
1631 s
->expected_downtime
= s
->dirty_bytes_rate
/ bandwidth
;
1634 qemu_file_reset_rate_limit(s
->file
);
1635 initial_time
= current_time
;
1636 initial_bytes
= qemu_ftell(s
->file
);
1638 if (qemu_file_rate_limit(s
->file
)) {
1639 /* usleep expects microseconds */
1640 g_usleep((initial_time
+ BUFFER_DELAY
- current_time
)*1000);
1644 trace_migration_thread_after_loop();
1645 /* If we enabled cpu throttling for auto-converge, turn it off. */
1646 cpu_throttle_stop();
1647 end_time
= qemu_clock_get_ms(QEMU_CLOCK_REALTIME
);
1649 qemu_mutex_lock_iothread();
1650 qemu_savevm_state_cleanup();
1651 if (s
->state
== MIGRATION_STATUS_COMPLETED
) {
1652 uint64_t transferred_bytes
= qemu_ftell(s
->file
);
1653 s
->total_time
= end_time
- s
->total_time
;
1654 if (!entered_postcopy
) {
1655 s
->downtime
= end_time
- start_time
;
1657 if (s
->total_time
) {
1658 s
->mbps
= (((double) transferred_bytes
* 8.0) /
1659 ((double) s
->total_time
)) / 1000;
1661 runstate_set(RUN_STATE_POSTMIGRATE
);
1663 if (old_vm_running
&& !entered_postcopy
) {
1667 qemu_bh_schedule(s
->cleanup_bh
);
1668 qemu_mutex_unlock_iothread();
1670 rcu_unregister_thread();
1674 void migrate_fd_connect(MigrationState
*s
)
1676 /* This is a best 1st approximation. ns to ms */
1677 s
->expected_downtime
= max_downtime
/1000000;
1678 s
->cleanup_bh
= qemu_bh_new(migrate_fd_cleanup
, s
);
1680 qemu_file_set_rate_limit(s
->file
,
1681 s
->bandwidth_limit
/ XFER_LIMIT_RATIO
);
1683 /* Notify before starting migration thread */
1684 notifier_list_notify(&migration_state_notifiers
, s
);
1687 * Open the return path; currently for postcopy but other things might
1690 if (migrate_postcopy_ram()) {
1691 if (open_return_path_on_source(s
)) {
1692 error_report("Unable to open return-path for postcopy");
1693 migrate_set_state(s
, MIGRATION_STATUS_SETUP
,
1694 MIGRATION_STATUS_FAILED
);
1695 migrate_fd_cleanup(s
);
1700 migrate_compress_threads_create();
1701 qemu_thread_create(&s
->thread
, "migration", migration_thread
, s
,
1702 QEMU_THREAD_JOINABLE
);
1703 s
->migration_thread_running
= true;
1706 PostcopyState
postcopy_state_get(void)
1708 return atomic_mb_read(&incoming_postcopy_state
);
1711 /* Set the state and return the old state */
1712 PostcopyState
postcopy_state_set(PostcopyState new_state
)
1714 return atomic_xchg(&incoming_postcopy_state
, new_state
);