xref: /openbmc/qemu/migration/postcopy-ram.c (revision 06e2b010)
1 /*
2  * Postcopy migration for RAM
3  *
4  * Copyright 2013-2015 Red Hat, Inc. and/or its affiliates
5  *
6  * Authors:
7  *  Dave Gilbert  <dgilbert@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU GPL, version 2 or later.
10  * See the COPYING file in the top-level directory.
11  *
12  */
13 
14 /*
15  * Postcopy is a migration technique where the execution flips from the
16  * source to the destination before all the data has been copied.
17  */
18 
19 #include "qemu/osdep.h"
20 #include "qemu/rcu.h"
21 #include "qemu/madvise.h"
22 #include "exec/target_page.h"
23 #include "migration.h"
24 #include "qemu-file.h"
25 #include "savevm.h"
26 #include "postcopy-ram.h"
27 #include "ram.h"
28 #include "qapi/error.h"
29 #include "qemu/notify.h"
30 #include "qemu/rcu.h"
31 #include "sysemu/sysemu.h"
32 #include "qemu/error-report.h"
33 #include "trace.h"
34 #include "hw/boards.h"
35 #include "exec/ramblock.h"
36 #include "socket.h"
37 #include "qemu-file.h"
38 #include "yank_functions.h"
39 #include "tls.h"
40 #include "qemu/userfaultfd.h"
41 
42 /* Arbitrary limit on size of each discard command,
43  * keeps them around ~200 bytes
44  */
45 #define MAX_DISCARDS_PER_COMMAND 12
46 
47 struct PostcopyDiscardState {
48     const char *ramblock_name;
49     uint16_t cur_entry;
50     /*
51      * Start and length of a discard range (bytes)
52      */
53     uint64_t start_list[MAX_DISCARDS_PER_COMMAND];
54     uint64_t length_list[MAX_DISCARDS_PER_COMMAND];
55     unsigned int nsentwords;
56     unsigned int nsentcmds;
57 };
58 
59 static NotifierWithReturnList postcopy_notifier_list;
60 
61 void postcopy_infrastructure_init(void)
62 {
63     notifier_with_return_list_init(&postcopy_notifier_list);
64 }
65 
66 void postcopy_add_notifier(NotifierWithReturn *nn)
67 {
68     notifier_with_return_list_add(&postcopy_notifier_list, nn);
69 }
70 
71 void postcopy_remove_notifier(NotifierWithReturn *n)
72 {
73     notifier_with_return_remove(n);
74 }
75 
76 int postcopy_notify(enum PostcopyNotifyReason reason, Error **errp)
77 {
78     struct PostcopyNotifyData pnd;
79     pnd.reason = reason;
80     pnd.errp = errp;
81 
82     return notifier_with_return_list_notify(&postcopy_notifier_list,
83                                             &pnd);
84 }
85 
86 /*
87  * NOTE: this routine is not thread safe, we can't call it concurrently. But it
88  * should be good enough for migration's purposes.
89  */
90 void postcopy_thread_create(MigrationIncomingState *mis,
91                             QemuThread *thread, const char *name,
92                             void *(*fn)(void *), int joinable)
93 {
94     qemu_sem_init(&mis->thread_sync_sem, 0);
95     qemu_thread_create(thread, name, fn, mis, joinable);
96     qemu_sem_wait(&mis->thread_sync_sem);
97     qemu_sem_destroy(&mis->thread_sync_sem);
98 }
99 
100 /* Postcopy needs to detect accesses to pages that haven't yet been copied
101  * across, and efficiently map new pages in, the techniques for doing this
102  * are target OS specific.
103  */
104 #if defined(__linux__)
105 
106 #include <poll.h>
107 #include <sys/ioctl.h>
108 #include <sys/syscall.h>
109 #include <asm/types.h> /* for __u64 */
110 #endif
111 
112 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
113 #include <sys/eventfd.h>
114 #include <linux/userfaultfd.h>
115 
116 typedef struct PostcopyBlocktimeContext {
117     /* time when page fault initiated per vCPU */
118     uint32_t *page_fault_vcpu_time;
119     /* page address per vCPU */
120     uintptr_t *vcpu_addr;
121     uint32_t total_blocktime;
122     /* blocktime per vCPU */
123     uint32_t *vcpu_blocktime;
124     /* point in time when last page fault was initiated */
125     uint32_t last_begin;
126     /* number of vCPU are suspended */
127     int smp_cpus_down;
128     uint64_t start_time;
129 
130     /*
131      * Handler for exit event, necessary for
132      * releasing whole blocktime_ctx
133      */
134     Notifier exit_notifier;
135 } PostcopyBlocktimeContext;
136 
137 static void destroy_blocktime_context(struct PostcopyBlocktimeContext *ctx)
138 {
139     g_free(ctx->page_fault_vcpu_time);
140     g_free(ctx->vcpu_addr);
141     g_free(ctx->vcpu_blocktime);
142     g_free(ctx);
143 }
144 
145 static void migration_exit_cb(Notifier *n, void *data)
146 {
147     PostcopyBlocktimeContext *ctx = container_of(n, PostcopyBlocktimeContext,
148                                                  exit_notifier);
149     destroy_blocktime_context(ctx);
150 }
151 
152 static struct PostcopyBlocktimeContext *blocktime_context_new(void)
153 {
154     MachineState *ms = MACHINE(qdev_get_machine());
155     unsigned int smp_cpus = ms->smp.cpus;
156     PostcopyBlocktimeContext *ctx = g_new0(PostcopyBlocktimeContext, 1);
157     ctx->page_fault_vcpu_time = g_new0(uint32_t, smp_cpus);
158     ctx->vcpu_addr = g_new0(uintptr_t, smp_cpus);
159     ctx->vcpu_blocktime = g_new0(uint32_t, smp_cpus);
160 
161     ctx->exit_notifier.notify = migration_exit_cb;
162     ctx->start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
163     qemu_add_exit_notifier(&ctx->exit_notifier);
164     return ctx;
165 }
166 
167 static uint32List *get_vcpu_blocktime_list(PostcopyBlocktimeContext *ctx)
168 {
169     MachineState *ms = MACHINE(qdev_get_machine());
170     uint32List *list = NULL;
171     int i;
172 
173     for (i = ms->smp.cpus - 1; i >= 0; i--) {
174         QAPI_LIST_PREPEND(list, ctx->vcpu_blocktime[i]);
175     }
176 
177     return list;
178 }
179 
180 /*
181  * This function just populates MigrationInfo from postcopy's
182  * blocktime context. It will not populate MigrationInfo,
183  * unless postcopy-blocktime capability was set.
184  *
185  * @info: pointer to MigrationInfo to populate
186  */
187 void fill_destination_postcopy_migration_info(MigrationInfo *info)
188 {
189     MigrationIncomingState *mis = migration_incoming_get_current();
190     PostcopyBlocktimeContext *bc = mis->blocktime_ctx;
191 
192     if (!bc) {
193         return;
194     }
195 
196     info->has_postcopy_blocktime = true;
197     info->postcopy_blocktime = bc->total_blocktime;
198     info->has_postcopy_vcpu_blocktime = true;
199     info->postcopy_vcpu_blocktime = get_vcpu_blocktime_list(bc);
200 }
201 
202 static uint32_t get_postcopy_total_blocktime(void)
203 {
204     MigrationIncomingState *mis = migration_incoming_get_current();
205     PostcopyBlocktimeContext *bc = mis->blocktime_ctx;
206 
207     if (!bc) {
208         return 0;
209     }
210 
211     return bc->total_blocktime;
212 }
213 
214 /**
215  * receive_ufd_features: check userfault fd features, to request only supported
216  * features in the future.
217  *
218  * Returns: true on success
219  *
220  * __NR_userfaultfd - should be checked before
221  *  @features: out parameter will contain uffdio_api.features provided by kernel
222  *              in case of success
223  */
224 static bool receive_ufd_features(uint64_t *features)
225 {
226     struct uffdio_api api_struct = {0};
227     int ufd;
228     bool ret = true;
229 
230     ufd = uffd_open(O_CLOEXEC);
231     if (ufd == -1) {
232         error_report("%s: uffd_open() failed: %s", __func__, strerror(errno));
233         return false;
234     }
235 
236     /* ask features */
237     api_struct.api = UFFD_API;
238     api_struct.features = 0;
239     if (ioctl(ufd, UFFDIO_API, &api_struct)) {
240         error_report("%s: UFFDIO_API failed: %s", __func__,
241                      strerror(errno));
242         ret = false;
243         goto release_ufd;
244     }
245 
246     *features = api_struct.features;
247 
248 release_ufd:
249     close(ufd);
250     return ret;
251 }
252 
253 /**
254  * request_ufd_features: this function should be called only once on a newly
255  * opened ufd, subsequent calls will lead to error.
256  *
257  * Returns: true on success
258  *
259  * @ufd: fd obtained from userfaultfd syscall
260  * @features: bit mask see UFFD_API_FEATURES
261  */
262 static bool request_ufd_features(int ufd, uint64_t features)
263 {
264     struct uffdio_api api_struct = {0};
265     uint64_t ioctl_mask;
266 
267     api_struct.api = UFFD_API;
268     api_struct.features = features;
269     if (ioctl(ufd, UFFDIO_API, &api_struct)) {
270         error_report("%s failed: UFFDIO_API failed: %s", __func__,
271                      strerror(errno));
272         return false;
273     }
274 
275     ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
276                  (__u64)1 << _UFFDIO_UNREGISTER;
277     if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
278         error_report("Missing userfault features: %" PRIx64,
279                      (uint64_t)(~api_struct.ioctls & ioctl_mask));
280         return false;
281     }
282 
283     return true;
284 }
285 
286 static bool ufd_check_and_apply(int ufd, MigrationIncomingState *mis)
287 {
288     uint64_t asked_features = 0;
289     static uint64_t supported_features;
290 
291     /*
292      * it's not possible to
293      * request UFFD_API twice per one fd
294      * userfault fd features is persistent
295      */
296     if (!supported_features) {
297         if (!receive_ufd_features(&supported_features)) {
298             error_report("%s failed", __func__);
299             return false;
300         }
301     }
302 
303 #ifdef UFFD_FEATURE_THREAD_ID
304     if (UFFD_FEATURE_THREAD_ID & supported_features) {
305         asked_features |= UFFD_FEATURE_THREAD_ID;
306         if (migrate_postcopy_blocktime()) {
307             if (!mis->blocktime_ctx) {
308                 mis->blocktime_ctx = blocktime_context_new();
309             }
310         }
311     }
312 #endif
313 
314     /*
315      * request features, even if asked_features is 0, due to
316      * kernel expects UFFD_API before UFFDIO_REGISTER, per
317      * userfault file descriptor
318      */
319     if (!request_ufd_features(ufd, asked_features)) {
320         error_report("%s failed: features %" PRIu64, __func__,
321                      asked_features);
322         return false;
323     }
324 
325     if (qemu_real_host_page_size() != ram_pagesize_summary()) {
326         bool have_hp = false;
327         /* We've got a huge page */
328 #ifdef UFFD_FEATURE_MISSING_HUGETLBFS
329         have_hp = supported_features & UFFD_FEATURE_MISSING_HUGETLBFS;
330 #endif
331         if (!have_hp) {
332             error_report("Userfault on this host does not support huge pages");
333             return false;
334         }
335     }
336     return true;
337 }
338 
339 /* Callback from postcopy_ram_supported_by_host block iterator.
340  */
341 static int test_ramblock_postcopiable(RAMBlock *rb, void *opaque)
342 {
343     const char *block_name = qemu_ram_get_idstr(rb);
344     ram_addr_t length = qemu_ram_get_used_length(rb);
345     size_t pagesize = qemu_ram_pagesize(rb);
346 
347     if (length % pagesize) {
348         error_report("Postcopy requires RAM blocks to be a page size multiple,"
349                      " block %s is 0x" RAM_ADDR_FMT " bytes with a "
350                      "page size of 0x%zx", block_name, length, pagesize);
351         return 1;
352     }
353     return 0;
354 }
355 
356 /*
357  * Note: This has the side effect of munlock'ing all of RAM, that's
358  * normally fine since if the postcopy succeeds it gets turned back on at the
359  * end.
360  */
361 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
362 {
363     long pagesize = qemu_real_host_page_size();
364     int ufd = -1;
365     bool ret = false; /* Error unless we change it */
366     void *testarea = NULL;
367     struct uffdio_register reg_struct;
368     struct uffdio_range range_struct;
369     uint64_t feature_mask;
370     Error *local_err = NULL;
371 
372     if (qemu_target_page_size() > pagesize) {
373         error_report("Target page size bigger than host page size");
374         goto out;
375     }
376 
377     ufd = uffd_open(O_CLOEXEC);
378     if (ufd == -1) {
379         error_report("%s: userfaultfd not available: %s", __func__,
380                      strerror(errno));
381         goto out;
382     }
383 
384     /* Give devices a chance to object */
385     if (postcopy_notify(POSTCOPY_NOTIFY_PROBE, &local_err)) {
386         error_report_err(local_err);
387         goto out;
388     }
389 
390     /* Version and features check */
391     if (!ufd_check_and_apply(ufd, mis)) {
392         goto out;
393     }
394 
395     /* We don't support postcopy with shared RAM yet */
396     if (foreach_not_ignored_block(test_ramblock_postcopiable, NULL)) {
397         goto out;
398     }
399 
400     /*
401      * userfault and mlock don't go together; we'll put it back later if
402      * it was enabled.
403      */
404     if (munlockall()) {
405         error_report("%s: munlockall: %s", __func__,  strerror(errno));
406         goto out;
407     }
408 
409     /*
410      *  We need to check that the ops we need are supported on anon memory
411      *  To do that we need to register a chunk and see the flags that
412      *  are returned.
413      */
414     testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE |
415                                     MAP_ANONYMOUS, -1, 0);
416     if (testarea == MAP_FAILED) {
417         error_report("%s: Failed to map test area: %s", __func__,
418                      strerror(errno));
419         goto out;
420     }
421     g_assert(QEMU_PTR_IS_ALIGNED(testarea, pagesize));
422 
423     reg_struct.range.start = (uintptr_t)testarea;
424     reg_struct.range.len = pagesize;
425     reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
426 
427     if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
428         error_report("%s userfault register: %s", __func__, strerror(errno));
429         goto out;
430     }
431 
432     range_struct.start = (uintptr_t)testarea;
433     range_struct.len = pagesize;
434     if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) {
435         error_report("%s userfault unregister: %s", __func__, strerror(errno));
436         goto out;
437     }
438 
439     feature_mask = (__u64)1 << _UFFDIO_WAKE |
440                    (__u64)1 << _UFFDIO_COPY |
441                    (__u64)1 << _UFFDIO_ZEROPAGE;
442     if ((reg_struct.ioctls & feature_mask) != feature_mask) {
443         error_report("Missing userfault map features: %" PRIx64,
444                      (uint64_t)(~reg_struct.ioctls & feature_mask));
445         goto out;
446     }
447 
448     /* Success! */
449     ret = true;
450 out:
451     if (testarea) {
452         munmap(testarea, pagesize);
453     }
454     if (ufd != -1) {
455         close(ufd);
456     }
457     return ret;
458 }
459 
460 /*
461  * Setup an area of RAM so that it *can* be used for postcopy later; this
462  * must be done right at the start prior to pre-copy.
463  * opaque should be the MIS.
464  */
465 static int init_range(RAMBlock *rb, void *opaque)
466 {
467     const char *block_name = qemu_ram_get_idstr(rb);
468     void *host_addr = qemu_ram_get_host_addr(rb);
469     ram_addr_t offset = qemu_ram_get_offset(rb);
470     ram_addr_t length = qemu_ram_get_used_length(rb);
471     trace_postcopy_init_range(block_name, host_addr, offset, length);
472 
473     /*
474      * Save the used_length before running the guest. In case we have to
475      * resize RAM blocks when syncing RAM block sizes from the source during
476      * precopy, we'll update it manually via the ram block notifier.
477      */
478     rb->postcopy_length = length;
479 
480     /*
481      * We need the whole of RAM to be truly empty for postcopy, so things
482      * like ROMs and any data tables built during init must be zero'd
483      * - we're going to get the copy from the source anyway.
484      * (Precopy will just overwrite this data, so doesn't need the discard)
485      */
486     if (ram_discard_range(block_name, 0, length)) {
487         return -1;
488     }
489 
490     return 0;
491 }
492 
493 /*
494  * At the end of migration, undo the effects of init_range
495  * opaque should be the MIS.
496  */
497 static int cleanup_range(RAMBlock *rb, void *opaque)
498 {
499     const char *block_name = qemu_ram_get_idstr(rb);
500     void *host_addr = qemu_ram_get_host_addr(rb);
501     ram_addr_t offset = qemu_ram_get_offset(rb);
502     ram_addr_t length = rb->postcopy_length;
503     MigrationIncomingState *mis = opaque;
504     struct uffdio_range range_struct;
505     trace_postcopy_cleanup_range(block_name, host_addr, offset, length);
506 
507     /*
508      * We turned off hugepage for the precopy stage with postcopy enabled
509      * we can turn it back on now.
510      */
511     qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE);
512 
513     /*
514      * We can also turn off userfault now since we should have all the
515      * pages.   It can be useful to leave it on to debug postcopy
516      * if you're not sure it's always getting every page.
517      */
518     range_struct.start = (uintptr_t)host_addr;
519     range_struct.len = length;
520 
521     if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
522         error_report("%s: userfault unregister %s", __func__, strerror(errno));
523 
524         return -1;
525     }
526 
527     return 0;
528 }
529 
530 /*
531  * Initialise postcopy-ram, setting the RAM to a state where we can go into
532  * postcopy later; must be called prior to any precopy.
533  * called from arch_init's similarly named ram_postcopy_incoming_init
534  */
535 int postcopy_ram_incoming_init(MigrationIncomingState *mis)
536 {
537     if (foreach_not_ignored_block(init_range, NULL)) {
538         return -1;
539     }
540 
541     return 0;
542 }
543 
544 static void postcopy_temp_pages_cleanup(MigrationIncomingState *mis)
545 {
546     int i;
547 
548     if (mis->postcopy_tmp_pages) {
549         for (i = 0; i < mis->postcopy_channels; i++) {
550             if (mis->postcopy_tmp_pages[i].tmp_huge_page) {
551                 munmap(mis->postcopy_tmp_pages[i].tmp_huge_page,
552                        mis->largest_page_size);
553                 mis->postcopy_tmp_pages[i].tmp_huge_page = NULL;
554             }
555         }
556         g_free(mis->postcopy_tmp_pages);
557         mis->postcopy_tmp_pages = NULL;
558     }
559 
560     if (mis->postcopy_tmp_zero_page) {
561         munmap(mis->postcopy_tmp_zero_page, mis->largest_page_size);
562         mis->postcopy_tmp_zero_page = NULL;
563     }
564 }
565 
566 /*
567  * At the end of a migration where postcopy_ram_incoming_init was called.
568  */
569 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
570 {
571     trace_postcopy_ram_incoming_cleanup_entry();
572 
573     if (mis->postcopy_prio_thread_created) {
574         qemu_thread_join(&mis->postcopy_prio_thread);
575         mis->postcopy_prio_thread_created = false;
576     }
577 
578     if (mis->have_fault_thread) {
579         Error *local_err = NULL;
580 
581         /* Let the fault thread quit */
582         qatomic_set(&mis->fault_thread_quit, 1);
583         postcopy_fault_thread_notify(mis);
584         trace_postcopy_ram_incoming_cleanup_join();
585         qemu_thread_join(&mis->fault_thread);
586 
587         if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_END, &local_err)) {
588             error_report_err(local_err);
589             return -1;
590         }
591 
592         if (foreach_not_ignored_block(cleanup_range, mis)) {
593             return -1;
594         }
595 
596         trace_postcopy_ram_incoming_cleanup_closeuf();
597         close(mis->userfault_fd);
598         close(mis->userfault_event_fd);
599         mis->have_fault_thread = false;
600     }
601 
602     if (enable_mlock) {
603         if (os_mlock() < 0) {
604             error_report("mlock: %s", strerror(errno));
605             /*
606              * It doesn't feel right to fail at this point, we have a valid
607              * VM state.
608              */
609         }
610     }
611 
612     postcopy_temp_pages_cleanup(mis);
613 
614     trace_postcopy_ram_incoming_cleanup_blocktime(
615             get_postcopy_total_blocktime());
616 
617     trace_postcopy_ram_incoming_cleanup_exit();
618     return 0;
619 }
620 
621 /*
622  * Disable huge pages on an area
623  */
624 static int nhp_range(RAMBlock *rb, void *opaque)
625 {
626     const char *block_name = qemu_ram_get_idstr(rb);
627     void *host_addr = qemu_ram_get_host_addr(rb);
628     ram_addr_t offset = qemu_ram_get_offset(rb);
629     ram_addr_t length = rb->postcopy_length;
630     trace_postcopy_nhp_range(block_name, host_addr, offset, length);
631 
632     /*
633      * Before we do discards we need to ensure those discards really
634      * do delete areas of the page, even if THP thinks a hugepage would
635      * be a good idea, so force hugepages off.
636      */
637     qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE);
638 
639     return 0;
640 }
641 
642 /*
643  * Userfault requires us to mark RAM as NOHUGEPAGE prior to discard
644  * however leaving it until after precopy means that most of the precopy
645  * data is still THPd
646  */
647 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
648 {
649     if (foreach_not_ignored_block(nhp_range, mis)) {
650         return -1;
651     }
652 
653     postcopy_state_set(POSTCOPY_INCOMING_DISCARD);
654 
655     return 0;
656 }
657 
658 /*
659  * Mark the given area of RAM as requiring notification to unwritten areas
660  * Used as a  callback on foreach_not_ignored_block.
661  *   host_addr: Base of area to mark
662  *   offset: Offset in the whole ram arena
663  *   length: Length of the section
664  *   opaque: MigrationIncomingState pointer
665  * Returns 0 on success
666  */
667 static int ram_block_enable_notify(RAMBlock *rb, void *opaque)
668 {
669     MigrationIncomingState *mis = opaque;
670     struct uffdio_register reg_struct;
671 
672     reg_struct.range.start = (uintptr_t)qemu_ram_get_host_addr(rb);
673     reg_struct.range.len = rb->postcopy_length;
674     reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
675 
676     /* Now tell our userfault_fd that it's responsible for this area */
677     if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
678         error_report("%s userfault register: %s", __func__, strerror(errno));
679         return -1;
680     }
681     if (!(reg_struct.ioctls & ((__u64)1 << _UFFDIO_COPY))) {
682         error_report("%s userfault: Region doesn't support COPY", __func__);
683         return -1;
684     }
685     if (reg_struct.ioctls & ((__u64)1 << _UFFDIO_ZEROPAGE)) {
686         qemu_ram_set_uf_zeroable(rb);
687     }
688 
689     return 0;
690 }
691 
692 int postcopy_wake_shared(struct PostCopyFD *pcfd,
693                          uint64_t client_addr,
694                          RAMBlock *rb)
695 {
696     size_t pagesize = qemu_ram_pagesize(rb);
697     struct uffdio_range range;
698     int ret;
699     trace_postcopy_wake_shared(client_addr, qemu_ram_get_idstr(rb));
700     range.start = ROUND_DOWN(client_addr, pagesize);
701     range.len = pagesize;
702     ret = ioctl(pcfd->fd, UFFDIO_WAKE, &range);
703     if (ret) {
704         error_report("%s: Failed to wake: %zx in %s (%s)",
705                      __func__, (size_t)client_addr, qemu_ram_get_idstr(rb),
706                      strerror(errno));
707     }
708     return ret;
709 }
710 
711 static int postcopy_request_page(MigrationIncomingState *mis, RAMBlock *rb,
712                                  ram_addr_t start, uint64_t haddr)
713 {
714     void *aligned = (void *)(uintptr_t)ROUND_DOWN(haddr, qemu_ram_pagesize(rb));
715 
716     /*
717      * Discarded pages (via RamDiscardManager) are never migrated. On unlikely
718      * access, place a zeropage, which will also set the relevant bits in the
719      * recv_bitmap accordingly, so we won't try placing a zeropage twice.
720      *
721      * Checking a single bit is sufficient to handle pagesize > TPS as either
722      * all relevant bits are set or not.
723      */
724     assert(QEMU_IS_ALIGNED(start, qemu_ram_pagesize(rb)));
725     if (ramblock_page_is_discarded(rb, start)) {
726         bool received = ramblock_recv_bitmap_test_byte_offset(rb, start);
727 
728         return received ? 0 : postcopy_place_page_zero(mis, aligned, rb);
729     }
730 
731     return migrate_send_rp_req_pages(mis, rb, start, haddr);
732 }
733 
734 /*
735  * Callback from shared fault handlers to ask for a page,
736  * the page must be specified by a RAMBlock and an offset in that rb
737  * Note: Only for use by shared fault handlers (in fault thread)
738  */
739 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb,
740                                  uint64_t client_addr, uint64_t rb_offset)
741 {
742     uint64_t aligned_rbo = ROUND_DOWN(rb_offset, qemu_ram_pagesize(rb));
743     MigrationIncomingState *mis = migration_incoming_get_current();
744 
745     trace_postcopy_request_shared_page(pcfd->idstr, qemu_ram_get_idstr(rb),
746                                        rb_offset);
747     if (ramblock_recv_bitmap_test_byte_offset(rb, aligned_rbo)) {
748         trace_postcopy_request_shared_page_present(pcfd->idstr,
749                                         qemu_ram_get_idstr(rb), rb_offset);
750         return postcopy_wake_shared(pcfd, client_addr, rb);
751     }
752     postcopy_request_page(mis, rb, aligned_rbo, client_addr);
753     return 0;
754 }
755 
756 static int get_mem_fault_cpu_index(uint32_t pid)
757 {
758     CPUState *cpu_iter;
759 
760     CPU_FOREACH(cpu_iter) {
761         if (cpu_iter->thread_id == pid) {
762             trace_get_mem_fault_cpu_index(cpu_iter->cpu_index, pid);
763             return cpu_iter->cpu_index;
764         }
765     }
766     trace_get_mem_fault_cpu_index(-1, pid);
767     return -1;
768 }
769 
770 static uint32_t get_low_time_offset(PostcopyBlocktimeContext *dc)
771 {
772     int64_t start_time_offset = qemu_clock_get_ms(QEMU_CLOCK_REALTIME) -
773                                     dc->start_time;
774     return start_time_offset < 1 ? 1 : start_time_offset & UINT32_MAX;
775 }
776 
777 /*
778  * This function is being called when pagefault occurs. It
779  * tracks down vCPU blocking time.
780  *
781  * @addr: faulted host virtual address
782  * @ptid: faulted process thread id
783  * @rb: ramblock appropriate to addr
784  */
785 static void mark_postcopy_blocktime_begin(uintptr_t addr, uint32_t ptid,
786                                           RAMBlock *rb)
787 {
788     int cpu, already_received;
789     MigrationIncomingState *mis = migration_incoming_get_current();
790     PostcopyBlocktimeContext *dc = mis->blocktime_ctx;
791     uint32_t low_time_offset;
792 
793     if (!dc || ptid == 0) {
794         return;
795     }
796     cpu = get_mem_fault_cpu_index(ptid);
797     if (cpu < 0) {
798         return;
799     }
800 
801     low_time_offset = get_low_time_offset(dc);
802     if (dc->vcpu_addr[cpu] == 0) {
803         qatomic_inc(&dc->smp_cpus_down);
804     }
805 
806     qatomic_xchg(&dc->last_begin, low_time_offset);
807     qatomic_xchg(&dc->page_fault_vcpu_time[cpu], low_time_offset);
808     qatomic_xchg(&dc->vcpu_addr[cpu], addr);
809 
810     /*
811      * check it here, not at the beginning of the function,
812      * due to, check could occur early than bitmap_set in
813      * qemu_ufd_copy_ioctl
814      */
815     already_received = ramblock_recv_bitmap_test(rb, (void *)addr);
816     if (already_received) {
817         qatomic_xchg(&dc->vcpu_addr[cpu], 0);
818         qatomic_xchg(&dc->page_fault_vcpu_time[cpu], 0);
819         qatomic_dec(&dc->smp_cpus_down);
820     }
821     trace_mark_postcopy_blocktime_begin(addr, dc, dc->page_fault_vcpu_time[cpu],
822                                         cpu, already_received);
823 }
824 
825 /*
826  *  This function just provide calculated blocktime per cpu and trace it.
827  *  Total blocktime is calculated in mark_postcopy_blocktime_end.
828  *
829  *
830  * Assume we have 3 CPU
831  *
832  *      S1        E1           S1               E1
833  * -----***********------------xxx***************------------------------> CPU1
834  *
835  *             S2                E2
836  * ------------****************xxx---------------------------------------> CPU2
837  *
838  *                         S3            E3
839  * ------------------------****xxx********-------------------------------> CPU3
840  *
841  * We have sequence S1,S2,E1,S3,S1,E2,E3,E1
842  * S2,E1 - doesn't match condition due to sequence S1,S2,E1 doesn't include CPU3
843  * S3,S1,E2 - sequence includes all CPUs, in this case overlap will be S1,E2 -
844  *            it's a part of total blocktime.
845  * S1 - here is last_begin
846  * Legend of the picture is following:
847  *              * - means blocktime per vCPU
848  *              x - means overlapped blocktime (total blocktime)
849  *
850  * @addr: host virtual address
851  */
852 static void mark_postcopy_blocktime_end(uintptr_t addr)
853 {
854     MigrationIncomingState *mis = migration_incoming_get_current();
855     PostcopyBlocktimeContext *dc = mis->blocktime_ctx;
856     MachineState *ms = MACHINE(qdev_get_machine());
857     unsigned int smp_cpus = ms->smp.cpus;
858     int i, affected_cpu = 0;
859     bool vcpu_total_blocktime = false;
860     uint32_t read_vcpu_time, low_time_offset;
861 
862     if (!dc) {
863         return;
864     }
865 
866     low_time_offset = get_low_time_offset(dc);
867     /* lookup cpu, to clear it,
868      * that algorithm looks straightforward, but it's not
869      * optimal, more optimal algorithm is keeping tree or hash
870      * where key is address value is a list of  */
871     for (i = 0; i < smp_cpus; i++) {
872         uint32_t vcpu_blocktime = 0;
873 
874         read_vcpu_time = qatomic_fetch_add(&dc->page_fault_vcpu_time[i], 0);
875         if (qatomic_fetch_add(&dc->vcpu_addr[i], 0) != addr ||
876             read_vcpu_time == 0) {
877             continue;
878         }
879         qatomic_xchg(&dc->vcpu_addr[i], 0);
880         vcpu_blocktime = low_time_offset - read_vcpu_time;
881         affected_cpu += 1;
882         /* we need to know is that mark_postcopy_end was due to
883          * faulted page, another possible case it's prefetched
884          * page and in that case we shouldn't be here */
885         if (!vcpu_total_blocktime &&
886             qatomic_fetch_add(&dc->smp_cpus_down, 0) == smp_cpus) {
887             vcpu_total_blocktime = true;
888         }
889         /* continue cycle, due to one page could affect several vCPUs */
890         dc->vcpu_blocktime[i] += vcpu_blocktime;
891     }
892 
893     qatomic_sub(&dc->smp_cpus_down, affected_cpu);
894     if (vcpu_total_blocktime) {
895         dc->total_blocktime += low_time_offset - qatomic_fetch_add(
896                 &dc->last_begin, 0);
897     }
898     trace_mark_postcopy_blocktime_end(addr, dc, dc->total_blocktime,
899                                       affected_cpu);
900 }
901 
902 static void postcopy_pause_fault_thread(MigrationIncomingState *mis)
903 {
904     trace_postcopy_pause_fault_thread();
905     qemu_sem_wait(&mis->postcopy_pause_sem_fault);
906     trace_postcopy_pause_fault_thread_continued();
907 }
908 
909 /*
910  * Handle faults detected by the USERFAULT markings
911  */
912 static void *postcopy_ram_fault_thread(void *opaque)
913 {
914     MigrationIncomingState *mis = opaque;
915     struct uffd_msg msg;
916     int ret;
917     size_t index;
918     RAMBlock *rb = NULL;
919 
920     trace_postcopy_ram_fault_thread_entry();
921     rcu_register_thread();
922     mis->last_rb = NULL; /* last RAMBlock we sent part of */
923     qemu_sem_post(&mis->thread_sync_sem);
924 
925     struct pollfd *pfd;
926     size_t pfd_len = 2 + mis->postcopy_remote_fds->len;
927 
928     pfd = g_new0(struct pollfd, pfd_len);
929 
930     pfd[0].fd = mis->userfault_fd;
931     pfd[0].events = POLLIN;
932     pfd[1].fd = mis->userfault_event_fd;
933     pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
934     trace_postcopy_ram_fault_thread_fds_core(pfd[0].fd, pfd[1].fd);
935     for (index = 0; index < mis->postcopy_remote_fds->len; index++) {
936         struct PostCopyFD *pcfd = &g_array_index(mis->postcopy_remote_fds,
937                                                  struct PostCopyFD, index);
938         pfd[2 + index].fd = pcfd->fd;
939         pfd[2 + index].events = POLLIN;
940         trace_postcopy_ram_fault_thread_fds_extra(2 + index, pcfd->idstr,
941                                                   pcfd->fd);
942     }
943 
944     while (true) {
945         ram_addr_t rb_offset;
946         int poll_result;
947 
948         /*
949          * We're mainly waiting for the kernel to give us a faulting HVA,
950          * however we can be told to quit via userfault_quit_fd which is
951          * an eventfd
952          */
953 
954         poll_result = poll(pfd, pfd_len, -1 /* Wait forever */);
955         if (poll_result == -1) {
956             error_report("%s: userfault poll: %s", __func__, strerror(errno));
957             break;
958         }
959 
960         if (!mis->to_src_file) {
961             /*
962              * Possibly someone tells us that the return path is
963              * broken already using the event. We should hold until
964              * the channel is rebuilt.
965              */
966             postcopy_pause_fault_thread(mis);
967         }
968 
969         if (pfd[1].revents) {
970             uint64_t tmp64 = 0;
971 
972             /* Consume the signal */
973             if (read(mis->userfault_event_fd, &tmp64, 8) != 8) {
974                 /* Nothing obviously nicer than posting this error. */
975                 error_report("%s: read() failed", __func__);
976             }
977 
978             if (qatomic_read(&mis->fault_thread_quit)) {
979                 trace_postcopy_ram_fault_thread_quit();
980                 break;
981             }
982         }
983 
984         if (pfd[0].revents) {
985             poll_result--;
986             ret = read(mis->userfault_fd, &msg, sizeof(msg));
987             if (ret != sizeof(msg)) {
988                 if (errno == EAGAIN) {
989                     /*
990                      * if a wake up happens on the other thread just after
991                      * the poll, there is nothing to read.
992                      */
993                     continue;
994                 }
995                 if (ret < 0) {
996                     error_report("%s: Failed to read full userfault "
997                                  "message: %s",
998                                  __func__, strerror(errno));
999                     break;
1000                 } else {
1001                     error_report("%s: Read %d bytes from userfaultfd "
1002                                  "expected %zd",
1003                                  __func__, ret, sizeof(msg));
1004                     break; /* Lost alignment, don't know what we'd read next */
1005                 }
1006             }
1007             if (msg.event != UFFD_EVENT_PAGEFAULT) {
1008                 error_report("%s: Read unexpected event %ud from userfaultfd",
1009                              __func__, msg.event);
1010                 continue; /* It's not a page fault, shouldn't happen */
1011             }
1012 
1013             rb = qemu_ram_block_from_host(
1014                      (void *)(uintptr_t)msg.arg.pagefault.address,
1015                      true, &rb_offset);
1016             if (!rb) {
1017                 error_report("postcopy_ram_fault_thread: Fault outside guest: %"
1018                              PRIx64, (uint64_t)msg.arg.pagefault.address);
1019                 break;
1020             }
1021 
1022             rb_offset = ROUND_DOWN(rb_offset, qemu_ram_pagesize(rb));
1023             trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,
1024                                                 qemu_ram_get_idstr(rb),
1025                                                 rb_offset,
1026                                                 msg.arg.pagefault.feat.ptid);
1027             mark_postcopy_blocktime_begin(
1028                     (uintptr_t)(msg.arg.pagefault.address),
1029                                 msg.arg.pagefault.feat.ptid, rb);
1030 
1031 retry:
1032             /*
1033              * Send the request to the source - we want to request one
1034              * of our host page sizes (which is >= TPS)
1035              */
1036             ret = postcopy_request_page(mis, rb, rb_offset,
1037                                         msg.arg.pagefault.address);
1038             if (ret) {
1039                 /* May be network failure, try to wait for recovery */
1040                 postcopy_pause_fault_thread(mis);
1041                 goto retry;
1042             }
1043         }
1044 
1045         /* Now handle any requests from external processes on shared memory */
1046         /* TODO: May need to handle devices deregistering during postcopy */
1047         for (index = 2; index < pfd_len && poll_result; index++) {
1048             if (pfd[index].revents) {
1049                 struct PostCopyFD *pcfd =
1050                     &g_array_index(mis->postcopy_remote_fds,
1051                                    struct PostCopyFD, index - 2);
1052 
1053                 poll_result--;
1054                 if (pfd[index].revents & POLLERR) {
1055                     error_report("%s: POLLERR on poll %zd fd=%d",
1056                                  __func__, index, pcfd->fd);
1057                     pfd[index].events = 0;
1058                     continue;
1059                 }
1060 
1061                 ret = read(pcfd->fd, &msg, sizeof(msg));
1062                 if (ret != sizeof(msg)) {
1063                     if (errno == EAGAIN) {
1064                         /*
1065                          * if a wake up happens on the other thread just after
1066                          * the poll, there is nothing to read.
1067                          */
1068                         continue;
1069                     }
1070                     if (ret < 0) {
1071                         error_report("%s: Failed to read full userfault "
1072                                      "message: %s (shared) revents=%d",
1073                                      __func__, strerror(errno),
1074                                      pfd[index].revents);
1075                         /*TODO: Could just disable this sharer */
1076                         break;
1077                     } else {
1078                         error_report("%s: Read %d bytes from userfaultfd "
1079                                      "expected %zd (shared)",
1080                                      __func__, ret, sizeof(msg));
1081                         /*TODO: Could just disable this sharer */
1082                         break; /*Lost alignment,don't know what we'd read next*/
1083                     }
1084                 }
1085                 if (msg.event != UFFD_EVENT_PAGEFAULT) {
1086                     error_report("%s: Read unexpected event %ud "
1087                                  "from userfaultfd (shared)",
1088                                  __func__, msg.event);
1089                     continue; /* It's not a page fault, shouldn't happen */
1090                 }
1091                 /* Call the device handler registered with us */
1092                 ret = pcfd->handler(pcfd, &msg);
1093                 if (ret) {
1094                     error_report("%s: Failed to resolve shared fault on %zd/%s",
1095                                  __func__, index, pcfd->idstr);
1096                     /* TODO: Fail? Disable this sharer? */
1097                 }
1098             }
1099         }
1100     }
1101     rcu_unregister_thread();
1102     trace_postcopy_ram_fault_thread_exit();
1103     g_free(pfd);
1104     return NULL;
1105 }
1106 
1107 static int postcopy_temp_pages_setup(MigrationIncomingState *mis)
1108 {
1109     PostcopyTmpPage *tmp_page;
1110     int err, i, channels;
1111     void *temp_page;
1112 
1113     if (migrate_postcopy_preempt()) {
1114         /* If preemption enabled, need extra channel for urgent requests */
1115         mis->postcopy_channels = RAM_CHANNEL_MAX;
1116     } else {
1117         /* Both precopy/postcopy on the same channel */
1118         mis->postcopy_channels = 1;
1119     }
1120 
1121     channels = mis->postcopy_channels;
1122     mis->postcopy_tmp_pages = g_malloc0_n(sizeof(PostcopyTmpPage), channels);
1123 
1124     for (i = 0; i < channels; i++) {
1125         tmp_page = &mis->postcopy_tmp_pages[i];
1126         temp_page = mmap(NULL, mis->largest_page_size, PROT_READ | PROT_WRITE,
1127                          MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1128         if (temp_page == MAP_FAILED) {
1129             err = errno;
1130             error_report("%s: Failed to map postcopy_tmp_pages[%d]: %s",
1131                          __func__, i, strerror(err));
1132             /* Clean up will be done later */
1133             return -err;
1134         }
1135         tmp_page->tmp_huge_page = temp_page;
1136         /* Initialize default states for each tmp page */
1137         postcopy_temp_page_reset(tmp_page);
1138     }
1139 
1140     /*
1141      * Map large zero page when kernel can't use UFFDIO_ZEROPAGE for hugepages
1142      */
1143     mis->postcopy_tmp_zero_page = mmap(NULL, mis->largest_page_size,
1144                                        PROT_READ | PROT_WRITE,
1145                                        MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1146     if (mis->postcopy_tmp_zero_page == MAP_FAILED) {
1147         err = errno;
1148         mis->postcopy_tmp_zero_page = NULL;
1149         error_report("%s: Failed to map large zero page %s",
1150                      __func__, strerror(err));
1151         return -err;
1152     }
1153 
1154     memset(mis->postcopy_tmp_zero_page, '\0', mis->largest_page_size);
1155 
1156     return 0;
1157 }
1158 
1159 int postcopy_ram_incoming_setup(MigrationIncomingState *mis)
1160 {
1161     /* Open the fd for the kernel to give us userfaults */
1162     mis->userfault_fd = uffd_open(O_CLOEXEC | O_NONBLOCK);
1163     if (mis->userfault_fd == -1) {
1164         error_report("%s: Failed to open userfault fd: %s", __func__,
1165                      strerror(errno));
1166         return -1;
1167     }
1168 
1169     /*
1170      * Although the host check already tested the API, we need to
1171      * do the check again as an ABI handshake on the new fd.
1172      */
1173     if (!ufd_check_and_apply(mis->userfault_fd, mis)) {
1174         return -1;
1175     }
1176 
1177     /* Now an eventfd we use to tell the fault-thread to quit */
1178     mis->userfault_event_fd = eventfd(0, EFD_CLOEXEC);
1179     if (mis->userfault_event_fd == -1) {
1180         error_report("%s: Opening userfault_event_fd: %s", __func__,
1181                      strerror(errno));
1182         close(mis->userfault_fd);
1183         return -1;
1184     }
1185 
1186     postcopy_thread_create(mis, &mis->fault_thread, "fault-default",
1187                            postcopy_ram_fault_thread, QEMU_THREAD_JOINABLE);
1188     mis->have_fault_thread = true;
1189 
1190     /* Mark so that we get notified of accesses to unwritten areas */
1191     if (foreach_not_ignored_block(ram_block_enable_notify, mis)) {
1192         error_report("ram_block_enable_notify failed");
1193         return -1;
1194     }
1195 
1196     if (postcopy_temp_pages_setup(mis)) {
1197         /* Error dumped in the sub-function */
1198         return -1;
1199     }
1200 
1201     if (migrate_postcopy_preempt()) {
1202         /*
1203          * This thread needs to be created after the temp pages because
1204          * it'll fetch RAM_CHANNEL_POSTCOPY PostcopyTmpPage immediately.
1205          */
1206         postcopy_thread_create(mis, &mis->postcopy_prio_thread, "fault-fast",
1207                                postcopy_preempt_thread, QEMU_THREAD_JOINABLE);
1208         mis->postcopy_prio_thread_created = true;
1209     }
1210 
1211     trace_postcopy_ram_enable_notify();
1212 
1213     return 0;
1214 }
1215 
1216 static int qemu_ufd_copy_ioctl(MigrationIncomingState *mis, void *host_addr,
1217                                void *from_addr, uint64_t pagesize, RAMBlock *rb)
1218 {
1219     int userfault_fd = mis->userfault_fd;
1220     int ret;
1221 
1222     if (from_addr) {
1223         struct uffdio_copy copy_struct;
1224         copy_struct.dst = (uint64_t)(uintptr_t)host_addr;
1225         copy_struct.src = (uint64_t)(uintptr_t)from_addr;
1226         copy_struct.len = pagesize;
1227         copy_struct.mode = 0;
1228         ret = ioctl(userfault_fd, UFFDIO_COPY, &copy_struct);
1229     } else {
1230         struct uffdio_zeropage zero_struct;
1231         zero_struct.range.start = (uint64_t)(uintptr_t)host_addr;
1232         zero_struct.range.len = pagesize;
1233         zero_struct.mode = 0;
1234         ret = ioctl(userfault_fd, UFFDIO_ZEROPAGE, &zero_struct);
1235     }
1236     if (!ret) {
1237         qemu_mutex_lock(&mis->page_request_mutex);
1238         ramblock_recv_bitmap_set_range(rb, host_addr,
1239                                        pagesize / qemu_target_page_size());
1240         /*
1241          * If this page resolves a page fault for a previous recorded faulted
1242          * address, take a special note to maintain the requested page list.
1243          */
1244         if (g_tree_lookup(mis->page_requested, host_addr)) {
1245             g_tree_remove(mis->page_requested, host_addr);
1246             mis->page_requested_count--;
1247             trace_postcopy_page_req_del(host_addr, mis->page_requested_count);
1248         }
1249         qemu_mutex_unlock(&mis->page_request_mutex);
1250         mark_postcopy_blocktime_end((uintptr_t)host_addr);
1251     }
1252     return ret;
1253 }
1254 
1255 int postcopy_notify_shared_wake(RAMBlock *rb, uint64_t offset)
1256 {
1257     int i;
1258     MigrationIncomingState *mis = migration_incoming_get_current();
1259     GArray *pcrfds = mis->postcopy_remote_fds;
1260 
1261     for (i = 0; i < pcrfds->len; i++) {
1262         struct PostCopyFD *cur = &g_array_index(pcrfds, struct PostCopyFD, i);
1263         int ret = cur->waker(cur, rb, offset);
1264         if (ret) {
1265             return ret;
1266         }
1267     }
1268     return 0;
1269 }
1270 
1271 /*
1272  * Place a host page (from) at (host) atomically
1273  * returns 0 on success
1274  */
1275 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
1276                         RAMBlock *rb)
1277 {
1278     size_t pagesize = qemu_ram_pagesize(rb);
1279 
1280     /* copy also acks to the kernel waking the stalled thread up
1281      * TODO: We can inhibit that ack and only do it if it was requested
1282      * which would be slightly cheaper, but we'd have to be careful
1283      * of the order of updating our page state.
1284      */
1285     if (qemu_ufd_copy_ioctl(mis, host, from, pagesize, rb)) {
1286         int e = errno;
1287         error_report("%s: %s copy host: %p from: %p (size: %zd)",
1288                      __func__, strerror(e), host, from, pagesize);
1289 
1290         return -e;
1291     }
1292 
1293     trace_postcopy_place_page(host);
1294     return postcopy_notify_shared_wake(rb,
1295                                        qemu_ram_block_host_offset(rb, host));
1296 }
1297 
1298 /*
1299  * Place a zero page at (host) atomically
1300  * returns 0 on success
1301  */
1302 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
1303                              RAMBlock *rb)
1304 {
1305     size_t pagesize = qemu_ram_pagesize(rb);
1306     trace_postcopy_place_page_zero(host);
1307 
1308     /* Normal RAMBlocks can zero a page using UFFDIO_ZEROPAGE
1309      * but it's not available for everything (e.g. hugetlbpages)
1310      */
1311     if (qemu_ram_is_uf_zeroable(rb)) {
1312         if (qemu_ufd_copy_ioctl(mis, host, NULL, pagesize, rb)) {
1313             int e = errno;
1314             error_report("%s: %s zero host: %p",
1315                          __func__, strerror(e), host);
1316 
1317             return -e;
1318         }
1319         return postcopy_notify_shared_wake(rb,
1320                                            qemu_ram_block_host_offset(rb,
1321                                                                       host));
1322     } else {
1323         return postcopy_place_page(mis, host, mis->postcopy_tmp_zero_page, rb);
1324     }
1325 }
1326 
1327 #else
1328 /* No target OS support, stubs just fail */
1329 void fill_destination_postcopy_migration_info(MigrationInfo *info)
1330 {
1331 }
1332 
1333 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
1334 {
1335     error_report("%s: No OS support", __func__);
1336     return false;
1337 }
1338 
1339 int postcopy_ram_incoming_init(MigrationIncomingState *mis)
1340 {
1341     error_report("postcopy_ram_incoming_init: No OS support");
1342     return -1;
1343 }
1344 
1345 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
1346 {
1347     assert(0);
1348     return -1;
1349 }
1350 
1351 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
1352 {
1353     assert(0);
1354     return -1;
1355 }
1356 
1357 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb,
1358                                  uint64_t client_addr, uint64_t rb_offset)
1359 {
1360     assert(0);
1361     return -1;
1362 }
1363 
1364 int postcopy_ram_incoming_setup(MigrationIncomingState *mis)
1365 {
1366     assert(0);
1367     return -1;
1368 }
1369 
1370 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
1371                         RAMBlock *rb)
1372 {
1373     assert(0);
1374     return -1;
1375 }
1376 
1377 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
1378                         RAMBlock *rb)
1379 {
1380     assert(0);
1381     return -1;
1382 }
1383 
1384 int postcopy_wake_shared(struct PostCopyFD *pcfd,
1385                          uint64_t client_addr,
1386                          RAMBlock *rb)
1387 {
1388     assert(0);
1389     return -1;
1390 }
1391 #endif
1392 
1393 /* ------------------------------------------------------------------------- */
1394 void postcopy_temp_page_reset(PostcopyTmpPage *tmp_page)
1395 {
1396     tmp_page->target_pages = 0;
1397     tmp_page->host_addr = NULL;
1398     /*
1399      * This is set to true when reset, and cleared as long as we received any
1400      * of the non-zero small page within this huge page.
1401      */
1402     tmp_page->all_zero = true;
1403 }
1404 
1405 void postcopy_fault_thread_notify(MigrationIncomingState *mis)
1406 {
1407     uint64_t tmp64 = 1;
1408 
1409     /*
1410      * Wakeup the fault_thread.  It's an eventfd that should currently
1411      * be at 0, we're going to increment it to 1
1412      */
1413     if (write(mis->userfault_event_fd, &tmp64, 8) != 8) {
1414         /* Not much we can do here, but may as well report it */
1415         error_report("%s: incrementing failed: %s", __func__,
1416                      strerror(errno));
1417     }
1418 }
1419 
1420 /**
1421  * postcopy_discard_send_init: Called at the start of each RAMBlock before
1422  *   asking to discard individual ranges.
1423  *
1424  * @ms: The current migration state.
1425  * @offset: the bitmap offset of the named RAMBlock in the migration bitmap.
1426  * @name: RAMBlock that discards will operate on.
1427  */
1428 static PostcopyDiscardState pds = {0};
1429 void postcopy_discard_send_init(MigrationState *ms, const char *name)
1430 {
1431     pds.ramblock_name = name;
1432     pds.cur_entry = 0;
1433     pds.nsentwords = 0;
1434     pds.nsentcmds = 0;
1435 }
1436 
1437 /**
1438  * postcopy_discard_send_range: Called by the bitmap code for each chunk to
1439  *   discard. May send a discard message, may just leave it queued to
1440  *   be sent later.
1441  *
1442  * @ms: Current migration state.
1443  * @start,@length: a range of pages in the migration bitmap in the
1444  *   RAM block passed to postcopy_discard_send_init() (length=1 is one page)
1445  */
1446 void postcopy_discard_send_range(MigrationState *ms, unsigned long start,
1447                                  unsigned long length)
1448 {
1449     size_t tp_size = qemu_target_page_size();
1450     /* Convert to byte offsets within the RAM block */
1451     pds.start_list[pds.cur_entry] = start  * tp_size;
1452     pds.length_list[pds.cur_entry] = length * tp_size;
1453     trace_postcopy_discard_send_range(pds.ramblock_name, start, length);
1454     pds.cur_entry++;
1455     pds.nsentwords++;
1456 
1457     if (pds.cur_entry == MAX_DISCARDS_PER_COMMAND) {
1458         /* Full set, ship it! */
1459         qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
1460                                               pds.ramblock_name,
1461                                               pds.cur_entry,
1462                                               pds.start_list,
1463                                               pds.length_list);
1464         pds.nsentcmds++;
1465         pds.cur_entry = 0;
1466     }
1467 }
1468 
1469 /**
1470  * postcopy_discard_send_finish: Called at the end of each RAMBlock by the
1471  * bitmap code. Sends any outstanding discard messages, frees the PDS
1472  *
1473  * @ms: Current migration state.
1474  */
1475 void postcopy_discard_send_finish(MigrationState *ms)
1476 {
1477     /* Anything unsent? */
1478     if (pds.cur_entry) {
1479         qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
1480                                               pds.ramblock_name,
1481                                               pds.cur_entry,
1482                                               pds.start_list,
1483                                               pds.length_list);
1484         pds.nsentcmds++;
1485     }
1486 
1487     trace_postcopy_discard_send_finish(pds.ramblock_name, pds.nsentwords,
1488                                        pds.nsentcmds);
1489 }
1490 
1491 /*
1492  * Current state of incoming postcopy; note this is not part of
1493  * MigrationIncomingState since it's state is used during cleanup
1494  * at the end as MIS is being freed.
1495  */
1496 static PostcopyState incoming_postcopy_state;
1497 
1498 PostcopyState  postcopy_state_get(void)
1499 {
1500     return qatomic_mb_read(&incoming_postcopy_state);
1501 }
1502 
1503 /* Set the state and return the old state */
1504 PostcopyState postcopy_state_set(PostcopyState new_state)
1505 {
1506     return qatomic_xchg(&incoming_postcopy_state, new_state);
1507 }
1508 
1509 /* Register a handler for external shared memory postcopy
1510  * called on the destination.
1511  */
1512 void postcopy_register_shared_ufd(struct PostCopyFD *pcfd)
1513 {
1514     MigrationIncomingState *mis = migration_incoming_get_current();
1515 
1516     mis->postcopy_remote_fds = g_array_append_val(mis->postcopy_remote_fds,
1517                                                   *pcfd);
1518 }
1519 
1520 /* Unregister a handler for external shared memory postcopy
1521  */
1522 void postcopy_unregister_shared_ufd(struct PostCopyFD *pcfd)
1523 {
1524     guint i;
1525     MigrationIncomingState *mis = migration_incoming_get_current();
1526     GArray *pcrfds = mis->postcopy_remote_fds;
1527 
1528     if (!pcrfds) {
1529         /* migration has already finished and freed the array */
1530         return;
1531     }
1532     for (i = 0; i < pcrfds->len; i++) {
1533         struct PostCopyFD *cur = &g_array_index(pcrfds, struct PostCopyFD, i);
1534         if (cur->fd == pcfd->fd) {
1535             mis->postcopy_remote_fds = g_array_remove_index(pcrfds, i);
1536             return;
1537         }
1538     }
1539 }
1540 
1541 void postcopy_preempt_new_channel(MigrationIncomingState *mis, QEMUFile *file)
1542 {
1543     /*
1544      * The new loading channel has its own threads, so it needs to be
1545      * blocked too.  It's by default true, just be explicit.
1546      */
1547     qemu_file_set_blocking(file, true);
1548     mis->postcopy_qemufile_dst = file;
1549     trace_postcopy_preempt_new_channel();
1550 }
1551 
1552 /*
1553  * Setup the postcopy preempt channel with the IOC.  If ERROR is specified,
1554  * setup the error instead.  This helper will free the ERROR if specified.
1555  */
1556 static void
1557 postcopy_preempt_send_channel_done(MigrationState *s,
1558                                    QIOChannel *ioc, Error *local_err)
1559 {
1560     if (local_err) {
1561         migrate_set_error(s, local_err);
1562         error_free(local_err);
1563     } else {
1564         migration_ioc_register_yank(ioc);
1565         s->postcopy_qemufile_src = qemu_file_new_output(ioc);
1566         trace_postcopy_preempt_new_channel();
1567     }
1568 
1569     /*
1570      * Kick the waiter in all cases.  The waiter should check upon
1571      * postcopy_qemufile_src to know whether it failed or not.
1572      */
1573     qemu_sem_post(&s->postcopy_qemufile_src_sem);
1574 }
1575 
1576 static void
1577 postcopy_preempt_tls_handshake(QIOTask *task, gpointer opaque)
1578 {
1579     g_autoptr(QIOChannel) ioc = QIO_CHANNEL(qio_task_get_source(task));
1580     MigrationState *s = opaque;
1581     Error *local_err = NULL;
1582 
1583     qio_task_propagate_error(task, &local_err);
1584     postcopy_preempt_send_channel_done(s, ioc, local_err);
1585 }
1586 
1587 static void
1588 postcopy_preempt_send_channel_new(QIOTask *task, gpointer opaque)
1589 {
1590     g_autoptr(QIOChannel) ioc = QIO_CHANNEL(qio_task_get_source(task));
1591     MigrationState *s = opaque;
1592     QIOChannelTLS *tioc;
1593     Error *local_err = NULL;
1594 
1595     if (qio_task_propagate_error(task, &local_err)) {
1596         goto out;
1597     }
1598 
1599     if (migrate_channel_requires_tls_upgrade(ioc)) {
1600         tioc = migration_tls_client_create(s, ioc, s->hostname, &local_err);
1601         if (!tioc) {
1602             goto out;
1603         }
1604         trace_postcopy_preempt_tls_handshake();
1605         qio_channel_set_name(QIO_CHANNEL(tioc), "migration-tls-preempt");
1606         qio_channel_tls_handshake(tioc, postcopy_preempt_tls_handshake,
1607                                   s, NULL, NULL);
1608         /* Setup the channel until TLS handshake finished */
1609         return;
1610     }
1611 
1612 out:
1613     /* This handles both good and error cases */
1614     postcopy_preempt_send_channel_done(s, ioc, local_err);
1615 }
1616 
1617 /* Returns 0 if channel established, -1 for error. */
1618 int postcopy_preempt_wait_channel(MigrationState *s)
1619 {
1620     /* If preempt not enabled, no need to wait */
1621     if (!migrate_postcopy_preempt()) {
1622         return 0;
1623     }
1624 
1625     /*
1626      * We need the postcopy preempt channel to be established before
1627      * starting doing anything.
1628      */
1629     qemu_sem_wait(&s->postcopy_qemufile_src_sem);
1630 
1631     return s->postcopy_qemufile_src ? 0 : -1;
1632 }
1633 
1634 int postcopy_preempt_setup(MigrationState *s, Error **errp)
1635 {
1636     if (!migrate_postcopy_preempt()) {
1637         return 0;
1638     }
1639 
1640     if (!migrate_multi_channels_is_allowed()) {
1641         error_setg(errp, "Postcopy preempt is not supported as current "
1642                    "migration stream does not support multi-channels.");
1643         return -1;
1644     }
1645 
1646     /* Kick an async task to connect */
1647     socket_send_channel_create(postcopy_preempt_send_channel_new, s);
1648 
1649     return 0;
1650 }
1651 
1652 static void postcopy_pause_ram_fast_load(MigrationIncomingState *mis)
1653 {
1654     trace_postcopy_pause_fast_load();
1655     qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
1656     qemu_sem_wait(&mis->postcopy_pause_sem_fast_load);
1657     qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
1658     trace_postcopy_pause_fast_load_continued();
1659 }
1660 
1661 void *postcopy_preempt_thread(void *opaque)
1662 {
1663     MigrationIncomingState *mis = opaque;
1664     int ret;
1665 
1666     trace_postcopy_preempt_thread_entry();
1667 
1668     rcu_register_thread();
1669 
1670     qemu_sem_post(&mis->thread_sync_sem);
1671 
1672     /* Sending RAM_SAVE_FLAG_EOS to terminate this thread */
1673     qemu_mutex_lock(&mis->postcopy_prio_thread_mutex);
1674     while (1) {
1675         ret = ram_load_postcopy(mis->postcopy_qemufile_dst,
1676                                 RAM_CHANNEL_POSTCOPY);
1677         /* If error happened, go into recovery routine */
1678         if (ret) {
1679             postcopy_pause_ram_fast_load(mis);
1680         } else {
1681             /* We're done */
1682             break;
1683         }
1684     }
1685     qemu_mutex_unlock(&mis->postcopy_prio_thread_mutex);
1686 
1687     rcu_unregister_thread();
1688 
1689     trace_postcopy_preempt_thread_exit();
1690 
1691     return NULL;
1692 }
1693