Disable mlock around incoming postcopy
[qemu/ar7.git] / migration / postcopy-ram.c
blob1a24b0937ea57b29b3fdeb937c2bca791265b462
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 <glib.h>
20 #include <stdio.h>
21 #include <unistd.h>
23 #include "qemu-common.h"
24 #include "migration/migration.h"
25 #include "migration/postcopy-ram.h"
26 #include "sysemu/sysemu.h"
27 #include "qemu/error-report.h"
28 #include "trace.h"
30 /* Arbitrary limit on size of each discard command,
31 * keeps them around ~200 bytes
33 #define MAX_DISCARDS_PER_COMMAND 12
35 struct PostcopyDiscardState {
36 const char *ramblock_name;
37 uint64_t offset; /* Bitmap entry for the 1st bit of this RAMBlock */
38 uint16_t cur_entry;
40 * Start and length of a discard range (bytes)
42 uint64_t start_list[MAX_DISCARDS_PER_COMMAND];
43 uint64_t length_list[MAX_DISCARDS_PER_COMMAND];
44 unsigned int nsentwords;
45 unsigned int nsentcmds;
48 /* Postcopy needs to detect accesses to pages that haven't yet been copied
49 * across, and efficiently map new pages in, the techniques for doing this
50 * are target OS specific.
52 #if defined(__linux__)
54 #include <poll.h>
55 #include <sys/eventfd.h>
56 #include <sys/mman.h>
57 #include <sys/ioctl.h>
58 #include <sys/syscall.h>
59 #include <sys/types.h>
60 #include <asm/types.h> /* for __u64 */
61 #endif
63 #if defined(__linux__) && defined(__NR_userfaultfd)
64 #include <linux/userfaultfd.h>
66 static bool ufd_version_check(int ufd)
68 struct uffdio_api api_struct;
69 uint64_t ioctl_mask;
71 api_struct.api = UFFD_API;
72 api_struct.features = 0;
73 if (ioctl(ufd, UFFDIO_API, &api_struct)) {
74 error_report("postcopy_ram_supported_by_host: UFFDIO_API failed: %s",
75 strerror(errno));
76 return false;
79 ioctl_mask = (__u64)1 << _UFFDIO_REGISTER |
80 (__u64)1 << _UFFDIO_UNREGISTER;
81 if ((api_struct.ioctls & ioctl_mask) != ioctl_mask) {
82 error_report("Missing userfault features: %" PRIx64,
83 (uint64_t)(~api_struct.ioctls & ioctl_mask));
84 return false;
87 return true;
91 * Note: This has the side effect of munlock'ing all of RAM, that's
92 * normally fine since if the postcopy succeeds it gets turned back on at the
93 * end.
95 bool postcopy_ram_supported_by_host(void)
97 long pagesize = getpagesize();
98 int ufd = -1;
99 bool ret = false; /* Error unless we change it */
100 void *testarea = NULL;
101 struct uffdio_register reg_struct;
102 struct uffdio_range range_struct;
103 uint64_t feature_mask;
105 if ((1ul << qemu_target_page_bits()) > pagesize) {
106 error_report("Target page size bigger than host page size");
107 goto out;
110 ufd = syscall(__NR_userfaultfd, O_CLOEXEC);
111 if (ufd == -1) {
112 error_report("%s: userfaultfd not available: %s", __func__,
113 strerror(errno));
114 goto out;
117 /* Version and features check */
118 if (!ufd_version_check(ufd)) {
119 goto out;
123 * userfault and mlock don't go together; we'll put it back later if
124 * it was enabled.
126 if (munlockall()) {
127 error_report("%s: munlockall: %s", __func__, strerror(errno));
128 return -1;
132 * We need to check that the ops we need are supported on anon memory
133 * To do that we need to register a chunk and see the flags that
134 * are returned.
136 testarea = mmap(NULL, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE |
137 MAP_ANONYMOUS, -1, 0);
138 if (testarea == MAP_FAILED) {
139 error_report("%s: Failed to map test area: %s", __func__,
140 strerror(errno));
141 goto out;
143 g_assert(((size_t)testarea & (pagesize-1)) == 0);
145 reg_struct.range.start = (uintptr_t)testarea;
146 reg_struct.range.len = pagesize;
147 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
149 if (ioctl(ufd, UFFDIO_REGISTER, &reg_struct)) {
150 error_report("%s userfault register: %s", __func__, strerror(errno));
151 goto out;
154 range_struct.start = (uintptr_t)testarea;
155 range_struct.len = pagesize;
156 if (ioctl(ufd, UFFDIO_UNREGISTER, &range_struct)) {
157 error_report("%s userfault unregister: %s", __func__, strerror(errno));
158 goto out;
161 feature_mask = (__u64)1 << _UFFDIO_WAKE |
162 (__u64)1 << _UFFDIO_COPY |
163 (__u64)1 << _UFFDIO_ZEROPAGE;
164 if ((reg_struct.ioctls & feature_mask) != feature_mask) {
165 error_report("Missing userfault map features: %" PRIx64,
166 (uint64_t)(~reg_struct.ioctls & feature_mask));
167 goto out;
170 /* Success! */
171 ret = true;
172 out:
173 if (testarea) {
174 munmap(testarea, pagesize);
176 if (ufd != -1) {
177 close(ufd);
179 return ret;
183 * postcopy_ram_discard_range: Discard a range of memory.
184 * We can assume that if we've been called postcopy_ram_hosttest returned true.
186 * @mis: Current incoming migration state.
187 * @start, @length: range of memory to discard.
189 * returns: 0 on success.
191 int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
192 size_t length)
194 trace_postcopy_ram_discard_range(start, length);
195 if (madvise(start, length, MADV_DONTNEED)) {
196 error_report("%s MADV_DONTNEED: %s", __func__, strerror(errno));
197 return -1;
200 return 0;
204 * Setup an area of RAM so that it *can* be used for postcopy later; this
205 * must be done right at the start prior to pre-copy.
206 * opaque should be the MIS.
208 static int init_range(const char *block_name, void *host_addr,
209 ram_addr_t offset, ram_addr_t length, void *opaque)
211 MigrationIncomingState *mis = opaque;
213 trace_postcopy_init_range(block_name, host_addr, offset, length);
216 * We need the whole of RAM to be truly empty for postcopy, so things
217 * like ROMs and any data tables built during init must be zero'd
218 * - we're going to get the copy from the source anyway.
219 * (Precopy will just overwrite this data, so doesn't need the discard)
221 if (postcopy_ram_discard_range(mis, host_addr, length)) {
222 return -1;
225 return 0;
229 * At the end of migration, undo the effects of init_range
230 * opaque should be the MIS.
232 static int cleanup_range(const char *block_name, void *host_addr,
233 ram_addr_t offset, ram_addr_t length, void *opaque)
235 MigrationIncomingState *mis = opaque;
236 struct uffdio_range range_struct;
237 trace_postcopy_cleanup_range(block_name, host_addr, offset, length);
240 * We turned off hugepage for the precopy stage with postcopy enabled
241 * we can turn it back on now.
243 if (qemu_madvise(host_addr, length, QEMU_MADV_HUGEPAGE)) {
244 error_report("%s HUGEPAGE: %s", __func__, strerror(errno));
245 return -1;
249 * We can also turn off userfault now since we should have all the
250 * pages. It can be useful to leave it on to debug postcopy
251 * if you're not sure it's always getting every page.
253 range_struct.start = (uintptr_t)host_addr;
254 range_struct.len = length;
256 if (ioctl(mis->userfault_fd, UFFDIO_UNREGISTER, &range_struct)) {
257 error_report("%s: userfault unregister %s", __func__, strerror(errno));
259 return -1;
262 return 0;
266 * Initialise postcopy-ram, setting the RAM to a state where we can go into
267 * postcopy later; must be called prior to any precopy.
268 * called from arch_init's similarly named ram_postcopy_incoming_init
270 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
272 if (qemu_ram_foreach_block(init_range, mis)) {
273 return -1;
276 return 0;
280 * At the end of a migration where postcopy_ram_incoming_init was called.
282 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
284 trace_postcopy_ram_incoming_cleanup_entry();
286 if (mis->have_fault_thread) {
287 uint64_t tmp64;
289 if (qemu_ram_foreach_block(cleanup_range, mis)) {
290 return -1;
293 * Tell the fault_thread to exit, it's an eventfd that should
294 * currently be at 0, we're going to increment it to 1
296 tmp64 = 1;
297 if (write(mis->userfault_quit_fd, &tmp64, 8) == 8) {
298 trace_postcopy_ram_incoming_cleanup_join();
299 qemu_thread_join(&mis->fault_thread);
300 } else {
301 /* Not much we can do here, but may as well report it */
302 error_report("%s: incrementing userfault_quit_fd: %s", __func__,
303 strerror(errno));
305 trace_postcopy_ram_incoming_cleanup_closeuf();
306 close(mis->userfault_fd);
307 close(mis->userfault_quit_fd);
308 mis->have_fault_thread = false;
311 if (enable_mlock) {
312 if (os_mlock() < 0) {
313 error_report("mlock: %s", strerror(errno));
315 * It doesn't feel right to fail at this point, we have a valid
316 * VM state.
321 postcopy_state_set(POSTCOPY_INCOMING_END);
322 migrate_send_rp_shut(mis, qemu_file_get_error(mis->from_src_file) != 0);
324 if (mis->postcopy_tmp_page) {
325 munmap(mis->postcopy_tmp_page, getpagesize());
326 mis->postcopy_tmp_page = NULL;
328 trace_postcopy_ram_incoming_cleanup_exit();
329 return 0;
333 * Disable huge pages on an area
335 static int nhp_range(const char *block_name, void *host_addr,
336 ram_addr_t offset, ram_addr_t length, void *opaque)
338 trace_postcopy_nhp_range(block_name, host_addr, offset, length);
341 * Before we do discards we need to ensure those discards really
342 * do delete areas of the page, even if THP thinks a hugepage would
343 * be a good idea, so force hugepages off.
345 if (qemu_madvise(host_addr, length, QEMU_MADV_NOHUGEPAGE)) {
346 error_report("%s: NOHUGEPAGE: %s", __func__, strerror(errno));
347 return -1;
350 return 0;
354 * Userfault requires us to mark RAM as NOHUGEPAGE prior to discard
355 * however leaving it until after precopy means that most of the precopy
356 * data is still THPd
358 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
360 if (qemu_ram_foreach_block(nhp_range, mis)) {
361 return -1;
364 postcopy_state_set(POSTCOPY_INCOMING_DISCARD);
366 return 0;
370 * Mark the given area of RAM as requiring notification to unwritten areas
371 * Used as a callback on qemu_ram_foreach_block.
372 * host_addr: Base of area to mark
373 * offset: Offset in the whole ram arena
374 * length: Length of the section
375 * opaque: MigrationIncomingState pointer
376 * Returns 0 on success
378 static int ram_block_enable_notify(const char *block_name, void *host_addr,
379 ram_addr_t offset, ram_addr_t length,
380 void *opaque)
382 MigrationIncomingState *mis = opaque;
383 struct uffdio_register reg_struct;
385 reg_struct.range.start = (uintptr_t)host_addr;
386 reg_struct.range.len = length;
387 reg_struct.mode = UFFDIO_REGISTER_MODE_MISSING;
389 /* Now tell our userfault_fd that it's responsible for this area */
390 if (ioctl(mis->userfault_fd, UFFDIO_REGISTER, &reg_struct)) {
391 error_report("%s userfault register: %s", __func__, strerror(errno));
392 return -1;
395 return 0;
399 * Handle faults detected by the USERFAULT markings
401 static void *postcopy_ram_fault_thread(void *opaque)
403 MigrationIncomingState *mis = opaque;
404 struct uffd_msg msg;
405 int ret;
406 size_t hostpagesize = getpagesize();
407 RAMBlock *rb = NULL;
408 RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */
410 trace_postcopy_ram_fault_thread_entry();
411 qemu_sem_post(&mis->fault_thread_sem);
413 while (true) {
414 ram_addr_t rb_offset;
415 ram_addr_t in_raspace;
416 struct pollfd pfd[2];
419 * We're mainly waiting for the kernel to give us a faulting HVA,
420 * however we can be told to quit via userfault_quit_fd which is
421 * an eventfd
423 pfd[0].fd = mis->userfault_fd;
424 pfd[0].events = POLLIN;
425 pfd[0].revents = 0;
426 pfd[1].fd = mis->userfault_quit_fd;
427 pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */
428 pfd[1].revents = 0;
430 if (poll(pfd, 2, -1 /* Wait forever */) == -1) {
431 error_report("%s: userfault poll: %s", __func__, strerror(errno));
432 break;
435 if (pfd[1].revents) {
436 trace_postcopy_ram_fault_thread_quit();
437 break;
440 ret = read(mis->userfault_fd, &msg, sizeof(msg));
441 if (ret != sizeof(msg)) {
442 if (errno == EAGAIN) {
444 * if a wake up happens on the other thread just after
445 * the poll, there is nothing to read.
447 continue;
449 if (ret < 0) {
450 error_report("%s: Failed to read full userfault message: %s",
451 __func__, strerror(errno));
452 break;
453 } else {
454 error_report("%s: Read %d bytes from userfaultfd expected %zd",
455 __func__, ret, sizeof(msg));
456 break; /* Lost alignment, don't know what we'd read next */
459 if (msg.event != UFFD_EVENT_PAGEFAULT) {
460 error_report("%s: Read unexpected event %ud from userfaultfd",
461 __func__, msg.event);
462 continue; /* It's not a page fault, shouldn't happen */
465 rb = qemu_ram_block_from_host(
466 (void *)(uintptr_t)msg.arg.pagefault.address,
467 true, &in_raspace, &rb_offset);
468 if (!rb) {
469 error_report("postcopy_ram_fault_thread: Fault outside guest: %"
470 PRIx64, (uint64_t)msg.arg.pagefault.address);
471 break;
474 rb_offset &= ~(hostpagesize - 1);
475 trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,
476 qemu_ram_get_idstr(rb),
477 rb_offset);
480 * Send the request to the source - we want to request one
481 * of our host page sizes (which is >= TPS)
483 if (rb != last_rb) {
484 last_rb = rb;
485 migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),
486 rb_offset, hostpagesize);
487 } else {
488 /* Save some space */
489 migrate_send_rp_req_pages(mis, NULL,
490 rb_offset, hostpagesize);
493 trace_postcopy_ram_fault_thread_exit();
494 return NULL;
497 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
499 /* Open the fd for the kernel to give us userfaults */
500 mis->userfault_fd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
501 if (mis->userfault_fd == -1) {
502 error_report("%s: Failed to open userfault fd: %s", __func__,
503 strerror(errno));
504 return -1;
508 * Although the host check already tested the API, we need to
509 * do the check again as an ABI handshake on the new fd.
511 if (!ufd_version_check(mis->userfault_fd)) {
512 return -1;
515 /* Now an eventfd we use to tell the fault-thread to quit */
516 mis->userfault_quit_fd = eventfd(0, EFD_CLOEXEC);
517 if (mis->userfault_quit_fd == -1) {
518 error_report("%s: Opening userfault_quit_fd: %s", __func__,
519 strerror(errno));
520 close(mis->userfault_fd);
521 return -1;
524 qemu_sem_init(&mis->fault_thread_sem, 0);
525 qemu_thread_create(&mis->fault_thread, "postcopy/fault",
526 postcopy_ram_fault_thread, mis, QEMU_THREAD_JOINABLE);
527 qemu_sem_wait(&mis->fault_thread_sem);
528 qemu_sem_destroy(&mis->fault_thread_sem);
529 mis->have_fault_thread = true;
531 /* Mark so that we get notified of accesses to unwritten areas */
532 if (qemu_ram_foreach_block(ram_block_enable_notify, mis)) {
533 return -1;
536 trace_postcopy_ram_enable_notify();
538 return 0;
542 * Place a host page (from) at (host) atomically
543 * returns 0 on success
545 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from)
547 struct uffdio_copy copy_struct;
549 copy_struct.dst = (uint64_t)(uintptr_t)host;
550 copy_struct.src = (uint64_t)(uintptr_t)from;
551 copy_struct.len = getpagesize();
552 copy_struct.mode = 0;
554 /* copy also acks to the kernel waking the stalled thread up
555 * TODO: We can inhibit that ack and only do it if it was requested
556 * which would be slightly cheaper, but we'd have to be careful
557 * of the order of updating our page state.
559 if (ioctl(mis->userfault_fd, UFFDIO_COPY, &copy_struct)) {
560 int e = errno;
561 error_report("%s: %s copy host: %p from: %p",
562 __func__, strerror(e), host, from);
564 return -e;
567 trace_postcopy_place_page(host);
568 return 0;
572 * Place a zero page at (host) atomically
573 * returns 0 on success
575 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host)
577 struct uffdio_zeropage zero_struct;
579 zero_struct.range.start = (uint64_t)(uintptr_t)host;
580 zero_struct.range.len = getpagesize();
581 zero_struct.mode = 0;
583 if (ioctl(mis->userfault_fd, UFFDIO_ZEROPAGE, &zero_struct)) {
584 int e = errno;
585 error_report("%s: %s zero host: %p",
586 __func__, strerror(e), host);
588 return -e;
591 trace_postcopy_place_page_zero(host);
592 return 0;
596 * Returns a target page of memory that can be mapped at a later point in time
597 * using postcopy_place_page
598 * The same address is used repeatedly, postcopy_place_page just takes the
599 * backing page away.
600 * Returns: Pointer to allocated page
603 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
605 if (!mis->postcopy_tmp_page) {
606 mis->postcopy_tmp_page = mmap(NULL, getpagesize(),
607 PROT_READ | PROT_WRITE, MAP_PRIVATE |
608 MAP_ANONYMOUS, -1, 0);
609 if (!mis->postcopy_tmp_page) {
610 error_report("%s: %s", __func__, strerror(errno));
611 return NULL;
615 return mis->postcopy_tmp_page;
618 #else
619 /* No target OS support, stubs just fail */
620 bool postcopy_ram_supported_by_host(void)
622 error_report("%s: No OS support", __func__);
623 return false;
626 int postcopy_ram_incoming_init(MigrationIncomingState *mis, size_t ram_pages)
628 error_report("postcopy_ram_incoming_init: No OS support");
629 return -1;
632 int postcopy_ram_incoming_cleanup(MigrationIncomingState *mis)
634 assert(0);
635 return -1;
638 int postcopy_ram_discard_range(MigrationIncomingState *mis, uint8_t *start,
639 size_t length)
641 assert(0);
642 return -1;
645 int postcopy_ram_prepare_discard(MigrationIncomingState *mis)
647 assert(0);
648 return -1;
651 int postcopy_ram_enable_notify(MigrationIncomingState *mis)
653 assert(0);
654 return -1;
657 int postcopy_place_page(MigrationIncomingState *mis, void *host, void *from)
659 assert(0);
660 return -1;
663 int postcopy_place_page_zero(MigrationIncomingState *mis, void *host)
665 assert(0);
666 return -1;
669 void *postcopy_get_tmp_page(MigrationIncomingState *mis)
671 assert(0);
672 return NULL;
675 #endif
677 /* ------------------------------------------------------------------------- */
680 * postcopy_discard_send_init: Called at the start of each RAMBlock before
681 * asking to discard individual ranges.
683 * @ms: The current migration state.
684 * @offset: the bitmap offset of the named RAMBlock in the migration
685 * bitmap.
686 * @name: RAMBlock that discards will operate on.
688 * returns: a new PDS.
690 PostcopyDiscardState *postcopy_discard_send_init(MigrationState *ms,
691 unsigned long offset,
692 const char *name)
694 PostcopyDiscardState *res = g_malloc0(sizeof(PostcopyDiscardState));
696 if (res) {
697 res->ramblock_name = name;
698 res->offset = offset;
701 return res;
705 * postcopy_discard_send_range: Called by the bitmap code for each chunk to
706 * discard. May send a discard message, may just leave it queued to
707 * be sent later.
709 * @ms: Current migration state.
710 * @pds: Structure initialised by postcopy_discard_send_init().
711 * @start,@length: a range of pages in the migration bitmap in the
712 * RAM block passed to postcopy_discard_send_init() (length=1 is one page)
714 void postcopy_discard_send_range(MigrationState *ms, PostcopyDiscardState *pds,
715 unsigned long start, unsigned long length)
717 size_t tp_bits = qemu_target_page_bits();
718 /* Convert to byte offsets within the RAM block */
719 pds->start_list[pds->cur_entry] = (start - pds->offset) << tp_bits;
720 pds->length_list[pds->cur_entry] = length << tp_bits;
721 trace_postcopy_discard_send_range(pds->ramblock_name, start, length);
722 pds->cur_entry++;
723 pds->nsentwords++;
725 if (pds->cur_entry == MAX_DISCARDS_PER_COMMAND) {
726 /* Full set, ship it! */
727 qemu_savevm_send_postcopy_ram_discard(ms->file, 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->file, pds->ramblock_name,
748 pds->cur_entry,
749 pds->start_list,
750 pds->length_list);
751 pds->nsentcmds++;
754 trace_postcopy_discard_send_finish(pds->ramblock_name, pds->nsentwords,
755 pds->nsentcmds);
757 g_free(pds);