]> git.proxmox.com Git - mirror_qemu.git/blob - migration/migration.c
Page request: Add MIG_RP_MSG_REQ_PAGES reverse command
[mirror_qemu.git] / migration / migration.c
1 /*
2 * QEMU live migration
3 *
4 * Copyright IBM, Corp. 2008
5 *
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
14 */
15
16 #include "qemu-common.h"
17 #include "qemu/error-report.h"
18 #include "qemu/main-loop.h"
19 #include "migration/migration.h"
20 #include "migration/qemu-file.h"
21 #include "sysemu/sysemu.h"
22 #include "block/block.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/sockets.h"
25 #include "qemu/rcu.h"
26 #include "migration/block.h"
27 #include "migration/postcopy-ram.h"
28 #include "qemu/thread.h"
29 #include "qmp-commands.h"
30 #include "trace.h"
31 #include "qapi/util.h"
32 #include "qapi-event.h"
33 #include "qom/cpu.h"
34
35 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
36
37 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
38 * data. */
39 #define BUFFER_DELAY 100
40 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
41
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
52
53 /* Migration XBZRLE default cache size */
54 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
55
56 static NotifierList migration_state_notifiers =
57 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
58
59 static bool deferred_incoming;
60
61 /*
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.
65 */
66 static PostcopyState incoming_postcopy_state;
67
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 */
71
72 /* For outgoing */
73 MigrationState *migrate_get_current(void)
74 {
75 static MigrationState current_migration = {
76 .state = MIGRATION_STATUS_NONE,
77 .bandwidth_limit = MAX_THROTTLE,
78 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
79 .mbps = -1,
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,
90 };
91
92 return &current_migration;
93 }
94
95 /* For incoming */
96 static MigrationIncomingState *mis_current;
97
98 MigrationIncomingState *migration_incoming_get_current(void)
99 {
100 return mis_current;
101 }
102
103 MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
104 {
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);
110
111 return mis_current;
112 }
113
114 void migration_incoming_state_destroy(void)
115 {
116 qemu_event_destroy(&mis_current->main_thread_load_event);
117 loadvm_free_handlers(mis_current);
118 g_free(mis_current);
119 mis_current = NULL;
120 }
121
122
123 typedef struct {
124 bool optional;
125 uint32_t size;
126 uint8_t runstate[100];
127 RunState state;
128 bool received;
129 } GlobalState;
130
131 static GlobalState global_state;
132
133 int global_state_store(void)
134 {
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();
139 return -EINVAL;
140 }
141 return 0;
142 }
143
144 void global_state_store_running(void)
145 {
146 const char *state = RunState_lookup[RUN_STATE_RUNNING];
147 strncpy((char *)global_state.runstate,
148 state, sizeof(global_state.runstate));
149 }
150
151 static bool global_state_received(void)
152 {
153 return global_state.received;
154 }
155
156 static RunState global_state_get_runstate(void)
157 {
158 return global_state.state;
159 }
160
161 void global_state_set_optional(void)
162 {
163 global_state.optional = true;
164 }
165
166 static bool global_state_needed(void *opaque)
167 {
168 GlobalState *s = opaque;
169 char *runstate = (char *)s->runstate;
170
171 /* If it is not optional, it is mandatory */
172
173 if (s->optional == false) {
174 return true;
175 }
176
177 /* If state is running or paused, it is not needed */
178
179 if (strcmp(runstate, "running") == 0 ||
180 strcmp(runstate, "paused") == 0) {
181 return false;
182 }
183
184 /* for any other state it is needed */
185 return true;
186 }
187
188 static int global_state_post_load(void *opaque, int version_id)
189 {
190 GlobalState *s = opaque;
191 Error *local_err = NULL;
192 int r;
193 char *runstate = (char *)s->runstate;
194
195 s->received = true;
196 trace_migrate_global_state_post_load(runstate);
197
198 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE_MAX,
199 -1, &local_err);
200
201 if (r == -1) {
202 if (local_err) {
203 error_report_err(local_err);
204 }
205 return -EINVAL;
206 }
207 s->state = r;
208
209 return 0;
210 }
211
212 static void global_state_pre_save(void *opaque)
213 {
214 GlobalState *s = opaque;
215
216 trace_migrate_global_state_pre_save((char *)s->runstate);
217 s->size = strlen((char *)s->runstate) + 1;
218 }
219
220 static const VMStateDescription vmstate_globalstate = {
221 .name = "globalstate",
222 .version_id = 1,
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()
231 },
232 };
233
234 void register_global_state(void)
235 {
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);
240 }
241
242 static void migrate_generate_event(int new_state)
243 {
244 if (migrate_use_events()) {
245 qapi_event_send_migration(new_state, &error_abort);
246 }
247 }
248
249 /*
250 * Called on -incoming with a defer: uri.
251 * The migration can be started later after any parameters have been
252 * changed.
253 */
254 static void deferred_incoming_migration(Error **errp)
255 {
256 if (deferred_incoming) {
257 error_setg(errp, "Incoming migration already deferred");
258 }
259 deferred_incoming = true;
260 }
261
262 /* Request a range of pages from the source VM at the given
263 * start address.
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
268 */
269 void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
270 ram_addr_t start, size_t len)
271 {
272 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname upto 256 */
273 size_t msglen = 12; /* start + len */
274
275 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
276 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
277
278 if (rbname) {
279 int rbname_len = strlen(rbname);
280 assert(rbname_len < 256);
281
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);
286 } else {
287 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES, msglen, bufc);
288 }
289 }
290
291 void qemu_start_incoming_migration(const char *uri, Error **errp)
292 {
293 const char *p;
294
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);
300 #ifdef CONFIG_RDMA
301 } else if (strstart(uri, "rdma:", &p)) {
302 rdma_start_incoming_migration(p, errp);
303 #endif
304 #if !defined(WIN32)
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);
311 #endif
312 } else {
313 error_setg(errp, "unknown migration protocol: %s", uri);
314 }
315 }
316
317 static void process_incoming_migration_co(void *opaque)
318 {
319 QEMUFile *f = opaque;
320 Error *local_err = NULL;
321 int ret;
322
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);
327
328 qemu_fclose(f);
329 free_xbzrle_decoded_buf();
330 migration_incoming_state_destroy();
331
332 if (ret < 0) {
333 migrate_generate_event(MIGRATION_STATUS_FAILED);
334 error_report("load of migration failed: %s", strerror(-ret));
335 migrate_decompress_threads_join();
336 exit(EXIT_FAILURE);
337 }
338
339 /* Make sure all file formats flush their mutable metadata */
340 bdrv_invalidate_cache_all(&local_err);
341 if (local_err) {
342 migrate_generate_event(MIGRATION_STATUS_FAILED);
343 error_report_err(local_err);
344 migrate_decompress_threads_join();
345 exit(EXIT_FAILURE);
346 }
347
348 /*
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.
351 */
352 qemu_announce_self();
353
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
356 runstate_set. */
357
358 if (!global_state_received() ||
359 global_state_get_runstate() == RUN_STATE_RUNNING) {
360 if (autostart) {
361 vm_start();
362 } else {
363 runstate_set(RUN_STATE_PAUSED);
364 }
365 } else {
366 runstate_set(global_state_get_runstate());
367 }
368 migrate_decompress_threads_join();
369 /*
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
372 * it's ready to use.
373 */
374 migrate_generate_event(MIGRATION_STATUS_COMPLETED);
375 }
376
377 void process_incoming_migration(QEMUFile *f)
378 {
379 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
380 int fd = qemu_get_fd(f);
381
382 assert(fd != -1);
383 migrate_decompress_threads_create();
384 qemu_set_nonblock(fd);
385 qemu_coroutine_enter(co, f);
386 }
387
388 /*
389 * Send a message on the return channel back to the source
390 * of the migration.
391 */
392 void migrate_send_rp_message(MigrationIncomingState *mis,
393 enum mig_rp_message_type message_type,
394 uint16_t len, void *data)
395 {
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);
403 }
404
405 /*
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
408 * error.
409 */
410 void migrate_send_rp_shut(MigrationIncomingState *mis,
411 uint32_t value)
412 {
413 uint32_t buf;
414
415 buf = cpu_to_be32(value);
416 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
417 }
418
419 /*
420 * Send a 'PONG' message on the return channel with the given value
421 * (normally in response to a 'PING')
422 */
423 void migrate_send_rp_pong(MigrationIncomingState *mis,
424 uint32_t value)
425 {
426 uint32_t buf;
427
428 buf = cpu_to_be32(value);
429 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
430 }
431
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;
437
438 uint64_t migrate_max_downtime(void)
439 {
440 return max_downtime;
441 }
442
443 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
444 {
445 MigrationCapabilityStatusList *head = NULL;
446 MigrationCapabilityStatusList *caps;
447 MigrationState *s = migrate_get_current();
448 int i;
449
450 caps = NULL; /* silence compiler warning */
451 for (i = 0; i < MIGRATION_CAPABILITY_MAX; i++) {
452 if (head == NULL) {
453 head = g_malloc0(sizeof(*caps));
454 caps = head;
455 } else {
456 caps->next = g_malloc0(sizeof(*caps));
457 caps = caps->next;
458 }
459 caps->value =
460 g_malloc(sizeof(*caps->value));
461 caps->value->capability = i;
462 caps->value->state = s->enabled_capabilities[i];
463 }
464
465 return head;
466 }
467
468 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
469 {
470 MigrationParameters *params;
471 MigrationState *s = migrate_get_current();
472
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];
483
484 return params;
485 }
486
487 /*
488 * Return true if we're already in the middle of a migration
489 * (i.e. any of the active or setup states)
490 */
491 static bool migration_is_setup_or_active(int state)
492 {
493 switch (state) {
494 case MIGRATION_STATUS_ACTIVE:
495 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
496 case MIGRATION_STATUS_SETUP:
497 return true;
498
499 default:
500 return false;
501
502 }
503 }
504
505 static void get_xbzrle_cache_stats(MigrationInfo *info)
506 {
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();
516 }
517 }
518
519 MigrationInfo *qmp_query_migrate(Error **errp)
520 {
521 MigrationInfo *info = g_malloc0(sizeof(*info));
522 MigrationState *s = migrate_get_current();
523
524 switch (s->state) {
525 case MIGRATION_STATUS_NONE:
526 /* no migration has happened ever */
527 break;
528 case MIGRATION_STATUS_SETUP:
529 info->has_status = true;
530 info->has_total_time = false;
531 break;
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)
537 - s->total_time;
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;
542
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;
555
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();
562 }
563
564 if (cpu_throttle_active()) {
565 info->has_x_cpu_throttle_percentage = true;
566 info->x_cpu_throttle_percentage = cpu_throttle_get_percentage();
567 }
568
569 get_xbzrle_cache_stats(info);
570 break;
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)
576 - s->total_time;
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;
581
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;
593
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();
600 }
601
602 get_xbzrle_cache_stats(info);
603 break;
604 case MIGRATION_STATUS_COMPLETED:
605 get_xbzrle_cache_stats(info);
606
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;
614
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;
626 break;
627 case MIGRATION_STATUS_FAILED:
628 info->has_status = true;
629 break;
630 case MIGRATION_STATUS_CANCELLED:
631 info->has_status = true;
632 break;
633 }
634 info->status = s->state;
635
636 return info;
637 }
638
639 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
640 Error **errp)
641 {
642 MigrationState *s = migrate_get_current();
643 MigrationCapabilityStatusList *cap;
644
645 if (migration_is_setup_or_active(s->state)) {
646 error_setg(errp, QERR_MIGRATION_ACTIVE);
647 return;
648 }
649
650 for (cap = params; cap; cap = cap->next) {
651 s->enabled_capabilities[cap->value->capability] = cap->value->state;
652 }
653
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.
660 */
661 error_report("Postcopy is not currently compatible with "
662 "compression");
663 s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM] =
664 false;
665 }
666 }
667 }
668
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)
679 {
680 MigrationState *s = migrate_get_current();
681
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");
685 return;
686 }
687 if (has_compress_threads &&
688 (compress_threads < 1 || compress_threads > 255)) {
689 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
690 "compress_threads",
691 "is invalid, it should be in the range of 1 to 255");
692 return;
693 }
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");
699 return;
700 }
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");
706 }
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");
712 }
713
714 if (has_compress_level) {
715 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
716 }
717 if (has_compress_threads) {
718 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
719 }
720 if (has_decompress_threads) {
721 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
722 decompress_threads;
723 }
724 if (has_x_cpu_throttle_initial) {
725 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INITIAL] =
726 x_cpu_throttle_initial;
727 }
728
729 if (has_x_cpu_throttle_increment) {
730 s->parameters[MIGRATION_PARAMETER_X_CPU_THROTTLE_INCREMENT] =
731 x_cpu_throttle_increment;
732 }
733 }
734
735 void qmp_migrate_start_postcopy(Error **errp)
736 {
737 MigrationState *s = migrate_get_current();
738
739 if (!migrate_postcopy_ram()) {
740 error_setg(errp, "Enable postcopy with migration_set_capability before"
741 " the start of migration");
742 return;
743 }
744
745 if (s->state == MIGRATION_STATUS_NONE) {
746 error_setg(errp, "Postcopy must be started after migration has been"
747 " started");
748 return;
749 }
750 /*
751 * we don't error if migration has finished since that would be racy
752 * with issuing this command.
753 */
754 atomic_set(&s->start_postcopy, true);
755 }
756
757 /* shared migration helpers */
758
759 static void migrate_set_state(MigrationState *s, int old_state, int new_state)
760 {
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);
764 }
765 }
766
767 static void migrate_fd_cleanup(void *opaque)
768 {
769 MigrationState *s = opaque;
770
771 qemu_bh_delete(s->cleanup_bh);
772 s->cleanup_bh = NULL;
773
774 if (s->file) {
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;
780 }
781 qemu_mutex_lock_iothread();
782
783 migrate_compress_threads_join();
784 qemu_fclose(s->file);
785 s->file = NULL;
786 }
787
788 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
789 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
790
791 if (s->state == MIGRATION_STATUS_CANCELLING) {
792 migrate_set_state(s, MIGRATION_STATUS_CANCELLING,
793 MIGRATION_STATUS_CANCELLED);
794 }
795
796 notifier_list_notify(&migration_state_notifiers, s);
797 }
798
799 void migrate_fd_error(MigrationState *s)
800 {
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);
805 }
806
807 static void migrate_fd_cancel(MigrationState *s)
808 {
809 int old_state ;
810 QEMUFile *f = migrate_get_current()->file;
811 trace_migrate_fd_cancel();
812
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);
816 }
817
818 do {
819 old_state = s->state;
820 if (!migration_is_setup_or_active(old_state)) {
821 break;
822 }
823 migrate_set_state(s, old_state, MIGRATION_STATUS_CANCELLING);
824 } while (s->state != MIGRATION_STATUS_CANCELLING);
825
826 /*
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.
832 */
833 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
834 qemu_file_shutdown(f);
835 }
836 }
837
838 void add_migration_state_change_notifier(Notifier *notify)
839 {
840 notifier_list_add(&migration_state_notifiers, notify);
841 }
842
843 void remove_migration_state_change_notifier(Notifier *notify)
844 {
845 notifier_remove(notify);
846 }
847
848 bool migration_in_setup(MigrationState *s)
849 {
850 return s->state == MIGRATION_STATUS_SETUP;
851 }
852
853 bool migration_has_finished(MigrationState *s)
854 {
855 return s->state == MIGRATION_STATUS_COMPLETED;
856 }
857
858 bool migration_has_failed(MigrationState *s)
859 {
860 return (s->state == MIGRATION_STATUS_CANCELLED ||
861 s->state == MIGRATION_STATUS_FAILED);
862 }
863
864 bool migration_in_postcopy(MigrationState *s)
865 {
866 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
867 }
868
869 MigrationState *migrate_init(const MigrationParams *params)
870 {
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];
884
885 memcpy(enabled_capabilities, s->enabled_capabilities,
886 sizeof(enabled_capabilities));
887
888 memset(s, 0, sizeof(*s));
889 s->params = *params;
890 memcpy(s->enabled_capabilities, enabled_capabilities,
891 sizeof(enabled_capabilities));
892 s->xbzrle_cache_size = xbzrle_cache_size;
893
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);
905
906 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
907 return s;
908 }
909
910 static GSList *migration_blockers;
911
912 void migrate_add_blocker(Error *reason)
913 {
914 migration_blockers = g_slist_prepend(migration_blockers, reason);
915 }
916
917 void migrate_del_blocker(Error *reason)
918 {
919 migration_blockers = g_slist_remove(migration_blockers, reason);
920 }
921
922 void qmp_migrate_incoming(const char *uri, Error **errp)
923 {
924 Error *local_err = NULL;
925 static bool once = true;
926
927 if (!deferred_incoming) {
928 error_setg(errp, "For use with '-incoming defer'");
929 return;
930 }
931 if (!once) {
932 error_setg(errp, "The incoming migration has already been started");
933 }
934
935 qemu_start_incoming_migration(uri, &local_err);
936
937 if (local_err) {
938 error_propagate(errp, local_err);
939 return;
940 }
941
942 once = false;
943 }
944
945 void qmp_migrate(const char *uri, bool has_blk, bool blk,
946 bool has_inc, bool inc, bool has_detach, bool detach,
947 Error **errp)
948 {
949 Error *local_err = NULL;
950 MigrationState *s = migrate_get_current();
951 MigrationParams params;
952 const char *p;
953
954 params.blk = has_blk && blk;
955 params.shared = has_inc && inc;
956
957 if (migration_is_setup_or_active(s->state) ||
958 s->state == MIGRATION_STATUS_CANCELLING) {
959 error_setg(errp, QERR_MIGRATION_ACTIVE);
960 return;
961 }
962 if (runstate_check(RUN_STATE_INMIGRATE)) {
963 error_setg(errp, "Guest is waiting for an incoming migration");
964 return;
965 }
966
967 if (qemu_savevm_state_blocked(errp)) {
968 return;
969 }
970
971 if (migration_blockers) {
972 *errp = error_copy(migration_blockers->data);
973 return;
974 }
975
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;
981
982 s = migrate_init(&params);
983
984 if (strstart(uri, "tcp:", &p)) {
985 tcp_start_outgoing_migration(s, p, &local_err);
986 #ifdef CONFIG_RDMA
987 } else if (strstart(uri, "rdma:", &p)) {
988 rdma_start_outgoing_migration(s, p, &local_err);
989 #endif
990 #if !defined(WIN32)
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);
997 #endif
998 } else {
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);
1002 return;
1003 }
1004
1005 if (local_err) {
1006 migrate_fd_error(s);
1007 error_propagate(errp, local_err);
1008 return;
1009 }
1010 }
1011
1012 void qmp_migrate_cancel(Error **errp)
1013 {
1014 migrate_fd_cancel(migrate_get_current());
1015 }
1016
1017 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1018 {
1019 MigrationState *s = migrate_get_current();
1020 int64_t new_size;
1021
1022 /* Check for truncation */
1023 if (value != (size_t)value) {
1024 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1025 "exceeding address space");
1026 return;
1027 }
1028
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 ");
1033 return;
1034 }
1035
1036 new_size = xbzrle_cache_resize(value);
1037 if (new_size < 0) {
1038 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1039 "is smaller than page size");
1040 return;
1041 }
1042
1043 s->xbzrle_cache_size = new_size;
1044 }
1045
1046 int64_t qmp_query_migrate_cache_size(Error **errp)
1047 {
1048 return migrate_xbzrle_cache_size();
1049 }
1050
1051 void qmp_migrate_set_speed(int64_t value, Error **errp)
1052 {
1053 MigrationState *s;
1054
1055 if (value < 0) {
1056 value = 0;
1057 }
1058 if (value > SIZE_MAX) {
1059 value = SIZE_MAX;
1060 }
1061
1062 s = migrate_get_current();
1063 s->bandwidth_limit = value;
1064 if (s->file) {
1065 qemu_file_set_rate_limit(s->file, s->bandwidth_limit / XFER_LIMIT_RATIO);
1066 }
1067 }
1068
1069 void qmp_migrate_set_downtime(double value, Error **errp)
1070 {
1071 value *= 1e9;
1072 value = MAX(0, MIN(UINT64_MAX, value));
1073 max_downtime = (uint64_t)value;
1074 }
1075
1076 bool migrate_postcopy_ram(void)
1077 {
1078 MigrationState *s;
1079
1080 s = migrate_get_current();
1081
1082 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_POSTCOPY_RAM];
1083 }
1084
1085 bool migrate_auto_converge(void)
1086 {
1087 MigrationState *s;
1088
1089 s = migrate_get_current();
1090
1091 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1092 }
1093
1094 bool migrate_zero_blocks(void)
1095 {
1096 MigrationState *s;
1097
1098 s = migrate_get_current();
1099
1100 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1101 }
1102
1103 bool migrate_use_compression(void)
1104 {
1105 MigrationState *s;
1106
1107 s = migrate_get_current();
1108
1109 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1110 }
1111
1112 int migrate_compress_level(void)
1113 {
1114 MigrationState *s;
1115
1116 s = migrate_get_current();
1117
1118 return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
1119 }
1120
1121 int migrate_compress_threads(void)
1122 {
1123 MigrationState *s;
1124
1125 s = migrate_get_current();
1126
1127 return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
1128 }
1129
1130 int migrate_decompress_threads(void)
1131 {
1132 MigrationState *s;
1133
1134 s = migrate_get_current();
1135
1136 return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1137 }
1138
1139 bool migrate_use_events(void)
1140 {
1141 MigrationState *s;
1142
1143 s = migrate_get_current();
1144
1145 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1146 }
1147
1148 int migrate_use_xbzrle(void)
1149 {
1150 MigrationState *s;
1151
1152 s = migrate_get_current();
1153
1154 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1155 }
1156
1157 int64_t migrate_xbzrle_cache_size(void)
1158 {
1159 MigrationState *s;
1160
1161 s = migrate_get_current();
1162
1163 return s->xbzrle_cache_size;
1164 }
1165
1166 /* migration thread support */
1167 /*
1168 * Something bad happened to the RP stream, mark an error
1169 * The caller shall print or trace something to indicate why
1170 */
1171 static void mark_source_rp_bad(MigrationState *s)
1172 {
1173 s->rp_state.error = true;
1174 }
1175
1176 static struct rp_cmd_args {
1177 ssize_t len; /* -1 = variable */
1178 const char *name;
1179 } rp_cmd_args[] = {
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" },
1186 };
1187
1188 /*
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.
1192 */
1193 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1194 ram_addr_t start, size_t len)
1195 {
1196 trace_migrate_handle_rp_req_pages(rbname, start, len);
1197 }
1198
1199 /*
1200 * Handles messages sent on the return path towards the source VM
1201 *
1202 */
1203 static void *source_return_path_thread(void *opaque)
1204 {
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;
1213 int res;
1214
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);
1221
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);
1227 goto out;
1228 }
1229
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);
1238 goto out;
1239 }
1240
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);
1248 goto out;
1249 }
1250
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);
1259 }
1260 /*
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.
1264 */
1265 goto out;
1266
1267 case MIG_RP_MSG_PONG:
1268 tmp32 = be32_to_cpup((uint32_t *)buf);
1269 trace_source_return_path_thread_pong(tmp32);
1270 break;
1271
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);
1276 break;
1277
1278 case MIG_RP_MSG_REQ_PAGES_ID:
1279 expected_len = 12 + 1; /* header + termination */
1280
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;
1288 }
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);
1293 goto out;
1294 }
1295 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1296 break;
1297
1298 default:
1299 break;
1300 }
1301 }
1302 if (rp && qemu_file_get_error(rp)) {
1303 trace_source_return_path_thread_bad_end();
1304 mark_source_rp_bad(ms);
1305 }
1306
1307 trace_source_return_path_thread_end();
1308 out:
1309 ms->rp_state.from_dst_file = NULL;
1310 qemu_fclose(rp);
1311 return NULL;
1312 }
1313
1314 static int open_return_path_on_source(MigrationState *ms)
1315 {
1316
1317 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->file);
1318 if (!ms->rp_state.from_dst_file) {
1319 return -1;
1320 }
1321
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);
1325
1326 trace_open_return_path_on_source_continue();
1327
1328 return 0;
1329 }
1330
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)
1333 {
1334 /*
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
1337 * it to exit.
1338 */
1339 if (qemu_file_get_error(ms->file) && ms->rp_state.from_dst_file) {
1340 /*
1341 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1342 * waiting for the destination.
1343 */
1344 qemu_file_shutdown(ms->rp_state.from_dst_file);
1345 mark_source_rp_bad(ms);
1346 }
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;
1351 }
1352
1353 /*
1354 * Switch from normal iteration to postcopy
1355 * Returns non-0 on error
1356 */
1357 static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1358 {
1359 int ret;
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);
1364
1365 trace_postcopy_start();
1366 qemu_mutex_lock_iothread();
1367 trace_postcopy_start_set_run();
1368
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);
1373
1374 if (ret < 0) {
1375 goto fail;
1376 }
1377
1378 /*
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
1382 * that are dirty
1383 */
1384 if (ram_postcopy_send_discard_bitmap(ms)) {
1385 error_report("postcopy send discard bitmap failed");
1386 goto fail;
1387 }
1388
1389 /*
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
1393 */
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);
1397
1398 /*
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.
1408 */
1409 QEMUFile *fb = qemu_bufopen("w", NULL);
1410 if (!fb) {
1411 error_report("Failed to create buffered file");
1412 goto fail;
1413 }
1414
1415 qemu_savevm_state_complete_precopy(fb);
1416 qemu_savevm_send_ping(fb, 3);
1417
1418 qemu_savevm_send_postcopy_run(fb);
1419
1420 /* <><> end of stuff going into the package */
1421 qsb = qemu_buf_get(fb);
1422
1423 /* Now send that blob */
1424 if (qemu_savevm_send_packaged(ms->file, qsb)) {
1425 goto fail_closefb;
1426 }
1427 qemu_fclose(fb);
1428 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1429
1430 qemu_mutex_unlock_iothread();
1431
1432 /*
1433 * Although this ping is just for debug, it could potentially be
1434 * used for getting a better measurement of downtime at the source.
1435 */
1436 qemu_savevm_send_ping(ms->file, 4);
1437
1438 ret = qemu_file_get_error(ms->file);
1439 if (ret) {
1440 error_report("postcopy_start: Migration stream errored");
1441 migrate_set_state(ms, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1442 MIGRATION_STATUS_FAILED);
1443 }
1444
1445 return ret;
1446
1447 fail_closefb:
1448 qemu_fclose(fb);
1449 fail:
1450 migrate_set_state(ms, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1451 MIGRATION_STATUS_FAILED);
1452 qemu_mutex_unlock_iothread();
1453 return -1;
1454 }
1455
1456 /**
1457 * migration_completion: Used by migration_thread when there's not much left.
1458 * The caller 'breaks' the loop when this returns.
1459 *
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
1464 */
1465 static void migration_completion(MigrationState *s, int current_active_state,
1466 bool *old_vm_running,
1467 int64_t *start_time)
1468 {
1469 int ret;
1470
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();
1477
1478 if (!ret) {
1479 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1480 if (ret >= 0) {
1481 qemu_file_set_rate_limit(s->file, INT64_MAX);
1482 qemu_savevm_state_complete_precopy(s->file);
1483 }
1484 }
1485 qemu_mutex_unlock_iothread();
1486
1487 if (ret < 0) {
1488 goto fail;
1489 }
1490 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1491 trace_migration_completion_postcopy_end();
1492
1493 qemu_savevm_state_complete_postcopy(s->file);
1494 trace_migration_completion_postcopy_end_after_complete();
1495 }
1496
1497 /*
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
1501 * a SHUT command).
1502 * Postcopy opens rp if enabled (even if it's not avtivated)
1503 */
1504 if (migrate_postcopy_ram()) {
1505 int rp_error;
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);
1509 if (rp_error) {
1510 goto fail;
1511 }
1512 }
1513
1514 if (qemu_file_get_error(s->file)) {
1515 trace_migration_completion_file_err();
1516 goto fail;
1517 }
1518
1519 migrate_set_state(s, current_active_state, MIGRATION_STATUS_COMPLETED);
1520 return;
1521
1522 fail:
1523 migrate_set_state(s, current_active_state, MIGRATION_STATUS_FAILED);
1524 }
1525
1526 /*
1527 * Master migration thread on the source VM.
1528 * It drives the migration and pumps the data down the outgoing channel.
1529 */
1530 static void *migration_thread(void *opaque)
1531 {
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;
1539 int64_t end_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;
1544
1545 rcu_register_thread();
1546
1547 qemu_savevm_state_header(s->file);
1548
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);
1552
1553 /* And do a ping that will make stuff easier to debug */
1554 qemu_savevm_send_ping(s->file, 1);
1555
1556 /*
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
1559 * early.
1560 */
1561 qemu_savevm_send_postcopy_advise(s->file);
1562 }
1563
1564 qemu_savevm_state_begin(s->file, &s->params);
1565
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);
1569
1570 trace_migration_thread_setup_complete();
1571
1572 while (s->state == MIGRATION_STATUS_ACTIVE ||
1573 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1574 int64_t current_time;
1575 uint64_t pending_size;
1576
1577 if (!qemu_file_rate_limit(s->file)) {
1578 uint64_t pend_post, pend_nonpost;
1579
1580 qemu_savevm_state_pending(s->file, max_size, &pend_nonpost,
1581 &pend_post);
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 */
1587
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)) {
1593
1594 if (!postcopy_start(s, &old_vm_running)) {
1595 current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1596 entered_postcopy = true;
1597 }
1598
1599 continue;
1600 }
1601 /* Just another iteration step */
1602 qemu_savevm_state_iterate(s->file);
1603 } else {
1604 trace_migration_thread_low_pending(pending_size);
1605 migration_completion(s, current_active_state,
1606 &old_vm_running, &start_time);
1607 break;
1608 }
1609 }
1610
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();
1614 break;
1615 }
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;
1622
1623 s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /
1624 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;
1625
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;
1632 }
1633
1634 qemu_file_reset_rate_limit(s->file);
1635 initial_time = current_time;
1636 initial_bytes = qemu_ftell(s->file);
1637 }
1638 if (qemu_file_rate_limit(s->file)) {
1639 /* usleep expects microseconds */
1640 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1641 }
1642 }
1643
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);
1648
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;
1656 }
1657 if (s->total_time) {
1658 s->mbps = (((double) transferred_bytes * 8.0) /
1659 ((double) s->total_time)) / 1000;
1660 }
1661 runstate_set(RUN_STATE_POSTMIGRATE);
1662 } else {
1663 if (old_vm_running && !entered_postcopy) {
1664 vm_start();
1665 }
1666 }
1667 qemu_bh_schedule(s->cleanup_bh);
1668 qemu_mutex_unlock_iothread();
1669
1670 rcu_unregister_thread();
1671 return NULL;
1672 }
1673
1674 void migrate_fd_connect(MigrationState *s)
1675 {
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);
1679
1680 qemu_file_set_rate_limit(s->file,
1681 s->bandwidth_limit / XFER_LIMIT_RATIO);
1682
1683 /* Notify before starting migration thread */
1684 notifier_list_notify(&migration_state_notifiers, s);
1685
1686 /*
1687 * Open the return path; currently for postcopy but other things might
1688 * also want it.
1689 */
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);
1696 return;
1697 }
1698 }
1699
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;
1704 }
1705
1706 PostcopyState postcopy_state_get(void)
1707 {
1708 return atomic_mb_read(&incoming_postcopy_state);
1709 }
1710
1711 /* Set the state and return the old state */
1712 PostcopyState postcopy_state_set(PostcopyState new_state)
1713 {
1714 return atomic_xchg(&incoming_postcopy_state, new_state);
1715 }
1716