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