kexec_load.2: Use syscall(SYS_...); for system calls without a wrapper
[man-pages.git] / man2 / mmap.2
blob03f2eeb2cb9e37e429ef83a64832d0dc515dafa7
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 len
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 ETXTBSY
632 .B MAP_DENYWRITE
633 was set but the object specified by
634 .I fd
635 is open for writing.
637 Use of a mapped region can result in these signals:
639 .B SIGSEGV
640 Attempted write into a region mapped as read-only.
642 .B SIGBUS
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.
648 .SH ATTRIBUTES
649 For an explanation of the terms used in this section, see
650 .BR attributes (7).
651 .ad l
654 allbox;
655 lbx lb lb
656 l l l.
657 Interface       Attribute       Value
659 .BR mmap (),
660 .BR munmap ()
661 T}      Thread safety   MT-Safe
665 .sp 1
666 .SH CONFORMING TO
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
672 .BR mmap (),
673 .BR msync (2),
675 .BR munmap ()
676 are available,
677 .B _POSIX_MAPPED_FILES
678 is defined in \fI<unistd.h>\fP to a value greater than 0.
679 (See also
680 .BR sysconf (3).)
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.
684 .SH NOTES
685 Memory mapped by
686 .BR mmap ()
687 is preserved across
688 .BR fork (2),
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.
697 The effect of
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),
702 .B PROT_WRITE
703 implies
704 .BR PROT_READ .
705 It is architecture dependent whether
706 .B PROT_READ
707 implies
708 .B PROT_EXEC
709 or not.
710 Portable programs should always set
711 .B PROT_EXEC
712 if they intend to execute code in the new mapping.
714 The portable way to create a mapping is to specify
715 .I addr
716 as 0 (NULL), and omit
717 .B MAP_FIXED
718 from
719 .IR flags .
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,
722 and will not be 0.
723 If the
724 .B MAP_FIXED
725 flag is specified, and
726 .I addr
727 is 0 (NULL), then the mapped address will be 0 (NULL).
729 Certain
730 .I flags
731 constants are defined only if suitable feature test macros are defined
732 (possibly by default):
733 .BR _DEFAULT_SOURCE
734 with glibc 2.19 or later;
736 .BR _BSD_SOURCE
738 .BR _SVID_SOURCE
739 in glibc 2.19 and earlier.
740 (Employing
741 .BR _GNU_SOURCE
742 also suffices,
743 and requiring that macro specifically would have been more logical,
744 since these flags are all Linux-specific.)
745 The relevant flags are:
746 .BR MAP_32BIT ,
747 .BR MAP_ANONYMOUS
748 (and the synonym
749 .BR MAP_ANON ),
750 .BR MAP_DENYWRITE ,
751 .BR MAP_EXECUTABLE ,
752 .BR MAP_FILE ,
753 .BR MAP_GROWSDOWN ,
754 .BR MAP_HUGETLB ,
755 .BR MAP_LOCKED ,
756 .BR MAP_NONBLOCK ,
757 .BR MAP_NORESERVE ,
758 .BR MAP_POPULATE ,
760 .BR MAP_STACK .
762 An application can determine which pages of a mapping are
763 currently resident in the buffer/page cache using
764 .BR mincore (2).
766 .SS Using MAP_FIXED safely
767 The only safe use for
768 .BR MAP_FIXED
769 is where the address range specified by
770 .IR addr
772 .I length
773 was previously reserved using another mapping;
774 otherwise, the use of
775 .BR MAP_FIXED
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
780 .I /proc/<pid>/maps
781 in order to locate an unused address range that it can map using
782 .BR MAP_FIXED ,
783 while thread B simultaneously acquires part or all of that same
784 address range.
785 When thread A subsequently employs
786 .BR mmap(MAP_FIXED) ,
787 it will effectively clobber the mapping that thread B created.
788 In this scenario,
789 thread B need not create a mapping directly; simply making a library call
790 that, internally, uses
791 .BR dlopen (3)
792 to load some other shared library, will suffice.
794 .BR dlopen (3)
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.
799 Examples include
800 .BR brk (2),
801 .BR malloc (3),
802 .BR pthread_create (3),
803 and the PAM libraries
804 .UR http://www.linux-pam.org
805 .UE .
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
815 .I st_atime
816 field for the mapped file may be updated at any time between the
817 .BR mmap ()
818 and the corresponding unmapping; the first reference to a mapped
819 page will update the field if it has not been already.
822 .I st_ctime
824 .I st_mtime
825 field for a file mapped with
826 .B PROT_WRITE
828 .B MAP_SHARED
829 will be updated after
830 a write to the mapped region, and before a subsequent
831 .BR msync (2)
832 with the
833 .B MS_SYNC
835 .B MS_ASYNC
836 flag, if one occurs.
838 .SS Huge page (Huge TLB) mappings
839 For mappings that employ huge pages, the requirements for the arguments of
840 .BR mmap ()
842 .BR munmap ()
843 differ somewhat from the requirements for mappings
844 that use the native system page size.
847 .BR mmap (),
848 .I offset
849 must be a multiple of the underlying huge page size.
850 The system automatically aligns
851 .I length
852 to be a multiple of the underlying huge page size.
855 .BR munmap (),
856 .IR addr ,
858 .I length
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
863 .BR mmap ()
864 wrapper function.
865 Originally, this function invoked a system call of the same name.
866 Since kernel 2.4, that system call has been superseded by
867 .BR mmap2 (2),
868 and nowadays
869 .\" Since around glibc 2.1/2.2, depending on the platform.
870 the glibc
871 .BR mmap ()
872 wrapper function invokes
873 .BR mmap2 (2)
874 with a suitably adjusted value for
875 .IR offset .
876 .SH BUGS
877 On Linux, there are no guarantees like those suggested above under
878 .BR MAP_NORESERVE .
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
883 .B MAP_POPULATE
884 flag has effect only if
885 .I prot
886 is specified as
887 .BR PROT_NONE .
889 SUSv3 specifies that
890 .BR mmap ()
891 should fail if
892 .I length
893 is 0.
894 However, in kernels before 2.6.12,
895 .BR mmap ()
896 succeeded in this case: no mapping was created and the call returned
897 .IR addr .
898 Since kernel 2.6.12,
899 .BR mmap ()
900 fails with the error
901 .B EINVAL
902 for this case.
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
914 .BR msync (2)
915 before the unmap takes place;
916 however, this doesn't work on
917 .BR tmpfs (5)
918 (for example, when using the POSIX shared memory interface documented in
919 .BR shm_overview (7)).
920 .SH EXAMPLES
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
929 .BR write (2)
930 to output the desired bytes.
931 .SS Program source
933 #include <sys/mman.h>
934 #include <sys/stat.h>
935 #include <fcntl.h>
936 #include <stdio.h>
937 #include <stdlib.h>
938 #include <unistd.h>
940 #define handle_error(msg) \e
941     do { perror(msg); exit(EXIT_FAILURE); } while (0)
944 main(int argc, char *argv[])
946     char *addr;
947     int fd;
948     struct stat sb;
949     off_t offset, pa_offset;
950     size_t length;
951     ssize_t s;
953     if (argc < 3 || argc > 4) {
954         fprintf(stderr, "%s file offset [length]\en", argv[0]);
955         exit(EXIT_FAILURE);
956     }
958     fd = open(argv[1], O_RDONLY);
959     if (fd == \-1)
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");
971         exit(EXIT_FAILURE);
972     }
974     if (argc == 4) {
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;
982     }
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);
990     if (s != length) {
991         if (s == \-1)
992             handle_error("write");
994         fprintf(stderr, "partial write");
995         exit(EXIT_FAILURE);
996     }
998     munmap(addr, length + offset \- pa_offset);
999     close(fd);
1001     exit(EXIT_SUCCESS);
1004 .SH SEE ALSO
1005 .BR ftruncate (2),
1006 .BR getpagesize (2),
1007 .BR memfd_create (2),
1008 .BR mincore (2),
1009 .BR mlock (2),
1010 .BR mmap2 (2),
1011 .BR mprotect (2),
1012 .BR mremap (2),
1013 .BR msync (2),
1014 .BR remap_file_pages (2),
1015 .BR setrlimit (2),
1016 .BR shmat (2),
1017 .BR userfaultfd (2),
1018 .BR shm_open (3),
1019 .BR shm_overview (7)
1021 The descriptions of the following files in
1022 .BR proc (5):
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