xref: /openbmc/qemu/migration/postcopy-ram.c (revision dda2441b)
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 "exec/target_page.h"
21 #include "migration.h"
22 #include "qemu-file.h"
23 #include "savevm.h"
24 #include "postcopy-ram.h"
25 #include "ram.h"
26 #include "qapi/error.h"
27 #include "qemu/notify.h"
28 #include "sysemu/sysemu.h"
29 #include "sysemu/balloon.h"
30 #include "qemu/error-report.h"
31 #include "trace.h"
32 
33 /* Arbitrary limit on size of each discard command,
34  * keeps them around ~200 bytes
35  */
36 #define MAX_DISCARDS_PER_COMMAND 12
37 
38 struct PostcopyDiscardState {
39     const char *ramblock_name;
40     uint16_t cur_entry;
41     /*
42      * Start and length of a discard range (bytes)
43      */
44     uint64_t start_list[MAX_DISCARDS_PER_COMMAND];
45     uint64_t length_list[MAX_DISCARDS_PER_COMMAND];
46     unsigned int nsentwords;
47     unsigned int nsentcmds;
48 };
49 
50 static NotifierWithReturnList postcopy_notifier_list;
51 
52 void postcopy_infrastructure_init(void)
53 {
54     notifier_with_return_list_init(&postcopy_notifier_list);
55 }
56 
57 void postcopy_add_notifier(NotifierWithReturn *nn)
58 {
59     notifier_with_return_list_add(&postcopy_notifier_list, nn);
60 }
61 
62 void postcopy_remove_notifier(NotifierWithReturn *n)
63 {
64     notifier_with_return_remove(n);
65 }
66 
67 int postcopy_notify(enum PostcopyNotifyReason reason, Error **errp)
68 {
69     struct PostcopyNotifyData pnd;
70     pnd.reason = reason;
71     pnd.errp = errp;
72 
73     return notifier_with_return_list_notify(&postcopy_notifier_list,
74                                             &pnd);
75 }
76 
77 /* Postcopy needs to detect accesses to pages that haven't yet been copied
78  * across, and efficiently map new pages in, the techniques for doing this
79  * are target OS specific.
80  */
81 #if defined(__linux__)
82 
83 #include <poll.h>
84 #include <sys/ioctl.h>
85 #include <sys/syscall.h>
86 #include <asm/types.h> /* for __u64 */
87 #endif
88 
89 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
90 #include <sys/eventfd.h>
91 #include <linux/userfaultfd.h>
92 
93 
94 /**
95  * receive_ufd_features: check userfault fd features, to request only supported
96  * features in the future.
97  *
98  * Returns: true on success
99  *
100  * __NR_userfaultfd - should be checked before
101  *  @features: out parameter will contain uffdio_api.features provided by kernel
102  *              in case of success
103  */
104 static bool receive_ufd_features(uint64_t *features)
105 {
106     struct uffdio_api api_struct = {0};
107     int ufd;
108     bool ret = true;
109 
110     /* if we are here __NR_userfaultfd should exists */
111     ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
112     if (ufd == -1) {
113         error_report("%s: syscall __NR_userfaultfd failed: %s", __func__,
114                      strerror(errno));
115         return false;
116     }
117 
118     /* ask features */
119     api_struct.api = UFFD_API;
120     api_struct.features = 0;
121     if (ioctl(ufd, UFFDIO_API, &api_struct)) {
122         error_report("%s: UFFDIO_API failed: %s", __func__,
123                      strerror(errno));
124         ret = false;
125         goto release_ufd;
126     }
127 
128     *features = api_struct.features;
129 
130 release_ufd:
131     close(ufd);
132     return ret;
133 }
134 
135 /**
136  * request_ufd_features: this function should be called only once on a newly
137  * opened ufd, subsequent calls will lead to error.
138  *
139  * Returns: true on succes
140  *
141  * @ufd: fd obtained from userfaultfd syscall
142  * @features: bit mask see UFFD_API_FEATURES
143  */
144 static bool request_ufd_features(int ufd, uint64_t features)
145 {
146     struct uffdio_api api_struct = {0};
147     uint64_t ioctl_mask;
148 
149     api_struct.api = UFFD_API;
150     api_struct.features = features;
151     if (ioctl(ufd, UFFDIO_API, &api_struct)) {
152         error_report("%s failed: UFFDIO_API failed: %s", __func__,
153                      strerror(errno));
154         return false;
155     }
156 
157     ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
158                  (__u64)1 << _UFFDIO_UNREGISTER;
159     if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
160         error_report("Missing userfault features: %" PRIx64,
161                      (uint64_t)(~api_struct.ioctls & ioctl_mask));
162         return false;
163     }
164 
165     return true;
166 }
167 
168 static bool ufd_check_and_apply(int ufd, MigrationIncomingState *mis)
169 {
170     uint64_t asked_features = 0;
171     static uint64_t supported_features;
172 
173     /*
174      * it's not possible to
175      * request UFFD_API twice per one fd
176      * userfault fd features is persistent
177      */
178     if (!supported_features) {
179         if (!receive_ufd_features(&supported_features)) {
180             error_report("%s failed", __func__);
181             return false;
182         }
183     }
184 
185     /*
186      * request features, even if asked_features is 0, due to
187      * kernel expects UFFD_API before UFFDIO_REGISTER, per
188      * userfault file descriptor
189      */
190     if (!request_ufd_features(ufd, asked_features)) {
191         error_report("%s failed: features %" PRIu64, __func__,
192                      asked_features);
193         return false;
194     }
195 
196     if (getpagesize() != ram_pagesize_summary()) {
197         bool have_hp = false;
198         /* We've got a huge page */
199 #ifdef UFFD_FEATURE_MISSING_HUGETLBFS
200         have_hp = supported_features & UFFD_FEATURE_MISSING_HUGETLBFS;
201 #endif
202         if (!have_hp) {
203             error_report("Userfault on this host does not support huge pages");
204             return false;
205         }
206     }
207     return true;
208 }
209 
210 /* Callback from postcopy_ram_supported_by_host block iterator.
211  */
212 static int test_ramblock_postcopiable(const char *block_name, void *host_addr,
213                              ram_addr_t offset, ram_addr_t length, void *opaque)
214 {
215     RAMBlock *rb = qemu_ram_block_by_name(block_name);
216     size_t pagesize = qemu_ram_pagesize(rb);
217 
218     if (length % pagesize) {
219         error_report("Postcopy requires RAM blocks to be a page size multiple,"
220                      " block %s is 0x" RAM_ADDR_FMT " bytes with a "
221                      "page size of 0x%zx", block_name, length, pagesize);
222         return 1;
223     }
224     return 0;
225 }
226 
227 /*
228  * Note: This has the side effect of munlock'ing all of RAM, that's
229  * normally fine since if the postcopy succeeds it gets turned back on at the
230  * end.
231  */
232 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
233 {
234     long pagesize = getpagesize();
235     int ufd = -1;
236     bool ret = false; /* Error unless we change it */
237     void *testarea = NULL;
238     struct uffdio_register reg_struct;
239     struct uffdio_range range_struct;
240     uint64_t feature_mask;
241     Error *local_err = NULL;
242 
243     if (qemu_target_page_size() > pagesize) {
244         error_report("Target page size bigger than host page size");
245         goto out;
246     }
247 
248     ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
249     if (ufd == -1) {
250         error_report("%s: userfaultfd not available: %s", __func__,
251                      strerror(errno));
252         goto out;
253     }
254 
255     /* Give devices a chance to object */
256     if (postcopy_notify(POSTCOPY_NOTIFY_PROBE, &local_err)) {
257         error_report_err(local_err);
258         goto out;
259     }
260 
261     /* Version and features check */
262     if (!ufd_check_and_apply(ufd, mis)) {
263         goto out;
264     }
265 
266     /* We don't support postcopy with shared RAM yet */
267     if (qemu_ram_foreach_block(test_ramblock_postcopiable, NULL)) {
268         goto out;
269     }
270 
271     /*
272      * userfault and mlock don't go together; we'll put it back later if
273      * it was enabled.
274      */
275     if (munlockall()) {
276         error_report("%s: munlockall: %s", __func__,  strerror(errno));
277         return -1;
278     }
279 
280     /*
281      *  We need to check that the ops we need are supported on anon memory
282      *  To do that we need to register a chunk and see the flags that
283      *  are returned.
284      */
285     testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE |
286                                     MAP_ANONYMOUS, -1, 0);
287     if (testarea == MAP_FAILED) {
288         error_report("%s: Failed to map test area: %s", __func__,
289                      strerror(errno));
290         goto out;
291     }
292     g_assert(((size_t)testarea & (pagesize-1)) == 0);
293 
294     reg_struct.range.start = (uintptr_t)testarea;
295     reg_struct.range.len = pagesize;
296     reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
297 
298     if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
299         error_report("%s userfault register: %s", __func__, strerror(errno));
300         goto out;
301     }
302 
303     range_struct.start = (uintptr_t)testarea;
304     range_struct.len = pagesize;
305     if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) {
306         error_report("%s userfault unregister: %s", __func__, strerror(errno));
307         goto out;
308     }
309 
310     feature_mask = (__u64)1 << _UFFDIO_WAKE |
311                    (__u64)1 << _UFFDIO_COPY |
312                    (__u64)1 << _UFFDIO_ZEROPAGE;
313     if ((reg_struct.ioctls & feature_mask) != feature_mask) {
314         error_report("Missing userfault map features: %" PRIx64,
315                      (uint64_t)(~reg_struct.ioctls & feature_mask));
316         goto out;
317     }
318 
319     /* Success! */
320     ret = true;
321 out:
322     if (testarea) {
323         munmap(testarea, pagesize);
324     }
325     if (ufd != -1) {
326         close(ufd);
327     }
328     return ret;
329 }
330 
331 /*
332  * Setup an area of RAM so that it *can* be used for postcopy later; this
333  * must be done right at the start prior to pre-copy.
334  * opaque should be the MIS.
335  */
336 static int init_range(const char *block_name, void *host_addr,
337                       ram_addr_t offset, ram_addr_t length, void *opaque)
338 {
339     trace_postcopy_init_range(block_name, host_addr, offset, length);
340 
341     /*
342      * We need the whole of RAM to be truly empty for postcopy, so things
343      * like ROMs and any data tables built during init must be zero'd
344      * - we're going to get the copy from the source anyway.
345      * (Precopy will just overwrite this data, so doesn't need the discard)
346      */
347     if (ram_discard_range(block_name, 0, length)) {
348         return -1;
349     }
350 
351     return 0;
352 }
353 
354 /*
355  * At the end of migration, undo the effects of init_range
356  * opaque should be the MIS.
357  */
358 static int cleanup_range(const char *block_name, void *host_addr,
359                         ram_addr_t offset, ram_addr_t length, void *opaque)
360 {
361     MigrationIncomingState *mis = opaque;
362     struct uffdio_range range_struct;
363     trace_postcopy_cleanup_range(block_name, host_addr, offset, length);
364 
365     /*
366      * We turned off hugepage for the precopy stage with postcopy enabled
367      * we can turn it back on now.
368      */
369     qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE);
370 
371     /*
372      * We can also turn off userfault now since we should have all the
373      * pages.   It can be useful to leave it on to debug postcopy
374      * if you're not sure it's always getting every page.
375      */
376     range_struct.start = (uintptr_t)host_addr;
377     range_struct.len = length;
378 
379     if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
380         error_report("%s: userfault unregister %s", __func__, strerror(errno));
381 
382         return -1;
383     }
384 
385     return 0;
386 }
387 
388 /*
389  * Initialise postcopy-ram, setting the RAM to a state where we can go into
390  * postcopy later; must be called prior to any precopy.
391  * called from arch_init's similarly named ram_postcopy_incoming_init
392  */
393 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
394 {
395     if (qemu_ram_foreach_block(init_range, NULL)) {
396         return -1;
397     }
398 
399     return 0;
400 }
401 
402 /*
403  * At the end of a migration where postcopy_ram_incoming_init was called.
404  */
405 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
406 {
407     trace_postcopy_ram_incoming_cleanup_entry();
408 
409     if (mis->have_fault_thread) {
410         Error *local_err = NULL;
411 
412         if (postcopy_notify(POSTCOPY_NOTIFY_INBOUND_END, &local_err)) {
413             error_report_err(local_err);
414             return -1;
415         }
416 
417         if (qemu_ram_foreach_block(cleanup_range, mis)) {
418             return -1;
419         }
420         /* Let the fault thread quit */
421         atomic_set(&mis->fault_thread_quit, 1);
422         postcopy_fault_thread_notify(mis);
423         trace_postcopy_ram_incoming_cleanup_join();
424         qemu_thread_join(&mis->fault_thread);
425 
426         trace_postcopy_ram_incoming_cleanup_closeuf();
427         close(mis->userfault_fd);
428         close(mis->userfault_event_fd);
429         mis->have_fault_thread = false;
430     }
431 
432     qemu_balloon_inhibit(false);
433 
434     if (enable_mlock) {
435         if (os_mlock() < 0) {
436             error_report("mlock: %s", strerror(errno));
437             /*
438              * It doesn't feel right to fail at this point, we have a valid
439              * VM state.
440              */
441         }
442     }
443 
444     postcopy_state_set(POSTCOPY_INCOMING_END);
445 
446     if (mis->postcopy_tmp_page) {
447         munmap(mis->postcopy_tmp_page, mis->largest_page_size);
448         mis->postcopy_tmp_page = NULL;
449     }
450     if (mis->postcopy_tmp_zero_page) {
451         munmap(mis->postcopy_tmp_zero_page, mis->largest_page_size);
452         mis->postcopy_tmp_zero_page = NULL;
453     }
454     trace_postcopy_ram_incoming_cleanup_exit();
455     return 0;
456 }
457 
458 /*
459  * Disable huge pages on an area
460  */
461 static int nhp_range(const char *block_name, void *host_addr,
462                     ram_addr_t offset, ram_addr_t length, void *opaque)
463 {
464     trace_postcopy_nhp_range(block_name, host_addr, offset, length);
465 
466     /*
467      * Before we do discards we need to ensure those discards really
468      * do delete areas of the page, even if THP thinks a hugepage would
469      * be a good idea, so force hugepages off.
470      */
471     qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE);
472 
473     return 0;
474 }
475 
476 /*
477  * Userfault requires us to mark RAM as NOHUGEPAGE prior to discard
478  * however leaving it until after precopy means that most of the precopy
479  * data is still THPd
480  */
481 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
482 {
483     if (qemu_ram_foreach_block(nhp_range, mis)) {
484         return -1;
485     }
486 
487     postcopy_state_set(POSTCOPY_INCOMING_DISCARD);
488 
489     return 0;
490 }
491 
492 /*
493  * Mark the given area of RAM as requiring notification to unwritten areas
494  * Used as a  callback on qemu_ram_foreach_block.
495  *   host_addr: Base of area to mark
496  *   offset: Offset in the whole ram arena
497  *   length: Length of the section
498  *   opaque: MigrationIncomingState pointer
499  * Returns 0 on success
500  */
501 static int ram_block_enable_notify(const char *block_name, void *host_addr,
502                                    ram_addr_t offset, ram_addr_t length,
503                                    void *opaque)
504 {
505     MigrationIncomingState *mis = opaque;
506     struct uffdio_register reg_struct;
507 
508     reg_struct.range.start = (uintptr_t)host_addr;
509     reg_struct.range.len = length;
510     reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
511 
512     /* Now tell our userfault_fd that it's responsible for this area */
513     if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
514         error_report("%s userfault register: %s", __func__, strerror(errno));
515         return -1;
516     }
517     if (!(reg_struct.ioctls & ((__u64)1 << _UFFDIO_COPY))) {
518         error_report("%s userfault: Region doesn't support COPY", __func__);
519         return -1;
520     }
521     if (reg_struct.ioctls & ((__u64)1 << _UFFDIO_ZEROPAGE)) {
522         RAMBlock *rb = qemu_ram_block_by_name(block_name);
523         qemu_ram_set_uf_zeroable(rb);
524     }
525 
526     return 0;
527 }
528 
529 int postcopy_wake_shared(struct PostCopyFD *pcfd,
530                          uint64_t client_addr,
531                          RAMBlock *rb)
532 {
533     size_t pagesize = qemu_ram_pagesize(rb);
534     struct uffdio_range range;
535     int ret;
536     trace_postcopy_wake_shared(client_addr, qemu_ram_get_idstr(rb));
537     range.start = client_addr & ~(pagesize - 1);
538     range.len = pagesize;
539     ret = ioctl(pcfd->fd, UFFDIO_WAKE, &range);
540     if (ret) {
541         error_report("%s: Failed to wake: %zx in %s (%s)",
542                      __func__, (size_t)client_addr, qemu_ram_get_idstr(rb),
543                      strerror(errno));
544     }
545     return ret;
546 }
547 
548 /*
549  * Callback from shared fault handlers to ask for a page,
550  * the page must be specified by a RAMBlock and an offset in that rb
551  * Note: Only for use by shared fault handlers (in fault thread)
552  */
553 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb,
554                                  uint64_t client_addr, uint64_t rb_offset)
555 {
556     size_t pagesize = qemu_ram_pagesize(rb);
557     uint64_t aligned_rbo = rb_offset & ~(pagesize - 1);
558     MigrationIncomingState *mis = migration_incoming_get_current();
559 
560     trace_postcopy_request_shared_page(pcfd->idstr, qemu_ram_get_idstr(rb),
561                                        rb_offset);
562     if (ramblock_recv_bitmap_test_byte_offset(rb, aligned_rbo)) {
563         trace_postcopy_request_shared_page_present(pcfd->idstr,
564                                         qemu_ram_get_idstr(rb), rb_offset);
565         return postcopy_wake_shared(pcfd, client_addr, rb);
566     }
567     if (rb != mis->last_rb) {
568         mis->last_rb = rb;
569         migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
570                                   aligned_rbo, pagesize);
571     } else {
572         /* Save some space */
573         migrate_send_rp_req_pages(mis, NULL, aligned_rbo, pagesize);
574     }
575     return 0;
576 }
577 
578 /*
579  * Handle faults detected by the USERFAULT markings
580  */
581 static void *postcopy_ram_fault_thread(void *opaque)
582 {
583     MigrationIncomingState *mis = opaque;
584     struct uffd_msg msg;
585     int ret;
586     size_t index;
587     RAMBlock *rb = NULL;
588 
589     trace_postcopy_ram_fault_thread_entry();
590     mis->last_rb = NULL; /* last RAMBlock we sent part of */
591     qemu_sem_post(&mis->fault_thread_sem);
592 
593     struct pollfd *pfd;
594     size_t pfd_len = 2 + mis->postcopy_remote_fds->len;
595 
596     pfd = g_new0(struct pollfd, pfd_len);
597 
598     pfd[0].fd = mis->userfault_fd;
599     pfd[0].events = POLLIN;
600     pfd[1].fd = mis->userfault_event_fd;
601     pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
602     trace_postcopy_ram_fault_thread_fds_core(pfd[0].fd, pfd[1].fd);
603     for (index = 0; index < mis->postcopy_remote_fds->len; index++) {
604         struct PostCopyFD *pcfd = &g_array_index(mis->postcopy_remote_fds,
605                                                  struct PostCopyFD, index);
606         pfd[2 + index].fd = pcfd->fd;
607         pfd[2 + index].events = POLLIN;
608         trace_postcopy_ram_fault_thread_fds_extra(2 + index, pcfd->idstr,
609                                                   pcfd->fd);
610     }
611 
612     while (true) {
613         ram_addr_t rb_offset;
614         int poll_result;
615 
616         /*
617          * We're mainly waiting for the kernel to give us a faulting HVA,
618          * however we can be told to quit via userfault_quit_fd which is
619          * an eventfd
620          */
621 
622         poll_result = poll(pfd, pfd_len, -1 /* Wait forever */);
623         if (poll_result == -1) {
624             error_report("%s: userfault poll: %s", __func__, strerror(errno));
625             break;
626         }
627 
628         if (pfd[1].revents) {
629             uint64_t tmp64 = 0;
630 
631             /* Consume the signal */
632             if (read(mis->userfault_event_fd, &tmp64, 8) != 8) {
633                 /* Nothing obviously nicer than posting this error. */
634                 error_report("%s: read() failed", __func__);
635             }
636 
637             if (atomic_read(&mis->fault_thread_quit)) {
638                 trace_postcopy_ram_fault_thread_quit();
639                 break;
640             }
641         }
642 
643         if (pfd[0].revents) {
644             poll_result--;
645             ret = read(mis->userfault_fd, &msg, sizeof(msg));
646             if (ret != sizeof(msg)) {
647                 if (errno == EAGAIN) {
648                     /*
649                      * if a wake up happens on the other thread just after
650                      * the poll, there is nothing to read.
651                      */
652                     continue;
653                 }
654                 if (ret < 0) {
655                     error_report("%s: Failed to read full userfault "
656                                  "message: %s",
657                                  __func__, strerror(errno));
658                     break;
659                 } else {
660                     error_report("%s: Read %d bytes from userfaultfd "
661                                  "expected %zd",
662                                  __func__, ret, sizeof(msg));
663                     break; /* Lost alignment, don't know what we'd read next */
664                 }
665             }
666             if (msg.event != UFFD_EVENT_PAGEFAULT) {
667                 error_report("%s: Read unexpected event %ud from userfaultfd",
668                              __func__, msg.event);
669                 continue; /* It's not a page fault, shouldn't happen */
670             }
671 
672             rb = qemu_ram_block_from_host(
673                      (void *)(uintptr_t)msg.arg.pagefault.address,
674                      true, &rb_offset);
675             if (!rb) {
676                 error_report("postcopy_ram_fault_thread: Fault outside guest: %"
677                              PRIx64, (uint64_t)msg.arg.pagefault.address);
678                 break;
679             }
680 
681             rb_offset &= ~(qemu_ram_pagesize(rb) - 1);
682             trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,
683                                                 qemu_ram_get_idstr(rb),
684                                                 rb_offset);
685             /*
686              * Send the request to the source - we want to request one
687              * of our host page sizes (which is >= TPS)
688              */
689             if (rb != mis->last_rb) {
690                 mis->last_rb = rb;
691                 migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
692                                          rb_offset, qemu_ram_pagesize(rb));
693             } else {
694                 /* Save some space */
695                 migrate_send_rp_req_pages(mis, NULL,
696                                          rb_offset, qemu_ram_pagesize(rb));
697             }
698         }
699 
700         /* Now handle any requests from external processes on shared memory */
701         /* TODO: May need to handle devices deregistering during postcopy */
702         for (index = 2; index < pfd_len && poll_result; index++) {
703             if (pfd[index].revents) {
704                 struct PostCopyFD *pcfd =
705                     &g_array_index(mis->postcopy_remote_fds,
706                                    struct PostCopyFD, index - 2);
707 
708                 poll_result--;
709                 if (pfd[index].revents & POLLERR) {
710                     error_report("%s: POLLERR on poll %zd fd=%d",
711                                  __func__, index, pcfd->fd);
712                     pfd[index].events = 0;
713                     continue;
714                 }
715 
716                 ret = read(pcfd->fd, &msg, sizeof(msg));
717                 if (ret != sizeof(msg)) {
718                     if (errno == EAGAIN) {
719                         /*
720                          * if a wake up happens on the other thread just after
721                          * the poll, there is nothing to read.
722                          */
723                         continue;
724                     }
725                     if (ret < 0) {
726                         error_report("%s: Failed to read full userfault "
727                                      "message: %s (shared) revents=%d",
728                                      __func__, strerror(errno),
729                                      pfd[index].revents);
730                         /*TODO: Could just disable this sharer */
731                         break;
732                     } else {
733                         error_report("%s: Read %d bytes from userfaultfd "
734                                      "expected %zd (shared)",
735                                      __func__, ret, sizeof(msg));
736                         /*TODO: Could just disable this sharer */
737                         break; /*Lost alignment,don't know what we'd read next*/
738                     }
739                 }
740                 if (msg.event != UFFD_EVENT_PAGEFAULT) {
741                     error_report("%s: Read unexpected event %ud "
742                                  "from userfaultfd (shared)",
743                                  __func__, msg.event);
744                     continue; /* It's not a page fault, shouldn't happen */
745                 }
746                 /* Call the device handler registered with us */
747                 ret = pcfd->handler(pcfd, &msg);
748                 if (ret) {
749                     error_report("%s: Failed to resolve shared fault on %zd/%s",
750                                  __func__, index, pcfd->idstr);
751                     /* TODO: Fail? Disable this sharer? */
752                 }
753             }
754         }
755     }
756     trace_postcopy_ram_fault_thread_exit();
757     return NULL;
758 }
759 
760 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
761 {
762     /* Open the fd for the kernel to give us userfaults */
763     mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
764     if (mis->userfault_fd == -1) {
765         error_report("%s: Failed to open userfault fd: %s", __func__,
766                      strerror(errno));
767         return -1;
768     }
769 
770     /*
771      * Although the host check already tested the API, we need to
772      * do the check again as an ABI handshake on the new fd.
773      */
774     if (!ufd_check_and_apply(mis->userfault_fd, mis)) {
775         return -1;
776     }
777 
778     /* Now an eventfd we use to tell the fault-thread to quit */
779     mis->userfault_event_fd = eventfd(0, EFD_CLOEXEC);
780     if (mis->userfault_event_fd == -1) {
781         error_report("%s: Opening userfault_event_fd: %s", __func__,
782                      strerror(errno));
783         close(mis->userfault_fd);
784         return -1;
785     }
786 
787     qemu_sem_init(&mis->fault_thread_sem, 0);
788     qemu_thread_create(&mis->fault_thread, "postcopy/fault",
789                        postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
790     qemu_sem_wait(&mis->fault_thread_sem);
791     qemu_sem_destroy(&mis->fault_thread_sem);
792     mis->have_fault_thread = true;
793 
794     /* Mark so that we get notified of accesses to unwritten areas */
795     if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
796         return -1;
797     }
798 
799     /*
800      * Ballooning can mark pages as absent while we're postcopying
801      * that would cause false userfaults.
802      */
803     qemu_balloon_inhibit(true);
804 
805     trace_postcopy_ram_enable_notify();
806 
807     return 0;
808 }
809 
810 static int qemu_ufd_copy_ioctl(int userfault_fd, void *host_addr,
811                                void *from_addr, uint64_t pagesize, RAMBlock *rb)
812 {
813     int ret;
814     if (from_addr) {
815         struct uffdio_copy copy_struct;
816         copy_struct.dst = (uint64_t)(uintptr_t)host_addr;
817         copy_struct.src = (uint64_t)(uintptr_t)from_addr;
818         copy_struct.len = pagesize;
819         copy_struct.mode = 0;
820         ret = ioctl(userfault_fd, UFFDIO_COPY, &copy_struct);
821     } else {
822         struct uffdio_zeropage zero_struct;
823         zero_struct.range.start = (uint64_t)(uintptr_t)host_addr;
824         zero_struct.range.len = pagesize;
825         zero_struct.mode = 0;
826         ret = ioctl(userfault_fd, UFFDIO_ZEROPAGE, &zero_struct);
827     }
828     if (!ret) {
829         ramblock_recv_bitmap_set_range(rb, host_addr,
830                                        pagesize / qemu_target_page_size());
831     }
832     return ret;
833 }
834 
835 int postcopy_notify_shared_wake(RAMBlock *rb, uint64_t offset)
836 {
837     int i;
838     MigrationIncomingState *mis = migration_incoming_get_current();
839     GArray *pcrfds = mis->postcopy_remote_fds;
840 
841     for (i = 0; i < pcrfds->len; i++) {
842         struct PostCopyFD *cur = &g_array_index(pcrfds, struct PostCopyFD, i);
843         int ret = cur->waker(cur, rb, offset);
844         if (ret) {
845             return ret;
846         }
847     }
848     return 0;
849 }
850 
851 /*
852  * Place a host page (from) at (host) atomically
853  * returns 0 on success
854  */
855 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
856                         RAMBlock *rb)
857 {
858     size_t pagesize = qemu_ram_pagesize(rb);
859 
860     /* copy also acks to the kernel waking the stalled thread up
861      * TODO: We can inhibit that ack and only do it if it was requested
862      * which would be slightly cheaper, but we'd have to be careful
863      * of the order of updating our page state.
864      */
865     if (qemu_ufd_copy_ioctl(mis->userfault_fd, host, from, pagesize, rb)) {
866         int e = errno;
867         error_report("%s: %s copy host: %p from: %p (size: %zd)",
868                      __func__, strerror(e), host, from, pagesize);
869 
870         return -e;
871     }
872 
873     trace_postcopy_place_page(host);
874     return postcopy_notify_shared_wake(rb,
875                                        qemu_ram_block_host_offset(rb, host));
876 }
877 
878 /*
879  * Place a zero page at (host) atomically
880  * returns 0 on success
881  */
882 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
883                              RAMBlock *rb)
884 {
885     size_t pagesize = qemu_ram_pagesize(rb);
886     trace_postcopy_place_page_zero(host);
887 
888     /* Normal RAMBlocks can zero a page using UFFDIO_ZEROPAGE
889      * but it's not available for everything (e.g. hugetlbpages)
890      */
891     if (qemu_ram_is_uf_zeroable(rb)) {
892         if (qemu_ufd_copy_ioctl(mis->userfault_fd, host, NULL, pagesize, rb)) {
893             int e = errno;
894             error_report("%s: %s zero host: %p",
895                          __func__, strerror(e), host);
896 
897             return -e;
898         }
899         return postcopy_notify_shared_wake(rb,
900                                            qemu_ram_block_host_offset(rb,
901                                                                       host));
902     } else {
903         /* The kernel can't use UFFDIO_ZEROPAGE for hugepages */
904         if (!mis->postcopy_tmp_zero_page) {
905             mis->postcopy_tmp_zero_page = mmap(NULL, mis->largest_page_size,
906                                                PROT_READ | PROT_WRITE,
907                                                MAP_PRIVATE | MAP_ANONYMOUS,
908                                                -1, 0);
909             if (mis->postcopy_tmp_zero_page == MAP_FAILED) {
910                 int e = errno;
911                 mis->postcopy_tmp_zero_page = NULL;
912                 error_report("%s: %s mapping large zero page",
913                              __func__, strerror(e));
914                 return -e;
915             }
916             memset(mis->postcopy_tmp_zero_page, '\0', mis->largest_page_size);
917         }
918         return postcopy_place_page(mis, host, mis->postcopy_tmp_zero_page,
919                                    rb);
920     }
921 }
922 
923 /*
924  * Returns a target page of memory that can be mapped at a later point in time
925  * using postcopy_place_page
926  * The same address is used repeatedly, postcopy_place_page just takes the
927  * backing page away.
928  * Returns: Pointer to allocated page
929  *
930  */
931 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
932 {
933     if (!mis->postcopy_tmp_page) {
934         mis->postcopy_tmp_page = mmap(NULL, mis->largest_page_size,
935                              PROT_READ | PROT_WRITE, MAP_PRIVATE |
936                              MAP_ANONYMOUS, -1, 0);
937         if (mis->postcopy_tmp_page == MAP_FAILED) {
938             mis->postcopy_tmp_page = NULL;
939             error_report("%s: %s", __func__, strerror(errno));
940             return NULL;
941         }
942     }
943 
944     return mis->postcopy_tmp_page;
945 }
946 
947 #else
948 /* No target OS support, stubs just fail */
949 bool postcopy_ram_supported_by_host(MigrationIncomingState *mis)
950 {
951     error_report("%s: No OS support", __func__);
952     return false;
953 }
954 
955 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
956 {
957     error_report("postcopy_ram_incoming_init: No OS support");
958     return -1;
959 }
960 
961 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
962 {
963     assert(0);
964     return -1;
965 }
966 
967 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
968 {
969     assert(0);
970     return -1;
971 }
972 
973 int postcopy_request_shared_page(struct PostCopyFD *pcfd, RAMBlock *rb,
974                                  uint64_t client_addr, uint64_t rb_offset)
975 {
976     assert(0);
977     return -1;
978 }
979 
980 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
981 {
982     assert(0);
983     return -1;
984 }
985 
986 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
987                         RAMBlock *rb)
988 {
989     assert(0);
990     return -1;
991 }
992 
993 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
994                         RAMBlock *rb)
995 {
996     assert(0);
997     return -1;
998 }
999 
1000 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
1001 {
1002     assert(0);
1003     return NULL;
1004 }
1005 
1006 int postcopy_wake_shared(struct PostCopyFD *pcfd,
1007                          uint64_t client_addr,
1008                          RAMBlock *rb)
1009 {
1010     assert(0);
1011     return -1;
1012 }
1013 #endif
1014 
1015 /* ------------------------------------------------------------------------- */
1016 
1017 void postcopy_fault_thread_notify(MigrationIncomingState *mis)
1018 {
1019     uint64_t tmp64 = 1;
1020 
1021     /*
1022      * Wakeup the fault_thread.  It's an eventfd that should currently
1023      * be at 0, we're going to increment it to 1
1024      */
1025     if (write(mis->userfault_event_fd, &tmp64, 8) != 8) {
1026         /* Not much we can do here, but may as well report it */
1027         error_report("%s: incrementing failed: %s", __func__,
1028                      strerror(errno));
1029     }
1030 }
1031 
1032 /**
1033  * postcopy_discard_send_init: Called at the start of each RAMBlock before
1034  *   asking to discard individual ranges.
1035  *
1036  * @ms: The current migration state.
1037  * @offset: the bitmap offset of the named RAMBlock in the migration
1038  *   bitmap.
1039  * @name: RAMBlock that discards will operate on.
1040  *
1041  * returns: a new PDS.
1042  */
1043 PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
1044                                                  const char *name)
1045 {
1046     PostcopyDiscardState *res = g_malloc0(sizeof(PostcopyDiscardState));
1047 
1048     if (res) {
1049         res->ramblock_name = name;
1050     }
1051 
1052     return res;
1053 }
1054 
1055 /**
1056  * postcopy_discard_send_range: Called by the bitmap code for each chunk to
1057  *   discard. May send a discard message, may just leave it queued to
1058  *   be sent later.
1059  *
1060  * @ms: Current migration state.
1061  * @pds: Structure initialised by postcopy_discard_send_init().
1062  * @start,@length: a range of pages in the migration bitmap in the
1063  *   RAM block passed to postcopy_discard_send_init() (length=1 is one page)
1064  */
1065 void postcopy_discard_send_range(MigrationState *ms, PostcopyDiscardState *pds,
1066                                 unsigned long start, unsigned long length)
1067 {
1068     size_t tp_size = qemu_target_page_size();
1069     /* Convert to byte offsets within the RAM block */
1070     pds->start_list[pds->cur_entry] = start  * tp_size;
1071     pds->length_list[pds->cur_entry] = length * tp_size;
1072     trace_postcopy_discard_send_range(pds->ramblock_name, start, length);
1073     pds->cur_entry++;
1074     pds->nsentwords++;
1075 
1076     if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
1077         /* Full set, ship it! */
1078         qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
1079                                               pds->ramblock_name,
1080                                               pds->cur_entry,
1081                                               pds->start_list,
1082                                               pds->length_list);
1083         pds->nsentcmds++;
1084         pds->cur_entry = 0;
1085     }
1086 }
1087 
1088 /**
1089  * postcopy_discard_send_finish: Called at the end of each RAMBlock by the
1090  * bitmap code. Sends any outstanding discard messages, frees the PDS
1091  *
1092  * @ms: Current migration state.
1093  * @pds: Structure initialised by postcopy_discard_send_init().
1094  */
1095 void postcopy_discard_send_finish(MigrationState *ms, PostcopyDiscardState *pds)
1096 {
1097     /* Anything unsent? */
1098     if (pds->cur_entry) {
1099         qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
1100                                               pds->ramblock_name,
1101                                               pds->cur_entry,
1102                                               pds->start_list,
1103                                               pds->length_list);
1104         pds->nsentcmds++;
1105     }
1106 
1107     trace_postcopy_discard_send_finish(pds->ramblock_name, pds->nsentwords,
1108                                        pds->nsentcmds);
1109 
1110     g_free(pds);
1111 }
1112 
1113 /*
1114  * Current state of incoming postcopy; note this is not part of
1115  * MigrationIncomingState since it's state is used during cleanup
1116  * at the end as MIS is being freed.
1117  */
1118 static PostcopyState incoming_postcopy_state;
1119 
1120 PostcopyState  postcopy_state_get(void)
1121 {
1122     return atomic_mb_read(&incoming_postcopy_state);
1123 }
1124 
1125 /* Set the state and return the old state */
1126 PostcopyState postcopy_state_set(PostcopyState new_state)
1127 {
1128     return atomic_xchg(&incoming_postcopy_state, new_state);
1129 }
1130 
1131 /* Register a handler for external shared memory postcopy
1132  * called on the destination.
1133  */
1134 void postcopy_register_shared_ufd(struct PostCopyFD *pcfd)
1135 {
1136     MigrationIncomingState *mis = migration_incoming_get_current();
1137 
1138     mis->postcopy_remote_fds = g_array_append_val(mis->postcopy_remote_fds,
1139                                                   *pcfd);
1140 }
1141 
1142 /* Unregister a handler for external shared memory postcopy
1143  */
1144 void postcopy_unregister_shared_ufd(struct PostCopyFD *pcfd)
1145 {
1146     guint i;
1147     MigrationIncomingState *mis = migration_incoming_get_current();
1148     GArray *pcrfds = mis->postcopy_remote_fds;
1149 
1150     for (i = 0; i < pcrfds->len; i++) {
1151         struct PostCopyFD *cur = &g_array_index(pcrfds, struct PostCopyFD, i);
1152         if (cur->fd == pcfd->fd) {
1153             mis->postcopy_remote_fds = g_array_remove_index(pcrfds, i);
1154             return;
1155         }
1156     }
1157 }
1158