1 .\" Copyright (C) 1996 Andries Brouwer <aeb@cwi.nl>
2 .\" and Copyright (C) 2006, 2007 Michael Kerrisk <mtk.manpages@gmail.com>
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein. The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
26 .\" Modified 1997-01-31 by Eric S. Raymond <esr@thyrsus.com>
27 .\" Modified 2000-03-25 by Jim Van Zandt <jrv@vanzandt.mv.com>
28 .\" Modified 2001-10-04 by John Levon <moz@compsoc.man.ac.uk>
29 .\" Modified 2003-02-02 by Andi Kleen <ak@muc.de>
30 .\" Modified 2003-05-21 by Michael Kerrisk <mtk.manpages@gmail.com>
31 .\" MAP_LOCKED works from 2.5.37
32 .\" Modified 2004-06-17 by Michael Kerrisk <mtk.manpages@gmail.com>
33 .\" Modified 2004-09-11 by aeb
34 .\" Modified 2004-12-08, from Eric Estievenart <eric.estievenart@free.fr>
35 .\" Modified 2004-12-08, mtk, formatting tidy-ups
36 .\" Modified 2006-12-04, mtk, various parts rewritten
37 .\" 2007-07-10, mtk, Added an example program.
38 .\" 2008-11-18, mtk, document MAP_STACK
40 .TH MMAP 2 2021-03-22 "Linux" "Linux Programmer's Manual"
42 mmap, munmap \- map or unmap files or devices into memory
45 .B #include <sys/mman.h>
47 .BI "void *mmap(void *" addr ", size_t " length \
48 ", int " prot ", int " flags ,
49 .BI " int " fd ", off_t " offset );
50 .BI "int munmap(void *" addr ", size_t " length );
53 See NOTES for information on feature test macro requirements.
56 creates a new mapping in the virtual address space of
58 The starting address for the new mapping is specified in
62 argument specifies the length of the mapping (which must be greater than 0).
67 then the kernel chooses the (page-aligned) address
68 at which to create the mapping;
69 this is the most portable method of creating a new mapping.
73 then the kernel takes it as a hint about where to place the mapping;
74 on Linux, the kernel will pick a nearby page boundary (but always above
75 or equal to the value specified by
76 .IR /proc/sys/vm/mmap_min_addr )
77 and attempt to create the mapping there.
78 If another mapping already exists there, the kernel picks a new address that
79 may or may not depend on the hint.
80 .\" Before Linux 2.6.24, the address was rounded up to the next page
81 .\" boundary; since 2.6.24, it is rounded down!
82 The address of the new mapping is returned as the result of the call.
84 The contents of a file mapping (as opposed to an anonymous mapping; see
86 below), are initialized using
88 bytes starting at offset
90 in the file (or other object) referred to by the file descriptor
93 must be a multiple of the page size as returned by
94 .IR sysconf(_SC_PAGE_SIZE) .
98 call has returned, the file descriptor,
100 can be closed immediately without invalidating the mapping.
104 argument describes the desired memory protection of the mapping
105 (and must not conflict with the open mode of the file).
108 or the bitwise OR of one or more of the following flags:
111 Pages may be executed.
117 Pages may be written.
120 Pages may not be accessed.
122 .SS The flags argument
125 argument determines whether updates to the mapping
126 are visible to other processes mapping the same region,
127 and whether updates are carried through to the underlying file.
128 This behavior is determined by including exactly one
129 of the following values in
134 Updates to the mapping are visible to other processes mapping the same region,
135 and (in the case of file-backed mappings)
136 are carried through to the underlying file.
137 (To precisely control when updates are carried through
138 to the underlying file requires the use of
141 .BR MAP_SHARED_VALIDATE " (since Linux 4.15)"
142 This flag provides the same behavior as
146 mappings ignore unknown flags in
148 By contrast, when creating a mapping using
149 .BR MAP_SHARED_VALIDATE ,
150 the kernel verifies all passed flags are known and fails the
151 mapping with the error
154 This mapping type is also required to be able to use some mapping flags
159 Create a private copy-on-write mapping.
160 Updates to the mapping are not visible to other processes
161 mapping the same file, and are not carried through to
163 It is unspecified whether changes made to the file after the
165 call are visible in the mapped region.
171 are described in POSIX.1-2001 and POSIX.1-2008.
172 .B MAP_SHARED_VALIDATE
173 is a Linux extension.
175 In addition, zero or more of the following values can be ORed in
178 .BR MAP_32BIT " (since Linux 2.4.20, 2.6)"
179 Put the mapping into the first 2 Gigabytes of the process address space.
180 This flag is supported only on x86-64, for 64-bit programs.
181 It was added to allow thread stacks to be allocated somewhere
182 in the first 2\ GB of memory,
183 so as to improve context-switch performance on some early
185 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
186 Modern x86-64 processors no longer have this performance problem,
187 so use of this flag is not required on those systems.
197 provided for compatibility with other implementations.
200 The mapping is not backed by any file;
201 its contents are initialized to zero.
205 however, some implementations require
212 and portable applications should ensure this.
215 argument should be zero.
216 .\" See the pgoff overflow check in do_mmap().
217 .\" See the offset check in sys_mmap in arch/x86/kernel/sys_x86_64.c.
222 is supported on Linux only since kernel 2.4.
225 This flag is ignored.
226 .\" Introduced in 1.1.36, removed in 1.3.24.
227 (Long ago\(emLinux 2.0 and earlier\(emit signaled
228 that attempts to write to the underlying file should fail with
230 But this was a source of denial-of-service attacks.)
233 This flag is ignored.
234 .\" Introduced in 1.1.38, removed in 1.3.24. Flag tested in proc_follow_link.
235 .\" (Long ago, it signaled that the underlying file is an executable.
236 .\" However, that information was not really used anywhere.)
237 .\" Linus talked about DOS related to MAP_EXECUTABLE, but he was thinking of
243 .\" On some systems, this was required as the opposite of
244 .\" MAP_ANONYMOUS -- mtk, 1 May 2007
249 as a hint: place the mapping at exactly that address.
251 must be suitably aligned: for most architectures a multiple of the page
252 size is sufficient; however, some architectures may impose additional
254 If the memory region specified by
258 overlaps pages of any existing mapping(s), then the overlapped
259 part of the existing mapping(s) will be discarded.
260 If the specified address cannot be used,
264 Software that aspires to be portable should use the
267 keeping in mind that the exact layout of a process's memory mappings
268 is allowed to change significantly between kernel versions,
269 C library versions, and operating system releases.
270 .IR "Carefully read the discussion of this flag in NOTES!"
272 .BR MAP_FIXED_NOREPLACE " (since Linux 4.17)"
273 .\" commit a4ff8e8620d3f4f50ac4b41e8067b7d395056843
274 This flag provides behavior that is similar to
278 enforcement, but differs in that
279 .B MAP_FIXED_NOREPLACE
280 never clobbers a preexisting mapped range.
281 If the requested range would collide with an existing mapping,
282 then this call fails with the error
284 This flag can therefore be used as a way to atomically
285 (with respect to other threads) attempt to map an address range:
286 one thread will succeed; all others will report failure.
288 Note that older kernels which do not recognize the
289 .BR MAP_FIXED_NOREPLACE
290 flag will typically (upon detecting a collision with a preexisting mapping)
291 fall back to a "non-\c
294 they will return an address that is different from the requested address.
295 Therefore, backward-compatible software
296 should check the returned address against the requested address.
299 This flag is used for stacks.
300 It indicates to the kernel virtual memory system that the mapping
301 should extend downward in memory.
302 The return address is one page lower than the memory area that is
303 actually created in the process's virtual address space.
304 Touching an address in the "guard" page below the mapping will cause
305 the mapping to grow by a page.
306 This growth can be repeated until the mapping grows to within a
307 page of the high end of the next lower mapping,
308 at which point touching the "guard" page will result in a
312 .BR MAP_HUGETLB " (since Linux 2.6.32)"
313 Allocate the mapping using "huge" pages.
314 See the Linux kernel source file
315 .I Documentation/admin\-guide/mm/hugetlbpage.rst
316 for further information, as well as NOTES, below.
318 .BR MAP_HUGE_2MB ", " MAP_HUGE_1GB " (since Linux 3.8)"
319 .\" See https://lwn.net/Articles/533499/
320 Used in conjunction with
322 to select alternative hugetlb page sizes (respectively, 2\ MB and 1\ GB)
323 on systems that support multiple hugetlb page sizes.
325 More generally, the desired huge page size can be configured by encoding
326 the base-2 logarithm of the desired page size in the six bits at the offset
328 (A value of zero in this bit field provides the default huge page size;
329 the default huge page size can be discovered via the
333 Thus, the above two constants are defined as:
337 #define MAP_HUGE_2MB (21 << MAP_HUGE_SHIFT)
338 #define MAP_HUGE_1GB (30 << MAP_HUGE_SHIFT)
342 The range of huge page sizes that are supported by the system
343 can be discovered by listing the subdirectories in
344 .IR /sys/kernel/mm/hugepages .
346 .BR MAP_LOCKED " (since Linux 2.5.37)"
347 Mark the mapped region to be locked in the same way as
349 This implementation will try to populate (prefault) the whole range but the
351 call doesn't fail with
354 Therefore major faults might happen later on.
355 So the semantic is not as strong as
361 when major faults are not acceptable after the initialization of the mapping.
364 flag is ignored in older kernels.
365 .\" If set, the mapped pages will not be swapped out.
367 .BR MAP_NONBLOCK " (since Linux 2.5.46)"
368 This flag is meaningful only in conjunction with
370 Don't perform read-ahead:
371 create page tables entries only for pages
372 that are already present in RAM.
374 .\" commit 54cb8821de07f2ffcd28c380ce9b93d5784b40d7
378 One day, the combination of
382 may be reimplemented.
385 Do not reserve swap space for this mapping.
386 When swap space is reserved, one has the guarantee
387 that it is possible to modify the mapping.
388 When swap space is not reserved one might get
391 if no physical memory is available.
392 See also the discussion of the file
393 .I /proc/sys/vm/overcommit_memory
396 In kernels before 2.6, this flag had effect only for
397 private writable mappings.
399 .BR MAP_POPULATE " (since Linux 2.5.46)"
400 Populate (prefault) page tables for a mapping.
401 For a file mapping, this causes read-ahead on the file.
402 This will help to reduce blocking on page faults later.
405 call doesn't fail if the mapping cannot be populated (for example, due
406 to limitations on the number of mapped huge pages when using
409 is supported for private mappings only since Linux 2.6.23.
411 .BR MAP_STACK " (since Linux 2.6.27)"
412 Allocate the mapping at an address suitable for a process
415 This flag is currently a no-op on Linux.
416 However, by employing this flag, applications can ensure that
417 they transparently obtain support if the flag
418 is implemented in the future.
419 Thus, it is used in the glibc threading implementation to allow for
420 the fact that some architectures may (later) require special treatment
421 for stack allocations.
422 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
423 .\" commit cd98a04a59e2f94fa64d5bf1e26498d27427d5e7
424 .\" http://thread.gmane.org/gmane.linux.kernel/720412
425 .\" "pthread_create() slow for many threads; also time to revisit 64b
426 .\" context switch optimization?"
427 A further reason to employ this flag is portability:
429 exists (and has an effect) on some other systems (e.g., some of the BSDs).
431 .BR MAP_SYNC " (since Linux 4.15)"
432 This flag is available only with the
433 .B MAP_SHARED_VALIDATE
437 will silently ignore this flag.
438 This flag is supported only for files supporting DAX
439 (direct mapping of persistent memory).
440 For other files, creating a mapping with this flag results in an
444 Shared file mappings with this flag provide the guarantee that while
445 some memory is mapped writable in the address space of the process,
446 it will be visible in the same file at the same offset even after
447 the system crashes or is rebooted.
448 In conjunction with the use of appropriate CPU instructions,
449 this provides users of such mappings with a more efficient way
450 of making data modifications persistent.
452 .BR MAP_UNINITIALIZED " (since Linux 2.6.33)"
453 Don't clear anonymous pages.
454 This flag is intended to improve performance on embedded devices.
455 This flag is honored only if the kernel was configured with the
456 .B CONFIG_MMAP_ALLOW_UNINITIALIZED
458 Because of the security implications,
459 that option is normally enabled only on embedded devices
460 (i.e., devices where one has complete control of the contents of user memory).
462 Of the above flags, only
464 is specified in POSIX.1-2001 and POSIX.1-2008.
465 However, most systems also support
469 .\" FIXME . for later review when Issue 8 is one day released...
470 .\" POSIX may add MAP_ANON in the future
471 .\" http://austingroupbugs.net/tag_view_page.php?tag_id=8
472 .\" http://austingroupbugs.net/view.php?id=850
476 system call deletes the mappings for the specified address range, and
477 causes further references to addresses within the range to generate
478 invalid memory references.
479 The region is also automatically unmapped
480 when the process is terminated.
481 On the other hand, closing the file
482 descriptor does not unmap the region.
486 must be a multiple of the page size (but
489 All pages containing a part
490 of the indicated range are unmapped, and subsequent references
491 to these pages will generate
493 It is not an error if the
494 indicated range does not contain any mapped pages.
498 returns a pointer to the mapped area.
502 .IR "(void\ *)\ \-1" )
505 is set to indicate the error.
510 On failure, it returns \-1, and
512 is set to indicate the error (probably to
517 A file descriptor refers to a non-regular file.
518 Or a file mapping was requested, but
520 is not open for reading.
527 is not open in read/write
532 is set, but the file is append-only.
535 The file has been locked, or too much memory has been locked (see
540 is not a valid file descriptor (and
545 .BR MAP_FIXED_NOREPLACE
548 and the range covered by
552 clashes with an existing mapping.
560 (e.g., they are too large, or not aligned on a page boundary).
573 .BR MAP_SHARED_VALIDATE .
576 .\" This is for shared anonymous segments
577 .\" [2.6.7] shmem_zero_setup()-->shmem_file_setup()-->get_empty_filp()
578 The system-wide limit on the total number of open files has been reached.
581 .\" A file could not be mapped for reading.
584 The underlying filesystem of the specified file does not support
588 No memory is available.
591 The process's maximum number of mappings would have been exceeded.
592 This error can also occur for
594 when unmapping a region in the middle of an existing mapping,
595 since this results in two smaller mappings on either side of
596 the region being unmapped.
604 would have been exceeded.
607 On 32-bit architecture together with the large file extension
610 the number of pages used for
612 plus number of pages used for
623 but the mapped area belongs to a file on a filesystem that
625 .\" (Since 2.4.25 / 2.6.0.)
628 The operation was prevented by a file seal; see
633 was set but the object specified by
637 Use of a mapped region can result in these signals:
640 Attempted write into a region mapped as read-only.
643 Attempted access to a page of the buffer that lies beyond the
644 end of the mapped file.
645 For an explanation of the treatment of the bytes in the page that
646 corresponds to the end of a mapped file that is not a multiple
647 of the page size, see NOTES.
649 For an explanation of the terms used in this section, see
657 Interface Attribute Value
661 T} Thread safety MT-Safe
667 POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.
668 .\" SVr4 documents additional error codes ENXIO and ENODEV.
669 .\" SUSv2 documents additional error codes EMFILE and EOVERFLOW.
671 On POSIX systems on which
677 .B _POSIX_MAPPED_FILES
678 is defined in \fI<unistd.h>\fP to a value greater than 0.
681 .\" POSIX.1-2001: It shall be defined to -1 or 0 or 200112L.
682 .\" -1: unavailable, 0: ask using sysconf().
683 .\" glibc defines it to 1.
689 with the same attributes.
691 A file is mapped in multiples of the page size.
692 For a file that is not
693 a multiple of the page size,
694 the remaining bytes in the partial page at the end of the mapping
695 are zeroed when mapped,
696 and modifications to that region are not written out to the file.
698 changing the size of the underlying file of a mapping on the pages that
699 correspond to added or removed regions of the file is unspecified.
701 On some hardware architectures (e.g., i386),
705 It is architecture dependent whether
710 Portable programs should always set
712 if they intend to execute code in the new mapping.
714 The portable way to create a mapping is to specify
716 as 0 (NULL), and omit
720 In this case, the system chooses the address for the mapping;
721 the address is chosen so as not to conflict with any existing mapping,
725 flag is specified, and
727 is 0 (NULL), then the mapped address will be 0 (NULL).
731 constants are defined only if suitable feature test macros are defined
732 (possibly by default):
734 with glibc 2.19 or later;
739 in glibc 2.19 and earlier.
743 and requiring that macro specifically would have been more logical,
744 since these flags are all Linux-specific.)
745 The relevant flags are:
762 An application can determine which pages of a mapping are
763 currently resident in the buffer/page cache using
766 .SS Using MAP_FIXED safely
767 The only safe use for
769 is where the address range specified by
773 was previously reserved using another mapping;
774 otherwise, the use of
776 is hazardous because it forcibly removes preexisting mappings,
777 making it easy for a multithreaded process to corrupt its own address space.
779 For example, suppose that thread A looks through
781 in order to locate an unused address range that it can map using
783 while thread B simultaneously acquires part or all of that same
785 When thread A subsequently employs
786 .BR mmap(MAP_FIXED) ,
787 it will effectively clobber the mapping that thread B created.
789 thread B need not create a mapping directly; simply making a library call
790 that, internally, uses
792 to load some other shared library, will suffice.
795 call will map the library into the process's address space.
796 Furthermore, almost any library call may be implemented in a way that
797 adds memory mappings to the address space, either with this technique,
798 or by simply allocating memory.
802 .BR pthread_create (3),
803 and the PAM libraries
804 .UR http://www.linux-pam.org
807 Since Linux 4.17, a multithreaded program can use the
808 .BR MAP_FIXED_NOREPLACE
809 flag to avoid the hazard described above
810 when attempting to create a mapping at a fixed address
811 that has not been reserved by a preexisting mapping.
813 .SS Timestamps changes for file-backed mappings
814 For file-backed mappings, the
816 field for the mapped file may be updated at any time between the
818 and the corresponding unmapping; the first reference to a mapped
819 page will update the field if it has not been already.
825 field for a file mapped with
829 will be updated after
830 a write to the mapped region, and before a subsequent
838 .SS Huge page (Huge TLB) mappings
839 For mappings that employ huge pages, the requirements for the arguments of
843 differ somewhat from the requirements for mappings
844 that use the native system page size.
849 must be a multiple of the underlying huge page size.
850 The system automatically aligns
852 to be a multiple of the underlying huge page size.
859 must both be a multiple of the underlying huge page size.
861 .SS C library/kernel differences
862 This page describes the interface provided by the glibc
865 Originally, this function invoked a system call of the same name.
866 Since kernel 2.4, that system call has been superseded by
869 .\" Since around glibc 2.1/2.2, depending on the platform.
872 wrapper function invokes
874 with a suitably adjusted value for
877 On Linux, there are no guarantees like those suggested above under
879 By default, any process can be killed
880 at any moment when the system runs out of memory.
882 In kernels before 2.6.7, the
884 flag has effect only if
894 However, in kernels before 2.6.12,
896 succeeded in this case: no mapping was created and the call returned
904 POSIX specifies that the system shall always
905 zero fill any partial page at the end
906 of the object and that system will never write any modification of the
907 object beyond its end.
908 On Linux, when you write data to such partial page after the end
909 of the object, the data stays in the page cache even after the file
910 is closed and unmapped
911 and even though the data is never written to the file itself,
912 subsequent mappings may see the modified content.
913 In some cases, this could be fixed by calling
915 before the unmap takes place;
916 however, this doesn't work on
918 (for example, when using the POSIX shared memory interface documented in
919 .BR shm_overview (7)).
921 .\" FIXME . Add an example here that uses an anonymous shared region for
922 .\" IPC between parent and child.
923 The following program prints part of the file specified in
924 its first command-line argument to standard output.
925 The range of bytes to be printed is specified via offset and length
926 values in the second and third command-line arguments.
927 The program creates a memory mapping of the required
928 pages of the file and then uses
930 to output the desired bytes.
933 #include <sys/mman.h>
934 #include <sys/stat.h>
940 #define handle_error(msg) \e
941 do { perror(msg); exit(EXIT_FAILURE); } while (0)
944 main(int argc, char *argv[])
949 off_t offset, pa_offset;
953 if (argc < 3 || argc > 4) {
954 fprintf(stderr, "%s file offset [length]\en", argv[0]);
958 fd = open(argv[1], O_RDONLY);
960 handle_error("open");
962 if (fstat(fd, &sb) == \-1) /* To obtain file size */
963 handle_error("fstat");
965 offset = atoi(argv[2]);
966 pa_offset = offset & \(ti(sysconf(_SC_PAGE_SIZE) \- 1);
967 /* offset for mmap() must be page aligned */
969 if (offset >= sb.st_size) {
970 fprintf(stderr, "offset is past end of file\en");
975 length = atoi(argv[3]);
976 if (offset + length > sb.st_size)
977 length = sb.st_size \- offset;
978 /* Can\(aqt display bytes past end of file */
980 } else { /* No length arg ==> display to end of file */
981 length = sb.st_size \- offset;
984 addr = mmap(NULL, length + offset \- pa_offset, PROT_READ,
985 MAP_PRIVATE, fd, pa_offset);
986 if (addr == MAP_FAILED)
987 handle_error("mmap");
989 s = write(STDOUT_FILENO, addr + offset \- pa_offset, length);
992 handle_error("write");
994 fprintf(stderr, "partial write");
998 munmap(addr, length + offset \- pa_offset);
1006 .BR getpagesize (2),
1007 .BR memfd_create (2),
1014 .BR remap_file_pages (2),
1017 .BR userfaultfd (2),
1019 .BR shm_overview (7)
1021 The descriptions of the following files in
1023 .IR /proc/[pid]/maps ,
1024 .IR /proc/[pid]/map_files ,
1026 .IR /proc/[pid]/smaps .
1028 B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128\(en129 and 389\(en391.
1030 .\" Repeat after me: private read-only mappings are 100% equivalent to
1031 .\" shared read-only mappings. No ifs, buts, or maybes. -- Linus