readv2: Note preadv2(..., RWF_NOWAIT) bug in BUGS section
[man-pages.git] / man2 / mmap.2
blob96b7444b082a60f397e21ffdc043da91dac464aa
1 .\" Copyright (C) 1996 Andries Brouwer <aeb@cwi.nl>
2 .\" and Copyright (C) 2006, 2007 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
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.
8 .\"
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.
13 .\"
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
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
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
39 .\"
40 .TH MMAP 2 2021-03-22 "Linux" "Linux Programmer's Manual"
41 .SH NAME
42 mmap, munmap \- map or unmap files or devices into memory
43 .SH SYNOPSIS
44 .nf
45 .B #include <sys/mman.h>
46 .PP
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 );
51 .fi
52 .PP
53 See NOTES for information on feature test macro requirements.
54 .SH DESCRIPTION
55 .BR mmap ()
56 creates a new mapping in the virtual address space of
57 the calling process.
58 The starting address for the new mapping is specified in
59 .IR addr .
60 The
61 .I length
62 argument specifies the length of the mapping (which must be greater than 0).
63 .PP
65 .I addr
66 is NULL,
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.
71 .I addr
72 is not NULL,
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.
83 .PP
84 The contents of a file mapping (as opposed to an anonymous mapping; see
85 .B MAP_ANONYMOUS
86 below), are initialized using
87 .I length
88 bytes starting at offset
89 .I offset
90 in the file (or other object) referred to by the file descriptor
91 .IR fd .
92 .I offset
93 must be a multiple of the page size as returned by
94 .IR sysconf(_SC_PAGE_SIZE) .
95 .PP
96 After the
97 .BR mmap ()
98 call has returned, the file descriptor,
99 .IR fd ,
100 can be closed immediately without invalidating the mapping.
103 .I prot
104 argument describes the desired memory protection of the mapping
105 (and must not conflict with the open mode of the file).
106 It is either
107 .B PROT_NONE
108 or the bitwise OR of one or more of the following flags:
109 .TP 1.1i
110 .B PROT_EXEC
111 Pages may be executed.
113 .B PROT_READ
114 Pages may be read.
116 .B PROT_WRITE
117 Pages may be written.
119 .B PROT_NONE
120 Pages may not be accessed.
122 .SS The flags argument
124 .I flags
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
130 .IR flags :
132 .B MAP_SHARED
133 Share this mapping.
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
139 .BR msync (2).)
141 .BR MAP_SHARED_VALIDATE " (since Linux 4.15)"
142 This flag provides the same behavior as
143 .B MAP_SHARED
144 except that
145 .B MAP_SHARED
146 mappings ignore unknown flags in
147 .IR flags .
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
152 .BR EOPNOTSUPP
153 for unknown flags.
154 This mapping type is also required to be able to use some mapping flags
155 (e.g.,
156 .BR MAP_SYNC ).
158 .B MAP_PRIVATE
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
162 the underlying file.
163 It is unspecified whether changes made to the file after the
164 .BR mmap ()
165 call are visible in the mapped region.
167 Both
168 .B MAP_SHARED
170 .B MAP_PRIVATE
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
176 .IR flags :
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
184 64-bit processors.
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.
189 .B MAP_32BIT
190 flag is ignored when
191 .B MAP_FIXED
192 is set.
194 .B MAP_ANON
195 Synonym for
196 .BR MAP_ANONYMOUS ;
197 provided for compatibility with other implementations.
199 .B MAP_ANONYMOUS
200 The mapping is not backed by any file;
201 its contents are initialized to zero.
203 .I fd
204 argument is ignored;
205 however, some implementations require
206 .I fd
207 to be \-1 if
208 .B MAP_ANONYMOUS
210 .BR MAP_ANON )
211 is specified,
212 and portable applications should ensure this.
214 .I offset
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.
218 The use of
219 .B MAP_ANONYMOUS
220 in conjunction with
221 .B MAP_SHARED
222 is supported on Linux only since kernel 2.4.
224 .B MAP_DENYWRITE
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
229 .BR ETXTBSY .
230 But this was a source of denial-of-service attacks.)
232 .B MAP_EXECUTABLE
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
238 .\" MAP_DENYWRITE?
240 .B MAP_FILE
241 Compatibility flag.
242 Ignored.
243 .\" On some systems, this was required as the opposite of
244 .\" MAP_ANONYMOUS -- mtk, 1 May 2007
246 .B MAP_FIXED
247 Don't interpret
248 .I addr
249 as a hint: place the mapping at exactly that address.
250 .I addr
251 must be suitably aligned: for most architectures a multiple of the page
252 size is sufficient; however, some architectures may impose additional
253 restrictions.
254 If the memory region specified by
255 .I addr
257 .I length
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,
261 .BR mmap ()
262 will fail.
264 Software that aspires to be portable should use the
265 .BR MAP_FIXED
266 flag with care,
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
275 .B MAP_FIXED
276 with respect to the
277 .I addr
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
283 .B EEXIST.
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
292 .B MAP_FIXED\c
293 " type of behavior:
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.
298 .B MAP_GROWSDOWN
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
309 .B SIGSEGV
310 signal.
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
321 .B MAP_HUGETLB
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
327 .BR MAP_HUGE_SHIFT .
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
330 .I Hugepagesize
331 field exposed by
332 .IR /proc/meminfo .)
333 Thus, the above two constants are defined as:
335 .in +4n
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
348 .BR mlock (2).
349 This implementation will try to populate (prefault) the whole range but the
350 .BR mmap ()
351 call doesn't fail with
352 .B ENOMEM
353 if this fails.
354 Therefore major faults might happen later on.
355 So the semantic is not as strong as
356 .BR mlock (2).
357 One should use
358 .BR mmap ()
359 plus
360 .BR mlock (2)
361 when major faults are not acceptable after the initialization of the mapping.
363 .BR MAP_LOCKED
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
369 .BR MAP_POPULATE .
370 Don't perform read-ahead:
371 create page tables entries only for pages
372 that are already present in RAM.
373 Since Linux 2.6.23,
374 .\" commit 54cb8821de07f2ffcd28c380ce9b93d5784b40d7
375 this flag causes
376 .BR MAP_POPULATE
377 to do nothing.
378 One day, the combination of
379 .BR MAP_POPULATE
381 .BR MAP_NONBLOCK
382 may be reimplemented.
384 .B MAP_NORESERVE
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
389 .B SIGSEGV
390 upon a write
391 if no physical memory is available.
392 See also the discussion of the file
393 .I /proc/sys/vm/overcommit_memory
395 .BR proc (5).
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.
404 .BR mmap ()
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
407 .BR MAP_HUGETLB ).
408 .BR MAP_POPULATE
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
413 or thread stack.
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:
428 .BR MAP_STACK
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
434 mapping type;
435 mappings of type
436 .B MAP_SHARED
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
441 .B EOPNOTSUPP
442 error.
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
457 option.
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
463 .B MAP_FIXED
464 is specified in POSIX.1-2001 and POSIX.1-2008.
465 However, most systems also support
466 .B MAP_ANONYMOUS
467 (or its synonym
468 .BR MAP_ANON ).
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
473 .SS munmap()
475 .BR munmap ()
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.
484 The address
485 .I addr
486 must be a multiple of the page size (but
487 .I length
488 need not be).
489 All pages containing a part
490 of the indicated range are unmapped, and subsequent references
491 to these pages will generate
492 .BR SIGSEGV .
493 It is not an error if the
494 indicated range does not contain any mapped pages.
495 .SH RETURN VALUE
496 On success,
497 .BR mmap ()
498 returns a pointer to the mapped area.
499 On error, the value
500 .B MAP_FAILED
501 (that is,
502 .IR "(void\ *)\ \-1" )
503 is returned, and
504 .I errno
505 is set to indicate the error.
507 On success,
508 .BR munmap ()
509 returns 0.
510 On failure, it returns \-1, and
511 .I errno
512 is set to indicate the error (probably to
513 .BR EINVAL ).
514 .SH ERRORS
516 .B EACCES
517 A file descriptor refers to a non-regular file.
518 Or a file mapping was requested, but
519 .I fd
520 is not open for reading.
522 .B MAP_SHARED
523 was requested and
524 .B PROT_WRITE
525 is set, but
526 .I fd
527 is not open in read/write
528 .RB ( O_RDWR )
529 mode.
531 .B PROT_WRITE
532 is set, but the file is append-only.
534 .B EAGAIN
535 The file has been locked, or too much memory has been locked (see
536 .BR setrlimit (2)).
538 .B EBADF
539 .I fd
540 is not a valid file descriptor (and
541 .B MAP_ANONYMOUS
542 was not set).
544 .B EEXIST
545 .BR MAP_FIXED_NOREPLACE
546 was specified in
547 .IR flags ,
548 and the range covered by
549 .IR addr
551 .IR length
552 clashes with an existing mapping.
554 .B EINVAL
555 We don't like
556 .IR addr ,
557 .IR length ,
559 .I offset
560 (e.g., they are too large, or not aligned on a page boundary).
562 .B EINVAL
563 (since Linux 2.6.12)
564 .I length
565 was 0.
567 .B EINVAL
568 .I flags
569 contained none of
570 .BR MAP_PRIVATE ,
571 .BR MAP_SHARED ,
573 .BR MAP_SHARED_VALIDATE .
575 .B ENFILE
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.
579 .\" .TP
580 .\" .B ENOEXEC
581 .\" A file could not be mapped for reading.
583 .B ENODEV
584 The underlying filesystem of the specified file does not support
585 memory mapping.
587 .B ENOMEM
588 No memory is available.
590 .B ENOMEM
591 The process's maximum number of mappings would have been exceeded.
592 This error can also occur for
593 .BR munmap (),
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.
598 .B ENOMEM
599 (since Linux 4.7)
600 The process's
601 .B RLIMIT_DATA
602 limit, described in
603 .BR getrlimit (2),
604 would have been exceeded.
606 .B EOVERFLOW
607 On 32-bit architecture together with the large file extension
608 (i.e., using 64-bit
609 .IR off_t ):
610 the number of pages used for
611 .I length
612 plus number of pages used for
613 .I offset
614 would overflow
615 .I "unsigned long"
616 (32 bits).
618 .B EPERM
620 .I prot
621 argument asks for
622 .B PROT_EXEC
623 but the mapped area belongs to a file on a filesystem that
624 was mounted no-exec.
625 .\" (Since 2.4.25 / 2.6.0.)
627 .B EPERM
628 The operation was prevented by a file seal; see
629 .BR fcntl (2).
631 .B EPERM
633 .B MAP_HUGETLB
634 flag was specified, but the caller was not privileged (did not have the
635 .B CAP_IPC_LOCK
636 capability)
637 and is not a member of the
638 .I sysctl_hugetlb_shm_group
639 group; see the description of
640 .I /proc/sys/vm/sysctl_hugetlb_shm_group
643 .B ETXTBSY
644 .B MAP_DENYWRITE
645 was set but the object specified by
646 .I fd
647 is open for writing.
649 Use of a mapped region can result in these signals:
651 .B SIGSEGV
652 Attempted write into a region mapped as read-only.
654 .B SIGBUS
655 Attempted access to a page of the buffer that lies beyond the
656 end of the mapped file.
657 For an explanation of the treatment of the bytes in the page that
658 corresponds to the end of a mapped file that is not a multiple
659 of the page size, see NOTES.
660 .SH ATTRIBUTES
661 For an explanation of the terms used in this section, see
662 .BR attributes (7).
663 .ad l
666 allbox;
667 lbx lb lb
668 l l l.
669 Interface       Attribute       Value
671 .BR mmap (),
672 .BR munmap ()
673 T}      Thread safety   MT-Safe
677 .sp 1
678 .SH CONFORMING TO
679 POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.
680 .\" SVr4 documents additional error codes ENXIO and ENODEV.
681 .\" SUSv2 documents additional error codes EMFILE and EOVERFLOW.
683 On POSIX systems on which
684 .BR mmap (),
685 .BR msync (2),
687 .BR munmap ()
688 are available,
689 .B _POSIX_MAPPED_FILES
690 is defined in \fI<unistd.h>\fP to a value greater than 0.
691 (See also
692 .BR sysconf (3).)
693 .\" POSIX.1-2001: It shall be defined to -1 or 0 or 200112L.
694 .\" -1: unavailable, 0: ask using sysconf().
695 .\" glibc defines it to 1.
696 .SH NOTES
697 Memory mapped by
698 .BR mmap ()
699 is preserved across
700 .BR fork (2),
701 with the same attributes.
703 A file is mapped in multiples of the page size.
704 For a file that is not
705 a multiple of the page size,
706 the remaining bytes in the partial page at the end of the mapping
707 are zeroed when mapped,
708 and modifications to that region are not written out to the file.
709 The effect of
710 changing the size of the underlying file of a mapping on the pages that
711 correspond to added or removed regions of the file is unspecified.
713 On some hardware architectures (e.g., i386),
714 .B PROT_WRITE
715 implies
716 .BR PROT_READ .
717 It is architecture dependent whether
718 .B PROT_READ
719 implies
720 .B PROT_EXEC
721 or not.
722 Portable programs should always set
723 .B PROT_EXEC
724 if they intend to execute code in the new mapping.
726 The portable way to create a mapping is to specify
727 .I addr
728 as 0 (NULL), and omit
729 .B MAP_FIXED
730 from
731 .IR flags .
732 In this case, the system chooses the address for the mapping;
733 the address is chosen so as not to conflict with any existing mapping,
734 and will not be 0.
735 If the
736 .B MAP_FIXED
737 flag is specified, and
738 .I addr
739 is 0 (NULL), then the mapped address will be 0 (NULL).
741 Certain
742 .I flags
743 constants are defined only if suitable feature test macros are defined
744 (possibly by default):
745 .BR _DEFAULT_SOURCE
746 with glibc 2.19 or later;
748 .BR _BSD_SOURCE
750 .BR _SVID_SOURCE
751 in glibc 2.19 and earlier.
752 (Employing
753 .BR _GNU_SOURCE
754 also suffices,
755 and requiring that macro specifically would have been more logical,
756 since these flags are all Linux-specific.)
757 The relevant flags are:
758 .BR MAP_32BIT ,
759 .BR MAP_ANONYMOUS
760 (and the synonym
761 .BR MAP_ANON ),
762 .BR MAP_DENYWRITE ,
763 .BR MAP_EXECUTABLE ,
764 .BR MAP_FILE ,
765 .BR MAP_GROWSDOWN ,
766 .BR MAP_HUGETLB ,
767 .BR MAP_LOCKED ,
768 .BR MAP_NONBLOCK ,
769 .BR MAP_NORESERVE ,
770 .BR MAP_POPULATE ,
772 .BR MAP_STACK .
774 An application can determine which pages of a mapping are
775 currently resident in the buffer/page cache using
776 .BR mincore (2).
778 .SS Using MAP_FIXED safely
779 The only safe use for
780 .BR MAP_FIXED
781 is where the address range specified by
782 .IR addr
784 .I length
785 was previously reserved using another mapping;
786 otherwise, the use of
787 .BR MAP_FIXED
788 is hazardous because it forcibly removes preexisting mappings,
789 making it easy for a multithreaded process to corrupt its own address space.
791 For example, suppose that thread A looks through
792 .I /proc/<pid>/maps
793 in order to locate an unused address range that it can map using
794 .BR MAP_FIXED ,
795 while thread B simultaneously acquires part or all of that same
796 address range.
797 When thread A subsequently employs
798 .BR mmap(MAP_FIXED) ,
799 it will effectively clobber the mapping that thread B created.
800 In this scenario,
801 thread B need not create a mapping directly; simply making a library call
802 that, internally, uses
803 .BR dlopen (3)
804 to load some other shared library, will suffice.
806 .BR dlopen (3)
807 call will map the library into the process's address space.
808 Furthermore, almost any library call may be implemented in a way that
809 adds memory mappings to the address space, either with this technique,
810 or by simply allocating memory.
811 Examples include
812 .BR brk (2),
813 .BR malloc (3),
814 .BR pthread_create (3),
815 and the PAM libraries
816 .UR http://www.linux-pam.org
817 .UE .
819 Since Linux 4.17, a multithreaded program can use the
820 .BR MAP_FIXED_NOREPLACE
821 flag to avoid the hazard described above
822 when attempting to create a mapping at a fixed address
823 that has not been reserved by a preexisting mapping.
825 .SS Timestamps changes for file-backed mappings
826 For file-backed mappings, the
827 .I st_atime
828 field for the mapped file may be updated at any time between the
829 .BR mmap ()
830 and the corresponding unmapping; the first reference to a mapped
831 page will update the field if it has not been already.
834 .I st_ctime
836 .I st_mtime
837 field for a file mapped with
838 .B PROT_WRITE
840 .B MAP_SHARED
841 will be updated after
842 a write to the mapped region, and before a subsequent
843 .BR msync (2)
844 with the
845 .B MS_SYNC
847 .B MS_ASYNC
848 flag, if one occurs.
850 .SS Huge page (Huge TLB) mappings
851 For mappings that employ huge pages, the requirements for the arguments of
852 .BR mmap ()
854 .BR munmap ()
855 differ somewhat from the requirements for mappings
856 that use the native system page size.
859 .BR mmap (),
860 .I offset
861 must be a multiple of the underlying huge page size.
862 The system automatically aligns
863 .I length
864 to be a multiple of the underlying huge page size.
867 .BR munmap (),
868 .IR addr ,
870 .I length
871 must both be a multiple of the underlying huge page size.
873 .SS C library/kernel differences
874 This page describes the interface provided by the glibc
875 .BR mmap ()
876 wrapper function.
877 Originally, this function invoked a system call of the same name.
878 Since kernel 2.4, that system call has been superseded by
879 .BR mmap2 (2),
880 and nowadays
881 .\" Since around glibc 2.1/2.2, depending on the platform.
882 the glibc
883 .BR mmap ()
884 wrapper function invokes
885 .BR mmap2 (2)
886 with a suitably adjusted value for
887 .IR offset .
888 .SH BUGS
889 On Linux, there are no guarantees like those suggested above under
890 .BR MAP_NORESERVE .
891 By default, any process can be killed
892 at any moment when the system runs out of memory.
894 In kernels before 2.6.7, the
895 .B MAP_POPULATE
896 flag has effect only if
897 .I prot
898 is specified as
899 .BR PROT_NONE .
901 SUSv3 specifies that
902 .BR mmap ()
903 should fail if
904 .I length
905 is 0.
906 However, in kernels before 2.6.12,
907 .BR mmap ()
908 succeeded in this case: no mapping was created and the call returned
909 .IR addr .
910 Since kernel 2.6.12,
911 .BR mmap ()
912 fails with the error
913 .B EINVAL
914 for this case.
916 POSIX specifies that the system shall always
917 zero fill any partial page at the end
918 of the object and that system will never write any modification of the
919 object beyond its end.
920 On Linux, when you write data to such partial page after the end
921 of the object, the data stays in the page cache even after the file
922 is closed and unmapped
923 and even though the data is never written to the file itself,
924 subsequent mappings may see the modified content.
925 In some cases, this could be fixed by calling
926 .BR msync (2)
927 before the unmap takes place;
928 however, this doesn't work on
929 .BR tmpfs (5)
930 (for example, when using the POSIX shared memory interface documented in
931 .BR shm_overview (7)).
932 .SH EXAMPLES
933 .\" FIXME . Add an example here that uses an anonymous shared region for
934 .\" IPC between parent and child.
935 The following program prints part of the file specified in
936 its first command-line argument to standard output.
937 The range of bytes to be printed is specified via offset and length
938 values in the second and third command-line arguments.
939 The program creates a memory mapping of the required
940 pages of the file and then uses
941 .BR write (2)
942 to output the desired bytes.
943 .SS Program source
945 #include <sys/mman.h>
946 #include <sys/stat.h>
947 #include <fcntl.h>
948 #include <stdio.h>
949 #include <stdlib.h>
950 #include <unistd.h>
952 #define handle_error(msg) \e
953     do { perror(msg); exit(EXIT_FAILURE); } while (0)
956 main(int argc, char *argv[])
958     char *addr;
959     int fd;
960     struct stat sb;
961     off_t offset, pa_offset;
962     size_t length;
963     ssize_t s;
965     if (argc < 3 || argc > 4) {
966         fprintf(stderr, "%s file offset [length]\en", argv[0]);
967         exit(EXIT_FAILURE);
968     }
970     fd = open(argv[1], O_RDONLY);
971     if (fd == \-1)
972         handle_error("open");
974     if (fstat(fd, &sb) == \-1)           /* To obtain file size */
975         handle_error("fstat");
977     offset = atoi(argv[2]);
978     pa_offset = offset & \(ti(sysconf(_SC_PAGE_SIZE) \- 1);
979         /* offset for mmap() must be page aligned */
981     if (offset >= sb.st_size) {
982         fprintf(stderr, "offset is past end of file\en");
983         exit(EXIT_FAILURE);
984     }
986     if (argc == 4) {
987         length = atoi(argv[3]);
988         if (offset + length > sb.st_size)
989             length = sb.st_size \- offset;
990                 /* Can\(aqt display bytes past end of file */
992     } else {    /* No length arg ==> display to end of file */
993         length = sb.st_size \- offset;
994     }
996     addr = mmap(NULL, length + offset \- pa_offset, PROT_READ,
997                 MAP_PRIVATE, fd, pa_offset);
998     if (addr == MAP_FAILED)
999         handle_error("mmap");
1001     s = write(STDOUT_FILENO, addr + offset \- pa_offset, length);
1002     if (s != length) {
1003         if (s == \-1)
1004             handle_error("write");
1006         fprintf(stderr, "partial write");
1007         exit(EXIT_FAILURE);
1008     }
1010     munmap(addr, length + offset \- pa_offset);
1011     close(fd);
1013     exit(EXIT_SUCCESS);
1016 .SH SEE ALSO
1017 .BR ftruncate (2),
1018 .BR getpagesize (2),
1019 .BR memfd_create (2),
1020 .BR mincore (2),
1021 .BR mlock (2),
1022 .BR mmap2 (2),
1023 .BR mprotect (2),
1024 .BR mremap (2),
1025 .BR msync (2),
1026 .BR remap_file_pages (2),
1027 .BR setrlimit (2),
1028 .BR shmat (2),
1029 .BR userfaultfd (2),
1030 .BR shm_open (3),
1031 .BR shm_overview (7)
1033 The descriptions of the following files in
1034 .BR proc (5):
1035 .IR /proc/[pid]/maps ,
1036 .IR /proc/[pid]/map_files ,
1038 .IR /proc/[pid]/smaps .
1040 B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128\(en129 and 389\(en391.
1042 .\" Repeat after me: private read-only mappings are 100% equivalent to
1043 .\" shared read-only mappings. No ifs, buts, or maybes. -- Linus