postcopy: Allow hugepages
[qemu.git] / migration / postcopy-ram.c
blob6b30b43d518be3237b4d3cb3f3b4c7ed479f99d3
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 return true;
88 * Note: This has the side effect of munlock'ing all of RAM, that's
89 * normally fine since if the postcopy succeeds it gets turned back on at the
90 * end.
92 bool postcopy_ram_supported_by_host(void)
94 long pagesize = getpagesize();
95 int ufd = -1;
96 bool ret = false; /* Error unless we change it */
97 void *testarea = NULL;
98 struct uffdio_register reg_struct;
99 struct uffdio_range range_struct;
100 uint64_t feature_mask;
102 if ((1ul << qemu_target_page_bits()) > pagesize) {
103 error_report("Target page size bigger than host page size");
104 goto out;
107 ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
108 if (ufd == -1) {
109 error_report("%s: userfaultfd not available: %s", __func__,
110 strerror(errno));
111 goto out;
114 /* Version and features check */
115 if (!ufd_version_check(ufd)) {
116 goto out;
118 /* TODO: Only allow huge pages if the kernel supports it */
121 * userfault and mlock don't go together; we'll put it back later if
122 * it was enabled.
124 if (munlockall()) {
125 error_report("%s: munlockall: %s", __func__, strerror(errno));
126 return -1;
130 * We need to check that the ops we need are supported on anon memory
131 * To do that we need to register a chunk and see the flags that
132 * are returned.
134 testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE |
135 MAP_ANONYMOUS, -1, 0);
136 if (testarea == MAP_FAILED) {
137 error_report("%s: Failed to map test area: %s", __func__,
138 strerror(errno));
139 goto out;
141 g_assert(((size_t)testarea & (pagesize-1)) == 0);
143 reg_struct.range.start = (uintptr_t)testarea;
144 reg_struct.range.len = pagesize;
145 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
147 if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
148 error_report("%s userfault register: %s", __func__, strerror(errno));
149 goto out;
152 range_struct.start = (uintptr_t)testarea;
153 range_struct.len = pagesize;
154 if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) {
155 error_report("%s userfault unregister: %s", __func__, strerror(errno));
156 goto out;
159 feature_mask = (__u64)1 << _UFFDIO_WAKE |
160 (__u64)1 << _UFFDIO_COPY |
161 (__u64)1 << _UFFDIO_ZEROPAGE;
162 if ((reg_struct.ioctls & feature_mask) != feature_mask) {
163 error_report("Missing userfault map features: %" PRIx64,
164 (uint64_t)(~reg_struct.ioctls & feature_mask));
165 goto out;
168 /* Success! */
169 ret = true;
170 out:
171 if (testarea) {
172 munmap(testarea, pagesize);
174 if (ufd != -1) {
175 close(ufd);
177 return ret;
181 * Setup an area of RAM so that it *can* be used for postcopy later; this
182 * must be done right at the start prior to pre-copy.
183 * opaque should be the MIS.
185 static int init_range(const char *block_name, void *host_addr,
186 ram_addr_t offset, ram_addr_t length, void *opaque)
188 MigrationIncomingState *mis = opaque;
190 trace_postcopy_init_range(block_name, host_addr, offset, length);
193 * We need the whole of RAM to be truly empty for postcopy, so things
194 * like ROMs and any data tables built during init must be zero'd
195 * - we're going to get the copy from the source anyway.
196 * (Precopy will just overwrite this data, so doesn't need the discard)
198 if (ram_discard_range(mis, block_name, 0, length)) {
199 return -1;
202 return 0;
206 * At the end of migration, undo the effects of init_range
207 * opaque should be the MIS.
209 static int cleanup_range(const char *block_name, void *host_addr,
210 ram_addr_t offset, ram_addr_t length, void *opaque)
212 MigrationIncomingState *mis = opaque;
213 struct uffdio_range range_struct;
214 trace_postcopy_cleanup_range(block_name, host_addr, offset, length);
217 * We turned off hugepage for the precopy stage with postcopy enabled
218 * we can turn it back on now.
220 qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE);
223 * We can also turn off userfault now since we should have all the
224 * pages. It can be useful to leave it on to debug postcopy
225 * if you're not sure it's always getting every page.
227 range_struct.start = (uintptr_t)host_addr;
228 range_struct.len = length;
230 if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
231 error_report("%s: userfault unregister %s", __func__, strerror(errno));
233 return -1;
236 return 0;
240 * Initialise postcopy-ram, setting the RAM to a state where we can go into
241 * postcopy later; must be called prior to any precopy.
242 * called from arch_init's similarly named ram_postcopy_incoming_init
244 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
246 if (qemu_ram_foreach_block(init_range, mis)) {
247 return -1;
250 return 0;
254 * At the end of a migration where postcopy_ram_incoming_init was called.
256 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
258 trace_postcopy_ram_incoming_cleanup_entry();
260 if (mis->have_fault_thread) {
261 uint64_t tmp64;
263 if (qemu_ram_foreach_block(cleanup_range, mis)) {
264 return -1;
267 * Tell the fault_thread to exit, it's an eventfd that should
268 * currently be at 0, we're going to increment it to 1
270 tmp64 = 1;
271 if (write(mis->userfault_quit_fd, &tmp64, 8) == 8) {
272 trace_postcopy_ram_incoming_cleanup_join();
273 qemu_thread_join(&mis->fault_thread);
274 } else {
275 /* Not much we can do here, but may as well report it */
276 error_report("%s: incrementing userfault_quit_fd: %s", __func__,
277 strerror(errno));
279 trace_postcopy_ram_incoming_cleanup_closeuf();
280 close(mis->userfault_fd);
281 close(mis->userfault_quit_fd);
282 mis->have_fault_thread = false;
285 qemu_balloon_inhibit(false);
287 if (enable_mlock) {
288 if (os_mlock() < 0) {
289 error_report("mlock: %s", strerror(errno));
291 * It doesn't feel right to fail at this point, we have a valid
292 * VM state.
297 postcopy_state_set(POSTCOPY_INCOMING_END);
298 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
300 if (mis->postcopy_tmp_page) {
301 munmap(mis->postcopy_tmp_page, mis->largest_page_size);
302 mis->postcopy_tmp_page = NULL;
304 if (mis->postcopy_tmp_zero_page) {
305 munmap(mis->postcopy_tmp_zero_page, mis->largest_page_size);
306 mis->postcopy_tmp_zero_page = NULL;
308 trace_postcopy_ram_incoming_cleanup_exit();
309 return 0;
313 * Disable huge pages on an area
315 static int nhp_range(const char *block_name, void *host_addr,
316 ram_addr_t offset, ram_addr_t length, void *opaque)
318 trace_postcopy_nhp_range(block_name, host_addr, offset, length);
321 * Before we do discards we need to ensure those discards really
322 * do delete areas of the page, even if THP thinks a hugepage would
323 * be a good idea, so force hugepages off.
325 qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE);
327 return 0;
331 * Userfault requires us to mark RAM as NOHUGEPAGE prior to discard
332 * however leaving it until after precopy means that most of the precopy
333 * data is still THPd
335 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
337 if (qemu_ram_foreach_block(nhp_range, mis)) {
338 return -1;
341 postcopy_state_set(POSTCOPY_INCOMING_DISCARD);
343 return 0;
347 * Mark the given area of RAM as requiring notification to unwritten areas
348 * Used as a callback on qemu_ram_foreach_block.
349 * host_addr: Base of area to mark
350 * offset: Offset in the whole ram arena
351 * length: Length of the section
352 * opaque: MigrationIncomingState pointer
353 * Returns 0 on success
355 static int ram_block_enable_notify(const char *block_name, void *host_addr,
356 ram_addr_t offset, ram_addr_t length,
357 void *opaque)
359 MigrationIncomingState *mis = opaque;
360 struct uffdio_register reg_struct;
362 reg_struct.range.start = (uintptr_t)host_addr;
363 reg_struct.range.len = length;
364 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
366 /* Now tell our userfault_fd that it's responsible for this area */
367 if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
368 error_report("%s userfault register: %s", __func__, strerror(errno));
369 return -1;
372 return 0;
376 * Handle faults detected by the USERFAULT markings
378 static void *postcopy_ram_fault_thread(void *opaque)
380 MigrationIncomingState *mis = opaque;
381 struct uffd_msg msg;
382 int ret;
383 RAMBlock *rb = NULL;
384 RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */
386 trace_postcopy_ram_fault_thread_entry();
387 qemu_sem_post(&mis->fault_thread_sem);
389 while (true) {
390 ram_addr_t rb_offset;
391 struct pollfd pfd[2];
394 * We're mainly waiting for the kernel to give us a faulting HVA,
395 * however we can be told to quit via userfault_quit_fd which is
396 * an eventfd
398 pfd[0].fd = mis->userfault_fd;
399 pfd[0].events = POLLIN;
400 pfd[0].revents = 0;
401 pfd[1].fd = mis->userfault_quit_fd;
402 pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
403 pfd[1].revents = 0;
405 if (poll(pfd, 2, -1 /* Wait forever */) == -1) {
406 error_report("%s: userfault poll: %s", __func__, strerror(errno));
407 break;
410 if (pfd[1].revents) {
411 trace_postcopy_ram_fault_thread_quit();
412 break;
415 ret = read(mis->userfault_fd, &msg, sizeof(msg));
416 if (ret != sizeof(msg)) {
417 if (errno == EAGAIN) {
419 * if a wake up happens on the other thread just after
420 * the poll, there is nothing to read.
422 continue;
424 if (ret < 0) {
425 error_report("%s: Failed to read full userfault message: %s",
426 __func__, strerror(errno));
427 break;
428 } else {
429 error_report("%s: Read %d bytes from userfaultfd expected %zd",
430 __func__, ret, sizeof(msg));
431 break; /* Lost alignment, don't know what we'd read next */
434 if (msg.event != UFFD_EVENT_PAGEFAULT) {
435 error_report("%s: Read unexpected event %ud from userfaultfd",
436 __func__, msg.event);
437 continue; /* It's not a page fault, shouldn't happen */
440 rb = qemu_ram_block_from_host(
441 (void *)(uintptr_t)msg.arg.pagefault.address,
442 true, &rb_offset);
443 if (!rb) {
444 error_report("postcopy_ram_fault_thread: Fault outside guest: %"
445 PRIx64, (uint64_t)msg.arg.pagefault.address);
446 break;
449 rb_offset &= ~(qemu_ram_pagesize(rb) - 1);
450 trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,
451 qemu_ram_get_idstr(rb),
452 rb_offset);
455 * Send the request to the source - we want to request one
456 * of our host page sizes (which is >= TPS)
458 if (rb != last_rb) {
459 last_rb = rb;
460 migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
461 rb_offset, qemu_ram_pagesize(rb));
462 } else {
463 /* Save some space */
464 migrate_send_rp_req_pages(mis, NULL,
465 rb_offset, qemu_ram_pagesize(rb));
468 trace_postcopy_ram_fault_thread_exit();
469 return NULL;
472 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
474 /* Open the fd for the kernel to give us userfaults */
475 mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
476 if (mis->userfault_fd == -1) {
477 error_report("%s: Failed to open userfault fd: %s", __func__,
478 strerror(errno));
479 return -1;
483 * Although the host check already tested the API, we need to
484 * do the check again as an ABI handshake on the new fd.
486 if (!ufd_version_check(mis->userfault_fd)) {
487 return -1;
490 /* Now an eventfd we use to tell the fault-thread to quit */
491 mis->userfault_quit_fd = eventfd(0, EFD_CLOEXEC);
492 if (mis->userfault_quit_fd == -1) {
493 error_report("%s: Opening userfault_quit_fd: %s", __func__,
494 strerror(errno));
495 close(mis->userfault_fd);
496 return -1;
499 qemu_sem_init(&mis->fault_thread_sem, 0);
500 qemu_thread_create(&mis->fault_thread, "postcopy/fault",
501 postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
502 qemu_sem_wait(&mis->fault_thread_sem);
503 qemu_sem_destroy(&mis->fault_thread_sem);
504 mis->have_fault_thread = true;
506 /* Mark so that we get notified of accesses to unwritten areas */
507 if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
508 return -1;
512 * Ballooning can mark pages as absent while we're postcopying
513 * that would cause false userfaults.
515 qemu_balloon_inhibit(true);
517 trace_postcopy_ram_enable_notify();
519 return 0;
523 * Place a host page (from) at (host) atomically
524 * returns 0 on success
526 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
527 size_t pagesize)
529 struct uffdio_copy copy_struct;
531 copy_struct.dst = (uint64_t)(uintptr_t)host;
532 copy_struct.src = (uint64_t)(uintptr_t)from;
533 copy_struct.len = pagesize;
534 copy_struct.mode = 0;
536 /* copy also acks to the kernel waking the stalled thread up
537 * TODO: We can inhibit that ack and only do it if it was requested
538 * which would be slightly cheaper, but we'd have to be careful
539 * of the order of updating our page state.
541 if (ioctl(mis->userfault_fd, UFFDIO_COPY, &copy_struct)) {
542 int e = errno;
543 error_report("%s: %s copy host: %p from: %p (size: %zd)",
544 __func__, strerror(e), host, from, pagesize);
546 return -e;
549 trace_postcopy_place_page(host);
550 return 0;
554 * Place a zero page at (host) atomically
555 * returns 0 on success
557 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
558 size_t pagesize)
560 trace_postcopy_place_page_zero(host);
562 if (pagesize == getpagesize()) {
563 struct uffdio_zeropage zero_struct;
564 zero_struct.range.start = (uint64_t)(uintptr_t)host;
565 zero_struct.range.len = getpagesize();
566 zero_struct.mode = 0;
568 if (ioctl(mis->userfault_fd, UFFDIO_ZEROPAGE, &zero_struct)) {
569 int e = errno;
570 error_report("%s: %s zero host: %p",
571 __func__, strerror(e), host);
573 return -e;
575 } else {
576 /* The kernel can't use UFFDIO_ZEROPAGE for hugepages */
577 if (!mis->postcopy_tmp_zero_page) {
578 mis->postcopy_tmp_zero_page = mmap(NULL, mis->largest_page_size,
579 PROT_READ | PROT_WRITE,
580 MAP_PRIVATE | MAP_ANONYMOUS,
581 -1, 0);
582 if (mis->postcopy_tmp_zero_page == MAP_FAILED) {
583 int e = errno;
584 mis->postcopy_tmp_zero_page = NULL;
585 error_report("%s: %s mapping large zero page",
586 __func__, strerror(e));
587 return -e;
589 memset(mis->postcopy_tmp_zero_page, '\0', mis->largest_page_size);
591 return postcopy_place_page(mis, host, mis->postcopy_tmp_zero_page,
592 pagesize);
595 return 0;
599 * Returns a target page of memory that can be mapped at a later point in time
600 * using postcopy_place_page
601 * The same address is used repeatedly, postcopy_place_page just takes the
602 * backing page away.
603 * Returns: Pointer to allocated page
606 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
608 if (!mis->postcopy_tmp_page) {
609 mis->postcopy_tmp_page = mmap(NULL, mis->largest_page_size,
610 PROT_READ | PROT_WRITE, MAP_PRIVATE |
611 MAP_ANONYMOUS, -1, 0);
612 if (mis->postcopy_tmp_page == MAP_FAILED) {
613 mis->postcopy_tmp_page = NULL;
614 error_report("%s: %s", __func__, strerror(errno));
615 return NULL;
619 return mis->postcopy_tmp_page;
622 #else
623 /* No target OS support, stubs just fail */
624 bool postcopy_ram_supported_by_host(void)
626 error_report("%s: No OS support", __func__);
627 return false;
630 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
632 error_report("postcopy_ram_incoming_init: No OS support");
633 return -1;
636 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
638 assert(0);
639 return -1;
642 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
644 assert(0);
645 return -1;
648 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
650 assert(0);
651 return -1;
654 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from,
655 size_t pagesize)
657 assert(0);
658 return -1;
661 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host,
662 size_t pagesize)
664 assert(0);
665 return -1;
668 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
670 assert(0);
671 return NULL;
674 #endif
676 /* ------------------------------------------------------------------------- */
679 * postcopy_discard_send_init: Called at the start of each RAMBlock before
680 * asking to discard individual ranges.
682 * @ms: The current migration state.
683 * @offset: the bitmap offset of the named RAMBlock in the migration
684 * bitmap.
685 * @name: RAMBlock that discards will operate on.
687 * returns: a new PDS.
689 PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
690 unsigned long offset,
691 const char *name)
693 PostcopyDiscardState *res = g_malloc0(sizeof(PostcopyDiscardState));
695 if (res) {
696 res->ramblock_name = name;
697 res->offset = offset;
700 return res;
704 * postcopy_discard_send_range: Called by the bitmap code for each chunk to
705 * discard. May send a discard message, may just leave it queued to
706 * be sent later.
708 * @ms: Current migration state.
709 * @pds: Structure initialised by postcopy_discard_send_init().
710 * @start,@length: a range of pages in the migration bitmap in the
711 * RAM block passed to postcopy_discard_send_init() (length=1 is one page)
713 void postcopy_discard_send_range(MigrationState *ms, PostcopyDiscardState *pds,
714 unsigned long start, unsigned long length)
716 size_t tp_bits = qemu_target_page_bits();
717 /* Convert to byte offsets within the RAM block */
718 pds->start_list[pds->cur_entry] = (start - pds->offset) << tp_bits;
719 pds->length_list[pds->cur_entry] = length << tp_bits;
720 trace_postcopy_discard_send_range(pds->ramblock_name, start, length);
721 pds->cur_entry++;
722 pds->nsentwords++;
724 if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
725 /* Full set, ship it! */
726 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
727 pds->ramblock_name,
728 pds->cur_entry,
729 pds->start_list,
730 pds->length_list);
731 pds->nsentcmds++;
732 pds->cur_entry = 0;
737 * postcopy_discard_send_finish: Called at the end of each RAMBlock by the
738 * bitmap code. Sends any outstanding discard messages, frees the PDS
740 * @ms: Current migration state.
741 * @pds: Structure initialised by postcopy_discard_send_init().
743 void postcopy_discard_send_finish(MigrationState *ms, PostcopyDiscardState *pds)
745 /* Anything unsent? */
746 if (pds->cur_entry) {
747 qemu_savevm_send_postcopy_ram_discard(ms->to_dst_file,
748 pds->ramblock_name,
749 pds->cur_entry,
750 pds->start_list,
751 pds->length_list);
752 pds->nsentcmds++;
755 trace_postcopy_discard_send_finish(pds->ramblock_name, pds->nsentwords,
756 pds->nsentcmds);
758 g_free(pds);