1mlock(2)                      System Calls Manual                     mlock(2)
2
3
4

NAME

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

LIBRARY

9       Standard C library (libc, -lc)
10

SYNOPSIS

12       #include <sys/mman.h>
13
14       int mlock(const void addr[.len], size_t len);
15       int mlock2(const void addr[.len], size_t len, unsigned int flags);
16       int munlock(const void addr[.len], size_t len);
17
18       int mlockall(int flags);
19       int munlockall(void);
20

DESCRIPTION

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

RETURN VALUE

101       On success, these system calls return 0.  On error, -1 is returned, er‐
102       rno is set to indicate the error, and no changes are made to any  locks
103       in the address space of the process.
104

ERRORS

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

VERSIONS

147   Linux
148       Under  Linux, mlock(), mlock2(), and munlock() automatically round addr
149       down to the nearest page boundary.  However, the POSIX.1  specification
150       of  mlock() and munlock() allows an implementation to require that addr
151       is page aligned, so portable applications should ensure this.
152
153       The VmLck field of the Linux-specific /proc/pid/status file  shows  how
154       many  kilobytes  of  memory  the  process  with ID PID has locked using
155       mlock(), mlock2(), mlockall(), and mmap(2) MAP_LOCKED.
156

STANDARDS

158       mlock()
159       munlock()
160       mlockall()
161       munlockall()
162              POSIX.1-2008.
163
164       mlock2()
165              Linux.
166
167       On  POSIX  systems  on  which  mlock()  and  munlock()  are  available,
168       _POSIX_MEMLOCK_RANGE  is  defined in <unistd.h> and the number of bytes
169       in a page can be determined from the constant PAGESIZE (if defined)  in
170       <limits.h> or by calling sysconf(_SC_PAGESIZE).
171
172       On  POSIX  systems  on which mlockall() and munlockall() are available,
173       _POSIX_MEMLOCK is defined in <unistd.h> to  a  value  greater  than  0.
174       (See also sysconf(3).)
175

HISTORY

177       mlock()
178       munlock()
179       mlockall()
180       munlockall()
181              POSIX.1-2001, POSIX.1-2008, SVr4.
182
183       mlock2()
184              Linux 4.4, glibc 2.27.
185

NOTES

187       Memory  locking  has  two  main  applications: real-time algorithms and
188       high-security data processing.  Real-time applications  require  deter‐
189       ministic timing, and, like scheduling, paging is one major cause of un‐
190       expected program execution delays.  Real-time applications will usually
191       also switch to a real-time scheduler with sched_setscheduler(2).  Cryp‐
192       tographic security software often handles critical bytes like passwords
193       or  secret  keys  as data structures.  As a result of paging, these se‐
194       crets could be transferred onto a persistent swap store  medium,  where
195       they  might be accessible to the enemy long after the security software
196       has erased the secrets in RAM and terminated.  (But be aware  that  the
197       suspend  mode on laptops and some desktop computers will save a copy of
198       the system's RAM to disk, regardless of memory locks.)
199
200       Real-time processes that are using mlockall() to prevent delays on page
201       faults  should  reserve  enough  locked stack pages before entering the
202       time-critical section, so that no page fault can be caused by  function
203       calls.   This  can  be  achieved by calling a function that allocates a
204       sufficiently large automatic variable (an array) and writes to the mem‐
205       ory  occupied  by this array in order to touch these stack pages.  This
206       way, enough pages will be mapped for the stack and can be  locked  into
207       RAM.   The  dummy writes ensure that not even copy-on-write page faults
208       can occur in the critical section.
209
210       Memory locks are not inherited by a child created via fork(2)  and  are
211       automatically  removed  (unlocked)  during  an  execve(2)  or  when the
212       process terminates.  The mlockall() MCL_FUTURE and MCL_FUTURE | MCL_ON‐
213       FAULT settings are not inherited by a child created via fork(2) and are
214       cleared during an execve(2).
215
216       Note that fork(2) will prepare the address space  for  a  copy-on-write
217       operation.   The consequence is that any write access that follows will
218       cause a page fault that in turn may cause high latencies  for  a  real-
219       time  process.  Therefore, it is crucial not to invoke fork(2) after an
220       mlockall() or mlock() operation—not even from a thread which runs at  a
221       low  priority  within a process which also has a thread running at ele‐
222       vated priority.
223
224       The memory lock on an address range is automatically removed if the ad‐
225       dress range is unmapped via munmap(2).
226
227       Memory  locks  do not stack, that is, pages which have been locked sev‐
228       eral times by calls to mlock(), mlock2(), or  mlockall()  will  be  un‐
229       locked  by a single call to munlock() for the corresponding range or by
230       munlockall().  Pages which are mapped to several locations or  by  sev‐
231       eral processes stay locked into RAM as long as they are locked at least
232       at one location or by at least one process.
233
234       If a call to mlockall() which uses the MCL_FUTURE flag is  followed  by
235       another  call  that does not specify this flag, the changes made by the
236       MCL_FUTURE call will be lost.
237
238       The mlock2() MLOCK_ONFAULT flag and the mlockall() MCL_ONFAULT flag al‐
239       low efficient memory locking for applications that deal with large map‐
240       pings where only a (small) portion of pages in the mapping are touched.
241       In such cases, locking all of the pages in a mapping would incur a sig‐
242       nificant penalty for memory locking.
243
244   Limits and permissions
245       In Linux 2.6.8 and earlier, a process must be privileged (CAP_IPC_LOCK)
246       in  order to lock memory and the RLIMIT_MEMLOCK soft resource limit de‐
247       fines a limit on how much memory the process may lock.
248
249       Since Linux 2.6.9, no limits are placed on the amount of memory that  a
250       privileged  process can lock and the RLIMIT_MEMLOCK soft resource limit
251       instead defines a limit on how much memory an unprivileged process  may
252       lock.
253

BUGS

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

SEE ALSO

276       mincore(2),  mmap(2), setrlimit(2), shmctl(2), sysconf(3), proc(5), ca‐
277       pabilities(7)
278
279
280
281Linux man-pages 6.05              2023-04-08                          mlock(2)
Impressum