postcopy: Check for userfault+hugepage feature
[qemu/ar7.git] / migration / postcopy-ram.c
blob102fb61485e9a46e7de93bec9c51c95e33aa1dd7
1 /*
2 * Postcopy migration for RAM
4 * Copyright 2013-2015 Red Hat, Inc. and/or its affiliates
6 * Authors:
7 * Dave Gilbert <dgilbert@redhat.com>
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.
15 * Postcopy is a migration technique where the execution flips from the
16 * source to the destination before all the data has been copied.
19 #include "qemu/osdep.h"
21 #include "qemu-common.h"
22 #include "migration/migration.h"
23 #include "migration/postcopy-ram.h"
24 #include "sysemu/sysemu.h"
25 #include "sysemu/balloon.h"
26 #include "qemu/error-report.h"
27 #include "trace.h"
29 /* Arbitrary limit on size of each discard command,
30 * keeps them around ~200 bytes
32 #define MAX_DISCARDS_PER_COMMAND 12
34 struct PostcopyDiscardState {
35 const char *ramblock_name;
36 uint64_t offset; /* Bitmap entry for the 1st bit of this RAMBlock */
37 uint16_t cur_entry;
39 * Start and length of a discard range (bytes)
41 uint64_t start_list[MAX_DISCARDS_PER_COMMAND];
42 uint64_t length_list[MAX_DISCARDS_PER_COMMAND];
43 unsigned int nsentwords;
44 unsigned int nsentcmds;
47 /* Postcopy needs to detect accesses to pages that haven't yet been copied
48 * across, and efficiently map new pages in, the techniques for doing this
49 * are target OS specific.
51 #if defined(__linux__)
53 #include <poll.h>
54 #include <sys/ioctl.h>
55 #include <sys/syscall.h>
56 #include <asm/types.h> /* for __u64 */
57 #endif
59 #if defined(__linux__) && defined(__NR_userfaultfd) && defined(CONFIG_EVENTFD)
60 #include <sys/eventfd.h>
61 #include <linux/userfaultfd.h>
63 static bool ufd_version_check(int ufd)
65 struct uffdio_api api_struct;
66 uint64_t ioctl_mask;
68 api_struct.api = UFFD_API;
69 api_struct.features = 0;
70 if (ioctl(ufd, UFFDIO_API, &api_struct)) {
71 error_report("postcopy_ram_supported_by_host: UFFDIO_API failed: %s",
72 strerror(errno));
73 return false;
76 ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
77 (__u64)1 << _UFFDIO_UNREGISTER;
78 if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
79 error_report("Missing userfault features: %" PRIx64,
80 (uint64_t)(~api_struct.ioctls & ioctl_mask));
81 return false;
84 if (getpagesize() != ram_pagesize_summary()) {
85 bool have_hp = false;
86 /* We've got a huge page */
87 #ifdef UFFD_FEATURE_MISSING_HUGETLBFS
88 have_hp = api_struct.features & UFFD_FEATURE_MISSING_HUGETLBFS;
89 #endif
90 if (!have_hp) {
91 error_report("Userfault on this host does not support huge pages");
92 return false;
95 return true;
99 * Note: This has the side effect of munlock'ing all of RAM, that's
100 * normally fine since if the postcopy succeeds it gets turned back on at the
101 * end.
103 bool postcopy_ram_supported_by_host(void)
105 long pagesize = getpagesize();
106 int ufd = -1;
107 bool ret = false; /* Error unless we change it */
108 void *testarea = NULL;
109 struct uffdio_register reg_struct;
110 struct uffdio_range range_struct;
111 uint64_t feature_mask;
113 if ((1ul << qemu_target_page_bits()) > pagesize) {
114 error_report("Target page size bigger than host page size");
115 goto out;
118 ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
119 if (ufd == -1) {
120 error_report("%s: userfaultfd not available: %s", __func__,
121 strerror(errno));
122 goto out;
125 /* Version and features check */
126 if (!ufd_version_check(ufd)) {
127 goto out;
131 * userfault and mlock don't go together; we'll put it back later if
132 * it was enabled.
134 if (munlockall()) {
135 error_report("%s: munlockall: %s", __func__, strerror(errno));
136 return -1;
140 * We need to check that the ops we need are supported on anon memory
141 * To do that we need to register a chunk and see the flags that
142 * are returned.
144 testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE |
145 MAP_ANONYMOUS, -1, 0);
146 if (testarea == MAP_FAILED) {
147 error_report("%s: Failed to map test area: %s", __func__,
148 strerror(errno));
149 goto out;
151 g_assert(((size_t)testarea & (pagesize-1)) == 0);
153 reg_struct.range.start = (uintptr_t)testarea;
154 reg_struct.range.len = pagesize;
155 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
157 if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
158 error_report("%s userfault register: %s", __func__, strerror(errno));
159 goto out;
162 range_struct.start = (uintptr_t)testarea;
163 range_struct.len = pagesize;
164 if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) {
165 error_report("%s userfault unregister: %s", __func__, strerror(errno));
166 goto out;
169 feature_mask = (__u64)1 << _UFFDIO_WAKE |
170 (__u64)1 << _UFFDIO_COPY |
171 (__u64)1 << _UFFDIO_ZEROPAGE;
172 if ((reg_struct.ioctls & feature_mask) != feature_mask) {
173 error_report("Missing userfault map features: %" PRIx64,
174 (uint64_t)(~reg_struct.ioctls & feature_mask));
175 goto out;
178 /* Success! */
179 ret = true;
180 out:
181 if (testarea) {
182 munmap(testarea, pagesize);
184 if (ufd != -1) {
185 close(ufd);
187 return ret;
191 * Setup an area of RAM so that it *can* be used for postcopy later; this
192 * must be done right at the start prior to pre-copy.
193 * opaque should be the MIS.
195 static int init_range(const char *block_name, void *host_addr,
196 ram_addr_t offset, ram_addr_t length, void *opaque)
198 MigrationIncomingState *mis = opaque;
200 trace_postcopy_init_range(block_name, host_addr, offset, length);
203 * We need the whole of RAM to be truly empty for postcopy, so things
204 * like ROMs and any data tables built during init must be zero'd
205 * - we're going to get the copy from the source anyway.
206 * (Precopy will just overwrite this data, so doesn't need the discard)
208 if (ram_discard_range(mis, block_name, 0, length)) {
209 return -1;
212 return 0;
216 * At the end of migration, undo the effects of init_range
217 * opaque should be the MIS.
219 static int cleanup_range(const char *block_name, void *host_addr,
220 ram_addr_t offset, ram_addr_t length, void *opaque)
222 MigrationIncomingState *mis = opaque;
223 struct uffdio_range range_struct;
224 trace_postcopy_cleanup_range(block_name, host_addr, offset, length);
227 * We turned off hugepage for the precopy stage with postcopy enabled
228 * we can turn it back on now.
230 qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE);
233 * We can also turn off userfault now since we should have all the
234 * pages. It can be useful to leave it on to debug postcopy
235 * if you're not sure it's always getting every page.
237 range_struct.start = (uintptr_t)host_addr;
238 range_struct.len = length;
240 if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
241 error_report("%s: userfault unregister %s", __func__, strerror(errno));
243 return -1;
246 return 0;
250 * Initialise postcopy-ram, setting the RAM to a state where we can go into
251 * postcopy later; must be called prior to any precopy.
252 * called from arch_init's similarly named ram_postcopy_incoming_init
254 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
256 if (qemu_ram_foreach_block(init_range, mis)) {
257 return -1;
260 return 0;
264 * At the end of a migration where postcopy_ram_incoming_init was called.
266 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
268 trace_postcopy_ram_incoming_cleanup_entry();
270 if (mis->have_fault_thread) {
271 uint64_t tmp64;
273 if (qemu_ram_foreach_block(cleanup_range, mis)) {
274 return -1;
277 * Tell the fault_thread to exit, it's an eventfd that should
278 * currently be at 0, we're going to increment it to 1
280 tmp64 = 1;
281 if (write(mis->userfault_quit_fd, &tmp64, 8) == 8) {
282 trace_postcopy_ram_incoming_cleanup_join();
283 qemu_thread_join(&mis->fault_thread);
284 } else {
285 /* Not much we can do here, but may as well report it */
286 error_report("%s: incrementing userfault_quit_fd: %s", __func__,
287 strerror(errno));
289 trace_postcopy_ram_incoming_cleanup_closeuf();
290 close(mis->userfault_fd);
291 close(mis->userfault_quit_fd);
292 mis->have_fault_thread = false;
295 qemu_balloon_inhibit(false);
297 if (enable_mlock) {
298 if (os_mlock() < 0) {
299 error_report("mlock: %s", strerror(errno));
301 * It doesn't feel right to fail at this point, we have a valid
302 * VM state.
307 postcopy_state_set(POSTCOPY_INCOMING_END);
308 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
310 if (mis->postcopy_tmp_page) {
311 munmap(mis->postcopy_tmp_page, mis->largest_page_size);
312 mis->postcopy_tmp_page = NULL;
314 if (mis->postcopy_tmp_zero_page) {
315 munmap(mis->postcopy_tmp_zero_page, mis->largest_page_size);
316 mis->postcopy_tmp_zero_page = NULL;
318 trace_postcopy_ram_incoming_cleanup_exit();
319 return 0;
323 * Disable huge pages on an area
325 static int nhp_range(const char *block_name, void *host_addr,
326 ram_addr_t offset, ram_addr_t length, void *opaque)
328 trace_postcopy_nhp_range(block_name, host_addr, offset, length);
331 * Before we do discards we need to ensure those discards really
332 * do delete areas of the page, even if THP thinks a hugepage would
333 * be a good idea, so force hugepages off.
335 qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE);
337 return 0;
341 * Userfault requires us to mark RAM as NOHUGEPAGE prior to discard
342 * however leaving it until after precopy means that most of the precopy
343 * data is still THPd
345 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
347 if (qemu_ram_foreach_block(nhp_range, mis)) {
348 return -1;
351 postcopy_state_set(POSTCOPY_INCOMING_DISCARD);
353 return 0;
357 * Mark the given area of RAM as requiring notification to unwritten areas
358 * Used as a callback on qemu_ram_foreach_block.
359 * host_addr: Base of area to mark
360 * offset: Offset in the whole ram arena
361 * length: Length of the section
362 * opaque: MigrationIncomingState pointer
363 * Returns 0 on success
365 static int ram_block_enable_notify(const char *block_name, void *host_addr,
366 ram_addr_t offset, ram_addr_t length,
367 void *opaque)
369 MigrationIncomingState *mis = opaque;
370 struct uffdio_register reg_struct;
372 reg_struct.range.start = (uintptr_t)host_addr;
373 reg_struct.range.len = length;
374 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
376 /* Now tell our userfault_fd that it's responsible for this area */
377 if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
378 error_report("%s userfault register: %s", __func__, strerror(errno));
379 return -1;
382 return 0;
386 * Handle faults detected by the USERFAULT markings
388 static void *postcopy_ram_fault_thread(void *opaque)
390 MigrationIncomingState *mis = opaque;
391 struct uffd_msg msg;
392 int ret;
393 RAMBlock *rb = NULL;
394 RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */
396 trace_postcopy_ram_fault_thread_entry();
397 qemu_sem_post(&mis->fault_thread_sem);
399 while (true) {
400 ram_addr_t rb_offset;
401 struct pollfd pfd[2];
404 * We're mainly waiting for the kernel to give us a faulting HVA,
405 * however we can be told to quit via userfault_quit_fd which is
406 * an eventfd
408 pfd[0].fd = mis->userfault_fd;
409 pfd[0].events = POLLIN;
410 pfd[0].revents = 0;
411 pfd[1].fd = mis->userfault_quit_fd;
412 pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
413 pfd[1].revents = 0;
415 if (poll(pfd, 2, -1 /* Wait forever */) == -1) {
416 error_report("%s: userfault poll: %s", __func__, strerror(errno));
417 break;
420 if (pfd[1].revents) {
421 trace_postcopy_ram_fault_thread_quit();
422 break;
425 ret = read(mis->userfault_fd, &msg, sizeof(msg));
426 if (ret != sizeof(msg)) {
427 if (errno == EAGAIN) {
429 * if a wake up happens on the other thread just after
430 * the poll, there is nothing to read.
432 continue;
434 if (ret < 0) {
435 error_report("%s: Failed to read full userfault message: %s",
436 __func__, strerror(errno));
437 break;
438 } else {
439 error_report("%s: Read %d bytes from userfaultfd expected %zd",
440 __func__, ret, sizeof(msg));
441 break; /* Lost alignment, don't know what we'd read next */
444 if (msg.event != UFFD_EVENT_PAGEFAULT) {
445 error_report("%s: Read unexpected event %ud from userfaultfd",
446 __func__, msg.event);
447 continue; /* It's not a page fault, shouldn't happen */
450 rb = qemu_ram_block_from_host(
451 (void *)(uintptr_t)msg.arg.pagefault.address,
452 true, &rb_offset);
453 if (!rb) {
454 error_report("postcopy_ram_fault_thread: Fault outside guest: %"
455 PRIx64, (uint64_t)msg.arg.pagefault.address);
456 break;
459 rb_offset &= ~(qemu_ram_pagesize(rb) - 1);
460 trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,
461 qemu_ram_get_idstr(rb),
462 rb_offset);
465 * Send the request to the source - we want to request one
466 * of our host page sizes (which is >= TPS)
468 if (rb != last_rb) {
469 last_rb = rb;
470 migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
471 rb_offset, qemu_ram_pagesize(rb));
472 } else {
473 /* Save some space */
474 migrate_send_rp_req_pages(mis, NULL,
475 rb_offset, qemu_ram_pagesize(rb));
478 trace_postcopy_ram_fault_thread_exit();
479 return NULL;
482 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
484 /* Open the fd for the kernel to give us userfaults */
485 mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
486 if (mis->userfault_fd == -1) {
487 error_report("%s: Failed to open userfault fd: %s", __func__,
488 strerror(errno));
489 return -1;
493 * Although the host check already tested the API, we need to
494 * do the check again as an ABI handshake on the new fd.
496 if (!ufd_version_check(mis->userfault_fd)) {
497 return -1;
500 /* Now an eventfd we use to tell the fault-thread to quit */
501 mis->userfault_quit_fd = eventfd(0, EFD_CLOEXEC);
502 if (mis->userfault_quit_fd == -1) {
503 error_report("%s: Opening userfault_quit_fd: %s", __func__,
504 strerror(errno));
505 close(mis->userfault_fd);
506 return -1;
509 qemu_sem_init(&mis->fault_thread_sem, 0);
510 qemu_thread_create(&mis->fault_thread, "postcopy/fault",
511 postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
512 qemu_sem_wait(&mis->fault_thread_sem);
513 qemu_sem_destroy(&mis->fault_thread_sem);
514 mis->have_fault_thread = true;
516 /* Mark so that we get notified of accesses to unwritten areas */
517 if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
518 return -1;
522 * Ballooning can mark pages as absent while we're postcopying
523 * that would cause false userfaults.
525 qemu_balloon_inhibit(true);
527 trace_postcopy_ram_enable_notify();
529 return 0;
533 * Place a host page (from) at (host) atomically
534 * returns 0 on success
536 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
537 size_t pagesize)
539 struct uffdio_copy copy_struct;
541 copy_struct.dst = (uint64_t)(uintptr_t)host;
542 copy_struct.src = (uint64_t)(uintptr_t)from;
543 copy_struct.len = pagesize;
544 copy_struct.mode = 0;
546 /* copy also acks to the kernel waking the stalled thread up
547 * TODO: We can inhibit that ack and only do it if it was requested
548 * which would be slightly cheaper, but we'd have to be careful
549 * of the order of updating our page state.
551 if (ioctl(mis->userfault_fd, UFFDIO_COPY, &copy_struct)) {
552 int e = errno;
553 error_report("%s: %s copy host: %p from: %p (size: %zd)",
554 __func__, strerror(e), host, from, pagesize);
556 return -e;
559 trace_postcopy_place_page(host);
560 return 0;
564 * Place a zero page at (host) atomically
565 * returns 0 on success
567 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
568 size_t pagesize)
570 trace_postcopy_place_page_zero(host);
572 if (pagesize == getpagesize()) {
573 struct uffdio_zeropage zero_struct;
574 zero_struct.range.start = (uint64_t)(uintptr_t)host;
575 zero_struct.range.len = getpagesize();
576 zero_struct.mode = 0;
578 if (ioctl(mis->userfault_fd, UFFDIO_ZEROPAGE, &zero_struct)) {
579 int e = errno;
580 error_report("%s: %s zero host: %p",
581 __func__, strerror(e), host);
583 return -e;
585 } else {
586 /* The kernel can't use UFFDIO_ZEROPAGE for hugepages */
587 if (!mis->postcopy_tmp_zero_page) {
588 mis->postcopy_tmp_zero_page = mmap(NULL, mis->largest_page_size,
589 PROT_READ | PROT_WRITE,
590 MAP_PRIVATE | MAP_ANONYMOUS,
591 -1, 0);
592 if (mis->postcopy_tmp_zero_page == MAP_FAILED) {
593 int e = errno;
594 mis->postcopy_tmp_zero_page = NULL;
595 error_report("%s: %s mapping large zero page",
596 __func__, strerror(e));
597 return -e;
599 memset(mis->postcopy_tmp_zero_page, '\0', mis->largest_page_size);
601 return postcopy_place_page(mis, host, mis->postcopy_tmp_zero_page,
602 pagesize);
605 return 0;
609 * Returns a target page of memory that can be mapped at a later point in time
610 * using postcopy_place_page
611 * The same address is used repeatedly, postcopy_place_page just takes the
612 * backing page away.
613 * Returns: Pointer to allocated page
616 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
618 if (!mis->postcopy_tmp_page) {
619 mis->postcopy_tmp_page = mmap(NULL, mis->largest_page_size,
620 PROT_READ | PROT_WRITE, MAP_PRIVATE |
621 MAP_ANONYMOUS, -1, 0);
622 if (mis->postcopy_tmp_page == MAP_FAILED) {
623 mis->postcopy_tmp_page = NULL;
624 error_report("%s: %s", __func__, strerror(errno));
625 return NULL;
629 return mis->postcopy_tmp_page;
632 #else
633 /* No target OS support, stubs just fail */
634 bool postcopy_ram_supported_by_host(void)
636 error_report("%s: No OS support", __func__);
637 return false;
640 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
642 error_report("postcopy_ram_incoming_init: No OS support");
643 return -1;
646 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
648 assert(0);
649 return -1;
652 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
654 assert(0);
655 return -1;
658 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
660 assert(0);
661 return -1;
664 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
665 size_t pagesize)
667 assert(0);
668 return -1;
671 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
672 size_t pagesize)
674 assert(0);
675 return -1;
678 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
680 assert(0);
681 return NULL;
684 #endif
686 /* ------------------------------------------------------------------------- */
689 * postcopy_discard_send_init: Called at the start of each RAMBlock before
690 * asking to discard individual ranges.
692 * @ms: The current migration state.
693 * @offset: the bitmap offset of the named RAMBlock in the migration
694 * bitmap.
695 * @name: RAMBlock that discards will operate on.
697 * returns: a new PDS.
699 PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
700 unsigned long offset,
701 const char *name)
703 PostcopyDiscardState *res = g_malloc0(sizeof(PostcopyDiscardState));
705 if (res) {
706 res->ramblock_name = name;
707 res->offset = offset;
710 return res;
714 * postcopy_discard_send_range: Called by the bitmap code for each chunk to
715 * discard. May send a discard message, may just leave it queued to
716 * be sent later.
718 * @ms: Current migration state.
719 * @pds: Structure initialised by postcopy_discard_send_init().
720 * @start,@length: a range of pages in the migration bitmap in the
721 * RAM block passed to postcopy_discard_send_init() (length=1 is one page)
723 void postcopy_discard_send_range(MigrationState *ms, PostcopyDiscardState *pds,
724 unsigned long start, unsigned long length)
726 size_t tp_bits = qemu_target_page_bits();
727 /* Convert to byte offsets within the RAM block */
728 pds->start_list[pds->cur_entry] = (start - pds->offset) << tp_bits;
729 pds->length_list[pds->cur_entry] = length << tp_bits;
730 trace_postcopy_discard_send_range(pds->ramblock_name, start, length);
731 pds->cur_entry++;
732 pds->nsentwords++;
734 if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
735 /* Full set, ship it! */
736 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
737 pds->ramblock_name,
738 pds->cur_entry,
739 pds->start_list,
740 pds->length_list);
741 pds->nsentcmds++;
742 pds->cur_entry = 0;
747 * postcopy_discard_send_finish: Called at the end of each RAMBlock by the
748 * bitmap code. Sends any outstanding discard messages, frees the PDS
750 * @ms: Current migration state.
751 * @pds: Structure initialised by postcopy_discard_send_init().
753 void postcopy_discard_send_finish(MigrationState *ms, PostcopyDiscardState *pds)
755 /* Anything unsent? */
756 if (pds->cur_entry) {
757 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
758 pds->ramblock_name,
759 pds->cur_entry,
760 pds->start_list,
761 pds->length_list);
762 pds->nsentcmds++;
765 trace_postcopy_discard_send_finish(pds->ramblock_name, pds->nsentwords,
766 pds->nsentcmds);
768 g_free(pds);