fanotify_mark.2: ERRORS: add missing EBADF error for invalid 'dirfd'
[man-pages.git] / man2 / mlock.2
blob7ed29b60c0061dd02eff6a2f2306a2ce0b8c9977
1 .\" Copyright (C) Michael Kerrisk, 2004
2 .\"     using some material drawn from earlier man pages
3 .\"     written by Thomas Kuhn, Copyright 1996
4 .\"
5 .\" %%%LICENSE_START(GPLv2+_DOC_FULL)
6 .\" This is free documentation; you can redistribute it and/or
7 .\" modify it under the terms of the GNU General Public License as
8 .\" published by the Free Software Foundation; either version 2 of
9 .\" the License, or (at your option) any later version.
10 .\"
11 .\" The GNU General Public License's references to "object code"
12 .\" and "executables" are to be interpreted as the output of any
13 .\" document formatting or typesetting system, including
14 .\" intermediate and printed output.
15 .\"
16 .\" This manual is distributed in the hope that it will be useful,
17 .\" but WITHOUT ANY WARRANTY; without even the implied warranty of
18 .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 .\" GNU General Public License for more details.
20 .\"
21 .\" You should have received a copy of the GNU General Public
22 .\" License along with this manual; if not, see
23 .\" <http://www.gnu.org/licenses/>.
24 .\" %%%LICENSE_END
25 .\"
26 .TH MLOCK 2 2021-03-22 "Linux" "Linux Programmer's Manual"
27 .SH NAME
28 mlock, mlock2, munlock, mlockall, munlockall \- lock and unlock memory
29 .SH SYNOPSIS
30 .nf
31 .B #include <sys/mman.h>
32 .PP
33 .BI "int mlock(const void *" addr ", size_t " len );
34 .BI "int mlock2(const void *" addr ", size_t " len ", unsigned int " flags );
35 .BI "int munlock(const void *" addr ", size_t " len );
36 .PP
37 .BI "int mlockall(int " flags );
38 .B int munlockall(void);
39 .fi
40 .SH DESCRIPTION
41 .BR mlock (),
42 .BR mlock2 (),
43 and
44 .BR mlockall ()
45 lock part or all of the calling process's virtual address
46 space into RAM, preventing that memory from being paged to the
47 swap area.
48 .PP
49 .BR munlock ()
50 and
51 .BR munlockall ()
52 perform the converse operation,
53 unlocking part or all of the calling process's virtual
54 address space, so that pages in the specified virtual address range may
55 once more to be swapped out if required by the kernel memory manager.
56 .PP
57 Memory locking and unlocking are performed in units of whole pages.
58 .SS mlock(), mlock2(), and munlock()
59 .BR mlock ()
60 locks pages in the address range starting at
61 .I addr
62 and continuing for
63 .I len
64 bytes.
65 All pages that contain a part of the specified address range are
66 guaranteed to be resident in RAM when the call returns successfully;
67 the pages are guaranteed to stay in RAM until later unlocked.
68 .PP
69 .BR mlock2 ()
70 .\" commit a8ca5d0ecbdde5cc3d7accacbd69968b0c98764e
71 .\" commit de60f5f10c58d4f34b68622442c0e04180367f3f
72 .\" commit b0f205c2a3082dd9081f9a94e50658c5fa906ff1
73 also locks pages in the specified range starting at
74 .I addr
75 and continuing for
76 .I len
77 bytes.
78 However, the state of the pages contained in that range after the call
79 returns successfully will depend on the value in the
80 .I flags
81 argument.
82 .PP
83 The
84 .I flags
85 argument can be either 0 or the following constant:
86 .TP
87 .B MLOCK_ONFAULT
88 Lock pages that are currently resident and mark the entire range so
89 that the remaining nonresident pages are locked when they are populated
90 by a page fault.
91 .PP
93 .I flags
94 is 0,
95 .BR mlock2 ()
96 behaves exactly the same as
97 .BR mlock ().
98 .PP
99 .BR munlock ()
100 unlocks pages in the address range starting at
101 .I addr
102 and continuing for
103 .I len
104 bytes.
105 After this call, all pages that contain a part of the specified
106 memory range can be moved to external swap space again by the kernel.
107 .SS mlockall() and munlockall()
108 .BR mlockall ()
109 locks all pages mapped into the address space of the
110 calling process.
111 This includes the pages of the code, data, and stack
112 segment, as well as shared libraries, user space kernel data, shared
113 memory, and memory-mapped files.
114 All mapped pages are guaranteed
115 to be resident in RAM when the call returns successfully;
116 the pages are guaranteed to stay in RAM until later unlocked.
119 .I flags
120 argument is constructed as the bitwise OR of one or more of the
121 following constants:
123 .B MCL_CURRENT
124 Lock all pages which are currently mapped into the address space of
125 the process.
127 .B MCL_FUTURE
128 Lock all pages which will become mapped into the address space of the
129 process in the future.
130 These could be, for instance, new pages required
131 by a growing heap and stack as well as new memory-mapped files or
132 shared memory regions.
134 .BR MCL_ONFAULT " (since Linux 4.4)"
135 Used together with
136 .BR MCL_CURRENT ,
137 .BR MCL_FUTURE ,
138 or both.
139 Mark all current (with
140 .BR MCL_CURRENT )
141 or future (with
142 .BR MCL_FUTURE )
143 mappings to lock pages when they are faulted in.
144 When used with
145 .BR MCL_CURRENT ,
146 all present pages are locked, but
147 .BR mlockall ()
148 will not fault in non-present pages.
149 When used with
150 .BR MCL_FUTURE ,
151 all future mappings will be marked to lock pages when they are faulted
152 in, but they will not be populated by the lock when the mapping is
153 created.
154 .B MCL_ONFAULT
155 must be used with either
156 .B MCL_CURRENT
158 .B MCL_FUTURE
159 or both.
162 .B MCL_FUTURE
163 has been specified, then a later system call (e.g.,
164 .BR mmap (2),
165 .BR sbrk (2),
166 .BR malloc (3)),
167 may fail if it would cause the number of locked bytes to exceed
168 the permitted maximum (see below).
169 In the same circumstances, stack growth may likewise fail:
170 the kernel will deny stack expansion and deliver a
171 .B SIGSEGV
172 signal to the process.
174 .BR munlockall ()
175 unlocks all pages mapped into the address space of the
176 calling process.
177 .SH RETURN VALUE
178 On success, these system calls return 0.
179 On error, \-1 is returned,
180 .I errno
181 is set to indicate the error,
182 and no changes are made to any locks in the
183 address space of the process.
184 .SH ERRORS
186 .B ENOMEM
187 (Linux 2.6.9 and later) the caller had a nonzero
188 .B RLIMIT_MEMLOCK
189 soft resource limit, but tried to lock more memory than the limit
190 permitted.
191 This limit is not enforced if the process is privileged
192 .RB ( CAP_IPC_LOCK ).
194 .B ENOMEM
195 (Linux 2.4 and earlier) the calling process tried to lock more than
196 half of RAM.
197 .\" In the case of mlock(), this check is somewhat buggy: it doesn't
198 .\" take into account whether the to-be-locked range overlaps with
199 .\" already locked pages.  Thus, suppose we allocate
200 .\" (num_physpages / 4 + 1) of memory, and lock those pages once using
201 .\" mlock(), and then lock the *same* page range a second time.
202 .\" In the case, the second mlock() call will fail, since the check
203 .\" calculates that the process is trying to lock (num_physpages / 2 + 2)
204 .\" pages, which of course is not true.  (MTK, Nov 04, kernel 2.4.28)
206 .B EPERM
207 The caller is not privileged, but needs privilege
208 .RB ( CAP_IPC_LOCK )
209 to perform the requested operation.
210 .\"SVr4 documents an additional EAGAIN error code.
213 .BR mlock (),
214 .BR mlock2 (),
216 .BR munlock ():
218 .B EAGAIN
219 Some or all of the specified address range could not be locked.
221 .B EINVAL
222 The result of the addition
223 .IR addr + len
224 was less than
225 .IR addr
226 (e.g., the addition may have resulted in an overflow).
228 .B EINVAL
229 (Not on Linux)
230 .I addr
231 was not a multiple of the page size.
233 .B ENOMEM
234 Some of the specified address range does not correspond to mapped
235 pages in the address space of the process.
237 .B ENOMEM
238 Locking or unlocking a region would result in the total number of
239 mappings with distinct attributes (e.g., locked versus unlocked)
240 exceeding the allowed maximum.
241 .\" I.e., the number of VMAs would exceed the 64kB maximum
242 (For example, unlocking a range in the middle of a currently locked
243 mapping would result in three mappings:
244 two locked mappings at each end and an unlocked mapping in the middle.)
247 .BR mlock2 ():
249 .B EINVAL
250 Unknown \fIflags\fP were specified.
253 .BR mlockall ():
255 .B EINVAL
256 Unknown \fIflags\fP were specified or
257 .B MCL_ONFAULT
258 was specified without either
259 .B MCL_FUTURE
261 .BR MCL_CURRENT .
264 .BR munlockall ():
266 .B EPERM
267 (Linux 2.6.8 and earlier) The caller was not privileged
268 .RB ( CAP_IPC_LOCK ).
269 .SH VERSIONS
270 .BR mlock2 ()
271 is available since Linux 4.4;
272 glibc support was added in version 2.27.
273 .SH CONFORMING TO
274 .BR mlock (),
275 .BR munlock (),
276 .BR mlockall (),
278 .BR munlockall ():
279 POSIX.1-2001, POSIX.1-2008, SVr4.
281 .BR mlock2 ()
282 is Linux specific.
284 On POSIX systems on which
285 .BR mlock ()
287 .BR munlock ()
288 are available,
289 .B _POSIX_MEMLOCK_RANGE
290 is defined in \fI<unistd.h>\fP and the number of bytes in a page
291 can be determined from the constant
292 .B PAGESIZE
293 (if defined) in \fI<limits.h>\fP or by calling
294 .IR sysconf(_SC_PAGESIZE) .
296 On POSIX systems on which
297 .BR mlockall ()
299 .BR munlockall ()
300 are available,
301 .B _POSIX_MEMLOCK
302 is defined in \fI<unistd.h>\fP to a value greater than 0.
303 (See also
304 .BR sysconf (3).)
305 .\" POSIX.1-2001: It shall be defined to -1 or 0 or 200112L.
306 .\" -1: unavailable, 0: ask using sysconf().
307 .\" glibc defines it to 1.
308 .SH NOTES
309 Memory locking has two main applications: real-time algorithms and
310 high-security data processing.
311 Real-time applications require
312 deterministic timing, and, like scheduling, paging is one major cause
313 of unexpected program execution delays.
314 Real-time applications will
315 usually also switch to a real-time scheduler with
316 .BR sched_setscheduler (2).
317 Cryptographic security software often handles critical bytes like
318 passwords or secret keys as data structures.
319 As a result of paging,
320 these secrets could be transferred onto a persistent swap store medium,
321 where they might be accessible to the enemy long after the security
322 software has erased the secrets in RAM and terminated.
323 (But be aware that the suspend mode on laptops and some desktop
324 computers will save a copy of the system's RAM to disk, regardless
325 of memory locks.)
327 Real-time processes that are using
328 .BR mlockall ()
329 to prevent delays on page faults should reserve enough
330 locked stack pages before entering the time-critical section,
331 so that no page fault can be caused by function calls.
332 This can be achieved by calling a function that allocates a
333 sufficiently large automatic variable (an array) and writes to the
334 memory occupied by this array in order to touch these stack pages.
335 This way, enough pages will be mapped for the stack and can be
336 locked into RAM.
337 The dummy writes ensure that not even copy-on-write
338 page faults can occur in the critical section.
340 Memory locks are not inherited by a child created via
341 .BR fork (2)
342 and are automatically removed (unlocked) during an
343 .BR execve (2)
344 or when the process terminates.
346 .BR mlockall ()
347 .B MCL_FUTURE
349 .B MCL_FUTURE | MCL_ONFAULT
350 settings are not inherited by a child created via
351 .BR fork (2)
352 and are cleared during an
353 .BR execve (2).
355 Note that
356 .BR fork (2)
357 will prepare the address space for a copy-on-write operation.
358 The consequence is that any write access that follows will cause
359 a page fault that in turn may cause high latencies for a real-time process.
360 Therefore, it is crucial not to invoke
361 .BR fork (2)
362 after an
363 .BR mlockall ()
365 .BR mlock ()
366 operation\(emnot even from a thread which runs at a low priority within
367 a process which also has a thread running at elevated priority.
369 The memory lock on an address range is automatically removed
370 if the address range is unmapped via
371 .BR munmap (2).
373 Memory locks do not stack, that is, pages which have been locked several times
374 by calls to
375 .BR mlock (),
376 .BR mlock2 (),
378 .BR mlockall ()
379 will be unlocked by a single call to
380 .BR munlock ()
381 for the corresponding range or by
382 .BR munlockall ().
383 Pages which are mapped to several locations or by several processes stay
384 locked into RAM as long as they are locked at least at one location or by
385 at least one process.
387 If a call to
388 .BR mlockall ()
389 which uses the
390 .B MCL_FUTURE
391 flag is followed by another call that does not specify this flag, the
392 changes made by the
393 .B MCL_FUTURE
394 call will be lost.
397 .BR mlock2 ()
398 .B MLOCK_ONFAULT
399 flag and the
400 .BR mlockall ()
401 .B MCL_ONFAULT
402 flag allow efficient memory locking for applications that deal with
403 large mappings where only a (small) portion of pages in the mapping are touched.
404 In such cases, locking all of the pages in a mapping would incur
405 a significant penalty for memory locking.
406 .SS Linux notes
407 Under Linux,
408 .BR mlock (),
409 .BR mlock2 (),
411 .BR munlock ()
412 automatically round
413 .I addr
414 down to the nearest page boundary.
415 However, the POSIX.1 specification of
416 .BR mlock ()
418 .BR munlock ()
419 allows an implementation to require that
420 .I addr
421 is page aligned, so portable applications should ensure this.
424 .I VmLck
425 field of the Linux-specific
426 .I /proc/[pid]/status
427 file shows how many kilobytes of memory the process with ID
428 .I PID
429 has locked using
430 .BR mlock (),
431 .BR mlock2 (),
432 .BR mlockall (),
434 .BR mmap (2)
435 .BR MAP_LOCKED .
436 .SS Limits and permissions
437 In Linux 2.6.8 and earlier,
438 a process must be privileged
439 .RB ( CAP_IPC_LOCK )
440 in order to lock memory and the
441 .B RLIMIT_MEMLOCK
442 soft resource limit defines a limit on how much memory the process may lock.
444 Since Linux 2.6.9, no limits are placed on the amount of memory
445 that a privileged process can lock and the
446 .B RLIMIT_MEMLOCK
447 soft resource limit instead defines a limit on how much memory an
448 unprivileged process may lock.
449 .SH BUGS
450 In Linux 4.8 and earlier,
451 a bug in the kernel's accounting of locked memory for unprivileged processes
452 (i.e., without
453 .BR CAP_IPC_LOCK )
454 meant that if the region specified by
455 .I addr
457 .I len
458 overlapped an existing lock,
459 then the already locked bytes in the overlapping region were counted twice
460 when checking against the limit.
461 Such double accounting could incorrectly calculate a "total locked memory"
462 value for the process that exceeded the
463 .BR RLIMIT_MEMLOCK
464 limit, with the result that
465 .BR mlock ()
467 .BR mlock2 ()
468 would fail on requests that should have succeeded.
469 This bug was fixed
470 .\" commit 0cf2f6f6dc605e587d2c1120f295934c77e810e8
471 in Linux 4.9.
473 In the 2.4 series Linux kernels up to and including 2.4.17,
474 a bug caused the
475 .BR mlockall ()
476 .B MCL_FUTURE
477 flag to be inherited across a
478 .BR fork (2).
479 This was rectified in kernel 2.4.18.
481 Since kernel 2.6.9, if a privileged process calls
482 .I mlockall(MCL_FUTURE)
483 and later drops privileges (loses the
484 .B CAP_IPC_LOCK
485 capability by, for example,
486 setting its effective UID to a nonzero value),
487 then subsequent memory allocations (e.g.,
488 .BR mmap (2),
489 .BR brk (2))
490 will fail if the
491 .B RLIMIT_MEMLOCK
492 resource limit is encountered.
493 .\" See the following LKML thread:
494 .\" http://marc.theaimsgroup.com/?l=linux-kernel&m=113801392825023&w=2
495 .\" "Rationale for RLIMIT_MEMLOCK"
496 .\" 23 Jan 2006
497 .SH SEE ALSO
498 .BR mincore (2),
499 .BR mmap (2),
500 .BR setrlimit (2),
501 .BR shmctl (2),
502 .BR sysconf (3),
503 .BR proc (5),
504 .BR capabilities (7)