userfaultfd.2: Describe memory types that can be used from 4.11
[man-pages.git] / man2 / userfaultfd.2
blobc89484f99ec134ee15ecf3a4f1a52c27405d80b1
1 .\" Copyright (c) 2016, IBM Corporation.
2 .\" Written by Mike Rapoport <rppt@linux.vnet.ibm.com>
3 .\" and Copyright (C) 2017 Michael Kerrisk <mtk.manpages@gmail.com>
4 .\"
5 .\" %%%LICENSE_START(VERBATIM)
6 .\" Permission is granted to make and distribute verbatim copies of this
7 .\" manual provided the copyright notice and this permission notice are
8 .\" preserved on all copies.
9 .\"
10 .\" Permission is granted to copy and distribute modified versions of this
11 .\" manual under the conditions for verbatim copying, provided that the
12 .\" entire resulting derived work is distributed under the terms of a
13 .\" permission notice identical to this one.
14 .\"
15 .\" Since the Linux kernel and libraries are constantly changing, this
16 .\" manual page may be incorrect or out-of-date.  The author(s) assume no
17 .\" responsibility for errors or omissions, or for damages resulting from
18 .\" the use of the information contained herein.  The author(s) may not
19 .\" have taken the same level of care in the production of this manual,
20 .\" which is licensed free of charge, as they might when working
21 .\" professionally.
22 .\"
23 .\" Formatted or processed versions of this manual, if unaccompanied by
24 .\" the source, must acknowledge the copyright and authors of this work.
25 .\" %%%LICENSE_END
26 .\"
27 .TH USERFAULTFD 2 2016-12-12 "Linux" "Linux Programmer's Manual"
28 .SH NAME
29 userfaultfd \- create a file descriptor for handling page faults in user space
30 .SH SYNOPSIS
31 .nf
32 .B #include <sys/types.h>
33 .B #include <linux/userfaultfd.h>
34 .sp
35 .BI "int userfaultfd(int " flags );
36 .fi
37 .PP
38 .IR Note :
39 There is no glibc wrapper for this system call; see NOTES.
40 .SH DESCRIPTION
41 .BR userfaultfd ()
42 creates a new userfaultfd object that can be used for delegation of page-fault
43 handling to a user-space application,
44 and returns a file descriptor that refers to the new object.
45 The new userfaultfd object is configured using
46 .BR ioctl (2).
48 Once the userfaultfd object is configured, the application can use
49 .BR read (2)
50 to receive userfaultfd notifications.
51 The reads from userfaultfd may be blocking or non-blocking,
52 depending on the value of
53 .I flags
54 used for the creation of the userfaultfd or subsequent calls to
55 .BR fcntl (2).
57 The following values may be bitwise ORed in
58 .IR flags
59 to change the behavior of
60 .BR userfaultfd ():
61 .TP
62 .BR O_CLOEXEC
63 Enable the close-on-exec flag for the new userfaultfd file descriptor.
64 See the description of the
65 .B O_CLOEXEC
66 flag in
67 .BR open (2).
68 .TP
69 .BR O_NONBLOCK
70 Enables non-blocking operation for the userfaultfd object.
71 See the description of the
72 .BR O_NONBLOCK
73 flag in
74 .BR open (2).
75 .PP
76 When the last file descriptor referring to a userfaultfd object is closed,
77 all memory ranges that were registered with the object are unregistered
78 and unread page-fault events are flushed.
79 .\"
80 .SS Usage
81 The userfaultfd mechanism is designed to allow a thread in a multithreaded
82 program to perform user-space paging for the other threads in the process.
83 When a page fault occurs for one of the regions registered
84 to the userfaultfd object,
85 the faulting thread is put to sleep and
86 an event is generated that can be read via the userfaultfd file descriptor.
87 The fault-handling thread reads events from this file descriptor and services
88 them using the operations described in
89 .BR ioctl_userfaultfd (2).
90 When servicing the page fault events,
91 the fault-handling thread can trigger a wake-up for the sleeping thread.
92 .\"
93 .SS Userfaultfd operation
94 After the userfaultfd object is created with
95 .BR userfaultfd (),
96 the application must enable it using the
97 .B UFFDIO_API
98 .BR ioctl (2)
99 operation.
100 This operation allows a handshake between the kernel and user space
101 to determine the API version and supported features.
102 This operation must be performed before any of the other
103 .BR ioctl (2)
104 operations described below (or those operations fail with the
105 .BR EINVAL
106 error).
108 After a successful
109 .B UFFDIO_API
110 operation,
111 the application then registers memory address ranges using the
112 .B UFFDIO_REGISTER
113 .BR ioctl (2)
114 operation.
115 After successful completion of a
116 .B UFFDIO_REGISTER
117 operation,
118 a page fault occurring in the requested memory range, and satisfying
119 the mode defined at the registration time, will be forwarded by the kernel to
120 the user-space application.
121 The application can then use the
122 .B UFFDIO_COPY
124 .B UFFDIO_ZERO
125 .BR ioctl (2)
126 operations to resolve the page fault.
128 Details of the various
129 .BR ioctl (2)
130 operations can be found in
131 .BR ioctl_userfaultfd (2).
133 Up to Linux 4.11,
134 userfaultfd can be used only with anonymous private memory mappings.
136 Since Linux 4.11,
137 userfaultfd can be also used with hugetlbfs and shared memory mappings.
140 .SS Reading from the userfaultfd structure
141 Each
142 .BR read (2)
143 from the userfaultfd file descriptor returns one or more
144 .I uffd_msg
145 structures, each of which describes a page-fault event:
148 .in +4n
149 struct uffd_msg {
150     __u8  event;                /* Type of event */
151     ...
152     union {
153         struct {
154             __u64 flags;        /* Flags describing fault */
155             __u64 address;      /* Faulting address */
156         } pagefault;
157         ...
158     } arg;
160     /* Padding fields omitted */
161 } __packed;
165 If multiple events are available and the supplied buffer is large enough,
166 .BR read (2)
167 returns as many events as will fit in the supplied buffer.
168 If the buffer supplied to
169 .BR read (2)
170 is smaller than the size of the
171 .I uffd_msg
172 structure, the
173 .BR read (2)
174 fails with the error
175 .BR EINVAL .
177 The fields set in the
178 .I uffd_msg
179 structure are as follows:
181 .I event
182 The type of event.
183 Currently, only one value can appear in this field:
184 .BR UFFD_EVENT_PAGEFAULT ,
185 which indicates a page-fault event.
187 .I address
188 The address that triggered the page fault.
190 .I flags
191 A bit mask of flags that describe the event.
193 .BR UFFD_EVENT_PAGEFAULT ,
194 the following flag may appear:
197 .B UFFD_PAGEFAULT_FLAG_WRITE
198 If the address is in a range that was registered with the
199 .B UFFDIO_REGISTER_MODE_MISSING
200 flag (see
201 .BR ioctl_userfaultfd (2))
202 and this flag is set, this a write fault;
203 otherwise it is a read fault.
205 .\" UFFD_PAGEFAULT_FLAG_WP is not yet supported.
209 .BR read (2)
210 on a userfaultfd file descriptor can fail with the following errors:
212 .B EINVAL
213 The userfaultfd object has not yet been enabled using the
214 .BR UFFDIO_API
215 .BR ioctl (2)
216 operation
218 If the
219 .B O_NONBLOCK
220 flag is enabled in the associated open file description,
221 the userfaultfd file descriptor can be monitored with
222 .BR poll (2),
223 .BR select (2),
225 .BR epoll (7).
226 When events are available, the file descriptor indicates as readable.
227 If the
228 .B O_NONBLOCK
229 flag is not enabled, then
230 .BR poll (2)
231 (always) indicates the file as having a
232 .BR POLLERR
233 condition, and
234 .BR select (2)
235 indicates the file descriptor as both readable and writable.
236 .\" FIXME What is the reason for this seemingly odd behavior with respect
237 .\" to the O_NONBLOCK flag? (see userfaultfd_poll() in fs/userfaultfd.c).
238 .\" Something needs to be said about this.
239 .SH RETURN VALUE
240 On success,
241 .BR userfaultfd ()
242 returns a new file descriptor that refers to the userfaultfd object.
243 On error, \-1 is returned, and
244 .I errno
245 is set appropriately.
246 .SH ERRORS
248 .B EINVAL
249 An unsupported value was specified in
250 .IR flags .
252 .BR EMFILE
253 The per-process limit on the number of open file descriptors has been
254 reached
256 .B ENFILE
257 The system-wide limit on the total number of open files has been
258 reached.
260 .B ENOMEM
261 Insufficient kernel memory was available.
262 .SH VERSIONS
264 .BR userfaultfd ()
265 system call first appeared in Linux 4.3.
266 .SH CONFORMING TO
267 .BR userfaultfd ()
268 is Linux-specific and should not be used in programs intended to be
269 portable.
270 .SH NOTES
271 Glibc does not provide a wrapper for this system call; call it using
272 .BR syscall (2).
274 The userfaultfd mechanism can be used as an alternative to
275 traditional user-space paging techniques based on the use of the
276 .BR SIGSEGV
277 signal and
278 .BR mmap (2).
279 It can also be used to implement lazy restore
280 for checkpoint/restore mechanisms,
281 as well as post-copy migration to allow (nearly) uninterrupted execution
282 when transferring virtual machines from one host to another.
283 .SH EXAMPLE
284 The program below demonstrates the use of the userfaultfd mechanism.
285 The program creates two threads, one of which acts as the
286 page-fault handler for the process, for the pages in a demand-page zero
287 region created using
288 .BR mmap (2).
290 The program takes one command-line argument,
291 which is the number of pages that will be created in a mapping
292 whose page faults will be handled via userfaultfd.
293 After creating a userfaultfd object,
294 the program then creates an anonymous private mapping of the specified size
295 and registers the address range of that mapping using the
296 .B UFFDIO_REGISTER
297 .BR ioctl (2)
298 operation.
299 The program then creates a second thread that will perform the
300 task of handling page faults.
302 The main thread then walks through the pages of the mapping fetching
303 bytes from successive pages.
304 Because the pages have not yet been accessed,
305 the first access of a byte in each page will trigger a page-fault event
306 on the userfaultfd file descriptor.
308 Each of the page-fault events is handled by the second thread,
309 which sits in a loop processing input from the userfaultfd file descriptor.
310 In each loop iteration, the second thread first calls
311 .BR poll (2)
312 to check the state of the file descriptor,
313 and then reads an event from the file descriptor.
314 All such events should be
315 .B UFFD_EVENT_PAGEFAULT
316 events,
317 which the thread handles by copying a page of data into
318 the faulting region using the
319 .B UFFDIO_COPY
320 .BR ioctl (2)
321 operation.
323 The following is an example of what we see when running the program:
326 .in +4n
327 $ \fB./userfaultfd_demo 3\fP
328 Address returned by mmap() = 0x7fd30106c000
330 fault_handler_thread():
331     poll() returns: nready = 1; POLLIN = 1; POLLERR = 0
332     UFFD_EVENT_PAGEFAULT event: flags = 0; address = 7fd30106c00f
333         (uffdio_copy.copy returned 4096)
334 Read address 0x7fd30106c00f in main(): A
335 Read address 0x7fd30106c40f in main(): A
336 Read address 0x7fd30106c80f in main(): A
337 Read address 0x7fd30106cc0f in main(): A
339 fault_handler_thread():
340     poll() returns: nready = 1; POLLIN = 1; POLLERR = 0
341     UFFD_EVENT_PAGEFAULT event: flags = 0; address = 7fd30106d00f
342         (uffdio_copy.copy returned 4096)
343 Read address 0x7fd30106d00f in main(): B
344 Read address 0x7fd30106d40f in main(): B
345 Read address 0x7fd30106d80f in main(): B
346 Read address 0x7fd30106dc0f in main(): B
348 fault_handler_thread():
349     poll() returns: nready = 1; POLLIN = 1; POLLERR = 0
350     UFFD_EVENT_PAGEFAULT event: flags = 0; address = 7fd30106e00f
351         (uffdio_copy.copy returned 4096)
352 Read address 0x7fd30106e00f in main(): C
353 Read address 0x7fd30106e40f in main(): C
354 Read address 0x7fd30106e80f in main(): C
355 Read address 0x7fd30106ec0f in main(): C
358 .SS Program source
361 /* userfaultfd_demo.c
363    Licensed under the GNU General Public License version 2 or later.
365 #define _GNU_SOURCE
366 #include <sys/types.h>
367 #include <stdio.h>
368 #include <linux/userfaultfd.h>
369 #include <pthread.h>
370 #include <errno.h>
371 #include <unistd.h>
372 #include <stdlib.h>
373 #include <fcntl.h>
374 #include <signal.h>
375 #include <poll.h>
376 #include <string.h>
377 #include <sys/mman.h>
378 #include <sys/syscall.h>
379 #include <sys/ioctl.h>
380 #include <poll.h>
382 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \\
383                         } while (0)
385 static int page_size;
387 static void *
388 fault_handler_thread(void *arg)
390     static struct uffd_msg msg;   /* Data read from userfaultfd */
391     static int fault_cnt = 0;     /* Number of faults so far handled */
392     long uffd;                    /* userfaultfd file descriptor */
393     static char *page = NULL;
394     struct uffdio_copy uffdio_copy;
395     ssize_t nread;
397     uffd = (long) arg;
399     /* Create a page that will be copied into the faulting region */
401     if (page == NULL) {
402         page = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
403                     MAP_PRIVATE | MAP_ANONYMOUS, \-1, 0);
404         if (page == MAP_FAILED)
405             errExit("mmap");
406     }
408     /* Loop, handling incoming events on the userfaultfd
409        file descriptor */
411     for (;;) {
413         /* See what poll() tells us about the userfaultfd */
415         struct pollfd pollfd;
416         int nready;
417         pollfd.fd = uffd;
418         pollfd.events = POLLIN;
419         nready = poll(&pollfd, 1, \-1);
420         if (nready == \-1)
421             errExit("poll");
423         printf("\\nfault_handler_thread():\\n");
424         printf("    poll() returns: nready = %d; "
425                 "POLLIN = %d; POLLERR = %d\\n", nready,
426                 (pollfd.revents & POLLIN) != 0,
427                 (pollfd.revents & POLLERR) != 0);
429         /* Read an event from the userfaultfd */
431         nread = read(uffd, &msg, sizeof(msg));
432         if (nread == 0) {
433             printf("EOF on userfaultfd!\\n");
434             exit(EXIT_FAILURE);
435         }
437         if (nread == \-1)
438             errExit("read");
440         /* We expect only one kind of event; verify that assumption */
442         if (msg.event != UFFD_EVENT_PAGEFAULT) {
443             fprintf(stderr, "Unexpected event on userfaultfd\\n");
444             exit(EXIT_FAILURE);
445         }
447         /* Display info about the page\-fault event */
449         printf("    UFFD_EVENT_PAGEFAULT event: ");
450         printf("flags = %llx; ", msg.arg.pagefault.flags);
451         printf("address = %llx\\n", msg.arg.pagefault.address);
453         /* Copy the page pointed to by \(aqpage\(aq into the faulting
454            region. Vary the contents that are copied in, so that it
455            is more obvious that each fault is handled separately. */
457         memset(page, \(aqA\(aq + fault_cnt % 20, page_size);
458         fault_cnt++;
460         uffdio_copy.src = (unsigned long) page;
462         /* We need to handle page faults in units of pages(!).
463            So, round faulting address down to page boundary */
465         uffdio_copy.dst = (unsigned long) msg.arg.pagefault.address &
466                                            ~(page_size \- 1);
467         uffdio_copy.len = page_size;
468         uffdio_copy.mode = 0;
469         uffdio_copy.copy = 0;
470         if (ioctl(uffd, UFFDIO_COPY, &uffdio_copy) == \-1)
471             errExit("ioctl\-UFFDIO_COPY");
473         printf("        (uffdio_copy.copy returned %lld)\\n",
474                 uffdio_copy.copy);
475     }
479 main(int argc, char *argv[])
481     long uffd;          /* userfaultfd file descriptor */
482     char *addr;         /* Start of region handled by userfaultfd */
483     unsigned long len;  /* Length of region handled by userfaultfd */
484     pthread_t thr;      /* ID of thread that handles page faults */
485     struct uffdio_api uffdio_api;
486     struct uffdio_register uffdio_register;
487     int s;
489     if (argc != 2) {
490         fprintf(stderr, "Usage: %s num\-pages\\n", argv[0]);
491         exit(EXIT_FAILURE);
492     }
494     page_size = sysconf(_SC_PAGE_SIZE);
495     len = strtoul(argv[1], NULL, 0) * page_size;
497     /* Create and enable userfaultfd object */
499     uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
500     if (uffd == \-1)
501         errExit("userfaultfd");
503     uffdio_api.api = UFFD_API;
504     uffdio_api.features = 0;
505     if (ioctl(uffd, UFFDIO_API, &uffdio_api) == \-1)
506         errExit("ioctl\-UFFDIO_API");
508     /* Create a private anonymous mapping. The memory will be
509        demand\-zero paged\-\-that is, not yet allocated. When we
510        actually touch the memory, it will be allocated via
511        the userfaultfd. */
513     addr = mmap(NULL, len, PROT_READ | PROT_WRITE,
514                 MAP_PRIVATE | MAP_ANONYMOUS, \-1, 0);
515     if (addr == MAP_FAILED)
516         errExit("mmap");
518     printf("Address returned by mmap() = %p\\n", addr);
520     /* Register the memory range of the mapping we just created for
521        handling by the userfaultfd object. In mode, we request to track
522        missing pages (i.e., pages that have not yet been faulted in). */
524     uffdio_register.range.start = (unsigned long) addr;
525     uffdio_register.range.len = len;
526     uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
527     if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register) == \-1)
528         errExit("ioctl\-UFFDIO_REGISTER");
530     /* Create a thread that will process the userfaultfd events */
532     s = pthread_create(&thr, NULL, fault_handler_thread, (void *) uffd);
533     if (s != 0) {
534         errno = s;
535         errExit("pthread_create");
536     }
538     /* Main thread now touches memory in the mapping, touching
539        locations 1024 bytes apart. This will trigger userfaultfd
540        events for all pages in the region. */
542     int l;
543     l = 0xf;    /* Ensure that faulting address is not on a page
544                    boundary, in order to test that we correctly
545                    handle that case in fault_handling_thread() */
546     while (l < len) {
547         char c = addr[l];
548         printf("Read address %p in main(): ", addr + l);
549         printf("%c\\n", c);
550         l += 1024;
551         usleep(100000);         /* Slow things down a little */
552     }
554     exit(EXIT_SUCCESS);
557 .SH SEE ALSO
558 .BR fcntl (2),
559 .BR ioctl (2),
560 .BR ioctl_userfaultfd (2),
561 .BR madvise (2),
562 .BR mmap (2)
564 .IR Documentation/vm/userfaultfd.txt
565 in the Linux kernel source tree