1MMAP(2) Linux Programmer's Manual MMAP(2)
2
3
4
6 mmap, munmap - map or unmap files or devices into memory
7
9 #include <sys/mman.h>
10
11 void *mmap(void *addr, size_t length, int prot, int flags,
12 int fd, off_t offset);
13 int munmap(void *addr, size_t length);
14
15 See NOTES for information on feature test macro requirements.
16
18 mmap() creates a new mapping in the virtual address space of the call‐
19 ing process. The starting address for the new mapping is specified in
20 addr. The length argument specifies the length of the mapping (which
21 must be greater than 0).
22
23 If addr is NULL, then the kernel chooses the (page-aligned) address at
24 which to create the mapping; this is the most portable method of creat‐
25 ing a new mapping. If addr is not NULL, then the kernel takes it as a
26 hint about where to place the mapping; on Linux, the kernel will pick a
27 nearby page boundary (but always above or equal to the value specified
28 by /proc/sys/vm/mmap_min_addr) and attempt to create the mapping there.
29 If another mapping already exists there, the kernel picks a new address
30 that may or may not depend on the hint. The address of the new mapping
31 is returned as the result of the call.
32
33 The contents of a file mapping (as opposed to an anonymous mapping; see
34 MAP_ANONYMOUS below), are initialized using length bytes starting at
35 offset offset in the file (or other object) referred to by the file
36 descriptor fd. offset must be a multiple of the page size as returned
37 by sysconf(_SC_PAGE_SIZE).
38
39 After the mmap() call has returned, the file descriptor, fd, can be
40 closed immediately without invalidating the mapping.
41
42 The prot argument describes the desired memory protection of the map‐
43 ping (and must not conflict with the open mode of the file). It is
44 either PROT_NONE or the bitwise OR of one or more of the following
45 flags:
46
47 PROT_EXEC Pages may be executed.
48
49 PROT_READ Pages may be read.
50
51 PROT_WRITE Pages may be written.
52
53 PROT_NONE Pages may not be accessed.
54
55 The flags argument
56 The flags argument determines whether updates to the mapping are visi‐
57 ble to other processes mapping the same region, and whether updates are
58 carried through to the underlying file. This behavior is determined by
59 including exactly one of the following values in flags:
60
61 MAP_SHARED
62 Share this mapping. Updates to the mapping are visible to other
63 processes mapping the same region, and (in the case of file-
64 backed mappings) are carried through to the underlying file.
65 (To precisely control when updates are carried through to the
66 underlying file requires the use of msync(2).)
67
68 MAP_SHARED_VALIDATE (since Linux 4.15)
69 This flag provides the same behavior as MAP_SHARED except that
70 MAP_SHARED mappings ignore unknown flags in flags. By contrast,
71 when creating a mapping using MAP_SHARED_VALIDATE, the kernel
72 verifies all passed flags are known and fails the mapping with
73 the error EOPNOTSUPP for unknown flags. This mapping type is
74 also required to be able to use some mapping flags (e.g.,
75 MAP_SYNC).
76
77 MAP_PRIVATE
78 Create a private copy-on-write mapping. Updates to the mapping
79 are not visible to other processes mapping the same file, and
80 are not carried through to the underlying file. It is unspeci‐
81 fied whether changes made to the file after the mmap() call are
82 visible in the mapped region.
83
84 Both MAP_SHARED and MAP_PRIVATE are described in POSIX.1-2001 and
85 POSIX.1-2008. MAP_SHARED_VALIDATE is a Linux extension.
86
87 In addition, zero or more of the following values can be ORed in flags:
88
89 MAP_32BIT (since Linux 2.4.20, 2.6)
90 Put the mapping into the first 2 Gigabytes of the process
91 address space. This flag is supported only on x86-64, for
92 64-bit programs. It was added to allow thread stacks to be
93 allocated somewhere in the first 2 GB of memory, so as to
94 improve context-switch performance on some early 64-bit proces‐
95 sors. Modern x86-64 processors no longer have this performance
96 problem, so use of this flag is not required on those systems.
97 The MAP_32BIT flag is ignored when MAP_FIXED is set.
98
99 MAP_ANON
100 Synonym for MAP_ANONYMOUS; provided for compatibility with other
101 implementations.
102
103 MAP_ANONYMOUS
104 The mapping is not backed by any file; its contents are initial‐
105 ized to zero. The fd argument is ignored; however, some imple‐
106 mentations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is
107 specified, and portable applications should ensure this. The
108 offset argument should be zero. The use of MAP_ANONYMOUS in
109 conjunction with MAP_SHARED is supported on Linux only since
110 kernel 2.4.
111
112 MAP_DENYWRITE
113 This flag is ignored. (Long ago—Linux 2.0 and earlier—it sig‐
114 naled that attempts to write to the underlying file should fail
115 with ETXTBUSY. But this was a source of denial-of-service
116 attacks.)
117
118 MAP_EXECUTABLE
119 This flag is ignored.
120
121 MAP_FILE
122 Compatibility flag. Ignored.
123
124 MAP_FIXED
125 Don't interpret addr as a hint: place the mapping at exactly
126 that address. addr must be suitably aligned: for most architec‐
127 tures a multiple of the page size is sufficient; however, some
128 architectures may impose additional restrictions. If the memory
129 region specified by addr and len overlaps pages of any existing
130 mapping(s), then the overlapped part of the existing mapping(s)
131 will be discarded. If the specified address cannot be used,
132 mmap() will fail.
133
134 Software that aspires to be portable should use the MAP_FIXED
135 flag with care, keeping in mind that the exact layout of a
136 process's memory mappings is allowed to change significantly
137 between kernel versions, C library versions, and operating sys‐
138 tem releases. Carefully read the discussion of this flag in
139 NOTES!
140
141 MAP_FIXED_NOREPLACE (since Linux 4.17)
142 This flag provides behavior that is similar to MAP_FIXED with
143 respect to the addr enforcement, but differs in that
144 MAP_FIXED_NOREPLACE never clobbers a preexisting mapped range.
145 If the requested range would collide with an existing mapping,
146 then this call fails with the error EEXIST. This flag can
147 therefore be used as a way to atomically (with respect to other
148 threads) attempt to map an address range: one thread will suc‐
149 ceed; all others will report failure.
150
151 Note that older kernels which do not recognize the
152 MAP_FIXED_NOREPLACE flag will typically (upon detecting a colli‐
153 sion with a preexisting mapping) fall back to a "non-MAP_FIXED"
154 type of behavior: they will return an address that is different
155 from the requested address. Therefore, backward-compatible
156 software should check the returned address against the requested
157 address.
158
159 MAP_GROWSDOWN
160 This flag is used for stacks. It indicates to the kernel vir‐
161 tual memory system that the mapping should extend downward in
162 memory. The return address is one page lower than the memory
163 area that is actually created in the process's virtual address
164 space. Touching an address in the "guard" page below the map‐
165 ping will cause the mapping to grow by a page. This growth can
166 be repeated until the mapping grows to within a page of the high
167 end of the next lower mapping, at which point touching the
168 "guard" page will result in a SIGSEGV signal.
169
170 MAP_HUGETLB (since Linux 2.6.32)
171 Allocate the mapping using "huge pages." See the Linux kernel
172 source file Documentation/admin-guide/mm/hugetlbpage.rst for
173 further information, as well as NOTES, below.
174
175 MAP_HUGE_2MB, MAP_HUGE_1GB (since Linux 3.8)
176 Used in conjunction with MAP_HUGETLB to select alternative
177 hugetlb page sizes (respectively, 2 MB and 1 GB) on systems that
178 support multiple hugetlb page sizes.
179
180 More generally, the desired huge page size can be configured by
181 encoding the base-2 logarithm of the desired page size in the
182 six bits at the offset MAP_HUGE_SHIFT. (A value of zero in this
183 bit field provides the default huge page size; the default huge
184 page size can be discovered via the Hugepagesize field exposed
185 by /proc/meminfo.) Thus, the above two constants are defined
186 as:
187
188 #define MAP_HUGE_2MB (21 << MAP_HUGE_SHIFT)
189 #define MAP_HUGE_1GB (30 << MAP_HUGE_SHIFT)
190
191 The range of huge page sizes that are supported by the system
192 can be discovered by listing the subdirectories in /sys/ker‐
193 nel/mm/hugepages.
194
195 MAP_LOCKED (since Linux 2.5.37)
196 Mark the mapped region to be locked in the same way as mlock(2).
197 This implementation will try to populate (prefault) the whole
198 range but the mmap() call doesn't fail with ENOMEM if this
199 fails. Therefore major faults might happen later on. So the
200 semantic is not as strong as mlock(2). One should use mmap()
201 plus mlock(2) when major faults are not acceptable after the
202 initialization of the mapping. The MAP_LOCKED flag is ignored
203 in older kernels.
204
205 MAP_NONBLOCK (since Linux 2.5.46)
206 This flag is meaningful only in conjunction with MAP_POPULATE.
207 Don't perform read-ahead: create page tables entries only for
208 pages that are already present in RAM. Since Linux 2.6.23, this
209 flag causes MAP_POPULATE to do nothing. One day, the combina‐
210 tion of MAP_POPULATE and MAP_NONBLOCK may be reimplemented.
211
212 MAP_NORESERVE
213 Do not reserve swap space for this mapping. When swap space is
214 reserved, one has the guarantee that it is possible to modify
215 the mapping. When swap space is not reserved one might get
216 SIGSEGV upon a write if no physical memory is available. See
217 also the discussion of the file /proc/sys/vm/overcommit_memory
218 in proc(5). In kernels before 2.6, this flag had effect only
219 for private writable mappings.
220
221 MAP_POPULATE (since Linux 2.5.46)
222 Populate (prefault) page tables for a mapping. For a file map‐
223 ping, this causes read-ahead on the file. This will help to
224 reduce blocking on page faults later. MAP_POPULATE is supported
225 for private mappings only since Linux 2.6.23.
226
227 MAP_STACK (since Linux 2.6.27)
228 Allocate the mapping at an address suitable for a process or
229 thread stack.
230
231 This flag is currently a no-op on Linux. However, by employing
232 this flag, applications can ensure that they transparently
233 obtain support if the flag is implemented in the future. Thus,
234 it is used in the glibc threading implementation to allow for
235 the fact that some architectures may (later) require special
236 treatment for stack allocations. A further reason to employ
237 this flag is portability: MAP_STACK exists (and has an effect)
238 on some other systems (e.g., some of the BSDs).
239
240 MAP_SYNC (since Linux 4.15)
241 This flag is available only with the MAP_SHARED_VALIDATE mapping
242 type; mappings of type MAP_SHARED will silently ignore this
243 flag. This flag is supported only for files supporting DAX
244 (direct mapping of persistent memory). For other files, creat‐
245 ing a mapping with this flag results in an EOPNOTSUPP error.
246
247 Shared file mappings with this flag provide the guarantee that
248 while some memory is writably mapped in the address space of the
249 process, it will be visible in the same file at the same offset
250 even after the system crashes or is rebooted. In conjunction
251 with the use of appropriate CPU instructions, this provides
252 users of such mappings with a more efficient way of making data
253 modifications persistent.
254
255 MAP_UNINITIALIZED (since Linux 2.6.33)
256 Don't clear anonymous pages. This flag is intended to improve
257 performance on embedded devices. This flag is honored only if
258 the kernel was configured with the CONFIG_MMAP_ALLOW_UNINITIAL‐
259 IZED option. Because of the security implications, that option
260 is normally enabled only on embedded devices (i.e., devices
261 where one has complete control of the contents of user memory).
262
263 Of the above flags, only MAP_FIXED is specified in POSIX.1-2001 and
264 POSIX.1-2008. However, most systems also support MAP_ANONYMOUS (or its
265 synonym MAP_ANON).
266
267 munmap()
268 The munmap() system call deletes the mappings for the specified address
269 range, and causes further references to addresses within the range to
270 generate invalid memory references. The region is also automatically
271 unmapped when the process is terminated. On the other hand, closing
272 the file descriptor does not unmap the region.
273
274 The address addr must be a multiple of the page size (but length need
275 not be). All pages containing a part of the indicated range are
276 unmapped, and subsequent references to these pages will generate
277 SIGSEGV. It is not an error if the indicated range does not contain
278 any mapped pages.
279
281 On success, mmap() returns a pointer to the mapped area. On error, the
282 value MAP_FAILED (that is, (void *) -1) is returned, and errno is set
283 to indicate the cause of the error.
284
285 On success, munmap() returns 0. On failure, it returns -1, and errno
286 is set to indicate the cause of the error (probably to EINVAL).
287
289 EACCES A file descriptor refers to a non-regular file. Or a file map‐
290 ping was requested, but fd is not open for reading. Or
291 MAP_SHARED was requested and PROT_WRITE is set, but fd is not
292 open in read/write (O_RDWR) mode. Or PROT_WRITE is set, but the
293 file is append-only.
294
295 EAGAIN The file has been locked, or too much memory has been locked
296 (see setrlimit(2)).
297
298 EBADF fd is not a valid file descriptor (and MAP_ANONYMOUS was not
299 set).
300
301 EEXIST MAP_FIXED_NOREPLACE was specified in flags, and the range cov‐
302 ered by addr and length clashes with an existing mapping.
303
304 EINVAL We don't like addr, length, or offset (e.g., they are too large,
305 or not aligned on a page boundary).
306
307 EINVAL (since Linux 2.6.12) length was 0.
308
309 EINVAL flags contained none of MAP_PRIVATE, MAP_SHARED or
310 MAP_SHARED_VALIDATE.
311
312 ENFILE The system-wide limit on the total number of open files has been
313 reached.
314
315 ENODEV The underlying filesystem of the specified file does not support
316 memory mapping.
317
318 ENOMEM No memory is available.
319
320 ENOMEM The process's maximum number of mappings would have been
321 exceeded. This error can also occur for munmap(), when unmap‐
322 ping a region in the middle of an existing mapping, since this
323 results in two smaller mappings on either side of the region
324 being unmapped.
325
326 ENOMEM (since Linux 4.7) The process's RLIMIT_DATA limit, described in
327 getrlimit(2), would have been exceeded.
328
329 EOVERFLOW
330 On 32-bit architecture together with the large file extension
331 (i.e., using 64-bit off_t): the number of pages used for length
332 plus number of pages used for offset would overflow unsigned
333 long (32 bits).
334
335 EPERM The prot argument asks for PROT_EXEC but the mapped area belongs
336 to a file on a filesystem that was mounted no-exec.
337
338 EPERM The operation was prevented by a file seal; see fcntl(2).
339
340 ETXTBSY
341 MAP_DENYWRITE was set but the object specified by fd is open for
342 writing.
343
344 Use of a mapped region can result in these signals:
345
346 SIGSEGV
347 Attempted write into a region mapped as read-only.
348
349 SIGBUS Attempted access to a portion of the buffer that does not corre‐
350 spond to the file (for example, beyond the end of the file,
351 including the case where another process has truncated the
352 file).
353
355 For an explanation of the terms used in this section, see
356 attributes(7).
357
358 ┌───────────────────┬───────────────┬─────────┐
359 │Interface │ Attribute │ Value │
360 ├───────────────────┼───────────────┼─────────┤
361 │mmap(), munmap() │ Thread safety │ MT-Safe │
362 └───────────────────┴───────────────┴─────────┘
364 POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.
365
366 On POSIX systems on which mmap(), msync(2), and munmap() are available,
367 _POSIX_MAPPED_FILES is defined in <unistd.h> to a value greater than 0.
368 (See also sysconf(3).)
369
371 Memory mapped by mmap() is preserved across fork(2), with the same
372 attributes.
373
374 A file is mapped in multiples of the page size. For a file that is not
375 a multiple of the page size, the remaining memory is zeroed when
376 mapped, and writes to that region are not written out to the file. The
377 effect of changing the size of the underlying file of a mapping on the
378 pages that correspond to added or removed regions of the file is
379 unspecified.
380
381 On some hardware architectures (e.g., i386), PROT_WRITE implies
382 PROT_READ. It is architecture dependent whether PROT_READ implies
383 PROT_EXEC or not. Portable programs should always set PROT_EXEC if
384 they intend to execute code in the new mapping.
385
386 The portable way to create a mapping is to specify addr as 0 (NULL),
387 and omit MAP_FIXED from flags. In this case, the system chooses the
388 address for the mapping; the address is chosen so as not to conflict
389 with any existing mapping, and will not be 0. If the MAP_FIXED flag is
390 specified, and addr is 0 (NULL), then the mapped address will be 0
391 (NULL).
392
393 Certain flags constants are defined only if suitable feature test
394 macros are defined (possibly by default): _DEFAULT_SOURCE with glibc
395 2.19 or later; or _BSD_SOURCE or _SVID_SOURCE in glibc 2.19 and ear‐
396 lier. (Employing _GNU_SOURCE also suffices, and requiring that macro
397 specifically would have been more logical, since these flags are all
398 Linux-specific.) The relevant flags are: MAP_32BIT, MAP_ANONYMOUS (and
399 the synonym MAP_ANON), MAP_DENYWRITE, MAP_EXECUTABLE, MAP_FILE,
400 MAP_GROWSDOWN, MAP_HUGETLB, MAP_LOCKED, MAP_NONBLOCK, MAP_NORESERVE,
401 MAP_POPULATE, and MAP_STACK.
402
403 An application can determine which pages of a mapping are currently
404 resident in the buffer/page cache using mincore(2).
405
406 Using MAP_FIXED safely
407 The only safe use for MAP_FIXED is where the address range specified by
408 addr and length was previously reserved using another mapping; other‐
409 wise, the use of MAP_FIXED is hazardous because it forcibly removes
410 preexisting mappings, making it easy for a multithreaded process to
411 corrupt its own address space.
412
413 For example, suppose that thread A looks through /proc/<pid>/maps and
414 in order to locate an unused address range that it can map using
415 MAP_FIXED, while thread B simultaneously acquires part or all of that
416 same address range. When thread A subsequently employs
417 mmap(MAP_FIXED), it will effectively clobber the mapping that thread B
418 created. In this scenario, thread B need not create a mapping
419 directly; simply making a library call that, internally, uses dlopen(3)
420 to load some other shared library, will suffice. The dlopen(3) call
421 will map the library into the process's address space. Furthermore,
422 almost any library call may be implemented in a way that adds memory
423 mappings to the address space, either with this technique, or by simply
424 allocating memory. Examples include brk(2), malloc(3), pthread_cre‐
425 ate(3), and the PAM libraries ⟨http://www.linux-pam.org⟩.
426
427 Since Linux 4.17, a multithreaded program can use the MAP_FIXED_NORE‐
428 PLACE flag to avoid the hazard described above when attempting to cre‐
429 ate a mapping at a fixed address that has not been reserved by a preex‐
430 isting mapping.
431
432 Timestamps changes for file-backed mappings
433 For file-backed mappings, the st_atime field for the mapped file may be
434 updated at any time between the mmap() and the corresponding unmapping;
435 the first reference to a mapped page will update the field if it has
436 not been already.
437
438 The st_ctime and st_mtime field for a file mapped with PROT_WRITE and
439 MAP_SHARED will be updated after a write to the mapped region, and
440 before a subsequent msync(2) with the MS_SYNC or MS_ASYNC flag, if one
441 occurs.
442
443 Huge page (Huge TLB) mappings
444 For mappings that employ huge pages, the requirements for the arguments
445 of mmap() and munmap() differ somewhat from the requirements for map‐
446 pings that use the native system page size.
447
448 For mmap(), offset must be a multiple of the underlying huge page size.
449 The system automatically aligns length to be a multiple of the underly‐
450 ing huge page size.
451
452 For munmap(), addr and length must both be a multiple of the underlying
453 huge page size.
454
455 C library/kernel differences
456 This page describes the interface provided by the glibc mmap() wrapper
457 function. Originally, this function invoked a system call of the same
458 name. Since kernel 2.4, that system call has been superseded by
459 mmap2(2), and nowadays the glibc mmap() wrapper function invokes
460 mmap2(2) with a suitably adjusted value for offset.
461
463 On Linux, there are no guarantees like those suggested above under
464 MAP_NORESERVE. By default, any process can be killed at any moment
465 when the system runs out of memory.
466
467 In kernels before 2.6.7, the MAP_POPULATE flag has effect only if prot
468 is specified as PROT_NONE.
469
470 SUSv3 specifies that mmap() should fail if length is 0. However, in
471 kernels before 2.6.12, mmap() succeeded in this case: no mapping was
472 created and the call returned addr. Since kernel 2.6.12, mmap() fails
473 with the error EINVAL for this case.
474
475 POSIX specifies that the system shall always zero fill any partial page
476 at the end of the object and that system will never write any modifica‐
477 tion of the object beyond its end. On Linux, when you write data to
478 such partial page after the end of the object, the data stays in the
479 page cache even after the file is closed and unmapped and even though
480 the data is never written to the file itself, subsequent mappings may
481 see the modified content. In some cases, this could be fixed by call‐
482 ing msync(2) before the unmap takes place; however, this doesn't work
483 on tmpfs(5) (for example, when using the POSIX shared memory interface
484 documented in shm_overview(7)).
485
487 The following program prints part of the file specified in its first
488 command-line argument to standard output. The range of bytes to be
489 printed is specified via offset and length values in the second and
490 third command-line arguments. The program creates a memory mapping of
491 the required pages of the file and then uses write(2) to output the
492 desired bytes.
493
494 Program source
495 #include <sys/mman.h>
496 #include <sys/stat.h>
497 #include <fcntl.h>
498 #include <stdio.h>
499 #include <stdlib.h>
500 #include <unistd.h>
501
502 #define handle_error(msg) \
503 do { perror(msg); exit(EXIT_FAILURE); } while (0)
504
505 int
506 main(int argc, char *argv[])
507 {
508 char *addr;
509 int fd;
510 struct stat sb;
511 off_t offset, pa_offset;
512 size_t length;
513 ssize_t s;
514
515 if (argc < 3 || argc > 4) {
516 fprintf(stderr, "%s file offset [length]\n", argv[0]);
517 exit(EXIT_FAILURE);
518 }
519
520 fd = open(argv[1], O_RDONLY);
521 if (fd == -1)
522 handle_error("open");
523
524 if (fstat(fd, &sb) == -1) /* To obtain file size */
525 handle_error("fstat");
526
527 offset = atoi(argv[2]);
528 pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
529 /* offset for mmap() must be page aligned */
530
531 if (offset >= sb.st_size) {
532 fprintf(stderr, "offset is past end of file\n");
533 exit(EXIT_FAILURE);
534 }
535
536 if (argc == 4) {
537 length = atoi(argv[3]);
538 if (offset + length > sb.st_size)
539 length = sb.st_size - offset;
540 /* Can't display bytes past end of file */
541
542 } else { /* No length arg ==> display to end of file */
543 length = sb.st_size - offset;
544 }
545
546 addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
547 MAP_PRIVATE, fd, pa_offset);
548 if (addr == MAP_FAILED)
549 handle_error("mmap");
550
551 s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
552 if (s != length) {
553 if (s == -1)
554 handle_error("write");
555
556 fprintf(stderr, "partial write");
557 exit(EXIT_FAILURE);
558 }
559
560 munmap(addr, length + offset - pa_offset);
561 close(fd);
562
563 exit(EXIT_SUCCESS);
564 }
565
567 ftruncate(2), getpagesize(2), memfd_create(2), mincore(2), mlock(2),
568 mmap2(2), mprotect(2), mremap(2), msync(2), remap_file_pages(2), setr‐
569 limit(2), shmat(2), userfaultfd(2), shm_open(3), shm_overview(7)
570
571 The descriptions of the following files in proc(5): /proc/[pid]/maps,
572 /proc/[pid]/map_files, and /proc/[pid]/smaps.
573
574 B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128–129 and 389–391.
575
577 This page is part of release 5.07 of the Linux man-pages project. A
578 description of the project, information about reporting bugs, and the
579 latest version of this page, can be found at
580 https://www.kernel.org/doc/man-pages/.
581
582
583
584Linux 2020-04-11 MMAP(2)