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