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