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