]> git.proxmox.com Git - mirror_qemu.git/blob - migration/migration.c
migration: Introduce multifd_recv_new_channel()
[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 "migration/blocker.h"
20 #include "exec.h"
21 #include "fd.h"
22 #include "socket.h"
23 #include "rdma.h"
24 #include "ram.h"
25 #include "migration/global_state.h"
26 #include "migration/misc.h"
27 #include "migration.h"
28 #include "savevm.h"
29 #include "qemu-file-channel.h"
30 #include "qemu-file.h"
31 #include "migration/vmstate.h"
32 #include "block/block.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-commands-migration.h"
35 #include "qapi/qapi-events-migration.h"
36 #include "qapi/qmp/qerror.h"
37 #include "qapi/qmp/qnull.h"
38 #include "qemu/rcu.h"
39 #include "block.h"
40 #include "postcopy-ram.h"
41 #include "qemu/thread.h"
42 #include "trace.h"
43 #include "exec/target_page.h"
44 #include "io/channel-buffer.h"
45 #include "migration/colo.h"
46 #include "hw/boards.h"
47 #include "monitor/monitor.h"
48
49 #define MAX_THROTTLE (32 << 20) /* Migration transfer speed throttling */
50
51 /* Amount of time to allocate to each "chunk" of bandwidth-throttled
52 * data. */
53 #define BUFFER_DELAY 100
54 #define XFER_LIMIT_RATIO (1000 / BUFFER_DELAY)
55
56 /* Time in milliseconds we are allowed to stop the source,
57 * for sending the last part */
58 #define DEFAULT_MIGRATE_SET_DOWNTIME 300
59
60 /* Maximum migrate downtime set to 2000 seconds */
61 #define MAX_MIGRATE_DOWNTIME_SECONDS 2000
62 #define MAX_MIGRATE_DOWNTIME (MAX_MIGRATE_DOWNTIME_SECONDS * 1000)
63
64 /* Default compression thread count */
65 #define DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT 8
66 /* Default decompression thread count, usually decompression is at
67 * least 4 times as fast as compression.*/
68 #define DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT 2
69 /*0: means nocompress, 1: best speed, ... 9: best compress ratio */
70 #define DEFAULT_MIGRATE_COMPRESS_LEVEL 1
71 /* Define default autoconverge cpu throttle migration parameters */
72 #define DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL 20
73 #define DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT 10
74
75 /* Migration XBZRLE default cache size */
76 #define DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE (64 * 1024 * 1024)
77
78 /* The delay time (in ms) between two COLO checkpoints
79 * Note: Please change this default value to 10000 when we support hybrid mode.
80 */
81 #define DEFAULT_MIGRATE_X_CHECKPOINT_DELAY 200
82 #define DEFAULT_MIGRATE_MULTIFD_CHANNELS 2
83 #define DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT 16
84
85 static NotifierList migration_state_notifiers =
86 NOTIFIER_LIST_INITIALIZER(migration_state_notifiers);
87
88 static bool deferred_incoming;
89
90 /* Messages sent on the return path from destination to source */
91 enum mig_rp_message_type {
92 MIG_RP_MSG_INVALID = 0, /* Must be 0 */
93 MIG_RP_MSG_SHUT, /* sibling will not send any more RP messages */
94 MIG_RP_MSG_PONG, /* Response to a PING; data (seq: be32 ) */
95
96 MIG_RP_MSG_REQ_PAGES_ID, /* data (start: be64, len: be32, id: string) */
97 MIG_RP_MSG_REQ_PAGES, /* data (start: be64, len: be32) */
98
99 MIG_RP_MSG_MAX
100 };
101
102 /* When we add fault tolerance, we could have several
103 migrations at once. For now we don't need to add
104 dynamic creation of migration */
105
106 static MigrationState *current_migration;
107
108 static bool migration_object_check(MigrationState *ms, Error **errp);
109 static int migration_maybe_pause(MigrationState *s,
110 int *current_active_state,
111 int new_state);
112
113 void migration_object_init(void)
114 {
115 MachineState *ms = MACHINE(qdev_get_machine());
116 Error *err = NULL;
117
118 /* This can only be called once. */
119 assert(!current_migration);
120 current_migration = MIGRATION_OBJ(object_new(TYPE_MIGRATION));
121
122 if (!migration_object_check(current_migration, &err)) {
123 error_report_err(err);
124 exit(1);
125 }
126
127 /*
128 * We cannot really do this in migration_instance_init() since at
129 * that time global properties are not yet applied, then this
130 * value will be definitely replaced by something else.
131 */
132 if (ms->enforce_config_section) {
133 current_migration->send_configuration = true;
134 }
135 }
136
137 void migration_object_finalize(void)
138 {
139 object_unref(OBJECT(current_migration));
140 }
141
142 /* For outgoing */
143 MigrationState *migrate_get_current(void)
144 {
145 /* This can only be called after the object created. */
146 assert(current_migration);
147 return current_migration;
148 }
149
150 MigrationIncomingState *migration_incoming_get_current(void)
151 {
152 static bool once;
153 static MigrationIncomingState mis_current;
154
155 if (!once) {
156 mis_current.state = MIGRATION_STATUS_NONE;
157 memset(&mis_current, 0, sizeof(MigrationIncomingState));
158 mis_current.postcopy_remote_fds = g_array_new(FALSE, TRUE,
159 sizeof(struct PostCopyFD));
160 qemu_mutex_init(&mis_current.rp_mutex);
161 qemu_event_init(&mis_current.main_thread_load_event, false);
162
163 init_dirty_bitmap_incoming_migration();
164
165 once = true;
166 }
167 return &mis_current;
168 }
169
170 void migration_incoming_state_destroy(void)
171 {
172 struct MigrationIncomingState *mis = migration_incoming_get_current();
173
174 if (mis->to_src_file) {
175 /* Tell source that we are done */
176 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
177 qemu_fclose(mis->to_src_file);
178 mis->to_src_file = NULL;
179 }
180
181 if (mis->from_src_file) {
182 qemu_fclose(mis->from_src_file);
183 mis->from_src_file = NULL;
184 }
185 if (mis->postcopy_remote_fds) {
186 g_array_free(mis->postcopy_remote_fds, TRUE);
187 mis->postcopy_remote_fds = NULL;
188 }
189
190 qemu_event_reset(&mis->main_thread_load_event);
191 }
192
193 static void migrate_generate_event(int new_state)
194 {
195 if (migrate_use_events()) {
196 qapi_event_send_migration(new_state, &error_abort);
197 }
198 }
199
200 /*
201 * Called on -incoming with a defer: uri.
202 * The migration can be started later after any parameters have been
203 * changed.
204 */
205 static void deferred_incoming_migration(Error **errp)
206 {
207 if (deferred_incoming) {
208 error_setg(errp, "Incoming migration already deferred");
209 }
210 deferred_incoming = true;
211 }
212
213 /*
214 * Send a message on the return channel back to the source
215 * of the migration.
216 */
217 static int migrate_send_rp_message(MigrationIncomingState *mis,
218 enum mig_rp_message_type message_type,
219 uint16_t len, void *data)
220 {
221 int ret = 0;
222
223 trace_migrate_send_rp_message((int)message_type, len);
224 qemu_mutex_lock(&mis->rp_mutex);
225
226 /*
227 * It's possible that the file handle got lost due to network
228 * failures.
229 */
230 if (!mis->to_src_file) {
231 ret = -EIO;
232 goto error;
233 }
234
235 qemu_put_be16(mis->to_src_file, (unsigned int)message_type);
236 qemu_put_be16(mis->to_src_file, len);
237 qemu_put_buffer(mis->to_src_file, data, len);
238 qemu_fflush(mis->to_src_file);
239
240 /* It's possible that qemu file got error during sending */
241 ret = qemu_file_get_error(mis->to_src_file);
242
243 error:
244 qemu_mutex_unlock(&mis->rp_mutex);
245 return ret;
246 }
247
248 /* Request a range of pages from the source VM at the given
249 * start address.
250 * rbname: Name of the RAMBlock to request the page in, if NULL it's the same
251 * as the last request (a name must have been given previously)
252 * Start: Address offset within the RB
253 * Len: Length in bytes required - must be a multiple of pagesize
254 */
255 int migrate_send_rp_req_pages(MigrationIncomingState *mis, const char *rbname,
256 ram_addr_t start, size_t len)
257 {
258 uint8_t bufc[12 + 1 + 255]; /* start (8), len (4), rbname up to 256 */
259 size_t msglen = 12; /* start + len */
260 enum mig_rp_message_type msg_type;
261
262 *(uint64_t *)bufc = cpu_to_be64((uint64_t)start);
263 *(uint32_t *)(bufc + 8) = cpu_to_be32((uint32_t)len);
264
265 if (rbname) {
266 int rbname_len = strlen(rbname);
267 assert(rbname_len < 256);
268
269 bufc[msglen++] = rbname_len;
270 memcpy(bufc + msglen, rbname, rbname_len);
271 msglen += rbname_len;
272 msg_type = MIG_RP_MSG_REQ_PAGES_ID;
273 } else {
274 msg_type = MIG_RP_MSG_REQ_PAGES;
275 }
276
277 return migrate_send_rp_message(mis, msg_type, msglen, bufc);
278 }
279
280 void qemu_start_incoming_migration(const char *uri, Error **errp)
281 {
282 const char *p;
283
284 qapi_event_send_migration(MIGRATION_STATUS_SETUP, &error_abort);
285 if (!strcmp(uri, "defer")) {
286 deferred_incoming_migration(errp);
287 } else if (strstart(uri, "tcp:", &p)) {
288 tcp_start_incoming_migration(p, errp);
289 #ifdef CONFIG_RDMA
290 } else if (strstart(uri, "rdma:", &p)) {
291 rdma_start_incoming_migration(p, errp);
292 #endif
293 } else if (strstart(uri, "exec:", &p)) {
294 exec_start_incoming_migration(p, errp);
295 } else if (strstart(uri, "unix:", &p)) {
296 unix_start_incoming_migration(p, errp);
297 } else if (strstart(uri, "fd:", &p)) {
298 fd_start_incoming_migration(p, errp);
299 } else {
300 error_setg(errp, "unknown migration protocol: %s", uri);
301 }
302 }
303
304 static void process_incoming_migration_bh(void *opaque)
305 {
306 Error *local_err = NULL;
307 MigrationIncomingState *mis = opaque;
308
309 /* Make sure all file formats flush their mutable metadata.
310 * If we get an error here, just don't restart the VM yet. */
311 bdrv_invalidate_cache_all(&local_err);
312 if (local_err) {
313 error_report_err(local_err);
314 local_err = NULL;
315 autostart = false;
316 }
317
318 /*
319 * This must happen after all error conditions are dealt with and
320 * we're sure the VM is going to be running on this host.
321 */
322 qemu_announce_self();
323
324 if (multifd_load_cleanup(&local_err) != 0) {
325 error_report_err(local_err);
326 autostart = false;
327 }
328 /* If global state section was not received or we are in running
329 state, we need to obey autostart. Any other state is set with
330 runstate_set. */
331
332 dirty_bitmap_mig_before_vm_start();
333
334 if (!global_state_received() ||
335 global_state_get_runstate() == RUN_STATE_RUNNING) {
336 if (autostart) {
337 vm_start();
338 } else {
339 runstate_set(RUN_STATE_PAUSED);
340 }
341 } else {
342 runstate_set(global_state_get_runstate());
343 }
344 /*
345 * This must happen after any state changes since as soon as an external
346 * observer sees this event they might start to prod at the VM assuming
347 * it's ready to use.
348 */
349 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
350 MIGRATION_STATUS_COMPLETED);
351 qemu_bh_delete(mis->bh);
352 migration_incoming_state_destroy();
353 }
354
355 static void process_incoming_migration_co(void *opaque)
356 {
357 MigrationIncomingState *mis = migration_incoming_get_current();
358 PostcopyState ps;
359 int ret;
360
361 assert(mis->from_src_file);
362 mis->largest_page_size = qemu_ram_pagesize_largest();
363 postcopy_state_set(POSTCOPY_INCOMING_NONE);
364 migrate_set_state(&mis->state, MIGRATION_STATUS_NONE,
365 MIGRATION_STATUS_ACTIVE);
366 ret = qemu_loadvm_state(mis->from_src_file);
367
368 ps = postcopy_state_get();
369 trace_process_incoming_migration_co_end(ret, ps);
370 if (ps != POSTCOPY_INCOMING_NONE) {
371 if (ps == POSTCOPY_INCOMING_ADVISE) {
372 /*
373 * Where a migration had postcopy enabled (and thus went to advise)
374 * but managed to complete within the precopy period, we can use
375 * the normal exit.
376 */
377 postcopy_ram_incoming_cleanup(mis);
378 } else if (ret >= 0) {
379 /*
380 * Postcopy was started, cleanup should happen at the end of the
381 * postcopy thread.
382 */
383 trace_process_incoming_migration_co_postcopy_end_main();
384 return;
385 }
386 /* Else if something went wrong then just fall out of the normal exit */
387 }
388
389 /* we get COLO info, and know if we are in COLO mode */
390 if (!ret && migration_incoming_enable_colo()) {
391 mis->migration_incoming_co = qemu_coroutine_self();
392 qemu_thread_create(&mis->colo_incoming_thread, "COLO incoming",
393 colo_process_incoming_thread, mis, QEMU_THREAD_JOINABLE);
394 mis->have_colo_incoming_thread = true;
395 qemu_coroutine_yield();
396
397 /* Wait checkpoint incoming thread exit before free resource */
398 qemu_thread_join(&mis->colo_incoming_thread);
399 }
400
401 if (ret < 0) {
402 Error *local_err = NULL;
403
404 migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,
405 MIGRATION_STATUS_FAILED);
406 error_report("load of migration failed: %s", strerror(-ret));
407 qemu_fclose(mis->from_src_file);
408 if (multifd_load_cleanup(&local_err) != 0) {
409 error_report_err(local_err);
410 }
411 exit(EXIT_FAILURE);
412 }
413 mis->bh = qemu_bh_new(process_incoming_migration_bh, mis);
414 qemu_bh_schedule(mis->bh);
415 }
416
417 static void migration_incoming_setup(QEMUFile *f)
418 {
419 MigrationIncomingState *mis = migration_incoming_get_current();
420
421 if (multifd_load_setup() != 0) {
422 /* We haven't been able to create multifd threads
423 nothing better to do */
424 exit(EXIT_FAILURE);
425 }
426
427 if (!mis->from_src_file) {
428 mis->from_src_file = f;
429 }
430 qemu_file_set_blocking(f, false);
431 }
432
433 static void migration_incoming_process(void)
434 {
435 Coroutine *co = qemu_coroutine_create(process_incoming_migration_co, NULL);
436 qemu_coroutine_enter(co);
437 }
438
439 void migration_fd_process_incoming(QEMUFile *f)
440 {
441 migration_incoming_setup(f);
442 migration_incoming_process();
443 }
444
445 void migration_ioc_process_incoming(QIOChannel *ioc)
446 {
447 MigrationIncomingState *mis = migration_incoming_get_current();
448
449 if (!mis->from_src_file) {
450 QEMUFile *f = qemu_fopen_channel_input(ioc);
451 migration_fd_process_incoming(f);
452 return;
453 }
454 multifd_recv_new_channel(ioc);
455 }
456
457 /**
458 * @migration_has_all_channels: We have received all channels that we need
459 *
460 * Returns true when we have got connections to all the channels that
461 * we need for migration.
462 */
463 bool migration_has_all_channels(void)
464 {
465 return true;
466 }
467
468 /*
469 * Send a 'SHUT' message on the return channel with the given value
470 * to indicate that we've finished with the RP. Non-0 value indicates
471 * error.
472 */
473 void migrate_send_rp_shut(MigrationIncomingState *mis,
474 uint32_t value)
475 {
476 uint32_t buf;
477
478 buf = cpu_to_be32(value);
479 migrate_send_rp_message(mis, MIG_RP_MSG_SHUT, sizeof(buf), &buf);
480 }
481
482 /*
483 * Send a 'PONG' message on the return channel with the given value
484 * (normally in response to a 'PING')
485 */
486 void migrate_send_rp_pong(MigrationIncomingState *mis,
487 uint32_t value)
488 {
489 uint32_t buf;
490
491 buf = cpu_to_be32(value);
492 migrate_send_rp_message(mis, MIG_RP_MSG_PONG, sizeof(buf), &buf);
493 }
494
495 MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)
496 {
497 MigrationCapabilityStatusList *head = NULL;
498 MigrationCapabilityStatusList *caps;
499 MigrationState *s = migrate_get_current();
500 int i;
501
502 caps = NULL; /* silence compiler warning */
503 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
504 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
505 if (i == MIGRATION_CAPABILITY_BLOCK) {
506 continue;
507 }
508 #endif
509 if (head == NULL) {
510 head = g_malloc0(sizeof(*caps));
511 caps = head;
512 } else {
513 caps->next = g_malloc0(sizeof(*caps));
514 caps = caps->next;
515 }
516 caps->value =
517 g_malloc(sizeof(*caps->value));
518 caps->value->capability = i;
519 caps->value->state = s->enabled_capabilities[i];
520 }
521
522 return head;
523 }
524
525 MigrationParameters *qmp_query_migrate_parameters(Error **errp)
526 {
527 MigrationParameters *params;
528 MigrationState *s = migrate_get_current();
529
530 /* TODO use QAPI_CLONE() instead of duplicating it inline */
531 params = g_malloc0(sizeof(*params));
532 params->has_compress_level = true;
533 params->compress_level = s->parameters.compress_level;
534 params->has_compress_threads = true;
535 params->compress_threads = s->parameters.compress_threads;
536 params->has_decompress_threads = true;
537 params->decompress_threads = s->parameters.decompress_threads;
538 params->has_cpu_throttle_initial = true;
539 params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;
540 params->has_cpu_throttle_increment = true;
541 params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;
542 params->has_tls_creds = true;
543 params->tls_creds = g_strdup(s->parameters.tls_creds);
544 params->has_tls_hostname = true;
545 params->tls_hostname = g_strdup(s->parameters.tls_hostname);
546 params->has_max_bandwidth = true;
547 params->max_bandwidth = s->parameters.max_bandwidth;
548 params->has_downtime_limit = true;
549 params->downtime_limit = s->parameters.downtime_limit;
550 params->has_x_checkpoint_delay = true;
551 params->x_checkpoint_delay = s->parameters.x_checkpoint_delay;
552 params->has_block_incremental = true;
553 params->block_incremental = s->parameters.block_incremental;
554 params->has_x_multifd_channels = true;
555 params->x_multifd_channels = s->parameters.x_multifd_channels;
556 params->has_x_multifd_page_count = true;
557 params->x_multifd_page_count = s->parameters.x_multifd_page_count;
558 params->has_xbzrle_cache_size = true;
559 params->xbzrle_cache_size = s->parameters.xbzrle_cache_size;
560
561 return params;
562 }
563
564 /*
565 * Return true if we're already in the middle of a migration
566 * (i.e. any of the active or setup states)
567 */
568 static bool migration_is_setup_or_active(int state)
569 {
570 switch (state) {
571 case MIGRATION_STATUS_ACTIVE:
572 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
573 case MIGRATION_STATUS_SETUP:
574 case MIGRATION_STATUS_PRE_SWITCHOVER:
575 case MIGRATION_STATUS_DEVICE:
576 return true;
577
578 default:
579 return false;
580
581 }
582 }
583
584 static void populate_ram_info(MigrationInfo *info, MigrationState *s)
585 {
586 info->has_ram = true;
587 info->ram = g_malloc0(sizeof(*info->ram));
588 info->ram->transferred = ram_counters.transferred;
589 info->ram->total = ram_bytes_total();
590 info->ram->duplicate = ram_counters.duplicate;
591 /* legacy value. It is not used anymore */
592 info->ram->skipped = 0;
593 info->ram->normal = ram_counters.normal;
594 info->ram->normal_bytes = ram_counters.normal *
595 qemu_target_page_size();
596 info->ram->mbps = s->mbps;
597 info->ram->dirty_sync_count = ram_counters.dirty_sync_count;
598 info->ram->postcopy_requests = ram_counters.postcopy_requests;
599 info->ram->page_size = qemu_target_page_size();
600
601 if (migrate_use_xbzrle()) {
602 info->has_xbzrle_cache = true;
603 info->xbzrle_cache = g_malloc0(sizeof(*info->xbzrle_cache));
604 info->xbzrle_cache->cache_size = migrate_xbzrle_cache_size();
605 info->xbzrle_cache->bytes = xbzrle_counters.bytes;
606 info->xbzrle_cache->pages = xbzrle_counters.pages;
607 info->xbzrle_cache->cache_miss = xbzrle_counters.cache_miss;
608 info->xbzrle_cache->cache_miss_rate = xbzrle_counters.cache_miss_rate;
609 info->xbzrle_cache->overflow = xbzrle_counters.overflow;
610 }
611
612 if (cpu_throttle_active()) {
613 info->has_cpu_throttle_percentage = true;
614 info->cpu_throttle_percentage = cpu_throttle_get_percentage();
615 }
616
617 if (s->state != MIGRATION_STATUS_COMPLETED) {
618 info->ram->remaining = ram_bytes_remaining();
619 info->ram->dirty_pages_rate = ram_counters.dirty_pages_rate;
620 }
621 }
622
623 static void populate_disk_info(MigrationInfo *info)
624 {
625 if (blk_mig_active()) {
626 info->has_disk = true;
627 info->disk = g_malloc0(sizeof(*info->disk));
628 info->disk->transferred = blk_mig_bytes_transferred();
629 info->disk->remaining = blk_mig_bytes_remaining();
630 info->disk->total = blk_mig_bytes_total();
631 }
632 }
633
634 static void fill_source_migration_info(MigrationInfo *info)
635 {
636 MigrationState *s = migrate_get_current();
637
638 switch (s->state) {
639 case MIGRATION_STATUS_NONE:
640 /* no migration has happened ever */
641 /* do not overwrite destination migration status */
642 return;
643 break;
644 case MIGRATION_STATUS_SETUP:
645 info->has_status = true;
646 info->has_total_time = false;
647 break;
648 case MIGRATION_STATUS_ACTIVE:
649 case MIGRATION_STATUS_CANCELLING:
650 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
651 case MIGRATION_STATUS_PRE_SWITCHOVER:
652 case MIGRATION_STATUS_DEVICE:
653 /* TODO add some postcopy stats */
654 info->has_status = true;
655 info->has_total_time = true;
656 info->total_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
657 - s->start_time;
658 info->has_expected_downtime = true;
659 info->expected_downtime = s->expected_downtime;
660 info->has_setup_time = true;
661 info->setup_time = s->setup_time;
662
663 populate_ram_info(info, s);
664 populate_disk_info(info);
665 break;
666 case MIGRATION_STATUS_COLO:
667 info->has_status = true;
668 /* TODO: display COLO specific information (checkpoint info etc.) */
669 break;
670 case MIGRATION_STATUS_COMPLETED:
671 info->has_status = true;
672 info->has_total_time = true;
673 info->total_time = s->total_time;
674 info->has_downtime = true;
675 info->downtime = s->downtime;
676 info->has_setup_time = true;
677 info->setup_time = s->setup_time;
678
679 populate_ram_info(info, s);
680 break;
681 case MIGRATION_STATUS_FAILED:
682 info->has_status = true;
683 if (s->error) {
684 info->has_error_desc = true;
685 info->error_desc = g_strdup(error_get_pretty(s->error));
686 }
687 break;
688 case MIGRATION_STATUS_CANCELLED:
689 info->has_status = true;
690 break;
691 }
692 info->status = s->state;
693 }
694
695 /**
696 * @migration_caps_check - check capability validity
697 *
698 * @cap_list: old capability list, array of bool
699 * @params: new capabilities to be applied soon
700 * @errp: set *errp if the check failed, with reason
701 *
702 * Returns true if check passed, otherwise false.
703 */
704 static bool migrate_caps_check(bool *cap_list,
705 MigrationCapabilityStatusList *params,
706 Error **errp)
707 {
708 MigrationCapabilityStatusList *cap;
709 bool old_postcopy_cap;
710 MigrationIncomingState *mis = migration_incoming_get_current();
711
712 old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];
713
714 for (cap = params; cap; cap = cap->next) {
715 cap_list[cap->value->capability] = cap->value->state;
716 }
717
718 #ifndef CONFIG_LIVE_BLOCK_MIGRATION
719 if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {
720 error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "
721 "block migration");
722 error_append_hint(errp, "Use drive_mirror+NBD instead.\n");
723 return false;
724 }
725 #endif
726
727 if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {
728 if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {
729 /* The decompression threads asynchronously write into RAM
730 * rather than use the atomic copies needed to avoid
731 * userfaulting. It should be possible to fix the decompression
732 * threads for compatibility in future.
733 */
734 error_setg(errp, "Postcopy is not currently compatible "
735 "with compression");
736 return false;
737 }
738
739 /* This check is reasonably expensive, so only when it's being
740 * set the first time, also it's only the destination that needs
741 * special support.
742 */
743 if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&
744 !postcopy_ram_supported_by_host(mis)) {
745 /* postcopy_ram_supported_by_host will have emitted a more
746 * detailed message
747 */
748 error_setg(errp, "Postcopy is not supported");
749 return false;
750 }
751 }
752
753 return true;
754 }
755
756 static void fill_destination_migration_info(MigrationInfo *info)
757 {
758 MigrationIncomingState *mis = migration_incoming_get_current();
759
760 switch (mis->state) {
761 case MIGRATION_STATUS_NONE:
762 return;
763 break;
764 case MIGRATION_STATUS_SETUP:
765 case MIGRATION_STATUS_CANCELLING:
766 case MIGRATION_STATUS_CANCELLED:
767 case MIGRATION_STATUS_ACTIVE:
768 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
769 case MIGRATION_STATUS_FAILED:
770 case MIGRATION_STATUS_COLO:
771 info->has_status = true;
772 break;
773 case MIGRATION_STATUS_COMPLETED:
774 info->has_status = true;
775 fill_destination_postcopy_migration_info(info);
776 break;
777 }
778 info->status = mis->state;
779 }
780
781 MigrationInfo *qmp_query_migrate(Error **errp)
782 {
783 MigrationInfo *info = g_malloc0(sizeof(*info));
784
785 fill_destination_migration_info(info);
786 fill_source_migration_info(info);
787
788 return info;
789 }
790
791 void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,
792 Error **errp)
793 {
794 MigrationState *s = migrate_get_current();
795 MigrationCapabilityStatusList *cap;
796 bool cap_list[MIGRATION_CAPABILITY__MAX];
797
798 if (migration_is_setup_or_active(s->state)) {
799 error_setg(errp, QERR_MIGRATION_ACTIVE);
800 return;
801 }
802
803 memcpy(cap_list, s->enabled_capabilities, sizeof(cap_list));
804 if (!migrate_caps_check(cap_list, params, errp)) {
805 return;
806 }
807
808 for (cap = params; cap; cap = cap->next) {
809 s->enabled_capabilities[cap->value->capability] = cap->value->state;
810 }
811 }
812
813 /*
814 * Check whether the parameters are valid. Error will be put into errp
815 * (if provided). Return true if valid, otherwise false.
816 */
817 static bool migrate_params_check(MigrationParameters *params, Error **errp)
818 {
819 if (params->has_compress_level &&
820 (params->compress_level > 9)) {
821 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "compress_level",
822 "is invalid, it should be in the range of 0 to 9");
823 return false;
824 }
825
826 if (params->has_compress_threads && (params->compress_threads < 1)) {
827 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
828 "compress_threads",
829 "is invalid, it should be in the range of 1 to 255");
830 return false;
831 }
832
833 if (params->has_decompress_threads && (params->decompress_threads < 1)) {
834 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
835 "decompress_threads",
836 "is invalid, it should be in the range of 1 to 255");
837 return false;
838 }
839
840 if (params->has_cpu_throttle_initial &&
841 (params->cpu_throttle_initial < 1 ||
842 params->cpu_throttle_initial > 99)) {
843 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
844 "cpu_throttle_initial",
845 "an integer in the range of 1 to 99");
846 return false;
847 }
848
849 if (params->has_cpu_throttle_increment &&
850 (params->cpu_throttle_increment < 1 ||
851 params->cpu_throttle_increment > 99)) {
852 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
853 "cpu_throttle_increment",
854 "an integer in the range of 1 to 99");
855 return false;
856 }
857
858 if (params->has_max_bandwidth && (params->max_bandwidth > SIZE_MAX)) {
859 error_setg(errp, "Parameter 'max_bandwidth' expects an integer in the"
860 " range of 0 to %zu bytes/second", SIZE_MAX);
861 return false;
862 }
863
864 if (params->has_downtime_limit &&
865 (params->downtime_limit > MAX_MIGRATE_DOWNTIME)) {
866 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
867 "the range of 0 to %d milliseconds",
868 MAX_MIGRATE_DOWNTIME);
869 return false;
870 }
871
872 /* x_checkpoint_delay is now always positive */
873
874 if (params->has_x_multifd_channels && (params->x_multifd_channels < 1)) {
875 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
876 "multifd_channels",
877 "is invalid, it should be in the range of 1 to 255");
878 return false;
879 }
880 if (params->has_x_multifd_page_count &&
881 (params->x_multifd_page_count < 1 ||
882 params->x_multifd_page_count > 10000)) {
883 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
884 "multifd_page_count",
885 "is invalid, it should be in the range of 1 to 10000");
886 return false;
887 }
888
889 if (params->has_xbzrle_cache_size &&
890 (params->xbzrle_cache_size < qemu_target_page_size() ||
891 !is_power_of_2(params->xbzrle_cache_size))) {
892 error_setg(errp, QERR_INVALID_PARAMETER_VALUE,
893 "xbzrle_cache_size",
894 "is invalid, it should be bigger than target page size"
895 " and a power of two");
896 return false;
897 }
898
899 return true;
900 }
901
902 static void migrate_params_test_apply(MigrateSetParameters *params,
903 MigrationParameters *dest)
904 {
905 *dest = migrate_get_current()->parameters;
906
907 /* TODO use QAPI_CLONE() instead of duplicating it inline */
908
909 if (params->has_compress_level) {
910 dest->compress_level = params->compress_level;
911 }
912
913 if (params->has_compress_threads) {
914 dest->compress_threads = params->compress_threads;
915 }
916
917 if (params->has_decompress_threads) {
918 dest->decompress_threads = params->decompress_threads;
919 }
920
921 if (params->has_cpu_throttle_initial) {
922 dest->cpu_throttle_initial = params->cpu_throttle_initial;
923 }
924
925 if (params->has_cpu_throttle_increment) {
926 dest->cpu_throttle_increment = params->cpu_throttle_increment;
927 }
928
929 if (params->has_tls_creds) {
930 assert(params->tls_creds->type == QTYPE_QSTRING);
931 dest->tls_creds = g_strdup(params->tls_creds->u.s);
932 }
933
934 if (params->has_tls_hostname) {
935 assert(params->tls_hostname->type == QTYPE_QSTRING);
936 dest->tls_hostname = g_strdup(params->tls_hostname->u.s);
937 }
938
939 if (params->has_max_bandwidth) {
940 dest->max_bandwidth = params->max_bandwidth;
941 }
942
943 if (params->has_downtime_limit) {
944 dest->downtime_limit = params->downtime_limit;
945 }
946
947 if (params->has_x_checkpoint_delay) {
948 dest->x_checkpoint_delay = params->x_checkpoint_delay;
949 }
950
951 if (params->has_block_incremental) {
952 dest->block_incremental = params->block_incremental;
953 }
954 if (params->has_x_multifd_channels) {
955 dest->x_multifd_channels = params->x_multifd_channels;
956 }
957 if (params->has_x_multifd_page_count) {
958 dest->x_multifd_page_count = params->x_multifd_page_count;
959 }
960 if (params->has_xbzrle_cache_size) {
961 dest->xbzrle_cache_size = params->xbzrle_cache_size;
962 }
963 }
964
965 static void migrate_params_apply(MigrateSetParameters *params, Error **errp)
966 {
967 MigrationState *s = migrate_get_current();
968
969 /* TODO use QAPI_CLONE() instead of duplicating it inline */
970
971 if (params->has_compress_level) {
972 s->parameters.compress_level = params->compress_level;
973 }
974
975 if (params->has_compress_threads) {
976 s->parameters.compress_threads = params->compress_threads;
977 }
978
979 if (params->has_decompress_threads) {
980 s->parameters.decompress_threads = params->decompress_threads;
981 }
982
983 if (params->has_cpu_throttle_initial) {
984 s->parameters.cpu_throttle_initial = params->cpu_throttle_initial;
985 }
986
987 if (params->has_cpu_throttle_increment) {
988 s->parameters.cpu_throttle_increment = params->cpu_throttle_increment;
989 }
990
991 if (params->has_tls_creds) {
992 g_free(s->parameters.tls_creds);
993 assert(params->tls_creds->type == QTYPE_QSTRING);
994 s->parameters.tls_creds = g_strdup(params->tls_creds->u.s);
995 }
996
997 if (params->has_tls_hostname) {
998 g_free(s->parameters.tls_hostname);
999 assert(params->tls_hostname->type == QTYPE_QSTRING);
1000 s->parameters.tls_hostname = g_strdup(params->tls_hostname->u.s);
1001 }
1002
1003 if (params->has_max_bandwidth) {
1004 s->parameters.max_bandwidth = params->max_bandwidth;
1005 if (s->to_dst_file) {
1006 qemu_file_set_rate_limit(s->to_dst_file,
1007 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
1008 }
1009 }
1010
1011 if (params->has_downtime_limit) {
1012 s->parameters.downtime_limit = params->downtime_limit;
1013 }
1014
1015 if (params->has_x_checkpoint_delay) {
1016 s->parameters.x_checkpoint_delay = params->x_checkpoint_delay;
1017 if (migration_in_colo_state()) {
1018 colo_checkpoint_notify(s);
1019 }
1020 }
1021
1022 if (params->has_block_incremental) {
1023 s->parameters.block_incremental = params->block_incremental;
1024 }
1025 if (params->has_x_multifd_channels) {
1026 s->parameters.x_multifd_channels = params->x_multifd_channels;
1027 }
1028 if (params->has_x_multifd_page_count) {
1029 s->parameters.x_multifd_page_count = params->x_multifd_page_count;
1030 }
1031 if (params->has_xbzrle_cache_size) {
1032 s->parameters.xbzrle_cache_size = params->xbzrle_cache_size;
1033 xbzrle_cache_resize(params->xbzrle_cache_size, errp);
1034 }
1035 }
1036
1037 void qmp_migrate_set_parameters(MigrateSetParameters *params, Error **errp)
1038 {
1039 MigrationParameters tmp;
1040
1041 /* TODO Rewrite "" to null instead */
1042 if (params->has_tls_creds
1043 && params->tls_creds->type == QTYPE_QNULL) {
1044 qobject_unref(params->tls_creds->u.n);
1045 params->tls_creds->type = QTYPE_QSTRING;
1046 params->tls_creds->u.s = strdup("");
1047 }
1048 /* TODO Rewrite "" to null instead */
1049 if (params->has_tls_hostname
1050 && params->tls_hostname->type == QTYPE_QNULL) {
1051 qobject_unref(params->tls_hostname->u.n);
1052 params->tls_hostname->type = QTYPE_QSTRING;
1053 params->tls_hostname->u.s = strdup("");
1054 }
1055
1056 migrate_params_test_apply(params, &tmp);
1057
1058 if (!migrate_params_check(&tmp, errp)) {
1059 /* Invalid parameter */
1060 return;
1061 }
1062
1063 migrate_params_apply(params, errp);
1064 }
1065
1066
1067 void qmp_migrate_start_postcopy(Error **errp)
1068 {
1069 MigrationState *s = migrate_get_current();
1070
1071 if (!migrate_postcopy()) {
1072 error_setg(errp, "Enable postcopy with migrate_set_capability before"
1073 " the start of migration");
1074 return;
1075 }
1076
1077 if (s->state == MIGRATION_STATUS_NONE) {
1078 error_setg(errp, "Postcopy must be started after migration has been"
1079 " started");
1080 return;
1081 }
1082 /*
1083 * we don't error if migration has finished since that would be racy
1084 * with issuing this command.
1085 */
1086 atomic_set(&s->start_postcopy, true);
1087 }
1088
1089 /* shared migration helpers */
1090
1091 void migrate_set_state(int *state, int old_state, int new_state)
1092 {
1093 assert(new_state < MIGRATION_STATUS__MAX);
1094 if (atomic_cmpxchg(state, old_state, new_state) == old_state) {
1095 trace_migrate_set_state(MigrationStatus_str(new_state));
1096 migrate_generate_event(new_state);
1097 }
1098 }
1099
1100 static MigrationCapabilityStatusList *migrate_cap_add(
1101 MigrationCapabilityStatusList *list,
1102 MigrationCapability index,
1103 bool state)
1104 {
1105 MigrationCapabilityStatusList *cap;
1106
1107 cap = g_new0(MigrationCapabilityStatusList, 1);
1108 cap->value = g_new0(MigrationCapabilityStatus, 1);
1109 cap->value->capability = index;
1110 cap->value->state = state;
1111 cap->next = list;
1112
1113 return cap;
1114 }
1115
1116 void migrate_set_block_enabled(bool value, Error **errp)
1117 {
1118 MigrationCapabilityStatusList *cap;
1119
1120 cap = migrate_cap_add(NULL, MIGRATION_CAPABILITY_BLOCK, value);
1121 qmp_migrate_set_capabilities(cap, errp);
1122 qapi_free_MigrationCapabilityStatusList(cap);
1123 }
1124
1125 static void migrate_set_block_incremental(MigrationState *s, bool value)
1126 {
1127 s->parameters.block_incremental = value;
1128 }
1129
1130 static void block_cleanup_parameters(MigrationState *s)
1131 {
1132 if (s->must_remove_block_options) {
1133 /* setting to false can never fail */
1134 migrate_set_block_enabled(false, &error_abort);
1135 migrate_set_block_incremental(s, false);
1136 s->must_remove_block_options = false;
1137 }
1138 }
1139
1140 static void migrate_fd_cleanup(void *opaque)
1141 {
1142 MigrationState *s = opaque;
1143
1144 qemu_bh_delete(s->cleanup_bh);
1145 s->cleanup_bh = NULL;
1146
1147 qemu_savevm_state_cleanup();
1148
1149 if (s->to_dst_file) {
1150 Error *local_err = NULL;
1151
1152 trace_migrate_fd_cleanup();
1153 qemu_mutex_unlock_iothread();
1154 if (s->migration_thread_running) {
1155 qemu_thread_join(&s->thread);
1156 s->migration_thread_running = false;
1157 }
1158 qemu_mutex_lock_iothread();
1159
1160 if (multifd_save_cleanup(&local_err) != 0) {
1161 error_report_err(local_err);
1162 }
1163 qemu_fclose(s->to_dst_file);
1164 s->to_dst_file = NULL;
1165 }
1166
1167 assert((s->state != MIGRATION_STATUS_ACTIVE) &&
1168 (s->state != MIGRATION_STATUS_POSTCOPY_ACTIVE));
1169
1170 if (s->state == MIGRATION_STATUS_CANCELLING) {
1171 migrate_set_state(&s->state, MIGRATION_STATUS_CANCELLING,
1172 MIGRATION_STATUS_CANCELLED);
1173 }
1174
1175 if (s->error) {
1176 /* It is used on info migrate. We can't free it */
1177 error_report_err(error_copy(s->error));
1178 }
1179 notifier_list_notify(&migration_state_notifiers, s);
1180 block_cleanup_parameters(s);
1181 }
1182
1183 void migrate_set_error(MigrationState *s, const Error *error)
1184 {
1185 qemu_mutex_lock(&s->error_mutex);
1186 if (!s->error) {
1187 s->error = error_copy(error);
1188 }
1189 qemu_mutex_unlock(&s->error_mutex);
1190 }
1191
1192 void migrate_fd_error(MigrationState *s, const Error *error)
1193 {
1194 trace_migrate_fd_error(error_get_pretty(error));
1195 assert(s->to_dst_file == NULL);
1196 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1197 MIGRATION_STATUS_FAILED);
1198 migrate_set_error(s, error);
1199 }
1200
1201 static void migrate_fd_cancel(MigrationState *s)
1202 {
1203 int old_state ;
1204 QEMUFile *f = migrate_get_current()->to_dst_file;
1205 trace_migrate_fd_cancel();
1206
1207 if (s->rp_state.from_dst_file) {
1208 /* shutdown the rp socket, so causing the rp thread to shutdown */
1209 qemu_file_shutdown(s->rp_state.from_dst_file);
1210 }
1211
1212 do {
1213 old_state = s->state;
1214 if (!migration_is_setup_or_active(old_state)) {
1215 break;
1216 }
1217 /* If the migration is paused, kick it out of the pause */
1218 if (old_state == MIGRATION_STATUS_PRE_SWITCHOVER) {
1219 qemu_sem_post(&s->pause_sem);
1220 }
1221 migrate_set_state(&s->state, old_state, MIGRATION_STATUS_CANCELLING);
1222 } while (s->state != MIGRATION_STATUS_CANCELLING);
1223
1224 /*
1225 * If we're unlucky the migration code might be stuck somewhere in a
1226 * send/write while the network has failed and is waiting to timeout;
1227 * if we've got shutdown(2) available then we can force it to quit.
1228 * The outgoing qemu file gets closed in migrate_fd_cleanup that is
1229 * called in a bh, so there is no race against this cancel.
1230 */
1231 if (s->state == MIGRATION_STATUS_CANCELLING && f) {
1232 qemu_file_shutdown(f);
1233 }
1234 if (s->state == MIGRATION_STATUS_CANCELLING && s->block_inactive) {
1235 Error *local_err = NULL;
1236
1237 bdrv_invalidate_cache_all(&local_err);
1238 if (local_err) {
1239 error_report_err(local_err);
1240 } else {
1241 s->block_inactive = false;
1242 }
1243 }
1244 }
1245
1246 void add_migration_state_change_notifier(Notifier *notify)
1247 {
1248 notifier_list_add(&migration_state_notifiers, notify);
1249 }
1250
1251 void remove_migration_state_change_notifier(Notifier *notify)
1252 {
1253 notifier_remove(notify);
1254 }
1255
1256 bool migration_in_setup(MigrationState *s)
1257 {
1258 return s->state == MIGRATION_STATUS_SETUP;
1259 }
1260
1261 bool migration_has_finished(MigrationState *s)
1262 {
1263 return s->state == MIGRATION_STATUS_COMPLETED;
1264 }
1265
1266 bool migration_has_failed(MigrationState *s)
1267 {
1268 return (s->state == MIGRATION_STATUS_CANCELLED ||
1269 s->state == MIGRATION_STATUS_FAILED);
1270 }
1271
1272 bool migration_in_postcopy(void)
1273 {
1274 MigrationState *s = migrate_get_current();
1275
1276 return (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
1277 }
1278
1279 bool migration_in_postcopy_after_devices(MigrationState *s)
1280 {
1281 return migration_in_postcopy() && s->postcopy_after_devices;
1282 }
1283
1284 bool migration_is_idle(void)
1285 {
1286 MigrationState *s = migrate_get_current();
1287
1288 switch (s->state) {
1289 case MIGRATION_STATUS_NONE:
1290 case MIGRATION_STATUS_CANCELLED:
1291 case MIGRATION_STATUS_COMPLETED:
1292 case MIGRATION_STATUS_FAILED:
1293 return true;
1294 case MIGRATION_STATUS_SETUP:
1295 case MIGRATION_STATUS_CANCELLING:
1296 case MIGRATION_STATUS_ACTIVE:
1297 case MIGRATION_STATUS_POSTCOPY_ACTIVE:
1298 case MIGRATION_STATUS_COLO:
1299 case MIGRATION_STATUS_PRE_SWITCHOVER:
1300 case MIGRATION_STATUS_DEVICE:
1301 return false;
1302 case MIGRATION_STATUS__MAX:
1303 g_assert_not_reached();
1304 }
1305
1306 return false;
1307 }
1308
1309 void migrate_init(MigrationState *s)
1310 {
1311 /*
1312 * Reinitialise all migration state, except
1313 * parameters/capabilities that the user set, and
1314 * locks.
1315 */
1316 s->bytes_xfer = 0;
1317 s->xfer_limit = 0;
1318 s->cleanup_bh = 0;
1319 s->to_dst_file = NULL;
1320 s->state = MIGRATION_STATUS_NONE;
1321 s->rp_state.from_dst_file = NULL;
1322 s->rp_state.error = false;
1323 s->mbps = 0.0;
1324 s->downtime = 0;
1325 s->expected_downtime = 0;
1326 s->setup_time = 0;
1327 s->start_postcopy = false;
1328 s->postcopy_after_devices = false;
1329 s->migration_thread_running = false;
1330 error_free(s->error);
1331 s->error = NULL;
1332
1333 migrate_set_state(&s->state, MIGRATION_STATUS_NONE, MIGRATION_STATUS_SETUP);
1334
1335 s->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1336 s->total_time = 0;
1337 s->vm_was_running = false;
1338 s->iteration_initial_bytes = 0;
1339 s->threshold_size = 0;
1340 }
1341
1342 static GSList *migration_blockers;
1343
1344 int migrate_add_blocker(Error *reason, Error **errp)
1345 {
1346 if (migrate_get_current()->only_migratable) {
1347 error_propagate(errp, error_copy(reason));
1348 error_prepend(errp, "disallowing migration blocker "
1349 "(--only_migratable) for: ");
1350 return -EACCES;
1351 }
1352
1353 if (migration_is_idle()) {
1354 migration_blockers = g_slist_prepend(migration_blockers, reason);
1355 return 0;
1356 }
1357
1358 error_propagate(errp, error_copy(reason));
1359 error_prepend(errp, "disallowing migration blocker (migration in "
1360 "progress) for: ");
1361 return -EBUSY;
1362 }
1363
1364 void migrate_del_blocker(Error *reason)
1365 {
1366 migration_blockers = g_slist_remove(migration_blockers, reason);
1367 }
1368
1369 void qmp_migrate_incoming(const char *uri, Error **errp)
1370 {
1371 Error *local_err = NULL;
1372 static bool once = true;
1373
1374 if (!deferred_incoming) {
1375 error_setg(errp, "For use with '-incoming defer'");
1376 return;
1377 }
1378 if (!once) {
1379 error_setg(errp, "The incoming migration has already been started");
1380 }
1381
1382 qemu_start_incoming_migration(uri, &local_err);
1383
1384 if (local_err) {
1385 error_propagate(errp, local_err);
1386 return;
1387 }
1388
1389 once = false;
1390 }
1391
1392 bool migration_is_blocked(Error **errp)
1393 {
1394 if (qemu_savevm_state_blocked(errp)) {
1395 return true;
1396 }
1397
1398 if (migration_blockers) {
1399 error_propagate(errp, error_copy(migration_blockers->data));
1400 return true;
1401 }
1402
1403 return false;
1404 }
1405
1406 void qmp_migrate(const char *uri, bool has_blk, bool blk,
1407 bool has_inc, bool inc, bool has_detach, bool detach,
1408 Error **errp)
1409 {
1410 Error *local_err = NULL;
1411 MigrationState *s = migrate_get_current();
1412 const char *p;
1413
1414 if (migration_is_setup_or_active(s->state) ||
1415 s->state == MIGRATION_STATUS_CANCELLING ||
1416 s->state == MIGRATION_STATUS_COLO) {
1417 error_setg(errp, QERR_MIGRATION_ACTIVE);
1418 return;
1419 }
1420 if (runstate_check(RUN_STATE_INMIGRATE)) {
1421 error_setg(errp, "Guest is waiting for an incoming migration");
1422 return;
1423 }
1424
1425 if (migration_is_blocked(errp)) {
1426 return;
1427 }
1428
1429 if ((has_blk && blk) || (has_inc && inc)) {
1430 if (migrate_use_block() || migrate_use_block_incremental()) {
1431 error_setg(errp, "Command options are incompatible with "
1432 "current migration capabilities");
1433 return;
1434 }
1435 migrate_set_block_enabled(true, &local_err);
1436 if (local_err) {
1437 error_propagate(errp, local_err);
1438 return;
1439 }
1440 s->must_remove_block_options = true;
1441 }
1442
1443 if (has_inc && inc) {
1444 migrate_set_block_incremental(s, true);
1445 }
1446
1447 migrate_init(s);
1448
1449 if (strstart(uri, "tcp:", &p)) {
1450 tcp_start_outgoing_migration(s, p, &local_err);
1451 #ifdef CONFIG_RDMA
1452 } else if (strstart(uri, "rdma:", &p)) {
1453 rdma_start_outgoing_migration(s, p, &local_err);
1454 #endif
1455 } else if (strstart(uri, "exec:", &p)) {
1456 exec_start_outgoing_migration(s, p, &local_err);
1457 } else if (strstart(uri, "unix:", &p)) {
1458 unix_start_outgoing_migration(s, p, &local_err);
1459 } else if (strstart(uri, "fd:", &p)) {
1460 fd_start_outgoing_migration(s, p, &local_err);
1461 } else {
1462 error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "uri",
1463 "a valid migration protocol");
1464 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
1465 MIGRATION_STATUS_FAILED);
1466 block_cleanup_parameters(s);
1467 return;
1468 }
1469
1470 if (local_err) {
1471 migrate_fd_error(s, local_err);
1472 error_propagate(errp, local_err);
1473 return;
1474 }
1475 }
1476
1477 void qmp_migrate_cancel(Error **errp)
1478 {
1479 migrate_fd_cancel(migrate_get_current());
1480 }
1481
1482 void qmp_migrate_continue(MigrationStatus state, Error **errp)
1483 {
1484 MigrationState *s = migrate_get_current();
1485 if (s->state != state) {
1486 error_setg(errp, "Migration not in expected state: %s",
1487 MigrationStatus_str(s->state));
1488 return;
1489 }
1490 qemu_sem_post(&s->pause_sem);
1491 }
1492
1493 void qmp_migrate_set_cache_size(int64_t value, Error **errp)
1494 {
1495 MigrateSetParameters p = {
1496 .has_xbzrle_cache_size = true,
1497 .xbzrle_cache_size = value,
1498 };
1499
1500 qmp_migrate_set_parameters(&p, errp);
1501 }
1502
1503 int64_t qmp_query_migrate_cache_size(Error **errp)
1504 {
1505 return migrate_xbzrle_cache_size();
1506 }
1507
1508 void qmp_migrate_set_speed(int64_t value, Error **errp)
1509 {
1510 MigrateSetParameters p = {
1511 .has_max_bandwidth = true,
1512 .max_bandwidth = value,
1513 };
1514
1515 qmp_migrate_set_parameters(&p, errp);
1516 }
1517
1518 void qmp_migrate_set_downtime(double value, Error **errp)
1519 {
1520 if (value < 0 || value > MAX_MIGRATE_DOWNTIME_SECONDS) {
1521 error_setg(errp, "Parameter 'downtime_limit' expects an integer in "
1522 "the range of 0 to %d seconds",
1523 MAX_MIGRATE_DOWNTIME_SECONDS);
1524 return;
1525 }
1526
1527 value *= 1000; /* Convert to milliseconds */
1528 value = MAX(0, MIN(INT64_MAX, value));
1529
1530 MigrateSetParameters p = {
1531 .has_downtime_limit = true,
1532 .downtime_limit = value,
1533 };
1534
1535 qmp_migrate_set_parameters(&p, errp);
1536 }
1537
1538 bool migrate_release_ram(void)
1539 {
1540 MigrationState *s;
1541
1542 s = migrate_get_current();
1543
1544 return s->enabled_capabilities[MIGRATION_CAPABILITY_RELEASE_RAM];
1545 }
1546
1547 bool migrate_postcopy_ram(void)
1548 {
1549 MigrationState *s;
1550
1551 s = migrate_get_current();
1552
1553 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM];
1554 }
1555
1556 bool migrate_postcopy(void)
1557 {
1558 return migrate_postcopy_ram() || migrate_dirty_bitmaps();
1559 }
1560
1561 bool migrate_auto_converge(void)
1562 {
1563 MigrationState *s;
1564
1565 s = migrate_get_current();
1566
1567 return s->enabled_capabilities[MIGRATION_CAPABILITY_AUTO_CONVERGE];
1568 }
1569
1570 bool migrate_zero_blocks(void)
1571 {
1572 MigrationState *s;
1573
1574 s = migrate_get_current();
1575
1576 return s->enabled_capabilities[MIGRATION_CAPABILITY_ZERO_BLOCKS];
1577 }
1578
1579 bool migrate_postcopy_blocktime(void)
1580 {
1581 MigrationState *s;
1582
1583 s = migrate_get_current();
1584
1585 return s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_BLOCKTIME];
1586 }
1587
1588 bool migrate_use_compression(void)
1589 {
1590 MigrationState *s;
1591
1592 s = migrate_get_current();
1593
1594 return s->enabled_capabilities[MIGRATION_CAPABILITY_COMPRESS];
1595 }
1596
1597 int migrate_compress_level(void)
1598 {
1599 MigrationState *s;
1600
1601 s = migrate_get_current();
1602
1603 return s->parameters.compress_level;
1604 }
1605
1606 int migrate_compress_threads(void)
1607 {
1608 MigrationState *s;
1609
1610 s = migrate_get_current();
1611
1612 return s->parameters.compress_threads;
1613 }
1614
1615 int migrate_decompress_threads(void)
1616 {
1617 MigrationState *s;
1618
1619 s = migrate_get_current();
1620
1621 return s->parameters.decompress_threads;
1622 }
1623
1624 bool migrate_dirty_bitmaps(void)
1625 {
1626 MigrationState *s;
1627
1628 s = migrate_get_current();
1629
1630 return s->enabled_capabilities[MIGRATION_CAPABILITY_DIRTY_BITMAPS];
1631 }
1632
1633 bool migrate_use_events(void)
1634 {
1635 MigrationState *s;
1636
1637 s = migrate_get_current();
1638
1639 return s->enabled_capabilities[MIGRATION_CAPABILITY_EVENTS];
1640 }
1641
1642 bool migrate_use_multifd(void)
1643 {
1644 MigrationState *s;
1645
1646 s = migrate_get_current();
1647
1648 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_MULTIFD];
1649 }
1650
1651 bool migrate_pause_before_switchover(void)
1652 {
1653 MigrationState *s;
1654
1655 s = migrate_get_current();
1656
1657 return s->enabled_capabilities[
1658 MIGRATION_CAPABILITY_PAUSE_BEFORE_SWITCHOVER];
1659 }
1660
1661 int migrate_multifd_channels(void)
1662 {
1663 MigrationState *s;
1664
1665 s = migrate_get_current();
1666
1667 return s->parameters.x_multifd_channels;
1668 }
1669
1670 int migrate_multifd_page_count(void)
1671 {
1672 MigrationState *s;
1673
1674 s = migrate_get_current();
1675
1676 return s->parameters.x_multifd_page_count;
1677 }
1678
1679 int migrate_use_xbzrle(void)
1680 {
1681 MigrationState *s;
1682
1683 s = migrate_get_current();
1684
1685 return s->enabled_capabilities[MIGRATION_CAPABILITY_XBZRLE];
1686 }
1687
1688 int64_t migrate_xbzrle_cache_size(void)
1689 {
1690 MigrationState *s;
1691
1692 s = migrate_get_current();
1693
1694 return s->parameters.xbzrle_cache_size;
1695 }
1696
1697 bool migrate_use_block(void)
1698 {
1699 MigrationState *s;
1700
1701 s = migrate_get_current();
1702
1703 return s->enabled_capabilities[MIGRATION_CAPABILITY_BLOCK];
1704 }
1705
1706 bool migrate_use_return_path(void)
1707 {
1708 MigrationState *s;
1709
1710 s = migrate_get_current();
1711
1712 return s->enabled_capabilities[MIGRATION_CAPABILITY_RETURN_PATH];
1713 }
1714
1715 bool migrate_use_block_incremental(void)
1716 {
1717 MigrationState *s;
1718
1719 s = migrate_get_current();
1720
1721 return s->parameters.block_incremental;
1722 }
1723
1724 /* migration thread support */
1725 /*
1726 * Something bad happened to the RP stream, mark an error
1727 * The caller shall print or trace something to indicate why
1728 */
1729 static void mark_source_rp_bad(MigrationState *s)
1730 {
1731 s->rp_state.error = true;
1732 }
1733
1734 static struct rp_cmd_args {
1735 ssize_t len; /* -1 = variable */
1736 const char *name;
1737 } rp_cmd_args[] = {
1738 [MIG_RP_MSG_INVALID] = { .len = -1, .name = "INVALID" },
1739 [MIG_RP_MSG_SHUT] = { .len = 4, .name = "SHUT" },
1740 [MIG_RP_MSG_PONG] = { .len = 4, .name = "PONG" },
1741 [MIG_RP_MSG_REQ_PAGES] = { .len = 12, .name = "REQ_PAGES" },
1742 [MIG_RP_MSG_REQ_PAGES_ID] = { .len = -1, .name = "REQ_PAGES_ID" },
1743 [MIG_RP_MSG_MAX] = { .len = -1, .name = "MAX" },
1744 };
1745
1746 /*
1747 * Process a request for pages received on the return path,
1748 * We're allowed to send more than requested (e.g. to round to our page size)
1749 * and we don't need to send pages that have already been sent.
1750 */
1751 static void migrate_handle_rp_req_pages(MigrationState *ms, const char* rbname,
1752 ram_addr_t start, size_t len)
1753 {
1754 long our_host_ps = getpagesize();
1755
1756 trace_migrate_handle_rp_req_pages(rbname, start, len);
1757
1758 /*
1759 * Since we currently insist on matching page sizes, just sanity check
1760 * we're being asked for whole host pages.
1761 */
1762 if (start & (our_host_ps-1) ||
1763 (len & (our_host_ps-1))) {
1764 error_report("%s: Misaligned page request, start: " RAM_ADDR_FMT
1765 " len: %zd", __func__, start, len);
1766 mark_source_rp_bad(ms);
1767 return;
1768 }
1769
1770 if (ram_save_queue_pages(rbname, start, len)) {
1771 mark_source_rp_bad(ms);
1772 }
1773 }
1774
1775 /*
1776 * Handles messages sent on the return path towards the source VM
1777 *
1778 */
1779 static void *source_return_path_thread(void *opaque)
1780 {
1781 MigrationState *ms = opaque;
1782 QEMUFile *rp = ms->rp_state.from_dst_file;
1783 uint16_t header_len, header_type;
1784 uint8_t buf[512];
1785 uint32_t tmp32, sibling_error;
1786 ram_addr_t start = 0; /* =0 to silence warning */
1787 size_t len = 0, expected_len;
1788 int res;
1789
1790 trace_source_return_path_thread_entry();
1791 while (!ms->rp_state.error && !qemu_file_get_error(rp) &&
1792 migration_is_setup_or_active(ms->state)) {
1793 trace_source_return_path_thread_loop_top();
1794 header_type = qemu_get_be16(rp);
1795 header_len = qemu_get_be16(rp);
1796
1797 if (qemu_file_get_error(rp)) {
1798 mark_source_rp_bad(ms);
1799 goto out;
1800 }
1801
1802 if (header_type >= MIG_RP_MSG_MAX ||
1803 header_type == MIG_RP_MSG_INVALID) {
1804 error_report("RP: Received invalid message 0x%04x length 0x%04x",
1805 header_type, header_len);
1806 mark_source_rp_bad(ms);
1807 goto out;
1808 }
1809
1810 if ((rp_cmd_args[header_type].len != -1 &&
1811 header_len != rp_cmd_args[header_type].len) ||
1812 header_len > sizeof(buf)) {
1813 error_report("RP: Received '%s' message (0x%04x) with"
1814 "incorrect length %d expecting %zu",
1815 rp_cmd_args[header_type].name, header_type, header_len,
1816 (size_t)rp_cmd_args[header_type].len);
1817 mark_source_rp_bad(ms);
1818 goto out;
1819 }
1820
1821 /* We know we've got a valid header by this point */
1822 res = qemu_get_buffer(rp, buf, header_len);
1823 if (res != header_len) {
1824 error_report("RP: Failed reading data for message 0x%04x"
1825 " read %d expected %d",
1826 header_type, res, header_len);
1827 mark_source_rp_bad(ms);
1828 goto out;
1829 }
1830
1831 /* OK, we have the message and the data */
1832 switch (header_type) {
1833 case MIG_RP_MSG_SHUT:
1834 sibling_error = ldl_be_p(buf);
1835 trace_source_return_path_thread_shut(sibling_error);
1836 if (sibling_error) {
1837 error_report("RP: Sibling indicated error %d", sibling_error);
1838 mark_source_rp_bad(ms);
1839 }
1840 /*
1841 * We'll let the main thread deal with closing the RP
1842 * we could do a shutdown(2) on it, but we're the only user
1843 * anyway, so there's nothing gained.
1844 */
1845 goto out;
1846
1847 case MIG_RP_MSG_PONG:
1848 tmp32 = ldl_be_p(buf);
1849 trace_source_return_path_thread_pong(tmp32);
1850 break;
1851
1852 case MIG_RP_MSG_REQ_PAGES:
1853 start = ldq_be_p(buf);
1854 len = ldl_be_p(buf + 8);
1855 migrate_handle_rp_req_pages(ms, NULL, start, len);
1856 break;
1857
1858 case MIG_RP_MSG_REQ_PAGES_ID:
1859 expected_len = 12 + 1; /* header + termination */
1860
1861 if (header_len >= expected_len) {
1862 start = ldq_be_p(buf);
1863 len = ldl_be_p(buf + 8);
1864 /* Now we expect an idstr */
1865 tmp32 = buf[12]; /* Length of the following idstr */
1866 buf[13 + tmp32] = '\0';
1867 expected_len += tmp32;
1868 }
1869 if (header_len != expected_len) {
1870 error_report("RP: Req_Page_id with length %d expecting %zd",
1871 header_len, expected_len);
1872 mark_source_rp_bad(ms);
1873 goto out;
1874 }
1875 migrate_handle_rp_req_pages(ms, (char *)&buf[13], start, len);
1876 break;
1877
1878 default:
1879 break;
1880 }
1881 }
1882 if (qemu_file_get_error(rp)) {
1883 trace_source_return_path_thread_bad_end();
1884 mark_source_rp_bad(ms);
1885 }
1886
1887 trace_source_return_path_thread_end();
1888 out:
1889 ms->rp_state.from_dst_file = NULL;
1890 qemu_fclose(rp);
1891 return NULL;
1892 }
1893
1894 static int open_return_path_on_source(MigrationState *ms)
1895 {
1896
1897 ms->rp_state.from_dst_file = qemu_file_get_return_path(ms->to_dst_file);
1898 if (!ms->rp_state.from_dst_file) {
1899 return -1;
1900 }
1901
1902 trace_open_return_path_on_source();
1903 qemu_thread_create(&ms->rp_state.rp_thread, "return path",
1904 source_return_path_thread, ms, QEMU_THREAD_JOINABLE);
1905
1906 trace_open_return_path_on_source_continue();
1907
1908 return 0;
1909 }
1910
1911 /* Returns 0 if the RP was ok, otherwise there was an error on the RP */
1912 static int await_return_path_close_on_source(MigrationState *ms)
1913 {
1914 /*
1915 * If this is a normal exit then the destination will send a SHUT and the
1916 * rp_thread will exit, however if there's an error we need to cause
1917 * it to exit.
1918 */
1919 if (qemu_file_get_error(ms->to_dst_file) && ms->rp_state.from_dst_file) {
1920 /*
1921 * shutdown(2), if we have it, will cause it to unblock if it's stuck
1922 * waiting for the destination.
1923 */
1924 qemu_file_shutdown(ms->rp_state.from_dst_file);
1925 mark_source_rp_bad(ms);
1926 }
1927 trace_await_return_path_close_on_source_joining();
1928 qemu_thread_join(&ms->rp_state.rp_thread);
1929 trace_await_return_path_close_on_source_close();
1930 return ms->rp_state.error;
1931 }
1932
1933 /*
1934 * Switch from normal iteration to postcopy
1935 * Returns non-0 on error
1936 */
1937 static int postcopy_start(MigrationState *ms)
1938 {
1939 int ret;
1940 QIOChannelBuffer *bioc;
1941 QEMUFile *fb;
1942 int64_t time_at_stop = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
1943 bool restart_block = false;
1944 int cur_state = MIGRATION_STATUS_ACTIVE;
1945 if (!migrate_pause_before_switchover()) {
1946 migrate_set_state(&ms->state, MIGRATION_STATUS_ACTIVE,
1947 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1948 }
1949
1950 trace_postcopy_start();
1951 qemu_mutex_lock_iothread();
1952 trace_postcopy_start_set_run();
1953
1954 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
1955 global_state_store();
1956 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
1957 if (ret < 0) {
1958 goto fail;
1959 }
1960
1961 ret = migration_maybe_pause(ms, &cur_state,
1962 MIGRATION_STATUS_POSTCOPY_ACTIVE);
1963 if (ret < 0) {
1964 goto fail;
1965 }
1966
1967 ret = bdrv_inactivate_all();
1968 if (ret < 0) {
1969 goto fail;
1970 }
1971 restart_block = true;
1972
1973 /*
1974 * Cause any non-postcopiable, but iterative devices to
1975 * send out their final data.
1976 */
1977 qemu_savevm_state_complete_precopy(ms->to_dst_file, true, false);
1978
1979 /*
1980 * in Finish migrate and with the io-lock held everything should
1981 * be quiet, but we've potentially still got dirty pages and we
1982 * need to tell the destination to throw any pages it's already received
1983 * that are dirty
1984 */
1985 if (migrate_postcopy_ram()) {
1986 if (ram_postcopy_send_discard_bitmap(ms)) {
1987 error_report("postcopy send discard bitmap failed");
1988 goto fail;
1989 }
1990 }
1991
1992 /*
1993 * send rest of state - note things that are doing postcopy
1994 * will notice we're in POSTCOPY_ACTIVE and not actually
1995 * wrap their state up here
1996 */
1997 qemu_file_set_rate_limit(ms->to_dst_file, INT64_MAX);
1998 if (migrate_postcopy_ram()) {
1999 /* Ping just for debugging, helps line traces up */
2000 qemu_savevm_send_ping(ms->to_dst_file, 2);
2001 }
2002
2003 /*
2004 * While loading the device state we may trigger page transfer
2005 * requests and the fd must be free to process those, and thus
2006 * the destination must read the whole device state off the fd before
2007 * it starts processing it. Unfortunately the ad-hoc migration format
2008 * doesn't allow the destination to know the size to read without fully
2009 * parsing it through each devices load-state code (especially the open
2010 * coded devices that use get/put).
2011 * So we wrap the device state up in a package with a length at the start;
2012 * to do this we use a qemu_buf to hold the whole of the device state.
2013 */
2014 bioc = qio_channel_buffer_new(4096);
2015 qio_channel_set_name(QIO_CHANNEL(bioc), "migration-postcopy-buffer");
2016 fb = qemu_fopen_channel_output(QIO_CHANNEL(bioc));
2017 object_unref(OBJECT(bioc));
2018
2019 /*
2020 * Make sure the receiver can get incoming pages before we send the rest
2021 * of the state
2022 */
2023 qemu_savevm_send_postcopy_listen(fb);
2024
2025 qemu_savevm_state_complete_precopy(fb, false, false);
2026 if (migrate_postcopy_ram()) {
2027 qemu_savevm_send_ping(fb, 3);
2028 }
2029
2030 qemu_savevm_send_postcopy_run(fb);
2031
2032 /* <><> end of stuff going into the package */
2033
2034 /* Last point of recovery; as soon as we send the package the destination
2035 * can open devices and potentially start running.
2036 * Lets just check again we've not got any errors.
2037 */
2038 ret = qemu_file_get_error(ms->to_dst_file);
2039 if (ret) {
2040 error_report("postcopy_start: Migration stream errored (pre package)");
2041 goto fail_closefb;
2042 }
2043
2044 restart_block = false;
2045
2046 /* Now send that blob */
2047 if (qemu_savevm_send_packaged(ms->to_dst_file, bioc->data, bioc->usage)) {
2048 goto fail_closefb;
2049 }
2050 qemu_fclose(fb);
2051
2052 /* Send a notify to give a chance for anything that needs to happen
2053 * at the transition to postcopy and after the device state; in particular
2054 * spice needs to trigger a transition now
2055 */
2056 ms->postcopy_after_devices = true;
2057 notifier_list_notify(&migration_state_notifiers, ms);
2058
2059 ms->downtime = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - time_at_stop;
2060
2061 qemu_mutex_unlock_iothread();
2062
2063 if (migrate_postcopy_ram()) {
2064 /*
2065 * Although this ping is just for debug, it could potentially be
2066 * used for getting a better measurement of downtime at the source.
2067 */
2068 qemu_savevm_send_ping(ms->to_dst_file, 4);
2069 }
2070
2071 if (migrate_release_ram()) {
2072 ram_postcopy_migrated_memory_release(ms);
2073 }
2074
2075 ret = qemu_file_get_error(ms->to_dst_file);
2076 if (ret) {
2077 error_report("postcopy_start: Migration stream errored");
2078 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2079 MIGRATION_STATUS_FAILED);
2080 }
2081
2082 return ret;
2083
2084 fail_closefb:
2085 qemu_fclose(fb);
2086 fail:
2087 migrate_set_state(&ms->state, MIGRATION_STATUS_POSTCOPY_ACTIVE,
2088 MIGRATION_STATUS_FAILED);
2089 if (restart_block) {
2090 /* A failure happened early enough that we know the destination hasn't
2091 * accessed block devices, so we're safe to recover.
2092 */
2093 Error *local_err = NULL;
2094
2095 bdrv_invalidate_cache_all(&local_err);
2096 if (local_err) {
2097 error_report_err(local_err);
2098 }
2099 }
2100 qemu_mutex_unlock_iothread();
2101 return -1;
2102 }
2103
2104 /**
2105 * migration_maybe_pause: Pause if required to by
2106 * migrate_pause_before_switchover called with the iothread locked
2107 * Returns: 0 on success
2108 */
2109 static int migration_maybe_pause(MigrationState *s,
2110 int *current_active_state,
2111 int new_state)
2112 {
2113 if (!migrate_pause_before_switchover()) {
2114 return 0;
2115 }
2116
2117 /* Since leaving this state is not atomic with posting the semaphore
2118 * it's possible that someone could have issued multiple migrate_continue
2119 * and the semaphore is incorrectly positive at this point;
2120 * the docs say it's undefined to reinit a semaphore that's already
2121 * init'd, so use timedwait to eat up any existing posts.
2122 */
2123 while (qemu_sem_timedwait(&s->pause_sem, 1) == 0) {
2124 /* This block intentionally left blank */
2125 }
2126
2127 qemu_mutex_unlock_iothread();
2128 migrate_set_state(&s->state, *current_active_state,
2129 MIGRATION_STATUS_PRE_SWITCHOVER);
2130 qemu_sem_wait(&s->pause_sem);
2131 migrate_set_state(&s->state, MIGRATION_STATUS_PRE_SWITCHOVER,
2132 new_state);
2133 *current_active_state = new_state;
2134 qemu_mutex_lock_iothread();
2135
2136 return s->state == new_state ? 0 : -EINVAL;
2137 }
2138
2139 /**
2140 * migration_completion: Used by migration_thread when there's not much left.
2141 * The caller 'breaks' the loop when this returns.
2142 *
2143 * @s: Current migration state
2144 */
2145 static void migration_completion(MigrationState *s)
2146 {
2147 int ret;
2148 int current_active_state = s->state;
2149
2150 if (s->state == MIGRATION_STATUS_ACTIVE) {
2151 qemu_mutex_lock_iothread();
2152 s->downtime_start = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2153 qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);
2154 s->vm_was_running = runstate_is_running();
2155 ret = global_state_store();
2156
2157 if (!ret) {
2158 bool inactivate = !migrate_colo_enabled();
2159 ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
2160 if (ret >= 0) {
2161 ret = migration_maybe_pause(s, &current_active_state,
2162 MIGRATION_STATUS_DEVICE);
2163 }
2164 if (ret >= 0) {
2165 qemu_file_set_rate_limit(s->to_dst_file, INT64_MAX);
2166 ret = qemu_savevm_state_complete_precopy(s->to_dst_file, false,
2167 inactivate);
2168 }
2169 if (inactivate && ret >= 0) {
2170 s->block_inactive = true;
2171 }
2172 }
2173 qemu_mutex_unlock_iothread();
2174
2175 if (ret < 0) {
2176 goto fail;
2177 }
2178 } else if (s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2179 trace_migration_completion_postcopy_end();
2180
2181 qemu_savevm_state_complete_postcopy(s->to_dst_file);
2182 trace_migration_completion_postcopy_end_after_complete();
2183 }
2184
2185 /*
2186 * If rp was opened we must clean up the thread before
2187 * cleaning everything else up (since if there are no failures
2188 * it will wait for the destination to send it's status in
2189 * a SHUT command).
2190 */
2191 if (s->rp_state.from_dst_file) {
2192 int rp_error;
2193 trace_migration_return_path_end_before();
2194 rp_error = await_return_path_close_on_source(s);
2195 trace_migration_return_path_end_after(rp_error);
2196 if (rp_error) {
2197 goto fail_invalidate;
2198 }
2199 }
2200
2201 if (qemu_file_get_error(s->to_dst_file)) {
2202 trace_migration_completion_file_err();
2203 goto fail_invalidate;
2204 }
2205
2206 if (!migrate_colo_enabled()) {
2207 migrate_set_state(&s->state, current_active_state,
2208 MIGRATION_STATUS_COMPLETED);
2209 }
2210
2211 return;
2212
2213 fail_invalidate:
2214 /* If not doing postcopy, vm_start() will be called: let's regain
2215 * control on images.
2216 */
2217 if (s->state == MIGRATION_STATUS_ACTIVE ||
2218 s->state == MIGRATION_STATUS_DEVICE) {
2219 Error *local_err = NULL;
2220
2221 qemu_mutex_lock_iothread();
2222 bdrv_invalidate_cache_all(&local_err);
2223 if (local_err) {
2224 error_report_err(local_err);
2225 } else {
2226 s->block_inactive = false;
2227 }
2228 qemu_mutex_unlock_iothread();
2229 }
2230
2231 fail:
2232 migrate_set_state(&s->state, current_active_state,
2233 MIGRATION_STATUS_FAILED);
2234 }
2235
2236 bool migrate_colo_enabled(void)
2237 {
2238 MigrationState *s = migrate_get_current();
2239 return s->enabled_capabilities[MIGRATION_CAPABILITY_X_COLO];
2240 }
2241
2242 static void migration_calculate_complete(MigrationState *s)
2243 {
2244 uint64_t bytes = qemu_ftell(s->to_dst_file);
2245 int64_t end_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2246
2247 s->total_time = end_time - s->start_time;
2248 if (!s->downtime) {
2249 /*
2250 * It's still not set, so we are precopy migration. For
2251 * postcopy, downtime is calculated during postcopy_start().
2252 */
2253 s->downtime = end_time - s->downtime_start;
2254 }
2255
2256 if (s->total_time) {
2257 s->mbps = ((double) bytes * 8.0) / s->total_time / 1000;
2258 }
2259 }
2260
2261 static void migration_update_counters(MigrationState *s,
2262 int64_t current_time)
2263 {
2264 uint64_t transferred, time_spent;
2265 double bandwidth;
2266
2267 if (current_time < s->iteration_start_time + BUFFER_DELAY) {
2268 return;
2269 }
2270
2271 transferred = qemu_ftell(s->to_dst_file) - s->iteration_initial_bytes;
2272 time_spent = current_time - s->iteration_start_time;
2273 bandwidth = (double)transferred / time_spent;
2274 s->threshold_size = bandwidth * s->parameters.downtime_limit;
2275
2276 s->mbps = (((double) transferred * 8.0) /
2277 ((double) time_spent / 1000.0)) / 1000.0 / 1000.0;
2278
2279 /*
2280 * if we haven't sent anything, we don't want to
2281 * recalculate. 10000 is a small enough number for our purposes
2282 */
2283 if (ram_counters.dirty_pages_rate && transferred > 10000) {
2284 s->expected_downtime = ram_counters.dirty_pages_rate *
2285 qemu_target_page_size() / bandwidth;
2286 }
2287
2288 qemu_file_reset_rate_limit(s->to_dst_file);
2289
2290 s->iteration_start_time = current_time;
2291 s->iteration_initial_bytes = qemu_ftell(s->to_dst_file);
2292
2293 trace_migrate_transferred(transferred, time_spent,
2294 bandwidth, s->threshold_size);
2295 }
2296
2297 /* Migration thread iteration status */
2298 typedef enum {
2299 MIG_ITERATE_RESUME, /* Resume current iteration */
2300 MIG_ITERATE_SKIP, /* Skip current iteration */
2301 MIG_ITERATE_BREAK, /* Break the loop */
2302 } MigIterateState;
2303
2304 /*
2305 * Return true if continue to the next iteration directly, false
2306 * otherwise.
2307 */
2308 static MigIterateState migration_iteration_run(MigrationState *s)
2309 {
2310 uint64_t pending_size, pend_pre, pend_compat, pend_post;
2311 bool in_postcopy = s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE;
2312
2313 qemu_savevm_state_pending(s->to_dst_file, s->threshold_size, &pend_pre,
2314 &pend_compat, &pend_post);
2315 pending_size = pend_pre + pend_compat + pend_post;
2316
2317 trace_migrate_pending(pending_size, s->threshold_size,
2318 pend_pre, pend_compat, pend_post);
2319
2320 if (pending_size && pending_size >= s->threshold_size) {
2321 /* Still a significant amount to transfer */
2322 if (migrate_postcopy() && !in_postcopy &&
2323 pend_pre <= s->threshold_size &&
2324 atomic_read(&s->start_postcopy)) {
2325 if (postcopy_start(s)) {
2326 error_report("%s: postcopy failed to start", __func__);
2327 }
2328 return MIG_ITERATE_SKIP;
2329 }
2330 /* Just another iteration step */
2331 qemu_savevm_state_iterate(s->to_dst_file,
2332 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE);
2333 } else {
2334 trace_migration_thread_low_pending(pending_size);
2335 migration_completion(s);
2336 return MIG_ITERATE_BREAK;
2337 }
2338
2339 return MIG_ITERATE_RESUME;
2340 }
2341
2342 static void migration_iteration_finish(MigrationState *s)
2343 {
2344 /* If we enabled cpu throttling for auto-converge, turn it off. */
2345 cpu_throttle_stop();
2346
2347 qemu_mutex_lock_iothread();
2348 switch (s->state) {
2349 case MIGRATION_STATUS_COMPLETED:
2350 migration_calculate_complete(s);
2351 runstate_set(RUN_STATE_POSTMIGRATE);
2352 break;
2353
2354 case MIGRATION_STATUS_ACTIVE:
2355 /*
2356 * We should really assert here, but since it's during
2357 * migration, let's try to reduce the usage of assertions.
2358 */
2359 if (!migrate_colo_enabled()) {
2360 error_report("%s: critical error: calling COLO code without "
2361 "COLO enabled", __func__);
2362 }
2363 migrate_start_colo_process(s);
2364 /*
2365 * Fixme: we will run VM in COLO no matter its old running state.
2366 * After exited COLO, we will keep running.
2367 */
2368 s->vm_was_running = true;
2369 /* Fallthrough */
2370 case MIGRATION_STATUS_FAILED:
2371 case MIGRATION_STATUS_CANCELLED:
2372 if (s->vm_was_running) {
2373 vm_start();
2374 } else {
2375 if (runstate_check(RUN_STATE_FINISH_MIGRATE)) {
2376 runstate_set(RUN_STATE_POSTMIGRATE);
2377 }
2378 }
2379 break;
2380
2381 default:
2382 /* Should not reach here, but if so, forgive the VM. */
2383 error_report("%s: Unknown ending state %d", __func__, s->state);
2384 break;
2385 }
2386 qemu_bh_schedule(s->cleanup_bh);
2387 qemu_mutex_unlock_iothread();
2388 }
2389
2390 /*
2391 * Master migration thread on the source VM.
2392 * It drives the migration and pumps the data down the outgoing channel.
2393 */
2394 static void *migration_thread(void *opaque)
2395 {
2396 MigrationState *s = opaque;
2397 int64_t setup_start = qemu_clock_get_ms(QEMU_CLOCK_HOST);
2398
2399 rcu_register_thread();
2400
2401 s->iteration_start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2402
2403 qemu_savevm_state_header(s->to_dst_file);
2404
2405 /*
2406 * If we opened the return path, we need to make sure dst has it
2407 * opened as well.
2408 */
2409 if (s->rp_state.from_dst_file) {
2410 /* Now tell the dest that it should open its end so it can reply */
2411 qemu_savevm_send_open_return_path(s->to_dst_file);
2412
2413 /* And do a ping that will make stuff easier to debug */
2414 qemu_savevm_send_ping(s->to_dst_file, 1);
2415 }
2416
2417 if (migrate_postcopy()) {
2418 /*
2419 * Tell the destination that we *might* want to do postcopy later;
2420 * if the other end can't do postcopy it should fail now, nice and
2421 * early.
2422 */
2423 qemu_savevm_send_postcopy_advise(s->to_dst_file);
2424 }
2425
2426 qemu_savevm_state_setup(s->to_dst_file);
2427
2428 s->setup_time = qemu_clock_get_ms(QEMU_CLOCK_HOST) - setup_start;
2429 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2430 MIGRATION_STATUS_ACTIVE);
2431
2432 trace_migration_thread_setup_complete();
2433
2434 while (s->state == MIGRATION_STATUS_ACTIVE ||
2435 s->state == MIGRATION_STATUS_POSTCOPY_ACTIVE) {
2436 int64_t current_time;
2437
2438 if (!qemu_file_rate_limit(s->to_dst_file)) {
2439 MigIterateState iter_state = migration_iteration_run(s);
2440 if (iter_state == MIG_ITERATE_SKIP) {
2441 continue;
2442 } else if (iter_state == MIG_ITERATE_BREAK) {
2443 break;
2444 }
2445 }
2446
2447 if (qemu_file_get_error(s->to_dst_file)) {
2448 if (migration_is_setup_or_active(s->state)) {
2449 migrate_set_state(&s->state, s->state,
2450 MIGRATION_STATUS_FAILED);
2451 }
2452 trace_migration_thread_file_err();
2453 break;
2454 }
2455
2456 current_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
2457
2458 migration_update_counters(s, current_time);
2459
2460 if (qemu_file_rate_limit(s->to_dst_file)) {
2461 /* usleep expects microseconds */
2462 g_usleep((s->iteration_start_time + BUFFER_DELAY -
2463 current_time) * 1000);
2464 }
2465 }
2466
2467 trace_migration_thread_after_loop();
2468 migration_iteration_finish(s);
2469 rcu_unregister_thread();
2470 return NULL;
2471 }
2472
2473 void migrate_fd_connect(MigrationState *s, Error *error_in)
2474 {
2475 s->expected_downtime = s->parameters.downtime_limit;
2476 s->cleanup_bh = qemu_bh_new(migrate_fd_cleanup, s);
2477 if (error_in) {
2478 migrate_fd_error(s, error_in);
2479 migrate_fd_cleanup(s);
2480 return;
2481 }
2482
2483 qemu_file_set_blocking(s->to_dst_file, true);
2484 qemu_file_set_rate_limit(s->to_dst_file,
2485 s->parameters.max_bandwidth / XFER_LIMIT_RATIO);
2486
2487 /* Notify before starting migration thread */
2488 notifier_list_notify(&migration_state_notifiers, s);
2489
2490 /*
2491 * Open the return path. For postcopy, it is used exclusively. For
2492 * precopy, only if user specified "return-path" capability would
2493 * QEMU uses the return path.
2494 */
2495 if (migrate_postcopy_ram() || migrate_use_return_path()) {
2496 if (open_return_path_on_source(s)) {
2497 error_report("Unable to open return-path for postcopy");
2498 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2499 MIGRATION_STATUS_FAILED);
2500 migrate_fd_cleanup(s);
2501 return;
2502 }
2503 }
2504
2505 if (multifd_save_setup() != 0) {
2506 migrate_set_state(&s->state, MIGRATION_STATUS_SETUP,
2507 MIGRATION_STATUS_FAILED);
2508 migrate_fd_cleanup(s);
2509 return;
2510 }
2511 qemu_thread_create(&s->thread, "live_migration", migration_thread, s,
2512 QEMU_THREAD_JOINABLE);
2513 s->migration_thread_running = true;
2514 }
2515
2516 void migration_global_dump(Monitor *mon)
2517 {
2518 MigrationState *ms = migrate_get_current();
2519
2520 monitor_printf(mon, "globals:\n");
2521 monitor_printf(mon, "store-global-state: %s\n",
2522 ms->store_global_state ? "on" : "off");
2523 monitor_printf(mon, "only-migratable: %s\n",
2524 ms->only_migratable ? "on" : "off");
2525 monitor_printf(mon, "send-configuration: %s\n",
2526 ms->send_configuration ? "on" : "off");
2527 monitor_printf(mon, "send-section-footer: %s\n",
2528 ms->send_section_footer ? "on" : "off");
2529 }
2530
2531 #define DEFINE_PROP_MIG_CAP(name, x) \
2532 DEFINE_PROP_BOOL(name, MigrationState, enabled_capabilities[x], false)
2533
2534 static Property migration_properties[] = {
2535 DEFINE_PROP_BOOL("store-global-state", MigrationState,
2536 store_global_state, true),
2537 DEFINE_PROP_BOOL("only-migratable", MigrationState, only_migratable, false),
2538 DEFINE_PROP_BOOL("send-configuration", MigrationState,
2539 send_configuration, true),
2540 DEFINE_PROP_BOOL("send-section-footer", MigrationState,
2541 send_section_footer, true),
2542
2543 /* Migration parameters */
2544 DEFINE_PROP_UINT8("x-compress-level", MigrationState,
2545 parameters.compress_level,
2546 DEFAULT_MIGRATE_COMPRESS_LEVEL),
2547 DEFINE_PROP_UINT8("x-compress-threads", MigrationState,
2548 parameters.compress_threads,
2549 DEFAULT_MIGRATE_COMPRESS_THREAD_COUNT),
2550 DEFINE_PROP_UINT8("x-decompress-threads", MigrationState,
2551 parameters.decompress_threads,
2552 DEFAULT_MIGRATE_DECOMPRESS_THREAD_COUNT),
2553 DEFINE_PROP_UINT8("x-cpu-throttle-initial", MigrationState,
2554 parameters.cpu_throttle_initial,
2555 DEFAULT_MIGRATE_CPU_THROTTLE_INITIAL),
2556 DEFINE_PROP_UINT8("x-cpu-throttle-increment", MigrationState,
2557 parameters.cpu_throttle_increment,
2558 DEFAULT_MIGRATE_CPU_THROTTLE_INCREMENT),
2559 DEFINE_PROP_SIZE("x-max-bandwidth", MigrationState,
2560 parameters.max_bandwidth, MAX_THROTTLE),
2561 DEFINE_PROP_UINT64("x-downtime-limit", MigrationState,
2562 parameters.downtime_limit,
2563 DEFAULT_MIGRATE_SET_DOWNTIME),
2564 DEFINE_PROP_UINT32("x-checkpoint-delay", MigrationState,
2565 parameters.x_checkpoint_delay,
2566 DEFAULT_MIGRATE_X_CHECKPOINT_DELAY),
2567 DEFINE_PROP_UINT8("x-multifd-channels", MigrationState,
2568 parameters.x_multifd_channels,
2569 DEFAULT_MIGRATE_MULTIFD_CHANNELS),
2570 DEFINE_PROP_UINT32("x-multifd-page-count", MigrationState,
2571 parameters.x_multifd_page_count,
2572 DEFAULT_MIGRATE_MULTIFD_PAGE_COUNT),
2573 DEFINE_PROP_SIZE("xbzrle-cache-size", MigrationState,
2574 parameters.xbzrle_cache_size,
2575 DEFAULT_MIGRATE_XBZRLE_CACHE_SIZE),
2576
2577 /* Migration capabilities */
2578 DEFINE_PROP_MIG_CAP("x-xbzrle", MIGRATION_CAPABILITY_XBZRLE),
2579 DEFINE_PROP_MIG_CAP("x-rdma-pin-all", MIGRATION_CAPABILITY_RDMA_PIN_ALL),
2580 DEFINE_PROP_MIG_CAP("x-auto-converge", MIGRATION_CAPABILITY_AUTO_CONVERGE),
2581 DEFINE_PROP_MIG_CAP("x-zero-blocks", MIGRATION_CAPABILITY_ZERO_BLOCKS),
2582 DEFINE_PROP_MIG_CAP("x-compress", MIGRATION_CAPABILITY_COMPRESS),
2583 DEFINE_PROP_MIG_CAP("x-events", MIGRATION_CAPABILITY_EVENTS),
2584 DEFINE_PROP_MIG_CAP("x-postcopy-ram", MIGRATION_CAPABILITY_POSTCOPY_RAM),
2585 DEFINE_PROP_MIG_CAP("x-colo", MIGRATION_CAPABILITY_X_COLO),
2586 DEFINE_PROP_MIG_CAP("x-release-ram", MIGRATION_CAPABILITY_RELEASE_RAM),
2587 DEFINE_PROP_MIG_CAP("x-block", MIGRATION_CAPABILITY_BLOCK),
2588 DEFINE_PROP_MIG_CAP("x-return-path", MIGRATION_CAPABILITY_RETURN_PATH),
2589 DEFINE_PROP_MIG_CAP("x-multifd", MIGRATION_CAPABILITY_X_MULTIFD),
2590
2591 DEFINE_PROP_END_OF_LIST(),
2592 };
2593
2594 static void migration_class_init(ObjectClass *klass, void *data)
2595 {
2596 DeviceClass *dc = DEVICE_CLASS(klass);
2597
2598 dc->user_creatable = false;
2599 dc->props = migration_properties;
2600 }
2601
2602 static void migration_instance_finalize(Object *obj)
2603 {
2604 MigrationState *ms = MIGRATION_OBJ(obj);
2605 MigrationParameters *params = &ms->parameters;
2606
2607 qemu_mutex_destroy(&ms->error_mutex);
2608 g_free(params->tls_hostname);
2609 g_free(params->tls_creds);
2610 qemu_sem_destroy(&ms->pause_sem);
2611 error_free(ms->error);
2612 }
2613
2614 static void migration_instance_init(Object *obj)
2615 {
2616 MigrationState *ms = MIGRATION_OBJ(obj);
2617 MigrationParameters *params = &ms->parameters;
2618
2619 ms->state = MIGRATION_STATUS_NONE;
2620 ms->mbps = -1;
2621 qemu_sem_init(&ms->pause_sem, 0);
2622 qemu_mutex_init(&ms->error_mutex);
2623
2624 params->tls_hostname = g_strdup("");
2625 params->tls_creds = g_strdup("");
2626
2627 /* Set has_* up only for parameter checks */
2628 params->has_compress_level = true;
2629 params->has_compress_threads = true;
2630 params->has_decompress_threads = true;
2631 params->has_cpu_throttle_initial = true;
2632 params->has_cpu_throttle_increment = true;
2633 params->has_max_bandwidth = true;
2634 params->has_downtime_limit = true;
2635 params->has_x_checkpoint_delay = true;
2636 params->has_block_incremental = true;
2637 params->has_x_multifd_channels = true;
2638 params->has_x_multifd_page_count = true;
2639 params->has_xbzrle_cache_size = true;
2640 }
2641
2642 /*
2643 * Return true if check pass, false otherwise. Error will be put
2644 * inside errp if provided.
2645 */
2646 static bool migration_object_check(MigrationState *ms, Error **errp)
2647 {
2648 MigrationCapabilityStatusList *head = NULL;
2649 /* Assuming all off */
2650 bool cap_list[MIGRATION_CAPABILITY__MAX] = { 0 }, ret;
2651 int i;
2652
2653 if (!migrate_params_check(&ms->parameters, errp)) {
2654 return false;
2655 }
2656
2657 for (i = 0; i < MIGRATION_CAPABILITY__MAX; i++) {
2658 if (ms->enabled_capabilities[i]) {
2659 head = migrate_cap_add(head, i, true);
2660 }
2661 }
2662
2663 ret = migrate_caps_check(cap_list, head, errp);
2664
2665 /* It works with head == NULL */
2666 qapi_free_MigrationCapabilityStatusList(head);
2667
2668 return ret;
2669 }
2670
2671 static const TypeInfo migration_type = {
2672 .name = TYPE_MIGRATION,
2673 /*
2674 * NOTE: TYPE_MIGRATION is not really a device, as the object is
2675 * not created using qdev_create(), it is not attached to the qdev
2676 * device tree, and it is never realized.
2677 *
2678 * TODO: Make this TYPE_OBJECT once QOM provides something like
2679 * TYPE_DEVICE's "-global" properties.
2680 */
2681 .parent = TYPE_DEVICE,
2682 .class_init = migration_class_init,
2683 .class_size = sizeof(MigrationClass),
2684 .instance_size = sizeof(MigrationState),
2685 .instance_init = migration_instance_init,
2686 .instance_finalize = migration_instance_finalize,
2687 };
2688
2689 static void register_migration_types(void)
2690 {
2691 type_register_static(&migration_type);
2692 }
2693
2694 type_init(register_migration_types);