migration: force QEMUFile to blocking mode for outgoing migration
[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/osdep.h"
17 #include "qemu/cutils.h"
18 #include "qemu/error-report.h"
19 #include "qemu/main-loop.h"
20 #include "migration/migration.h"
21 #include "migration/qemu-file.h"
22 #include "sysemu/sysemu.h"
23 #include "block/block.h"
24 #include "qapi/qmp/qerror.h"
25 #include "qapi/util.h"
26 #include "qemu/sockets.h"
27 #include "qemu/rcu.h"
28 #include "migration/block.h"
29 #include "migration/postcopy-ram.h"
30 #include "qemu/thread.h"
31 #include "qmp-commands.h"
32 #include "trace.h"
33 #include "qapi-event.h"
34 #include "qom/cpu.h"
35 #include "exec/memory.h"
36 #include "exec/address-spaces.h"
37
38 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
39
40 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
41 * data. */
42 #define BUFFER_DELAY 100
43 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
44
45 /* Default compression thread count */
46 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
47 /* Default decompression thread count, usually decompression is at
48 * least 4 times as fast as compression.*/
49 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
50 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
51 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
52 /* Define default autoconverge cpu throttle migration parameters */
53 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
54 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
55
56 /* Migration XBZRLE default cache size */
57 #define DEFAULT_MIGRATE_CACHE_SIZE (64 * 1024 * 1024)
58
59 static NotifierList migration_state_notifiers =
60 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
61
62 static bool deferred_incoming;
63
64 /*
65 * Current state of incoming postcopy; note this is not part of
66 * MigrationIncomingState since it's state is used during cleanup
67 * at the end as MIS is being freed.
68 */
69 static PostcopyState incoming_postcopy_state;
70
71 /* When we add fault tolerance, we could have several
72 migrations at once. For now we don't need to add
73 dynamic creation of migration */
74
75 /* For outgoing */
76 MigrationState *migrate_get_current(void)
77 {
78 static bool once;
79 static MigrationState current_migration = {
80 .state = MIGRATION_STATUS_NONE,
81 .bandwidth_limit = MAX_THROTTLE,
82 .xbzrle_cache_size = DEFAULT_MIGRATE_CACHE_SIZE,
83 .mbps = -1,
84 .parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] =
85 DEFAULT_MIGRATE_COMPRESS_LEVEL,
86 .parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] =
87 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT,
88 .parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
89 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT,
90 .parameters[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL] =
91 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL,
92 .parameters[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT] =
93 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT,
94 };
95
96 if (!once) {
97 qemu_mutex_init(&current_migration.src_page_req_mutex);
98 once = true;
99 }
100 return &current_migration;
101 }
102
103 /* For incoming */
104 static MigrationIncomingState *mis_current;
105
106 MigrationIncomingState *migration_incoming_get_current(void)
107 {
108 return mis_current;
109 }
110
111 MigrationIncomingState *migration_incoming_state_new(QEMUFile* f)
112 {
113 mis_current = g_new0(MigrationIncomingState, 1);
114 mis_current->from_src_file = f;
115 mis_current->state = MIGRATION_STATUS_NONE;
116 QLIST_INIT(&mis_current->loadvm_handlers);
117 qemu_mutex_init(&mis_current->rp_mutex);
118 qemu_event_init(&mis_current->main_thread_load_event, false);
119
120 return mis_current;
121 }
122
123 void migration_incoming_state_destroy(void)
124 {
125 qemu_event_destroy(&mis_current->main_thread_load_event);
126 loadvm_free_handlers(mis_current);
127 g_free(mis_current);
128 mis_current = NULL;
129 }
130
131
132 typedef struct {
133 bool optional;
134 uint32_t size;
135 uint8_t runstate[100];
136 RunState state;
137 bool received;
138 } GlobalState;
139
140 static GlobalState global_state;
141
142 int global_state_store(void)
143 {
144 if (!runstate_store((char *)global_state.runstate,
145 sizeof(global_state.runstate))) {
146 error_report("runstate name too big: %s", global_state.runstate);
147 trace_migrate_state_too_big();
148 return -EINVAL;
149 }
150 return 0;
151 }
152
153 void global_state_store_running(void)
154 {
155 const char *state = RunState_lookup[RUN_STATE_RUNNING];
156 strncpy((char *)global_state.runstate,
157 state, sizeof(global_state.runstate));
158 }
159
160 static bool global_state_received(void)
161 {
162 return global_state.received;
163 }
164
165 static RunState global_state_get_runstate(void)
166 {
167 return global_state.state;
168 }
169
170 void global_state_set_optional(void)
171 {
172 global_state.optional = true;
173 }
174
175 static bool global_state_needed(void *opaque)
176 {
177 GlobalState *s = opaque;
178 char *runstate = (char *)s->runstate;
179
180 /* If it is not optional, it is mandatory */
181
182 if (s->optional == false) {
183 return true;
184 }
185
186 /* If state is running or paused, it is not needed */
187
188 if (strcmp(runstate, "running") == 0 ||
189 strcmp(runstate, "paused") == 0) {
190 return false;
191 }
192
193 /* for any other state it is needed */
194 return true;
195 }
196
197 static int global_state_post_load(void *opaque, int version_id)
198 {
199 GlobalState *s = opaque;
200 Error *local_err = NULL;
201 int r;
202 char *runstate = (char *)s->runstate;
203
204 s->received = true;
205 trace_migrate_global_state_post_load(runstate);
206
207 r = qapi_enum_parse(RunState_lookup, runstate, RUN_STATE__MAX,
208 -1, &local_err);
209
210 if (r == -1) {
211 if (local_err) {
212 error_report_err(local_err);
213 }
214 return -EINVAL;
215 }
216 s->state = r;
217
218 return 0;
219 }
220
221 static void global_state_pre_save(void *opaque)
222 {
223 GlobalState *s = opaque;
224
225 trace_migrate_global_state_pre_save((char *)s->runstate);
226 s->size = strlen((char *)s->runstate) + 1;
227 }
228
229 static const VMStateDescription vmstate_globalstate = {
230 .name = "globalstate",
231 .version_id = 1,
232 .minimum_version_id = 1,
233 .post_load = global_state_post_load,
234 .pre_save = global_state_pre_save,
235 .needed = global_state_needed,
236 .fields = (VMStateField[]) {
237 VMSTATE_UINT32(size, GlobalState),
238 VMSTATE_BUFFER(runstate, GlobalState),
239 VMSTATE_END_OF_LIST()
240 },
241 };
242
243 void register_global_state(void)
244 {
245 /* We would use it independently that we receive it */
246 strcpy((char *)&global_state.runstate, "");
247 global_state.received = false;
248 vmstate_register(NULL, 0, &vmstate_globalstate, &global_state);
249 }
250
251 static void migrate_generate_event(int new_state)
252 {
253 if (migrate_use_events()) {
254 qapi_event_send_migration(new_state, &error_abort);
255 }
256 }
257
258 /*
259 * Called on -incoming with a defer: uri.
260 * The migration can be started later after any parameters have been
261 * changed.
262 */
263 static void deferred_incoming_migration(Error **errp)
264 {
265 if (deferred_incoming) {
266 error_setg(errp, "Incoming migration already deferred");
267 }
268 deferred_incoming = true;
269 }
270
271 /* Request a range of pages from the source VM at the given
272 * start address.
273 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
274 * as the last request (a name must have been given previously)
275 * Start: Address offset within the RB
276 * Len: Length in bytes required - must be a multiple of pagesize
277 */
278 void migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
279 ram_addr_t start, size_t len)
280 {
281 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
282 size_t msglen = 12; /* start + len */
283
284 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
285 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
286
287 if (rbname) {
288 int rbname_len = strlen(rbname);
289 assert(rbname_len < 256);
290
291 bufc[msglen++] = rbname_len;
292 memcpy(bufc + msglen, rbname, rbname_len);
293 msglen += rbname_len;
294 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES_ID, msglen, bufc);
295 } else {
296 migrate_send_rp_message(mis, MIG_RP_MSG_REQ_PAGES, msglen, bufc);
297 }
298 }
299
300 void qemu_start_incoming_migration(const char *uri, Error **errp)
301 {
302 const char *p;
303
304 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
305 if (!strcmp(uri, "defer")) {
306 deferred_incoming_migration(errp);
307 } else if (strstart(uri, "tcp:", &p)) {
308 tcp_start_incoming_migration(p, errp);
309 #ifdef CONFIG_RDMA
310 } else if (strstart(uri, "rdma:", &p)) {
311 rdma_start_incoming_migration(p, errp);
312 #endif
313 #if !defined(WIN32)
314 } else if (strstart(uri, "exec:", &p)) {
315 exec_start_incoming_migration(p, errp);
316 } else if (strstart(uri, "unix:", &p)) {
317 unix_start_incoming_migration(p, errp);
318 } else if (strstart(uri, "fd:", &p)) {
319 fd_start_incoming_migration(p, errp);
320 #endif
321 } else {
322 error_setg(errp, "unknown migration protocol: %s", uri);
323 }
324 }
325
326 static void process_incoming_migration_bh(void *opaque)
327 {
328 Error *local_err = NULL;
329 MigrationIncomingState *mis = opaque;
330
331 /* Make sure all file formats flush their mutable metadata */
332 bdrv_invalidate_cache_all(&local_err);
333 if (local_err) {
334 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
335 MIGRATION_STATUS_FAILED);
336 error_report_err(local_err);
337 migrate_decompress_threads_join();
338 exit(EXIT_FAILURE);
339 }
340
341 /*
342 * This must happen after all error conditions are dealt with and
343 * we're sure the VM is going to be running on this host.
344 */
345 qemu_announce_self();
346
347 /* If global state section was not received or we are in running
348 state, we need to obey autostart. Any other state is set with
349 runstate_set. */
350
351 if (!global_state_received() ||
352 global_state_get_runstate() == RUN_STATE_RUNNING) {
353 if (autostart) {
354 vm_start();
355 } else {
356 runstate_set(RUN_STATE_PAUSED);
357 }
358 } else {
359 runstate_set(global_state_get_runstate());
360 }
361 migrate_decompress_threads_join();
362 /*
363 * This must happen after any state changes since as soon as an external
364 * observer sees this event they might start to prod at the VM assuming
365 * it's ready to use.
366 */
367 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
368 MIGRATION_STATUS_COMPLETED);
369 qemu_bh_delete(mis->bh);
370 migration_incoming_state_destroy();
371 }
372
373 static void process_incoming_migration_co(void *opaque)
374 {
375 QEMUFile *f = opaque;
376 MigrationIncomingState *mis;
377 PostcopyState ps;
378 int ret;
379
380 mis = migration_incoming_state_new(f);
381 postcopy_state_set(POSTCOPY_INCOMING_NONE);
382 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
383 MIGRATION_STATUS_ACTIVE);
384 ret = qemu_loadvm_state(f);
385
386 ps = postcopy_state_get();
387 trace_process_incoming_migration_co_end(ret, ps);
388 if (ps != POSTCOPY_INCOMING_NONE) {
389 if (ps == POSTCOPY_INCOMING_ADVISE) {
390 /*
391 * Where a migration had postcopy enabled (and thus went to advise)
392 * but managed to complete within the precopy period, we can use
393 * the normal exit.
394 */
395 postcopy_ram_incoming_cleanup(mis);
396 } else if (ret >= 0) {
397 /*
398 * Postcopy was started, cleanup should happen at the end of the
399 * postcopy thread.
400 */
401 trace_process_incoming_migration_co_postcopy_end_main();
402 return;
403 }
404 /* Else if something went wrong then just fall out of the normal exit */
405 }
406
407 qemu_fclose(f);
408 free_xbzrle_decoded_buf();
409
410 if (ret < 0) {
411 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
412 MIGRATION_STATUS_FAILED);
413 error_report("load of migration failed: %s", strerror(-ret));
414 migrate_decompress_threads_join();
415 exit(EXIT_FAILURE);
416 }
417
418 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
419 qemu_bh_schedule(mis->bh);
420 }
421
422 void process_incoming_migration(QEMUFile *f)
423 {
424 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co);
425
426 migrate_decompress_threads_create();
427 qemu_file_set_blocking(f, false);
428 qemu_coroutine_enter(co, f);
429 }
430
431 /*
432 * Send a message on the return channel back to the source
433 * of the migration.
434 */
435 void migrate_send_rp_message(MigrationIncomingState *mis,
436 enum mig_rp_message_type message_type,
437 uint16_t len, void *data)
438 {
439 trace_migrate_send_rp_message((int)message_type, len);
440 qemu_mutex_lock(&mis->rp_mutex);
441 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
442 qemu_put_be16(mis->to_src_file, len);
443 qemu_put_buffer(mis->to_src_file, data, len);
444 qemu_fflush(mis->to_src_file);
445 qemu_mutex_unlock(&mis->rp_mutex);
446 }
447
448 /*
449 * Send a 'SHUT' message on the return channel with the given value
450 * to indicate that we've finished with the RP. Non-0 value indicates
451 * error.
452 */
453 void migrate_send_rp_shut(MigrationIncomingState *mis,
454 uint32_t value)
455 {
456 uint32_t buf;
457
458 buf = cpu_to_be32(value);
459 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
460 }
461
462 /*
463 * Send a 'PONG' message on the return channel with the given value
464 * (normally in response to a 'PING')
465 */
466 void migrate_send_rp_pong(MigrationIncomingState *mis,
467 uint32_t value)
468 {
469 uint32_t buf;
470
471 buf = cpu_to_be32(value);
472 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
473 }
474
475 /* amount of nanoseconds we are willing to wait for migration to be down.
476 * the choice of nanoseconds is because it is the maximum resolution that
477 * get_clock() can achieve. It is an internal measure. All user-visible
478 * units must be in seconds */
479 static uint64_t max_downtime = 300000000;
480
481 uint64_t migrate_max_downtime(void)
482 {
483 return max_downtime;
484 }
485
486 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
487 {
488 MigrationCapabilityStatusList *head = NULL;
489 MigrationCapabilityStatusList *caps;
490 MigrationState *s = migrate_get_current();
491 int i;
492
493 caps = NULL; /* silence compiler warning */
494 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
495 if (head == NULL) {
496 head = g_malloc0(sizeof(*caps));
497 caps = head;
498 } else {
499 caps->next = g_malloc0(sizeof(*caps));
500 caps = caps->next;
501 }
502 caps->value =
503 g_malloc(sizeof(*caps->value));
504 caps->value->capability = i;
505 caps->value->state = s->enabled_capabilities[i];
506 }
507
508 return head;
509 }
510
511 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
512 {
513 MigrationParameters *params;
514 MigrationState *s = migrate_get_current();
515
516 params = g_malloc0(sizeof(*params));
517 params->compress_level = s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
518 params->compress_threads =
519 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
520 params->decompress_threads =
521 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
522 params->cpu_throttle_initial =
523 s->parameters[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL];
524 params->cpu_throttle_increment =
525 s->parameters[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT];
526
527 return params;
528 }
529
530 /*
531 * Return true if we're already in the middle of a migration
532 * (i.e. any of the active or setup states)
533 */
534 static bool migration_is_setup_or_active(int state)
535 {
536 switch (state) {
537 case MIGRATION_STATUS_ACTIVE:
538 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
539 case MIGRATION_STATUS_SETUP:
540 return true;
541
542 default:
543 return false;
544
545 }
546 }
547
548 static void get_xbzrle_cache_stats(MigrationInfo *info)
549 {
550 if (migrate_use_xbzrle()) {
551 info->has_xbzrle_cache = true;
552 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
553 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
554 info->xbzrle_cache->bytes = xbzrle_mig_bytes_transferred();
555 info->xbzrle_cache->pages = xbzrle_mig_pages_transferred();
556 info->xbzrle_cache->cache_miss = xbzrle_mig_pages_cache_miss();
557 info->xbzrle_cache->cache_miss_rate = xbzrle_mig_cache_miss_rate();
558 info->xbzrle_cache->overflow = xbzrle_mig_pages_overflow();
559 }
560 }
561
562 MigrationInfo *qmp_query_migrate(Error **errp)
563 {
564 MigrationInfo *info = g_malloc0(sizeof(*info));
565 MigrationState *s = migrate_get_current();
566
567 switch (s->state) {
568 case MIGRATION_STATUS_NONE:
569 /* no migration has happened ever */
570 break;
571 case MIGRATION_STATUS_SETUP:
572 info->has_status = true;
573 info->has_total_time = false;
574 break;
575 case MIGRATION_STATUS_ACTIVE:
576 case MIGRATION_STATUS_CANCELLING:
577 info->has_status = true;
578 info->has_total_time = true;
579 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
580 - s->total_time;
581 info->has_expected_downtime = true;
582 info->expected_downtime = s->expected_downtime;
583 info->has_setup_time = true;
584 info->setup_time = s->setup_time;
585
586 info->has_ram = true;
587 info->ram = g_malloc0(sizeof(*info->ram));
588 info->ram->transferred = ram_bytes_transferred();
589 info->ram->remaining = ram_bytes_remaining();
590 info->ram->total = ram_bytes_total();
591 info->ram->duplicate = dup_mig_pages_transferred();
592 info->ram->skipped = skipped_mig_pages_transferred();
593 info->ram->normal = norm_mig_pages_transferred();
594 info->ram->normal_bytes = norm_mig_bytes_transferred();
595 info->ram->dirty_pages_rate = s->dirty_pages_rate;
596 info->ram->mbps = s->mbps;
597 info->ram->dirty_sync_count = s->dirty_sync_count;
598
599 if (blk_mig_active()) {
600 info->has_disk = true;
601 info->disk = g_malloc0(sizeof(*info->disk));
602 info->disk->transferred = blk_mig_bytes_transferred();
603 info->disk->remaining = blk_mig_bytes_remaining();
604 info->disk->total = blk_mig_bytes_total();
605 }
606
607 if (cpu_throttle_active()) {
608 info->has_cpu_throttle_percentage = true;
609 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
610 }
611
612 get_xbzrle_cache_stats(info);
613 break;
614 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
615 /* Mostly the same as active; TODO add some postcopy stats */
616 info->has_status = true;
617 info->has_total_time = true;
618 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
619 - s->total_time;
620 info->has_expected_downtime = true;
621 info->expected_downtime = s->expected_downtime;
622 info->has_setup_time = true;
623 info->setup_time = s->setup_time;
624
625 info->has_ram = true;
626 info->ram = g_malloc0(sizeof(*info->ram));
627 info->ram->transferred = ram_bytes_transferred();
628 info->ram->remaining = ram_bytes_remaining();
629 info->ram->total = ram_bytes_total();
630 info->ram->duplicate = dup_mig_pages_transferred();
631 info->ram->skipped = skipped_mig_pages_transferred();
632 info->ram->normal = norm_mig_pages_transferred();
633 info->ram->normal_bytes = norm_mig_bytes_transferred();
634 info->ram->dirty_pages_rate = s->dirty_pages_rate;
635 info->ram->mbps = s->mbps;
636 info->ram->dirty_sync_count = s->dirty_sync_count;
637
638 if (blk_mig_active()) {
639 info->has_disk = true;
640 info->disk = g_malloc0(sizeof(*info->disk));
641 info->disk->transferred = blk_mig_bytes_transferred();
642 info->disk->remaining = blk_mig_bytes_remaining();
643 info->disk->total = blk_mig_bytes_total();
644 }
645
646 get_xbzrle_cache_stats(info);
647 break;
648 case MIGRATION_STATUS_COMPLETED:
649 get_xbzrle_cache_stats(info);
650
651 info->has_status = true;
652 info->has_total_time = true;
653 info->total_time = s->total_time;
654 info->has_downtime = true;
655 info->downtime = s->downtime;
656 info->has_setup_time = true;
657 info->setup_time = s->setup_time;
658
659 info->has_ram = true;
660 info->ram = g_malloc0(sizeof(*info->ram));
661 info->ram->transferred = ram_bytes_transferred();
662 info->ram->remaining = 0;
663 info->ram->total = ram_bytes_total();
664 info->ram->duplicate = dup_mig_pages_transferred();
665 info->ram->skipped = skipped_mig_pages_transferred();
666 info->ram->normal = norm_mig_pages_transferred();
667 info->ram->normal_bytes = norm_mig_bytes_transferred();
668 info->ram->mbps = s->mbps;
669 info->ram->dirty_sync_count = s->dirty_sync_count;
670 break;
671 case MIGRATION_STATUS_FAILED:
672 info->has_status = true;
673 break;
674 case MIGRATION_STATUS_CANCELLED:
675 info->has_status = true;
676 break;
677 }
678 info->status = s->state;
679
680 return info;
681 }
682
683 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
684 Error **errp)
685 {
686 MigrationState *s = migrate_get_current();
687 MigrationCapabilityStatusList *cap;
688
689 if (migration_is_setup_or_active(s->state)) {
690 error_setg(errp, QERR_MIGRATION_ACTIVE);
691 return;
692 }
693
694 for (cap = params; cap; cap = cap->next) {
695 s->enabled_capabilities[cap->value->capability] = cap->value->state;
696 }
697
698 if (migrate_postcopy_ram()) {
699 if (migrate_use_compression()) {
700 /* The decompression threads asynchronously write into RAM
701 * rather than use the atomic copies needed to avoid
702 * userfaulting. It should be possible to fix the decompression
703 * threads for compatibility in future.
704 */
705 error_report("Postcopy is not currently compatible with "
706 "compression");
707 s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM] =
708 false;
709 }
710 }
711 }
712
713 void qmp_migrate_set_parameters(bool has_compress_level,
714 int64_t compress_level,
715 bool has_compress_threads,
716 int64_t compress_threads,
717 bool has_decompress_threads,
718 int64_t decompress_threads,
719 bool has_cpu_throttle_initial,
720 int64_t cpu_throttle_initial,
721 bool has_cpu_throttle_increment,
722 int64_t cpu_throttle_increment, Error **errp)
723 {
724 MigrationState *s = migrate_get_current();
725
726 if (has_compress_level && (compress_level < 0 || compress_level > 9)) {
727 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
728 "is invalid, it should be in the range of 0 to 9");
729 return;
730 }
731 if (has_compress_threads &&
732 (compress_threads < 1 || compress_threads > 255)) {
733 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
734 "compress_threads",
735 "is invalid, it should be in the range of 1 to 255");
736 return;
737 }
738 if (has_decompress_threads &&
739 (decompress_threads < 1 || decompress_threads > 255)) {
740 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
741 "decompress_threads",
742 "is invalid, it should be in the range of 1 to 255");
743 return;
744 }
745 if (has_cpu_throttle_initial &&
746 (cpu_throttle_initial < 1 || cpu_throttle_initial > 99)) {
747 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
748 "cpu_throttle_initial",
749 "an integer in the range of 1 to 99");
750 }
751 if (has_cpu_throttle_increment &&
752 (cpu_throttle_increment < 1 || cpu_throttle_increment > 99)) {
753 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
754 "cpu_throttle_increment",
755 "an integer in the range of 1 to 99");
756 }
757
758 if (has_compress_level) {
759 s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL] = compress_level;
760 }
761 if (has_compress_threads) {
762 s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS] = compress_threads;
763 }
764 if (has_decompress_threads) {
765 s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS] =
766 decompress_threads;
767 }
768 if (has_cpu_throttle_initial) {
769 s->parameters[MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL] =
770 cpu_throttle_initial;
771 }
772
773 if (has_cpu_throttle_increment) {
774 s->parameters[MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT] =
775 cpu_throttle_increment;
776 }
777 }
778
779 void qmp_migrate_start_postcopy(Error **errp)
780 {
781 MigrationState *s = migrate_get_current();
782
783 if (!migrate_postcopy_ram()) {
784 error_setg(errp, "Enable postcopy with migrate_set_capability before"
785 " the start of migration");
786 return;
787 }
788
789 if (s->state == MIGRATION_STATUS_NONE) {
790 error_setg(errp, "Postcopy must be started after migration has been"
791 " started");
792 return;
793 }
794 /*
795 * we don't error if migration has finished since that would be racy
796 * with issuing this command.
797 */
798 atomic_set(&s->start_postcopy, true);
799 }
800
801 /* shared migration helpers */
802
803 void migrate_set_state(int *state, int old_state, int new_state)
804 {
805 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
806 trace_migrate_set_state(new_state);
807 migrate_generate_event(new_state);
808 }
809 }
810
811 static void migrate_fd_cleanup(void *opaque)
812 {
813 MigrationState *s = opaque;
814
815 qemu_bh_delete(s->cleanup_bh);
816 s->cleanup_bh = NULL;
817
818 flush_page_queue(s);
819
820 if (s->to_dst_file) {
821 trace_migrate_fd_cleanup();
822 qemu_mutex_unlock_iothread();
823 if (s->migration_thread_running) {
824 qemu_thread_join(&s->thread);
825 s->migration_thread_running = false;
826 }
827 qemu_mutex_lock_iothread();
828
829 migrate_compress_threads_join();
830 qemu_fclose(s->to_dst_file);
831 s->to_dst_file = NULL;
832 }
833
834 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
835 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
836
837 if (s->state == MIGRATION_STATUS_CANCELLING) {
838 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
839 MIGRATION_STATUS_CANCELLED);
840 }
841
842 notifier_list_notify(&migration_state_notifiers, s);
843 }
844
845 void migrate_fd_error(MigrationState *s)
846 {
847 trace_migrate_fd_error();
848 assert(s->to_dst_file == NULL);
849 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
850 MIGRATION_STATUS_FAILED);
851 notifier_list_notify(&migration_state_notifiers, s);
852 }
853
854 static void migrate_fd_cancel(MigrationState *s)
855 {
856 int old_state ;
857 QEMUFile *f = migrate_get_current()->to_dst_file;
858 trace_migrate_fd_cancel();
859
860 if (s->rp_state.from_dst_file) {
861 /* shutdown the rp socket, so causing the rp thread to shutdown */
862 qemu_file_shutdown(s->rp_state.from_dst_file);
863 }
864
865 do {
866 old_state = s->state;
867 if (!migration_is_setup_or_active(old_state)) {
868 break;
869 }
870 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
871 } while (s->state != MIGRATION_STATUS_CANCELLING);
872
873 /*
874 * If we're unlucky the migration code might be stuck somewhere in a
875 * send/write while the network has failed and is waiting to timeout;
876 * if we've got shutdown(2) available then we can force it to quit.
877 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
878 * called in a bh, so there is no race against this cancel.
879 */
880 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
881 qemu_file_shutdown(f);
882 }
883 }
884
885 void add_migration_state_change_notifier(Notifier *notify)
886 {
887 notifier_list_add(&migration_state_notifiers, notify);
888 }
889
890 void remove_migration_state_change_notifier(Notifier *notify)
891 {
892 notifier_remove(notify);
893 }
894
895 bool migration_in_setup(MigrationState *s)
896 {
897 return s->state == MIGRATION_STATUS_SETUP;
898 }
899
900 bool migration_has_finished(MigrationState *s)
901 {
902 return s->state == MIGRATION_STATUS_COMPLETED;
903 }
904
905 bool migration_has_failed(MigrationState *s)
906 {
907 return (s->state == MIGRATION_STATUS_CANCELLED ||
908 s->state == MIGRATION_STATUS_FAILED);
909 }
910
911 bool migration_in_postcopy(MigrationState *s)
912 {
913 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
914 }
915
916 bool migration_in_postcopy_after_devices(MigrationState *s)
917 {
918 return migration_in_postcopy(s) && s->postcopy_after_devices;
919 }
920
921 MigrationState *migrate_init(const MigrationParams *params)
922 {
923 MigrationState *s = migrate_get_current();
924
925 /*
926 * Reinitialise all migration state, except
927 * parameters/capabilities that the user set, and
928 * locks.
929 */
930 s->bytes_xfer = 0;
931 s->xfer_limit = 0;
932 s->cleanup_bh = 0;
933 s->to_dst_file = NULL;
934 s->state = MIGRATION_STATUS_NONE;
935 s->params = *params;
936 s->rp_state.from_dst_file = NULL;
937 s->rp_state.error = false;
938 s->mbps = 0.0;
939 s->downtime = 0;
940 s->expected_downtime = 0;
941 s->dirty_pages_rate = 0;
942 s->dirty_bytes_rate = 0;
943 s->setup_time = 0;
944 s->dirty_sync_count = 0;
945 s->start_postcopy = false;
946 s->postcopy_after_devices = false;
947 s->migration_thread_running = false;
948 s->last_req_rb = NULL;
949
950 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
951
952 QSIMPLEQ_INIT(&s->src_page_requests);
953
954 s->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
955 return s;
956 }
957
958 static GSList *migration_blockers;
959
960 void migrate_add_blocker(Error *reason)
961 {
962 migration_blockers = g_slist_prepend(migration_blockers, reason);
963 }
964
965 void migrate_del_blocker(Error *reason)
966 {
967 migration_blockers = g_slist_remove(migration_blockers, reason);
968 }
969
970 void qmp_migrate_incoming(const char *uri, Error **errp)
971 {
972 Error *local_err = NULL;
973 static bool once = true;
974
975 if (!deferred_incoming) {
976 error_setg(errp, "For use with '-incoming defer'");
977 return;
978 }
979 if (!once) {
980 error_setg(errp, "The incoming migration has already been started");
981 }
982
983 qemu_start_incoming_migration(uri, &local_err);
984
985 if (local_err) {
986 error_propagate(errp, local_err);
987 return;
988 }
989
990 once = false;
991 }
992
993 bool migration_is_blocked(Error **errp)
994 {
995 if (qemu_savevm_state_blocked(errp)) {
996 return true;
997 }
998
999 if (migration_blockers) {
1000 *errp = error_copy(migration_blockers->data);
1001 return true;
1002 }
1003
1004 return false;
1005 }
1006
1007 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1008 bool has_inc, bool inc, bool has_detach, bool detach,
1009 Error **errp)
1010 {
1011 Error *local_err = NULL;
1012 MigrationState *s = migrate_get_current();
1013 MigrationParams params;
1014 const char *p;
1015
1016 params.blk = has_blk && blk;
1017 params.shared = has_inc && inc;
1018
1019 if (migration_is_setup_or_active(s->state) ||
1020 s->state == MIGRATION_STATUS_CANCELLING) {
1021 error_setg(errp, QERR_MIGRATION_ACTIVE);
1022 return;
1023 }
1024 if (runstate_check(RUN_STATE_INMIGRATE)) {
1025 error_setg(errp, "Guest is waiting for an incoming migration");
1026 return;
1027 }
1028
1029 if (migration_is_blocked(errp)) {
1030 return;
1031 }
1032
1033 s = migrate_init(&params);
1034
1035 if (strstart(uri, "tcp:", &p)) {
1036 tcp_start_outgoing_migration(s, p, &local_err);
1037 #ifdef CONFIG_RDMA
1038 } else if (strstart(uri, "rdma:", &p)) {
1039 rdma_start_outgoing_migration(s, p, &local_err);
1040 #endif
1041 #if !defined(WIN32)
1042 } else if (strstart(uri, "exec:", &p)) {
1043 exec_start_outgoing_migration(s, p, &local_err);
1044 } else if (strstart(uri, "unix:", &p)) {
1045 unix_start_outgoing_migration(s, p, &local_err);
1046 } else if (strstart(uri, "fd:", &p)) {
1047 fd_start_outgoing_migration(s, p, &local_err);
1048 #endif
1049 } else {
1050 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1051 "a valid migration protocol");
1052 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1053 MIGRATION_STATUS_FAILED);
1054 return;
1055 }
1056
1057 if (local_err) {
1058 migrate_fd_error(s);
1059 error_propagate(errp, local_err);
1060 return;
1061 }
1062 }
1063
1064 void qmp_migrate_cancel(Error **errp)
1065 {
1066 migrate_fd_cancel(migrate_get_current());
1067 }
1068
1069 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1070 {
1071 MigrationState *s = migrate_get_current();
1072 int64_t new_size;
1073
1074 /* Check for truncation */
1075 if (value != (size_t)value) {
1076 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1077 "exceeding address space");
1078 return;
1079 }
1080
1081 /* Cache should not be larger than guest ram size */
1082 if (value > ram_bytes_total()) {
1083 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1084 "exceeds guest ram size ");
1085 return;
1086 }
1087
1088 new_size = xbzrle_cache_resize(value);
1089 if (new_size < 0) {
1090 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "cache size",
1091 "is smaller than page size");
1092 return;
1093 }
1094
1095 s->xbzrle_cache_size = new_size;
1096 }
1097
1098 int64_t qmp_query_migrate_cache_size(Error **errp)
1099 {
1100 return migrate_xbzrle_cache_size();
1101 }
1102
1103 void qmp_migrate_set_speed(int64_t value, Error **errp)
1104 {
1105 MigrationState *s;
1106
1107 if (value < 0) {
1108 value = 0;
1109 }
1110 if (value > SIZE_MAX) {
1111 value = SIZE_MAX;
1112 }
1113
1114 s = migrate_get_current();
1115 s->bandwidth_limit = value;
1116 if (s->to_dst_file) {
1117 qemu_file_set_rate_limit(s->to_dst_file,
1118 s->bandwidth_limit / XFER_LIMIT_RATIO);
1119 }
1120 }
1121
1122 void qmp_migrate_set_downtime(double value, Error **errp)
1123 {
1124 value *= 1e9;
1125 value = MAX(0, MIN(UINT64_MAX, value));
1126 max_downtime = (uint64_t)value;
1127 }
1128
1129 bool migrate_postcopy_ram(void)
1130 {
1131 MigrationState *s;
1132
1133 s = migrate_get_current();
1134
1135 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1136 }
1137
1138 bool migrate_auto_converge(void)
1139 {
1140 MigrationState *s;
1141
1142 s = migrate_get_current();
1143
1144 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1145 }
1146
1147 bool migrate_zero_blocks(void)
1148 {
1149 MigrationState *s;
1150
1151 s = migrate_get_current();
1152
1153 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1154 }
1155
1156 bool migrate_use_compression(void)
1157 {
1158 MigrationState *s;
1159
1160 s = migrate_get_current();
1161
1162 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1163 }
1164
1165 int migrate_compress_level(void)
1166 {
1167 MigrationState *s;
1168
1169 s = migrate_get_current();
1170
1171 return s->parameters[MIGRATION_PARAMETER_COMPRESS_LEVEL];
1172 }
1173
1174 int migrate_compress_threads(void)
1175 {
1176 MigrationState *s;
1177
1178 s = migrate_get_current();
1179
1180 return s->parameters[MIGRATION_PARAMETER_COMPRESS_THREADS];
1181 }
1182
1183 int migrate_decompress_threads(void)
1184 {
1185 MigrationState *s;
1186
1187 s = migrate_get_current();
1188
1189 return s->parameters[MIGRATION_PARAMETER_DECOMPRESS_THREADS];
1190 }
1191
1192 bool migrate_use_events(void)
1193 {
1194 MigrationState *s;
1195
1196 s = migrate_get_current();
1197
1198 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1199 }
1200
1201 int migrate_use_xbzrle(void)
1202 {
1203 MigrationState *s;
1204
1205 s = migrate_get_current();
1206
1207 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1208 }
1209
1210 int64_t migrate_xbzrle_cache_size(void)
1211 {
1212 MigrationState *s;
1213
1214 s = migrate_get_current();
1215
1216 return s->xbzrle_cache_size;
1217 }
1218
1219 /* migration thread support */
1220 /*
1221 * Something bad happened to the RP stream, mark an error
1222 * The caller shall print or trace something to indicate why
1223 */
1224 static void mark_source_rp_bad(MigrationState *s)
1225 {
1226 s->rp_state.error = true;
1227 }
1228
1229 static struct rp_cmd_args {
1230 ssize_t len; /* -1 = variable */
1231 const char *name;
1232 } rp_cmd_args[] = {
1233 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1234 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1235 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1236 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1237 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1238 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1239 };
1240
1241 /*
1242 * Process a request for pages received on the return path,
1243 * We're allowed to send more than requested (e.g. to round to our page size)
1244 * and we don't need to send pages that have already been sent.
1245 */
1246 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1247 ram_addr_t start, size_t len)
1248 {
1249 long our_host_ps = getpagesize();
1250
1251 trace_migrate_handle_rp_req_pages(rbname, start, len);
1252
1253 /*
1254 * Since we currently insist on matching page sizes, just sanity check
1255 * we're being asked for whole host pages.
1256 */
1257 if (start & (our_host_ps-1) ||
1258 (len & (our_host_ps-1))) {
1259 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1260 " len: %zd", __func__, start, len);
1261 mark_source_rp_bad(ms);
1262 return;
1263 }
1264
1265 if (ram_save_queue_pages(ms, rbname, start, len)) {
1266 mark_source_rp_bad(ms);
1267 }
1268 }
1269
1270 /*
1271 * Handles messages sent on the return path towards the source VM
1272 *
1273 */
1274 static void *source_return_path_thread(void *opaque)
1275 {
1276 MigrationState *ms = opaque;
1277 QEMUFile *rp = ms->rp_state.from_dst_file;
1278 uint16_t header_len, header_type;
1279 uint8_t buf[512];
1280 uint32_t tmp32, sibling_error;
1281 ram_addr_t start = 0; /* =0 to silence warning */
1282 size_t len = 0, expected_len;
1283 int res;
1284
1285 trace_source_return_path_thread_entry();
1286 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1287 migration_is_setup_or_active(ms->state)) {
1288 trace_source_return_path_thread_loop_top();
1289 header_type = qemu_get_be16(rp);
1290 header_len = qemu_get_be16(rp);
1291
1292 if (header_type >= MIG_RP_MSG_MAX ||
1293 header_type == MIG_RP_MSG_INVALID) {
1294 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1295 header_type, header_len);
1296 mark_source_rp_bad(ms);
1297 goto out;
1298 }
1299
1300 if ((rp_cmd_args[header_type].len != -1 &&
1301 header_len != rp_cmd_args[header_type].len) ||
1302 header_len > sizeof(buf)) {
1303 error_report("RP: Received '%s' message (0x%04x) with"
1304 "incorrect length %d expecting %zu",
1305 rp_cmd_args[header_type].name, header_type, header_len,
1306 (size_t)rp_cmd_args[header_type].len);
1307 mark_source_rp_bad(ms);
1308 goto out;
1309 }
1310
1311 /* We know we've got a valid header by this point */
1312 res = qemu_get_buffer(rp, buf, header_len);
1313 if (res != header_len) {
1314 error_report("RP: Failed reading data for message 0x%04x"
1315 " read %d expected %d",
1316 header_type, res, header_len);
1317 mark_source_rp_bad(ms);
1318 goto out;
1319 }
1320
1321 /* OK, we have the message and the data */
1322 switch (header_type) {
1323 case MIG_RP_MSG_SHUT:
1324 sibling_error = be32_to_cpup((uint32_t *)buf);
1325 trace_source_return_path_thread_shut(sibling_error);
1326 if (sibling_error) {
1327 error_report("RP: Sibling indicated error %d", sibling_error);
1328 mark_source_rp_bad(ms);
1329 }
1330 /*
1331 * We'll let the main thread deal with closing the RP
1332 * we could do a shutdown(2) on it, but we're the only user
1333 * anyway, so there's nothing gained.
1334 */
1335 goto out;
1336
1337 case MIG_RP_MSG_PONG:
1338 tmp32 = be32_to_cpup((uint32_t *)buf);
1339 trace_source_return_path_thread_pong(tmp32);
1340 break;
1341
1342 case MIG_RP_MSG_REQ_PAGES:
1343 start = be64_to_cpup((uint64_t *)buf);
1344 len = be32_to_cpup((uint32_t *)(buf + 8));
1345 migrate_handle_rp_req_pages(ms, NULL, start, len);
1346 break;
1347
1348 case MIG_RP_MSG_REQ_PAGES_ID:
1349 expected_len = 12 + 1; /* header + termination */
1350
1351 if (header_len >= expected_len) {
1352 start = be64_to_cpup((uint64_t *)buf);
1353 len = be32_to_cpup((uint32_t *)(buf + 8));
1354 /* Now we expect an idstr */
1355 tmp32 = buf[12]; /* Length of the following idstr */
1356 buf[13 + tmp32] = '\0';
1357 expected_len += tmp32;
1358 }
1359 if (header_len != expected_len) {
1360 error_report("RP: Req_Page_id with length %d expecting %zd",
1361 header_len, expected_len);
1362 mark_source_rp_bad(ms);
1363 goto out;
1364 }
1365 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1366 break;
1367
1368 default:
1369 break;
1370 }
1371 }
1372 if (qemu_file_get_error(rp)) {
1373 trace_source_return_path_thread_bad_end();
1374 mark_source_rp_bad(ms);
1375 }
1376
1377 trace_source_return_path_thread_end();
1378 out:
1379 ms->rp_state.from_dst_file = NULL;
1380 qemu_fclose(rp);
1381 return NULL;
1382 }
1383
1384 static int open_return_path_on_source(MigrationState *ms)
1385 {
1386
1387 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
1388 if (!ms->rp_state.from_dst_file) {
1389 return -1;
1390 }
1391
1392 trace_open_return_path_on_source();
1393 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1394 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1395
1396 trace_open_return_path_on_source_continue();
1397
1398 return 0;
1399 }
1400
1401 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1402 static int await_return_path_close_on_source(MigrationState *ms)
1403 {
1404 /*
1405 * If this is a normal exit then the destination will send a SHUT and the
1406 * rp_thread will exit, however if there's an error we need to cause
1407 * it to exit.
1408 */
1409 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
1410 /*
1411 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1412 * waiting for the destination.
1413 */
1414 qemu_file_shutdown(ms->rp_state.from_dst_file);
1415 mark_source_rp_bad(ms);
1416 }
1417 trace_await_return_path_close_on_source_joining();
1418 qemu_thread_join(&ms->rp_state.rp_thread);
1419 trace_await_return_path_close_on_source_close();
1420 return ms->rp_state.error;
1421 }
1422
1423 /*
1424 * Switch from normal iteration to postcopy
1425 * Returns non-0 on error
1426 */
1427 static int postcopy_start(MigrationState *ms, bool *old_vm_running)
1428 {
1429 int ret;
1430 const QEMUSizedBuffer *qsb;
1431 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1432 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1433 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1434
1435 trace_postcopy_start();
1436 qemu_mutex_lock_iothread();
1437 trace_postcopy_start_set_run();
1438
1439 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1440 *old_vm_running = runstate_is_running();
1441 global_state_store();
1442 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1443 if (ret < 0) {
1444 goto fail;
1445 }
1446
1447 ret = bdrv_inactivate_all();
1448 if (ret < 0) {
1449 goto fail;
1450 }
1451
1452 /*
1453 * Cause any non-postcopiable, but iterative devices to
1454 * send out their final data.
1455 */
1456 qemu_savevm_state_complete_precopy(ms->to_dst_file, true);
1457
1458 /*
1459 * in Finish migrate and with the io-lock held everything should
1460 * be quiet, but we've potentially still got dirty pages and we
1461 * need to tell the destination to throw any pages it's already received
1462 * that are dirty
1463 */
1464 if (ram_postcopy_send_discard_bitmap(ms)) {
1465 error_report("postcopy send discard bitmap failed");
1466 goto fail;
1467 }
1468
1469 /*
1470 * send rest of state - note things that are doing postcopy
1471 * will notice we're in POSTCOPY_ACTIVE and not actually
1472 * wrap their state up here
1473 */
1474 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
1475 /* Ping just for debugging, helps line traces up */
1476 qemu_savevm_send_ping(ms->to_dst_file, 2);
1477
1478 /*
1479 * While loading the device state we may trigger page transfer
1480 * requests and the fd must be free to process those, and thus
1481 * the destination must read the whole device state off the fd before
1482 * it starts processing it. Unfortunately the ad-hoc migration format
1483 * doesn't allow the destination to know the size to read without fully
1484 * parsing it through each devices load-state code (especially the open
1485 * coded devices that use get/put).
1486 * So we wrap the device state up in a package with a length at the start;
1487 * to do this we use a qemu_buf to hold the whole of the device state.
1488 */
1489 QEMUFile *fb = qemu_bufopen("w", NULL);
1490 if (!fb) {
1491 error_report("Failed to create buffered file");
1492 goto fail;
1493 }
1494
1495 /*
1496 * Make sure the receiver can get incoming pages before we send the rest
1497 * of the state
1498 */
1499 qemu_savevm_send_postcopy_listen(fb);
1500
1501 qemu_savevm_state_complete_precopy(fb, false);
1502 qemu_savevm_send_ping(fb, 3);
1503
1504 qemu_savevm_send_postcopy_run(fb);
1505
1506 /* <><> end of stuff going into the package */
1507 qsb = qemu_buf_get(fb);
1508
1509 /* Now send that blob */
1510 if (qemu_savevm_send_packaged(ms->to_dst_file, qsb)) {
1511 goto fail_closefb;
1512 }
1513 qemu_fclose(fb);
1514
1515 /* Send a notify to give a chance for anything that needs to happen
1516 * at the transition to postcopy and after the device state; in particular
1517 * spice needs to trigger a transition now
1518 */
1519 ms->postcopy_after_devices = true;
1520 notifier_list_notify(&migration_state_notifiers, ms);
1521
1522 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
1523
1524 qemu_mutex_unlock_iothread();
1525
1526 /*
1527 * Although this ping is just for debug, it could potentially be
1528 * used for getting a better measurement of downtime at the source.
1529 */
1530 qemu_savevm_send_ping(ms->to_dst_file, 4);
1531
1532 ret = qemu_file_get_error(ms->to_dst_file);
1533 if (ret) {
1534 error_report("postcopy_start: Migration stream errored");
1535 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1536 MIGRATION_STATUS_FAILED);
1537 }
1538
1539 return ret;
1540
1541 fail_closefb:
1542 qemu_fclose(fb);
1543 fail:
1544 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
1545 MIGRATION_STATUS_FAILED);
1546 qemu_mutex_unlock_iothread();
1547 return -1;
1548 }
1549
1550 /**
1551 * migration_completion: Used by migration_thread when there's not much left.
1552 * The caller 'breaks' the loop when this returns.
1553 *
1554 * @s: Current migration state
1555 * @current_active_state: The migration state we expect to be in
1556 * @*old_vm_running: Pointer to old_vm_running flag
1557 * @*start_time: Pointer to time to update
1558 */
1559 static void migration_completion(MigrationState *s, int current_active_state,
1560 bool *old_vm_running,
1561 int64_t *start_time)
1562 {
1563 int ret;
1564
1565 if (s->state == MIGRATION_STATUS_ACTIVE) {
1566 qemu_mutex_lock_iothread();
1567 *start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1568 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1569 *old_vm_running = runstate_is_running();
1570 ret = global_state_store();
1571
1572 if (!ret) {
1573 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1574 if (ret >= 0) {
1575 ret = bdrv_inactivate_all();
1576 }
1577 if (ret >= 0) {
1578 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
1579 qemu_savevm_state_complete_precopy(s->to_dst_file, false);
1580 }
1581 }
1582 qemu_mutex_unlock_iothread();
1583
1584 if (ret < 0) {
1585 goto fail;
1586 }
1587 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1588 trace_migration_completion_postcopy_end();
1589
1590 qemu_savevm_state_complete_postcopy(s->to_dst_file);
1591 trace_migration_completion_postcopy_end_after_complete();
1592 }
1593
1594 /*
1595 * If rp was opened we must clean up the thread before
1596 * cleaning everything else up (since if there are no failures
1597 * it will wait for the destination to send it's status in
1598 * a SHUT command).
1599 * Postcopy opens rp if enabled (even if it's not avtivated)
1600 */
1601 if (migrate_postcopy_ram()) {
1602 int rp_error;
1603 trace_migration_completion_postcopy_end_before_rp();
1604 rp_error = await_return_path_close_on_source(s);
1605 trace_migration_completion_postcopy_end_after_rp(rp_error);
1606 if (rp_error) {
1607 goto fail_invalidate;
1608 }
1609 }
1610
1611 if (qemu_file_get_error(s->to_dst_file)) {
1612 trace_migration_completion_file_err();
1613 goto fail_invalidate;
1614 }
1615
1616 migrate_set_state(&s->state, current_active_state,
1617 MIGRATION_STATUS_COMPLETED);
1618 return;
1619
1620 fail_invalidate:
1621 /* If not doing postcopy, vm_start() will be called: let's regain
1622 * control on images.
1623 */
1624 if (s->state == MIGRATION_STATUS_ACTIVE) {
1625 Error *local_err = NULL;
1626
1627 bdrv_invalidate_cache_all(&local_err);
1628 if (local_err) {
1629 error_report_err(local_err);
1630 }
1631 }
1632
1633 fail:
1634 migrate_set_state(&s->state, current_active_state,
1635 MIGRATION_STATUS_FAILED);
1636 }
1637
1638 /*
1639 * Master migration thread on the source VM.
1640 * It drives the migration and pumps the data down the outgoing channel.
1641 */
1642 static void *migration_thread(void *opaque)
1643 {
1644 MigrationState *s = opaque;
1645 /* Used by the bandwidth calcs, updated later */
1646 int64_t initial_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1647 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
1648 int64_t initial_bytes = 0;
1649 int64_t max_size = 0;
1650 int64_t start_time = initial_time;
1651 int64_t end_time;
1652 bool old_vm_running = false;
1653 bool entered_postcopy = false;
1654 /* The active state we expect to be in; ACTIVE or POSTCOPY_ACTIVE */
1655 enum MigrationStatus current_active_state = MIGRATION_STATUS_ACTIVE;
1656
1657 rcu_register_thread();
1658
1659 qemu_savevm_state_header(s->to_dst_file);
1660
1661 if (migrate_postcopy_ram()) {
1662 /* Now tell the dest that it should open its end so it can reply */
1663 qemu_savevm_send_open_return_path(s->to_dst_file);
1664
1665 /* And do a ping that will make stuff easier to debug */
1666 qemu_savevm_send_ping(s->to_dst_file, 1);
1667
1668 /*
1669 * Tell the destination that we *might* want to do postcopy later;
1670 * if the other end can't do postcopy it should fail now, nice and
1671 * early.
1672 */
1673 qemu_savevm_send_postcopy_advise(s->to_dst_file);
1674 }
1675
1676 qemu_savevm_state_begin(s->to_dst_file, &s->params);
1677
1678 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
1679 current_active_state = MIGRATION_STATUS_ACTIVE;
1680 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1681 MIGRATION_STATUS_ACTIVE);
1682
1683 trace_migration_thread_setup_complete();
1684
1685 while (s->state == MIGRATION_STATUS_ACTIVE ||
1686 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
1687 int64_t current_time;
1688 uint64_t pending_size;
1689
1690 if (!qemu_file_rate_limit(s->to_dst_file)) {
1691 uint64_t pend_post, pend_nonpost;
1692
1693 qemu_savevm_state_pending(s->to_dst_file, max_size, &pend_nonpost,
1694 &pend_post);
1695 pending_size = pend_nonpost + pend_post;
1696 trace_migrate_pending(pending_size, max_size,
1697 pend_post, pend_nonpost);
1698 if (pending_size && pending_size >= max_size) {
1699 /* Still a significant amount to transfer */
1700
1701 if (migrate_postcopy_ram() &&
1702 s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE &&
1703 pend_nonpost <= max_size &&
1704 atomic_read(&s->start_postcopy)) {
1705
1706 if (!postcopy_start(s, &old_vm_running)) {
1707 current_active_state = MIGRATION_STATUS_POSTCOPY_ACTIVE;
1708 entered_postcopy = true;
1709 }
1710
1711 continue;
1712 }
1713 /* Just another iteration step */
1714 qemu_savevm_state_iterate(s->to_dst_file, entered_postcopy);
1715 } else {
1716 trace_migration_thread_low_pending(pending_size);
1717 migration_completion(s, current_active_state,
1718 &old_vm_running, &start_time);
1719 break;
1720 }
1721 }
1722
1723 if (qemu_file_get_error(s->to_dst_file)) {
1724 migrate_set_state(&s->state, current_active_state,
1725 MIGRATION_STATUS_FAILED);
1726 trace_migration_thread_file_err();
1727 break;
1728 }
1729 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1730 if (current_time >= initial_time + BUFFER_DELAY) {
1731 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file) -
1732 initial_bytes;
1733 uint64_t time_spent = current_time - initial_time;
1734 double bandwidth = (double)transferred_bytes / time_spent;
1735 max_size = bandwidth * migrate_max_downtime() / 1000000;
1736
1737 s->mbps = (((double) transferred_bytes * 8.0) /
1738 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
1739
1740 trace_migrate_transferred(transferred_bytes, time_spent,
1741 bandwidth, max_size);
1742 /* if we haven't sent anything, we don't want to recalculate
1743 10000 is a small enough number for our purposes */
1744 if (s->dirty_bytes_rate && transferred_bytes > 10000) {
1745 s->expected_downtime = s->dirty_bytes_rate / bandwidth;
1746 }
1747
1748 qemu_file_reset_rate_limit(s->to_dst_file);
1749 initial_time = current_time;
1750 initial_bytes = qemu_ftell(s->to_dst_file);
1751 }
1752 if (qemu_file_rate_limit(s->to_dst_file)) {
1753 /* usleep expects microseconds */
1754 g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);
1755 }
1756 }
1757
1758 trace_migration_thread_after_loop();
1759 /* If we enabled cpu throttling for auto-converge, turn it off. */
1760 cpu_throttle_stop();
1761 end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1762
1763 qemu_mutex_lock_iothread();
1764 qemu_savevm_state_cleanup();
1765 if (s->state == MIGRATION_STATUS_COMPLETED) {
1766 uint64_t transferred_bytes = qemu_ftell(s->to_dst_file);
1767 s->total_time = end_time - s->total_time;
1768 if (!entered_postcopy) {
1769 s->downtime = end_time - start_time;
1770 }
1771 if (s->total_time) {
1772 s->mbps = (((double) transferred_bytes * 8.0) /
1773 ((double) s->total_time)) / 1000;
1774 }
1775 runstate_set(RUN_STATE_POSTMIGRATE);
1776 } else {
1777 if (old_vm_running && !entered_postcopy) {
1778 vm_start();
1779 }
1780 }
1781 qemu_bh_schedule(s->cleanup_bh);
1782 qemu_mutex_unlock_iothread();
1783
1784 rcu_unregister_thread();
1785 return NULL;
1786 }
1787
1788 void migrate_fd_connect(MigrationState *s)
1789 {
1790 /* This is a best 1st approximation. ns to ms */
1791 s->expected_downtime = max_downtime/1000000;
1792 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
1793
1794 qemu_file_set_blocking(s->to_dst_file, true);
1795 qemu_file_set_rate_limit(s->to_dst_file,
1796 s->bandwidth_limit / XFER_LIMIT_RATIO);
1797
1798 /* Notify before starting migration thread */
1799 notifier_list_notify(&migration_state_notifiers, s);
1800
1801 /*
1802 * Open the return path; currently for postcopy but other things might
1803 * also want it.
1804 */
1805 if (migrate_postcopy_ram()) {
1806 if (open_return_path_on_source(s)) {
1807 error_report("Unable to open return-path for postcopy");
1808 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1809 MIGRATION_STATUS_FAILED);
1810 migrate_fd_cleanup(s);
1811 return;
1812 }
1813 }
1814
1815 migrate_compress_threads_create();
1816 qemu_thread_create(&s->thread, "migration", migration_thread, s,
1817 QEMU_THREAD_JOINABLE);
1818 s->migration_thread_running = true;
1819 }
1820
1821 PostcopyState postcopy_state_get(void)
1822 {
1823 return atomic_mb_read(&incoming_postcopy_state);
1824 }
1825
1826 /* Set the state and return the old state */
1827 PostcopyState postcopy_state_set(PostcopyState new_state)
1828 {
1829 return atomic_xchg(&incoming_postcopy_state, new_state);
1830 }
1831