1MMAP(2)                    Linux Programmer's Manual                   MMAP(2)
2
3
4

NAME

6       mmap, munmap - map or unmap files or devices into memory
7

SYNOPSIS

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

DESCRIPTION

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.
21
22       If addr is NULL, then the kernel chooses the address at which to create
23       the mapping; this is the most portable method of creating  a  new  map‐
24       ping.   If  addr  is not NULL, then the kernel takes it as a hint about
25       where to place the mapping; on Linux, the mapping will be created at  a
26       nearby  page  boundary.   The address of the new mapping is returned as
27       the result of the call.
28
29       The contents of a file mapping (as opposed to an anonymous mapping; see
30       MAP_ANONYMOUS  below),  are  initialized using length bytes starting at
31       offset offset in the file (or other object) referred  to  by  the  file
32       descriptor  fd.  offset must be a multiple of the page size as returned
33       by sysconf(_SC_PAGE_SIZE).
34
35       The prot argument describes the desired memory protection of  the  map‐
36       ping  (and  must  not  conflict with the open mode of the file).  It is
37       either PROT_NONE or the bitwise OR of one  or  more  of  the  following
38       flags:
39
40       PROT_EXEC  Pages may be executed.
41
42       PROT_READ  Pages may be read.
43
44       PROT_WRITE Pages may be written.
45
46       PROT_NONE  Pages may not be accessed.
47
48       The  flags argument determines whether updates to the mapping are visi‐
49       ble to other processes mapping the same region, and whether updates are
50       carried through to the underlying file.  This behavior is determined by
51       including exactly one of the following values in flags:
52
53       MAP_SHARED Share this mapping.  Updates to the mapping are  visible  to
54                  other  processes that map this file, and are carried through
55                  to the underlying  file.   The  file  may  not  actually  be
56                  updated until msync(2) or munmap() is called.
57
58       MAP_PRIVATE
59                  Create a private copy-on-write mapping.  Updates to the map‐
60                  ping are not visible to other  processes  mapping  the  same
61                  file,  and  are  not carried through to the underlying file.
62                  It is unspecified whether changes made to the file after the
63                  mmap() call are visible in the mapped region.
64
65       Both of these flags are described in POSIX.1-2001.
66
67       In addition, zero or more of the following values can be ORed in flags:
68
69       MAP_32BIT (since Linux 2.4.20, 2.6)
70              Put  the  mapping  into  the  first  2  Gigabytes of the process
71              address space.  This flag  is  supported  only  on  x86-64,  for
72              64-bit  programs.   It  was  added  to allow thread stacks to be
73              allocated somewhere in the first 2GB of memory, so as to improve
74              context-switch  performance  on  some  early  64-bit processors.
75              Modern x86-64 processors no longer have this  performance  prob‐
76              lem,  so use of this flag is not required on those systems.  The
77              MAP_32BIT flag is ignored when MAP_FIXED is set.
78
79       MAP_ANON
80              Synonym for MAP_ANONYMOUS.  Deprecated.
81
82       MAP_ANONYMOUS
83              The mapping is not backed by any file; its contents are initial‐
84              ized to zero.  The fd and offset arguments are ignored; however,
85              some implementations require fd to be -1  if  MAP_ANONYMOUS  (or
86              MAP_ANON)  is specified, and portable applications should ensure
87              this.  The use of MAP_ANONYMOUS in conjunction  with  MAP_SHARED
88              is supported on Linux only since kernel 2.4.
89
90       MAP_DENYWRITE
91              This  flag  is ignored.  (Long ago, it signaled that attempts to
92              write to the underlying file should  fail  with  ETXTBUSY.   But
93              this was a source of denial-of-service attacks.)
94
95       MAP_EXECUTABLE
96              This flag is ignored.
97
98       MAP_FILE
99              Compatibility flag.  Ignored.
100
101       MAP_FIXED
102              Don't  interpret  addr  as  a hint: place the mapping at exactly
103              that address.  addr must be a multiple of the page size.  If the
104              memory  region  specified  by addr and len overlaps pages of any
105              existing mapping(s), then the overlapped part  of  the  existing
106              mapping(s)  will  be discarded.  If the specified address cannot
107              be used, mmap() will fail.  Because requiring  a  fixed  address
108              for  a  mapping is less portable, the use of this option is dis‐
109              couraged.
110
111       MAP_GROWSDOWN
112              Used for stacks.  Indicates to the kernel virtual memory  system
113              that the mapping should extend downward in memory.
114
115       MAP_HUGETLB (since Linux 2.6.32)
116              Allocate  the  mapping using "huge pages."  See the Linux kernel
117              source file Documentation/vm/hugetlbpage.txt for further  infor‐
118              mation.
119
120       MAP_LOCKED (since Linux 2.5.37)
121              Lock the pages of the mapped region into memory in the manner of
122              mlock(2).  This flag is ignored in older kernels.
123
124       MAP_NONBLOCK (since Linux 2.5.46)
125              Only meaningful in conjunction with MAP_POPULATE.  Don't perform
126              read-ahead:  create  page tables entries only for pages that are
127              already present in RAM.  Since Linux 2.6.23,  this  flag  causes
128              MAP_POPULATE to do nothing.  One day the combination of MAP_POP‐
129              ULATE and MAP_NONBLOCK may be reimplemented.
130
131       MAP_NORESERVE
132              Do not reserve swap space for this mapping.  When swap space  is
133              reserved,  one  has  the guarantee that it is possible to modify
134              the mapping.  When swap space is  not  reserved  one  might  get
135              SIGSEGV  upon  a  write if no physical memory is available.  See
136              also the discussion of the  file  /proc/sys/vm/overcommit_memory
137              in  proc(5).   In  kernels before 2.6, this flag had effect only
138              for private writable mappings.
139
140       MAP_POPULATE (since Linux 2.5.46)
141              Populate (prefault) page tables for a mapping.  For a file  map‐
142              ping, this causes read-ahead on the file.  Later accesses to the
143              mapping will not be blocked by  page  faults.   MAP_POPULATE  is
144              supported for private mappings only since Linux 2.6.23.
145
146       MAP_STACK (since Linux 2.6.27)
147              Allocate  the  mapping  at  an address suitable for a process or
148              thread stack.  This flag is currently a no-op, but  is  used  in
149              the glibc threading implementation so that if some architectures
150              require special treatment for  stack  allocations,  support  can
151              later be transparently implemented for glibc.
152
153       MAP_UNINITIALIZED (since Linux 2.6.33)
154              Don't  clear  anonymous pages.  This flag is intended to improve
155              performance on embedded devices.  This flag is honored  only  if
156              the  kernel was configured with the CONFIG_MMAP_ALLOW_UNINITIAL‐
157              IZED option.  Because of the security implications, that  option
158              is  normally  enabled  only  on  embedded devices (i.e., devices
159              where one has complete control of the contents of user memory).
160
161       Of the above flags, only MAP_FIXED is specified in POSIX.1-2001.   How‐
162       ever,   most   systems  also  support  MAP_ANONYMOUS  (or  its  synonym
163       MAP_ANON).
164
165       Some systems document the additional flags MAP_AUTOGROW, MAP_AUTORESRV,
166       MAP_COPY, and MAP_LOCAL.
167
168       Memory  mapped  by  mmap()  is  preserved across fork(2), with the same
169       attributes.
170
171       A file is mapped in multiples of the page size.  For a file that is not
172       a  multiple  of  the  page  size,  the  remaining memory is zeroed when
173       mapped, and writes to that region are not written out to the file.  The
174       effect  of changing the size of the underlying file of a mapping on the
175       pages that correspond to added  or  removed  regions  of  the  file  is
176       unspecified.
177
178   munmap()
179       The munmap() system call deletes the mappings for the specified address
180       range, and causes further references to addresses within the  range  to
181       generate  invalid  memory references.  The region is also automatically
182       unmapped when the process is terminated.  On the  other  hand,  closing
183       the file descriptor does not unmap the region.
184
185       The  address  addr must be a multiple of the page size.  All pages con‐
186       taining a part of the indicated range are unmapped, and subsequent ref‐
187       erences  to  these  pages will generate SIGSEGV.  It is not an error if
188       the indicated range does not contain any mapped pages.
189
190   Timestamps changes for file-backed mappings
191       For file-backed mappings, the st_atime field for the mapped file may be
192       updated at any time between the mmap() and the corresponding unmapping;
193       the first reference to a mapped page will update the field  if  it  has
194       not been already.
195
196       The  st_ctime  and st_mtime field for a file mapped with PROT_WRITE and
197       MAP_SHARED will be updated after a write  to  the  mapped  region,  and
198       before  a subsequent msync(2) with the MS_SYNC or MS_ASYNC flag, if one
199       occurs.
200

RETURN VALUE

202       On success, mmap() returns a pointer to the mapped area.  On error, the
203       value  MAP_FAILED  (that is, (void *) -1) is returned, and errno is set
204       appropriately.  On success, munmap() returns  0,  on  failure  -1,  and
205       errno is set (probably to EINVAL).
206

ERRORS

208       EACCES A  file descriptor refers to a non-regular file.  Or MAP_PRIVATE
209              was requested, but fd is not open for  reading.   Or  MAP_SHARED
210              was  requested  and  PROT_WRITE  is  set,  but fd is not open in
211              read/write (O_RDWR) mode.  Or PROT_WRITE is set, but the file is
212              append-only.
213
214       EAGAIN The  file  has  been  locked, or too much memory has been locked
215              (see setrlimit(2)).
216
217       EBADF  fd is not a valid file descriptor  (and  MAP_ANONYMOUS  was  not
218              set).
219
220       EINVAL We don't like addr, length, or offset (e.g., they are too large,
221              or not aligned on a page boundary).
222
223       EINVAL (since Linux 2.6.12) length was 0.
224
225       EINVAL flags contained neither MAP_PRIVATE or MAP_SHARED, or  contained
226              both of these values.
227
228       ENFILE The  system  limit  on  the  total number of open files has been
229              reached.
230
231       ENODEV The underlying file system of the specified file does  not  sup‐
232              port memory mapping.
233
234       ENOMEM No  memory is available, or the process's maximum number of map‐
235              pings would have been exceeded.
236
237       EPERM  The prot argument asks for PROT_EXEC but the mapped area belongs
238              to a file on a file system that was mounted no-exec.
239
240       ETXTBSY
241              MAP_DENYWRITE was set but the object specified by fd is open for
242              writing.
243
244       EOVERFLOW
245              On 32-bit architecture together with the  large  file  extension
246              (i.e.,  using 64-bit off_t): the number of pages used for length
247              plus number of pages used for  offset  would  overflow  unsigned
248              long (32 bits).
249
250       Use of a mapped region can result in these signals:
251
252       SIGSEGV
253              Attempted write into a region mapped as read-only.
254
255       SIGBUS Attempted access to a portion of the buffer that does not corre‐
256              spond to the file (for example, beyond  the  end  of  the  file,
257              including  the  case  where  another  process  has truncated the
258              file).
259

CONFORMING TO

261       SVr4, 4.4BSD, POSIX.1-2001.
262

AVAILABILITY

264       On POSIX systems on which mmap(), msync(2) and munmap() are  available,
265       _POSIX_MAPPED_FILES is defined in <unistd.h> to a value greater than 0.
266       (See also sysconf(3).)
267

NOTES

269       This page describes the interface provided by the glibc mmap()  wrapper
270       function.   Originally, this function invoked a system call of the same
271       name.  Since kernel 2.4,  that  system  call  has  been  superseded  by
272       mmap2(2),  and  nowadays  the  glibc  mmap()  wrapper  function invokes
273       mmap2(2) with a suitably adjusted value for offset.
274
275       On  some  hardware  architectures  (e.g.,  i386),  PROT_WRITE   implies
276       PROT_READ.   It  is  architecture  dependent  whether PROT_READ implies
277       PROT_EXEC or not.  Portable programs should  always  set  PROT_EXEC  if
278       they intend to execute code in the new mapping.
279
280       The  portable  way  to create a mapping is to specify addr as 0 (NULL),
281       and omit MAP_FIXED from flags.  In this case, the  system  chooses  the
282       address  for  the  mapping; the address is chosen so as not to conflict
283       with any existing mapping, and will not be 0.  If the MAP_FIXED flag is
284       specified,  and  addr  is  0  (NULL), then the mapped address will be 0
285       (NULL).
286
287       Certain flags constants are  defined  only  if  either  _BSD_SOURCE  or
288       _SVID_SOURCE  is  defined.   (Requiring  _GNU_SOURCE also suffices, and
289       requiring that macro specifically would have been more  logical,  since
290       these   flags  are  all  Linux  specific.)   The  relevant  flags  are:
291       MAP_32BIT, MAP_ANONYMOUS (and  the  synonym  MAP_ANON),  MAP_DENYWRITE,
292       MAP_EXECUTABLE,   MAP_FILE,   MAP_GROWSDOWN,  MAP_HUGETLB,  MAP_LOCKED,
293       MAP_NONBLOCK, MAP_NORESERVE, MAP_POPULATE, and MAP_STACK.
294

BUGS

296       On Linux there are no  guarantees  like  those  suggested  above  under
297       MAP_NORESERVE.   By  default,  any  process can be killed at any moment
298       when the system runs out of memory.
299
300       In kernels before 2.6.7, the MAP_POPULATE flag has effect only if  prot
301       is specified as PROT_NONE.
302
303       SUSv3  specifies  that  mmap() should fail if length is 0.  However, in
304       kernels before 2.6.12, mmap() succeeded in this case:  no  mapping  was
305       created  and the call returned addr.  Since kernel 2.6.12, mmap() fails
306       with the error EINVAL for this case.
307
308       POSIX specifies that the system shall always zero fill any partial page
309       at the end of the object and that system will never write any modifica‐
310       tion of the object beyond its end.  On Linux, when you  write  data  to
311       such  partial  page  after the end of the object, the data stays in the
312       page cache even after the file is closed and unmapped and  even  though
313       the  data  is never written to the file itself, subsequent mappings may
314       see the modified content.  In some cases, this could be fixed by  call‐
315       ing  msync(2)  before the unmap takes place; however, this doesn't work
316       on tmpfs (for example, when using POSIX shared memory  interface  docu‐
317       mented in shm_overview(7)).
318

EXAMPLE

320       The  following  program  prints part of the file specified in its first
321       command-line argument to standard output.  The range  of  bytes  to  be
322       printed  is  specified  via  offset and length values in the second and
323       third command-line arguments.  The program creates a memory mapping  of
324       the  required  pages  of  the file and then uses write(2) to output the
325       desired bytes.
326
327       #include <sys/mman.h>
328       #include <sys/stat.h>
329       #include <fcntl.h>
330       #include <stdio.h>
331       #include <stdlib.h>
332       #include <unistd.h>
333
334       #define handle_error(msg) \
335           do { perror(msg); exit(EXIT_FAILURE); } while (0)
336
337       int
338       main(int argc, char *argv[])
339       {
340           char *addr;
341           int fd;
342           struct stat sb;
343           off_t offset, pa_offset;
344           size_t length;
345           ssize_t s;
346
347           if (argc < 3 || argc > 4) {
348               fprintf(stderr, "%s file offset [length]\n", argv[0]);
349               exit(EXIT_FAILURE);
350           }
351
352           fd = open(argv[1], O_RDONLY);
353           if (fd == -1)
354               handle_error("open");
355
356           if (fstat(fd, &sb) == -1)           /* To obtain file size */
357               handle_error("fstat");
358
359           offset = atoi(argv[2]);
360           pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
361               /* offset for mmap() must be page aligned */
362
363           if (offset >= sb.st_size) {
364               fprintf(stderr, "offset is past end of file\n");
365               exit(EXIT_FAILURE);
366           }
367
368           if (argc == 4) {
369               length = atoi(argv[3]);
370               if (offset + length > sb.st_size)
371                   length = sb.st_size - offset;
372                       /* Can't display bytes past end of file */
373
374           } else {    /* No length arg ==> display to end of file */
375               length = sb.st_size - offset;
376           }
377
378           addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
379                       MAP_PRIVATE, fd, pa_offset);
380           if (addr == MAP_FAILED)
381               handle_error("mmap");
382
383           s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
384           if (s != length) {
385               if (s == -1)
386                   handle_error("write");
387
388               fprintf(stderr, "partial write");
389               exit(EXIT_FAILURE);
390           }
391
392           exit(EXIT_SUCCESS);
393       }
394

SEE ALSO

396       getpagesize(2), mincore(2), mlock(2), mmap2(2), mprotect(2), mremap(2),
397       msync(2),  remap_file_pages(2),  setrlimit(2),  shmat(2),  shm_open(3),
398       shm_overview(7)
399
400       The descriptions of the following files in  proc(5):  /proc/[pid]/maps,
401       /proc/[pid]/map_files, and /proc/[pid]/smaps.
402
403       B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128-129 and 389-391.
404

COLOPHON

406       This  page  is  part of release 3.53 of the Linux man-pages project.  A
407       description of the project, and information about reporting  bugs,  can
408       be found at http://www.kernel.org/doc/man-pages/.
409
410
411
412Linux                             2013-04-17                           MMAP(2)
Impressum