mlock(2)

๐Ÿ’– mlock(2) โ€” lock and unlock memory ๐Ÿ’–

System Calls Manual ยท part 1 of 2, bestie, buckle in ๐Ÿฆ‹


๐ŸŒธ NAME ๐ŸŒธ

mlock, mlock2, munlock, mlockall, munlockall โ€” lock and unlock memory.


๐Ÿ“š LIBRARY ๐Ÿ“š

Standard C library (libc, -lc).


โœจ SYNOPSIS โœจ

#include <sys/mman.h>

int mlock(size_t size;
          const void addr[size], size_t size);
int mlock2(size_t size;
          const void addr[size], size_t size, unsigned int flags);
int munlock(size_t size;
          const void addr[size], size_t size);

int mlockall(int flags);
int munlockall(void);

๐Ÿงš DESCRIPTION ๐Ÿงš

okay so here's the vibe: mlock(), mlock2(), and mlockall() lock some or all of the calling process's virtual address space into RAM, which means that memory literally cannot get paged out to the swap area. It stays put. Iconic behavior, honestly.

munlock() and munlockall() do the exact opposite โ€” they unlock part or all of the calling process's virtual address space, so pages in the specified virtual address range can get swapped out again if the kernel memory manager decides it needs to.

Memory locking and unlocking happen in units of whole pages. No partial pages, no crumbs. ๐Ÿ“

๐Ÿ”’ mlock(), mlock2(), and munlock()

mlock() locks pages in the address range starting at addr and continuing for size bytes. Every page that contains even a part of the specified address range is guaranteed to be resident in RAM when the call returns successfully, and those pages are guaranteed to stay in RAM until they get unlocked later. Periodt.

mlock2() also locks pages in the specified range starting at addr and continuing for size bytes. BUT โ€” and this is the plot twist โ€” the state of the pages in that range after a successful return depends on the value in the flags argument.

The flags argument can be either 0 or this constant:

  • MLOCK_ONFAULT โ€” lock pages that are currently resident, and mark the entire range so that the remaining nonresident pages get locked when they're populated by a page fault. ๐Ÿฆ‹

If flags is 0, then mlock2() behaves exactly the same as mlock(). Same energy, no notes.

munlock() unlocks pages in the address range starting at addr and continuing for size bytes. After this call, all pages that contain a part of the specified memory range can be moved to external swap space again by the kernel. Free them, let them roam. ๐Ÿ’…

๐Ÿ” mlockall() and munlockall()

mlockall() locks ALL pages mapped into the address space of the calling process. Not a subset. Not a vibe check. Everything. That includes the pages of the code, data, and stack segment, plus shared libraries, user space kernel data, shared memory, and memory-mapped files. All mapped pages are guaranteed to be resident in RAM when the call returns successfully, and they're guaranteed to stay in RAM until they get unlocked later. ๐Ÿ‘‘

The flags argument is constructed as the bitwise OR of one or more of these constants:

  • MCL_CURRENT โ€” lock all pages which are currently mapped into the address space of the process.
  • MCL_FUTURE โ€” lock all pages which will become mapped into the address space of the process in the future. These could be, for instance, new pages required by a growing heap and stack as well as new memory-mapped files or shared memory regions.
  • MCL_ONFAULT (since Linux 4.4) โ€” used together with MCL_CURRENT, MCL_FUTURE, or both. Mark all current (with MCL_CURRENT) or future (with MCL_FUTURE) mappings to lock pages when they are faulted in. When used with MCL_CURRENT, all present pages are locked, but mlockall() will not fault in non-present pages. When used with MCL_FUTURE, all future mappings will be marked to lock pages when they are faulted in, but they will not be populated by the lock when the mapping is created. MCL_ONFAULT must be used with either MCL_CURRENT or MCL_FUTURE or both.
โš ๏ธ If MCL_FUTURE has been specified, then a later system call (e.g., mmap(2), sbrk(2), malloc(3)) may fail if it would cause the number of locked bytes to exceed the permitted maximum (see below ๐Ÿ‘€). In the same circumstances, stack growth may likewise fail: the kernel will deny stack expansion and deliver a SIGSEGV signal to the process. Not cute at all, bestie.

munlockall() unlocks all pages mapped into the address space of the calling process.


๐Ÿซถ RETURN VALUE ๐Ÿซถ

On success, these system calls return 0. On error, -1 is returned, errno is set to indicate the error, and no changes are made to any locks in the address space of the process. So if it fails, it fails clean โ€” nothing half-locked, nothing messy.


๐Ÿ’€ ERRORS ๐Ÿ’€

  • EAGAIN (mlock(), mlock2(), and munlock()) โ€” some or all of the specified address range could not be locked.
  • EINVAL (mlock(), mlock2(), and munlock()) โ€” the result of the addition addr+size was less than addr (e.g., the addition may have resulted in an overflow).
  • EINVAL (mlock2()) โ€” unknown flags were specified.
  • EINVAL (mlockall()) โ€” unknown flags were specified, or MCL_ONFAULT was specified without either MCL_FUTURE or MCL_CURRENT.
  • EINVAL (Not on Linux) โ€” addr was not a multiple of the page size.
  • ENOMEM (mlock(), mlock2(), and munlock()) โ€” some of the specified address range does not correspond to mapped pages in the address space of the process.
  • ENOMEM (mlock(), mlock2(), and munlock()) โ€” locking or unlocking a region would result in the total number of mappings with distinct attributes (e.g., locked versus unlocked) exceeding the allowed maximum. (For example, unlocking a range in the middle of a currently locked mapping would result in three mappings: two locked mappings at each end and an unlocked mapping in the middle. The drama of it all. ๐Ÿ˜ญ)
  • ENOMEM (Linux 2.6.9 and later) โ€” the caller had a nonzero RLIMIT_MEMLOCK soft resource limit, but tried to lock more memory than the limit permitted. This limit is not enforced if the process is privileged (CAP_IPC_LOCK).
  • ENOMEM (Linux 2.4 and earlier) โ€” the calling process tried to lock more than half of RAM.
  • EPERM โ€” the caller is not privileged, but needs privilege (CAP_IPC_LOCK) to perform the requested operation.
  • EPERM (munlockall()) (Linux 2.6.8 and earlier) โ€” the caller was not privileged (CAP_IPC_LOCK).

๐ŸŒˆ VERSIONS ๐ŸŒˆ

๐Ÿง Linux

Under Linux, mlock(), mlock2(), and munlock() automatically round addr down to the nearest page boundary. BUT โ€” the POSIX.1 specification of mlock() and munlock() allows an implementation to require that addr is page aligned, so portable applications should make sure of that themselves. Don't rely on the Linux generosity if you want your code to travel. โœˆ๏ธ

The VmLck field of the Linux-specific /proc/pid/status file shows how many kilobytes of memory the process with ID PID has locked using mlock(), mlock2(), mlockall(), and mmap(2) MAP_LOCKED.


๐Ÿ“ STANDARDS ๐Ÿ“

  • mlock()
  • munlock()
  • mlockall()
  • munlockall() โ€” POSIX.1-2024.
  • mlock2() โ€” Linux.

On POSIX systems on which mlock() and munlock() are available, _POSIX_MEMLOCK_RANGE is defined in <unistd.h>, and the number of bytes in a page can be determined from the constant PAGESIZE (if defined) in <limits.h> or by calling sysconf(_SC_PAGESIZE).

On POSIX systems on which mlockall() and munlockall() are available, _POSIX_MEMLOCK is defined in <unistd.h> to a value greater than 0. (See also sysconf(3).)


๐Ÿ“œ HISTORY ๐Ÿ“œ

  • mlock()
  • munlock()
  • mlockall()
  • munlockall() โ€” SVr4, POSIX.1-1996.
  • mlock2() โ€” Linux 4.4, glibc 2.27.

๐Ÿ’ญ NOTES ๐Ÿ’ญ

Memory locking has two main applications: real-time algorithms and high-security data processing. โœจ

Real-time applications require deterministic timing, and, like scheduling, paging is one major cause of unexpected program execution delays. Real-time applications will usually also switch to a real-time scheduler with sched_setscheduler(2).

Cryptographic security software often handles critical bytes like passwords or secret keys as data structures. As a result of paging, these secrets could be transferred onto a persistent swap store medium, where they might be accessible to the enemy long after the security software has erased the secrets in RAM and terminated. ๐Ÿ•ต๏ธ (But be aware that the suspend mode on laptops and some desktop computers will save a copy of the system's RAM to disk, regardless of memory locks. So likeโ€ฆ the lock is not a magic force field, bestie.)

Real-time processes that are using mlockall() to prevent delays on page faults should reserve enough locked stack pages before entering the time-critical section, so that no page fault can be caused by function calls. This can be achieved by calling a function that allocates a sufficiently large automatic variable (an array) and writes to the memory occupied by this array in order to touch these stack pages. This way, enough pages will be mapped for the stack and can be locked into RAM. The dummy writes ensure that not even copy-on-write page faults can occur in the critical section. Pre-touching = main character prep. ๐Ÿ’…

Memory locks are not inherited by a child created via fork(2), and are automatically removed (unlocked) during an execve(2) or when the process terminates. The mlockall() MCL_FUTURE and MCL_FUTURE | MCL_ONFAULT settings are not inherited by a child created via fork(2) and are cleared during an execve(2).

๐Ÿ˜ญ Note that fork(2) will prepare the address space for a copy-on-write operation. The consequence is that any write access that follows will cause a page fault that in turn may cause high latencies for a real-time process. Therefore, it is crucial not to invoke fork(2) after an mlockall() or mlock() operation โ€” not even from a thread which runs at a low priority within a process which also has a thread running at elevated priority. Like. Do not do it. Fr fr.

The memory lock on an address range is automatically removed if the address range is unmapped via munmap(2).

Memory locks do not stack. That is, pages which have been locked several times by calls to mlock(), mlock2(), or mlockall() will be unlocked by a single call to munlock() for the corresponding range or by munlockall(). Pages which are mapped to several locations or by several processes stay locked into RAM as long as they are locked at least at one location or by at least one process.

If a call to mlockall() which uses the MCL_FUTURE flag is followed by another call that does not specify this flag, the changes made by the MCL_FUTURE call will be lost. Gone. Poof. ๐Ÿ™ˆ

The mlock2() MLOCK_ONFAULT flag and the mlockall() MCL_ONFAULT flag allow efficient memory locking for applications that deal with large mappings where only a (small) portion of pages in the mapping are touched. In such cases, locking all of the pages in a mapping would incur a significant penalty for memory locking. So it's giving efficiency. ๐Ÿ”ฅ

๐Ÿ”‘ Limits and permissions

In Linux 2.6.8 and earlier, a process must be privileged (CAP_IPC_LOCK) in order to lock memory, and the RLIMIT_MEMLOCK soft resource limit defines a limit on how much memory the process may lock.

Since Linux 2.6.9, no limits are placed on the amount of memory that a privileged process can lock, and the RLIMIT_MEMLOCK soft resource limit instead defines a limit on how much memory an unprivileged process may lock.


~ to be continued, bestie โ€” part 2 is coming and it has even more lore ~ ๐ŸŽ€

๐Ÿ’€ BUGS ๐Ÿ’€

okay besties, story time, because the kernel was not giving for a while there. ๐Ÿ™ˆ

In Linux 4.8 and earlier, there was a bug in the kernel's accounting of locked memory for unprivileged processes (i.e., without CAP_IPC_LOCK), and the way it worked was: if the region you specified with addr and size overlapped an existing lock, then the already locked bytes in the overlapping region got counted twice when checking against the limit. not once. twice. double dipped. ๐Ÿ˜ญ

and like, that double accounting could incorrectly calculate a "total locked memory" value for the process that exceeded the RLIMIT_MEMLOCK limit, which meant mlock() and mlock2() would fail on requests that should have succeeded. so the kernel was out here rejecting your perfectly valid asks because its math was off. embarrassing for the kernel honestly.

โœจ this bug was fixed in Linux 4.9. so if you're on 4.9+, you're slaying. if you're on 4.8 or earlier, lowkey you're on your own. ๐Ÿ’…

In the Linux 2.4 series of kernels up to and including Linux 2.4.17, a bug caused the mlockall() MCL_FUTURE flag to be inherited across a fork(2). which, if you know anything about MCL_FUTURE, is not the vibe โ€” that flag is supposed to be about you, not your kids. ๐Ÿ™ˆ this was rectified in Linux 2.4.18. good.


And here's a fun one that's not a bug, it's just how it be since Linux 2.6.9: if a privileged process calls mlockall(MCL_FUTURE) and later drops privileges (loses the CAP_IPC_LOCK capability by, for example, setting its effective UID to a nonzero value), then subsequent memory allocations (e.g., mmap(2), brk(2)) will fail if the RLIMIT_MEMLOCK resource limit is encountered.

like. you gave up your superpowers and now the memory limit applies to you and it's like. yeah bestie that's how limits work. ๐Ÿซถ so keep that in mind if you're the "drop privileges after setup" girlie โ€” the lock doesn't expire, but your permission to ignore the limit absolutely does.


๐ŸŒˆ SEE ALSO ๐ŸŒˆ

the whole squad, go read these too, they're all iconic in their own way:


and that's the page, bestie!! ๐ŸŽ€ you made it to the end, that's main character energy fr fr. this was Linux man-pages 6.20, dated 2026-02-11, and it's the mlock(2) page โ€” go lock some memory, love you, bye!! ๐Ÿ’–โœจ๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from
  • arch rolling: man-pages 6.20-1 ยท BSD-2-Clause AND BSD-3-Clause AND BSD-4.3TAHOE AND BSD-4-Clause-UC AND GPL-1.0-or-later AND GPL-2.0-only AND GPL-2.0-or-later AND GPL-3.0-or-later AND LGPL-3.0-linking-exception AND LGPL-3.0-or-later AND LicenseRef-Public-Domain AND LicenseRef-UltraPermissive AND Linux-man-pages-1-para AND Linux-man-pages-copyleft AND Linux-man-pages-copyleft-2-para AND Linux-man-pages-copyleft-var AND MIT AND Spencer-94
  • nixpkgs unstable: man-pages 6.20
  • ๐Ÿ“œ the page's license: GPL-2.0-or-later
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms