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