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