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

NAME

6       mmap, mmap64, 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       void *mmap64(void *addr, size_t length, int prot, int flags,
14                  int fd, off64_t offset);
15       int munmap(void *addr, size_t length);
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  only  supported  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 only supported on Linux 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 downwards in memory.
114
115       MAP_HUGETLB (since Linux 2.6.32)
116              Allocate  the mapping using "huge pages."  See the kernel source
117              file Documentation/vm/hugetlbpage.txt for further information.
118
119       MAP_LOCKED (since Linux 2.5.37)
120              Lock the pages of the mapped region into memory in the manner of
121              mlock(2).  This flag is ignored in older kernels.
122
123       MAP_NONBLOCK (since Linux 2.5.46)
124              Only meaningful in conjunction with MAP_POPULATE.  Don't perform
125              read-ahead: only create page tables entries for pages  that  are
126              already  present  in  RAM.  Since Linux 2.6.23, this flag causes
127              MAP_POPULATE to do nothing.  One day the combination of MAP_POP‐
128              ULATE and MAP_NONBLOCK may be reimplemented.
129
130       MAP_NORESERVE
131              Do  not reserve swap space for this mapping.  When swap space is
132              reserved, one has the guarantee that it is  possible  to  modify
133              the  mapping.   When  swap  space  is not reserved one might get
134              SIGSEGV upon a write if no physical memory  is  available.   See
135              also  the  discussion of the file /proc/sys/vm/overcommit_memory
136              in proc(5).  In kernels before 2.6, this flag  only  had  effect
137              for private writable mappings.
138
139       MAP_POPULATE (since Linux 2.5.46)
140              Populate  (prefault) page tables for a mapping.  For a file map‐
141              ping, this causes read-ahead on the file.  Later accesses to the
142              mapping  will  not  be  blocked by page faults.  MAP_POPULATE is
143              only supported for private mappings since Linux 2.6.23.
144
145       Of the above flags, only MAP_FIXED is specified in POSIX.1-2001.   How‐
146       ever,   most   systems  also  support  MAP_ANONYMOUS  (or  its  synonym
147       MAP_ANON).
148
149       MAP_STACK (since Linux 2.6.27)
150              Allocate the mapping at an address suitable  for  a  process  or
151              thread  stack.   This  flag is currently a no-op, but is used in
152              the glibc threading implementation so that if some architectures
153              require  special  treatment  for  stack allocations, support can
154              later be transparently implemented for glibc.
155
156       Some systems document the additional flags MAP_AUTOGROW, MAP_AUTORESRV,
157       MAP_COPY, and MAP_LOCAL.
158
159       Memory  mapped  by  mmap()  is  preserved across fork(2), with the same
160       attributes.
161
162       A file is mapped in multiples of the page size.  For a file that is not
163       a  multiple  of  the  page  size,  the  remaining memory is zeroed when
164       mapped, and writes to that region are not written out to the file.  The
165       effect  of changing the size of the underlying file of a mapping on the
166       pages that correspond to added  or  removed  regions  of  the  file  is
167       unspecified.
168
169   mmap64()
170       The  mmap64()  system  call operates in exactly the same way as mmap(),
171       except that the  final  argument  specifies  the  offset  as  a  64-bit
172       off64_t. This  enables  applications to aceess the large files.
173
174   munmap()
175       The munmap() system call deletes the mappings for the specified address
176       range, and causes further references to addresses within the  range  to
177       generate  invalid  memory references.  The region is also automatically
178       unmapped when the process is terminated.  On the  other  hand,  closing
179       the file descriptor does not unmap the region.
180
181       The  address  addr must be a multiple of the page size.  All pages con‐
182       taining a part of the indicated range are unmapped, and subsequent ref‐
183       erences  to  these  pages will generate SIGSEGV.  It is not an error if
184       the indicated range does not contain any mapped pages.
185
186   Timestamps changes for file-backed mappings
187       For file-backed mappings, the st_atime field for the mapped file may be
188       updated at any time between the mmap() and the corresponding unmapping;
189       the first reference to a mapped page will update the field  if  it  has
190       not been already.
191
192       The  st_ctime  and st_mtime field for a file mapped with PROT_WRITE and
193       MAP_SHARED will be updated after a write  to  the  mapped  region,  and
194       before  a subsequent msync(2) with the MS_SYNC or MS_ASYNC flag, if one
195       occurs.
196

RETURN VALUE

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

ERRORS

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

CONFORMING TO

251       SVr4, 4.4BSD, POSIX.1-2001.
252

AVAILABILITY

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

NOTES

259       Since  kernel  2.4,  this  system call has been superseded by mmap2(2).
260       Nowadays, the glibc mmap() wrapper function  invokes  mmap2(2)  with  a
261       suitably adjusted value for offset.
262
263       On   some  hardware  architectures  (e.g.,  i386),  PROT_WRITE  implies
264       PROT_READ.  It is  architecture  dependent  whether  PROT_READ  implies
265       PROT_EXEC  or  not.   Portable  programs should always set PROT_EXEC if
266       they intend to execute code in the new mapping.
267
268       The portable way to create a mapping is to specify addr  as  0  (NULL),
269       and  omit  MAP_FIXED  from flags.  In this case, the system chooses the
270       address for the mapping; the address is chosen so as  not  to  conflict
271       with any existing mapping, and will not be 0.  If the MAP_FIXED flag is
272       specified, and addr is 0 (NULL), then the  mapped  address  will  be  0
273       (NULL).
274

BUGS

276       On  Linux  there  are  no  guarantees  like those suggested above under
277       MAP_NORESERVE.  By default, any process can be  killed  at  any  moment
278       when the system runs out of memory.
279
280       In  kernels before 2.6.7, the MAP_POPULATE flag only has effect if prot
281       is specified as PROT_NONE.
282
283       SUSv3 specifies that mmap() should fail if length is  0.   However,  in
284       kernels  before  2.6.12,  mmap() succeeded in this case: no mapping was
285       created and the call returned addr.  Since kernel 2.6.12, mmap()  fails
286       with the error EINVAL for this case.
287

EXAMPLE

289       The  following  program  prints part of the file specified in its first
290       command-line argument to standard output.  The range  of  bytes  to  be
291       printed  is  specified  via  offset and length values in the second and
292       third command-line arguments.  The program creates a memory mapping  of
293       the  required  pages  of  the file and then uses write(2) to output the
294       desired bytes.
295
296       #include <sys/mman.h>
297       #include <sys/stat.h>
298       #include <fcntl.h>
299       #include <stdio.h>
300       #include <stdlib.h>
301       #include <unistd.h>
302
303       #define handle_error(msg) \
304           do { perror(msg); exit(EXIT_FAILURE); } while (0)
305
306       int
307       main(int argc, char *argv[])
308       {
309           char *addr;
310           int fd;
311           struct stat sb;
312           off_t offset, pa_offset;
313           size_t length;
314           ssize_t s;
315
316           if (argc < 3 || argc > 4) {
317               fprintf(stderr, "%s file offset [length]\n", argv[0]);
318               exit(EXIT_FAILURE);
319           }
320
321           fd = open(argv[1], O_RDONLY);
322           if (fd == -1)
323               handle_error("open");
324
325           if (fstat(fd, &sb) == -1)           /* To obtain file size */
326               handle_error("fstat");
327
328           offset = atoi(argv[2]);
329           pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
330               /* offset for mmap() must be page aligned */
331
332           if (offset >= sb.st_size) {
333               fprintf(stderr, "offset is past end of file\n");
334               exit(EXIT_FAILURE);
335           }
336
337           if (argc == 4) {
338               length = atoi(argv[3]);
339               if (offset + length > sb.st_size)
340                   length = sb.st_size - offset;
341                       /* Can't display bytes past end of file */
342
343           } else {    /* No length arg ==> display to end of file */
344               length = sb.st_size - offset;
345           }
346
347           addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
348                       MAP_PRIVATE, fd, pa_offset);
349           if (addr == MAP_FAILED)
350               handle_error("mmap");
351
352           s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
353           if (s != length) {
354               if (s == -1)
355                   handle_error("write");
356
357               fprintf(stderr, "partial write");
358               exit(EXIT_FAILURE);
359           }
360
361           exit(EXIT_SUCCESS);
362       } /* main */
363

SEE ALSO

365       getpagesize(2), mincore(2), mlock(2), mmap2(2), mprotect(2), mremap(2),
366       msync(2),  remap_file_pages(2),  setrlimit(2),  shmat(2),  shm_open(3),
367       shm_overview(7)
368       B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128-129 and 389-391.
369

COLOPHON

371       This page is part of release 3.24 of the Linux  man-pages  project.   A
372       description  of  the project, and information about reporting bugs, can
373       be found at http://www.kernel.org/doc/man-pages/.
374
375
376
377Linux                             2009-09-26                           MMAP(2)
Impressum