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

NAME

6       mlock, mlock2, munlock, mlockall, munlockall - lock and unlock memory
7

SYNOPSIS

9       #include <sys/mman.h>
10
11       int mlock(const void *addr, size_t len);
12       int mlock2(const void *addr, size_t len, int flags);
13       int munlock(const void *addr, size_t len);
14
15       int mlockall(int flags);
16       int munlockall(void);
17

DESCRIPTION

19       mlock(),  mlock2(),  and  mlockall()  lock  part  or all of the calling
20       process's virtual address space into RAM, preventing that  memory  from
21       being paged to the swap area.
22
23       munlock()  and  munlockall()  perform the converse operation, unlocking
24       part or all of the calling process's virtual  address  space,  so  that
25       pages  in  the  specified  virtual  address  range  may once more to be
26       swapped out if required by the kernel memory manager.
27
28       Memory locking and unlocking are performed in units of whole pages.
29
30   mlock(), mlock2(), and munlock()
31       mlock() locks pages in the address range starting at addr and  continu‐
32       ing  for  len  bytes.   All  pages that contain a part of the specified
33       address range are guaranteed to  be  resident  in  RAM  when  the  call
34       returns  successfully;  the  pages  are guaranteed to stay in RAM until
35       later unlocked.
36
37       mlock2() also locks pages in the specified range starting at  addr  and
38       continuing for len bytes.  However, the state of the pages contained in
39       that range after the call returns successfully will depend on the value
40       in the flags argument.
41
42       The flags argument can be either 0 or the following constant:
43
44       MLOCK_ONFAULT
45              Lock pages that are currently resident and mark the entire range
46              so that the remaining nonresident pages  locked  when  they  are
47              populated by a page fault.
48
49       If flags is 0, mlock2() behaves exactly the same as mlock().
50
51       munlock()  unlocks pages in the address range starting at addr and con‐
52       tinuing for len bytes.  After this call, all pages that contain a  part
53       of the specified memory range can be moved to external swap space again
54       by the kernel.
55
56   mlockall() and munlockall()
57       mlockall() locks all pages mapped into the address space of the calling
58       process.   This includes the pages of the code, data and stack segment,
59       as well as shared libraries, user space kernel data, shared memory, and
60       memory-mapped files.  All mapped pages are guaranteed to be resident in
61       RAM when the call returns successfully; the  pages  are  guaranteed  to
62       stay in RAM until later unlocked.
63
64       The  flags  argument is constructed as the bitwise OR of one or more of
65       the following constants:
66
67       MCL_CURRENT Lock all pages which are currently mapped into the  address
68                   space of the process.
69
70       MCL_FUTURE  Lock  all  pages  which will become mapped into the address
71                   space of the process in the future.  These  could  be,  for
72                   instance, new pages required by a growing heap and stack as
73                   well as new memory-mapped files or shared memory regions.
74
75       MCL_ONFAULT (since Linux 4.4)
76                   Used together with MCL_CURRENT, MCL_FUTURE, or both.   Mark
77                   all  current (with MCL_CURRENT) or future (with MCL_FUTURE)
78                   mappings to lock pages when they are faulted in.  When used
79                   with  MCL_CURRENT, all present pages are locked, but mlock‐
80                   all() will not fault in non-present pages.  When used  with
81                   MCL_FUTURE,  all  future  mappings  will  be marked to lock
82                   pages when they are faulted in, but they will not be  popu‐
83                   lated by the lock when the mapping is created.  MCL_ONFAULT
84                   must be used with either MCL_CURRENT or MCL_FUTURE or both.
85
86       If MCL_FUTURE has been specified,  then  a  later  system  call  (e.g.,
87       mmap(2),  sbrk(2), malloc(3)), may fail if it would cause the number of
88       locked bytes to exceed the permitted maximum (see below).  In the  same
89       circumstances,  stack  growth  may  likewise fail: the kernel will deny
90       stack expansion and deliver a SIGSEGV signal to the process.
91
92       munlockall() unlocks all pages mapped into the  address  space  of  the
93       calling process.
94

RETURN VALUE

96       On  success,  these  system  calls return 0.  On error, -1 is returned,
97       errno is set appropriately, and no changes are made to any locks in the
98       address space of the process.
99

ERRORS

101       ENOMEM (Linux  2.6.9 and later) the caller had a nonzero RLIMIT_MEMLOCK
102              soft resource limit, but tried to  lock  more  memory  than  the
103              limit  permitted.   This limit is not enforced if the process is
104              privileged (CAP_IPC_LOCK).
105
106       ENOMEM (Linux 2.4 and earlier) the calling process tried to  lock  more
107              than half of RAM.
108
109       EPERM  The caller is not privileged, but needs privilege (CAP_IPC_LOCK)
110              to perform the requested operation.
111
112       For mlock(), mlock2(), and munlock():
113
114       EAGAIN Some or all of the specified address range could not be locked.
115
116       EINVAL The result of the addition addr+len was less  than  addr  (e.g.,
117              the addition may have resulted in an overflow).
118
119       EINVAL (Not on Linux) addr was not a multiple of the page size.
120
121       ENOMEM Some  of  the  specified  address  range  does not correspond to
122              mapped pages in the address space of the process.
123
124       ENOMEM Locking or unlocking a region would result in the  total  number
125              of  mappings  with  distinct  attributes  (e.g.,  locked  versus
126              unlocked) exceeding the allowed maximum.  (For example,  unlock‐
127              ing  a  range  in the middle of a currently locked mapping would
128              result in three mappings: two locked mappings at each end and an
129              unlocked mapping in the middle.)
130
131       For mlock2():
132
133       EINVAL Unknown flags were specified.
134
135       For mlockall():
136
137       EINVAL Unknown  flags were specified or MCL_ONFAULT was specified with‐
138              out either MCL_FUTURE or MCL_CURRENT.
139
140       For munlockall():
141
142       EPERM  (Linux  2.6.8  and  earlier)  The  caller  was  not   privileged
143              (CAP_IPC_LOCK).
144

VERSIONS

146       mlock2()  is available since Linux 4.4; glibc support was added in ver‐
147       sion 2.27.
148

CONFORMING TO

150       POSIX.1-2001, POSIX.1-2008, SVr4.
151
152       mlock2 () is Linux specific.
153

AVAILABILITY

155       On  POSIX  systems  on  which  mlock()  and  munlock()  are  available,
156       _POSIX_MEMLOCK_RANGE  is  defined in <unistd.h> and the number of bytes
157       in a page can be determined from the constant PAGESIZE (if defined)  in
158       <limits.h> or by calling sysconf(_SC_PAGESIZE).
159
160       On  POSIX  systems  on which mlockall() and munlockall() are available,
161       _POSIX_MEMLOCK is defined in <unistd.h> to  a  value  greater  than  0.
162       (See also sysconf(3).)
163

NOTES

165       Memory  locking  has  two  main  applications: real-time algorithms and
166       high-security data processing.  Real-time applications  require  deter‐
167       ministic  timing,  and,  like  scheduling, paging is one major cause of
168       unexpected program execution delays.  Real-time applications will  usu‐
169       ally  also  switch to a real-time scheduler with sched_setscheduler(2).
170       Cryptographic security software often handles critical bytes like pass‐
171       words  or secret keys as data structures.  As a result of paging, these
172       secrets could be transferred onto a persistent swap store medium, where
173       they  might be accessible to the enemy long after the security software
174       has erased the secrets in RAM and terminated.  (But be aware  that  the
175       suspend  mode on laptops and some desktop computers will save a copy of
176       the system's RAM to disk, regardless of memory locks.)
177
178       Real-time processes that are using mlockall() to prevent delays on page
179       faults  should  reserve  enough  locked stack pages before entering the
180       time-critical section, so that no page fault can be caused by  function
181       calls.   This  can  be  achieved by calling a function that allocates a
182       sufficiently large automatic variable (an array) and writes to the mem‐
183       ory  occupied  by this array in order to touch these stack pages.  This
184       way, enough pages will be mapped for the stack and can be  locked  into
185       RAM.   The  dummy writes ensure that not even copy-on-write page faults
186       can occur in the critical section.
187
188       Memory locks are not inherited by a child created via fork(2)  and  are
189       automatically  removed  (unlocked)  during  an  execve(2)  or  when the
190       process  terminates.   The  mlockall()  MCL_FUTURE  and  MCL_FUTURE   |
191       MCL_ONFAULT  settings  are not inherited by a child created via fork(2)
192       and are cleared during an execve(2).
193
194       Note that fork(2) will prepare the address space  for  a  copy-on-write
195       operation.   The consequence is that any write access that follows will
196       cause a page fault that in turn may cause high latencies  for  a  real-
197       time  process.  Therefore, it is crucial not to invoke fork(2) after an
198       mlockall() or mlock() operation—not even from a thread which runs at  a
199       low  priority  within a process which also has a thread running at ele‐
200       vated priority.
201
202       The memory lock on an address range is  automatically  removed  if  the
203       address range is unmapped via munmap(2).
204
205       Memory  locks  do not stack, that is, pages which have been locked sev‐
206       eral times by  calls  to  mlock(),  mlock2(),  or  mlockall()  will  be
207       unlocked  by  a single call to munlock() for the corresponding range or
208       by munlockall().  Pages which are mapped to  several  locations  or  by
209       several  processes  stay  locked into RAM as long as they are locked at
210       least at one location or by at least one process.
211
212       If a call to mlockall() which uses the MCL_FUTURE flag is  followed  by
213       another  call  that does not specify this flag, the changes made by the
214       MCL_FUTURE call will be lost.
215
216       The mlock2() MLOCK_ONFAULT flag and  the  mlockall()  MCL_ONFAULT  flag
217       allow  efficient  memory  locking for applications that deal with large
218       mappings where only a (small) portion  of  pages  in  the  mapping  are
219       touched.   In  such  cases, locking all of the pages in a mapping would
220       incur a significant penalty for memory locking.
221
222   Linux notes
223       Under Linux, mlock(), mlock2(), and munlock() automatically round  addr
224       down  to the nearest page boundary.  However, the POSIX.1 specification
225       of mlock() and munlock() allows an implementation to require that  addr
226       is page aligned, so portable applications should ensure this.
227
228       The VmLck field of the Linux-specific /proc/[pid]/status file shows how
229       many kilobytes of memory the process  with  ID  PID  has  locked  using
230       mlock(), mlock2(), mlockall(), and mmap(2) MAP_LOCKED.
231
232   Limits and permissions
233       In Linux 2.6.8 and earlier, a process must be privileged (CAP_IPC_LOCK)
234       in order to lock memory and  the  RLIMIT_MEMLOCK  soft  resource  limit
235       defines a limit on how much memory the process may lock.
236
237       Since  Linux 2.6.9, no limits are placed on the amount of memory that a
238       privileged process can lock and the RLIMIT_MEMLOCK soft resource  limit
239       instead  defines a limit on how much memory an unprivileged process may
240       lock.
241

BUGS

243       In Linux 4.8 and earlier, a bug in the kernel's  accounting  of  locked
244       memory  for  unprivileged  processes (i.e., without CAP_IPC_LOCK) meant
245       that if the region specified by addr and  len  overlapped  an  existing
246       lock,  then  the  already  locked  bytes in the overlapping region were
247       counted twice when checking against the limit.  Such double  accounting
248       could  incorrectly  calculate  a  "total  locked  memory" value for the
249       process that exceeded the RLIMIT_MEMLOCK limit, with  the  result  that
250       mlock() and mlock2() would fail on requests that should have succeeded.
251       This bug was fixed in Linux 4.9
252
253       In the 2.4 series Linux kernels up  to  and  including  2.4.17,  a  bug
254       caused the mlockall() MCL_FUTURE flag to be inherited across a fork(2).
255       This was rectified in kernel 2.4.18.
256
257       Since kernel 2.6.9, if a privileged process calls  mlockall(MCL_FUTURE)
258       and  later  drops privileges (loses the CAP_IPC_LOCK capability by, for
259       example, setting its effective UID to a nonzero value), then subsequent
260       memory allocations (e.g., mmap(2), brk(2)) will fail if the RLIMIT_MEM‐
261       LOCK resource limit is encountered.
262

SEE ALSO

264       mincore(2),  mmap(2),  setrlimit(2),  shmctl(2),  sysconf(3),  proc(5),
265       capabilities(7)
266

COLOPHON

268       This  page  is  part of release 4.16 of the Linux man-pages project.  A
269       description of the project, information about reporting bugs,  and  the
270       latest     version     of     this    page,    can    be    found    at
271       https://www.kernel.org/doc/man-pages/.
272
273
274
275Linux                             2018-02-02                          MLOCK(2)
Impressum