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