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