madvise(2)

okay so bestie, sit DOWN, hydrate, and get comfy bc today's main character is madvise(2), straight out of the System Calls Manual, and she is genuinely one of the most underrated little syscalls in the whole lineup. it's giving "hey kernel, lemme give you a heads up about how I'm about to use this memory" energy and honestly? we're obsessed. ๐Ÿซถ

โœจ NAME โœจ

madvise โ€” give advice about use of memory ๐Ÿ’…

๐Ÿ“š LIBRARY ๐Ÿ“š

Standard C library (libc, -lc) ๐ŸŽ€

๐Ÿฆ‹ SYNOPSIS ๐Ÿฆ‹

#include <sys/mman.h>

int madvise(size_t size;
            void addr[size], size_t size, int advice);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

madvise():
    Since glibc 2.19:
        _DEFAULT_SOURCE
    Up to and including glibc 2.19:
        _BSD_SOURCE

๐Ÿ’– DESCRIPTION ๐Ÿ’–

so, the madvise() system call is how you pass advice or directions to the kernel about the address range that starts at the address addr and is size bytes long. bestie. bestie. it only ever operates on WHOLE pages, so addr must be page-aligned, no negotiating. and the size value gets rounded up to a multiple of the page size. the whole goal of all this advice-giving? in most cases it's to make the system or your app perform better. slay. โœจ

so initially this syscall supported a set of "conventional" advice values, and those are also available on several other implementations (quick note though: madvise() is not specified in POSIX, iykyk). and then later, a bunch of Linux-specific advice values got added to the lineup. ๐ŸŒˆ

๐ŸŒธ Conventional advice values ๐ŸŒธ

the advice values listed below let an application tell the kernel how it expects to use some mapped or shared memory areas, so the kernel can pick appropriate read-ahead and caching techniques. here's the tea: these advice values do not influence the semantics of the application (except in the case of MADV_DONTNEED), but they may influence its performance. all of the advice values listed right here have analogs in the POSIX-specified posix_madvise(3) function and the values mean the same thing โ€” with the exception of MADV_DONTNEED, which is the one doing its own thing. ๐Ÿ’…

the advice is indicated in the advice argument, and it's one of these:

  • MADV_NORMAL โ€” no special treatment at all. this is the default, the baseline, the no-makeup-makeup look. ๐Ÿ’…
  • MADV_RANDOM โ€” expect page references in random order. (so basically, read ahead may be less useful than it normally would be.) ๐ŸŽฒ
  • MADV_SEQUENTIAL โ€” expect page references in sequential order. (which means the pages in the given range can be aggressively read ahead, and they may be freed soon after they get accessed.) ๐Ÿƒโ€โ™€๏ธ
  • MADV_WILLNEED โ€” expect access in the near future. (so it might be a good idea to read some pages ahead, like a little pregame.) ๐Ÿ‘€
  • MADV_DONTNEED โ€” do not expect access in the near future. (for the time being the application is finished with the given range, so the kernel can free the resources associated with it.)

after a successful MADV_DONTNEED operation, the semantics of memory access in the specified region get changed: subsequent accesses of pages in the range will still succeed, but they result in either repopulating the memory contents from the up-to-date contents of the underlying mapped file (for shared file mappings, shared anonymous mappings, and shmem-based techniques such as System V shared memory segments) or zero-fill-on-demand pages for anonymous private mappings.

note that when MADV_DONTNEED is applied to shared mappings, it might NOT lead to immediate freeing of the pages in the range. the kernel is free to delay freeing the pages until an appropriate moment. the resident set size (RSS) of the calling process will be immediately reduced though. no cap. ๐Ÿ˜ค

MADV_DONTNEED cannot be applied to locked pages, or VM_PFNMAP pages. (pages marked with the kernel-internal VM_PFNMAP flag are special memory areas that are not managed by the virtual memory subsystem. such pages are typically created by device drivers that map the pages into user space.) ๐Ÿšซ

support for Huge TLB pages was added in Linux 5.18. addresses within a mapping backed by Huge TLB pages must be aligned to the underlying Huge TLB page size, and the range size is rounded up to a multiple of the underlying Huge TLB page size. ๐Ÿ“

๐Ÿฆ„ Linux-specific advice values ๐Ÿฆ„

the following Linux-specific advice values have no counterparts in the POSIX-specified posix_madvise(3), and they may or may not have counterparts in the madvise() interface available on other implementations. heads up tho: some of these operations change the semantics of memory accesses. โš ๏ธ

  • MADV_REMOVE (since Linux 2.6.16) โ€” free up a given range of pages and its associated backing store. this is equivalent to punching a hole in the corresponding range of the backing store (see fallocate(2)). subsequent accesses in the specified address range will see data with a value of zero. ๐Ÿ•ณ๏ธ

the specified address range must be mapped shared and writable. this flag cannot be applied to locked pages, or VM_PFNMAP pages.

in the initial implementation, only tmpfs(5) supported MADV_REMOVE; but since Linux 3.5, any filesystem which supports the fallocate(2) FALLOC_FL_PUNCH_HOLE mode also supports MADV_REMOVE. filesystems which do not support MADV_REMOVE fail with the error EOPNOTSUPP. ๐Ÿ’€

support for the Huge TLB filesystem was added in Linux 4.3. ๐ŸŽ‰

  • MADV_DONTFORK (since Linux 2.6.16) โ€” do not make the pages in this range available to the child after a fork(2). this is useful to prevent copy-on-write semantics from changing the physical location of a page if the parent writes to it after a fork(2). (such page relocations cause problems for hardware that DMAs into the page.) ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘ง no sharing, sorry not sorry.
  • MADV_DOFORK (since Linux 2.6.16) โ€” undo the effect of MADV_DONTFORK, restoring the default behavior, whereby a mapping is inherited across fork(2). we're back babes ๐Ÿซถ
  • MADV_HWPOISON (since Linux 2.6.32) โ€” poison the pages in the range specified by addr and size and handle subsequent references to those pages like a hardware memory corruption. this operation is available only for privileged (CAP_SYS_ADMIN) processes. this operation may result in the calling process receiving a SIGBUS and the page being unmapped. โ˜ ๏ธ

this feature is intended for testing of memory error-handling code; it is available only if the kernel was configured with CONFIG_MEMORY_FAILURE.

  • MADV_MERGEABLE (since Linux 2.6.32) โ€” enable Kernel Samepage Merging (KSM) for the pages in the range specified by addr and size. the kernel regularly scans those areas of user memory that have been marked as mergeable, looking for pages with identical content. these get replaced by a single write-protected page (which is automatically copied if a process later wants to update the content of the page). KSM merges only private anonymous pages (see mmap(2)). ๐Ÿงฌโœจ

the KSM feature is intended for applications that generate many instances of the same data (e.g., virtualization systems such as KVM). it can consume a LOT of processing power; use with care bestie, fr fr. see the Linux kernel source file Documentation/admin-guide/mm/ksm.rst for more details. ๐Ÿ“–

the MADV_MERGEABLE and MADV_UNMERGEABLE operations are available only if the kernel was configured with CONFIG_KSM.

  • MADV_UNMERGEABLE (since Linux 2.6.32) โ€” undo the effect of an earlier MADV_MERGEABLE operation on the specified address range; KSM unmerges whatever pages it had merged in the address range specified by addr and size. it's giving "actually, nevermind" ๐Ÿ’…
  • MADV_SOFT_OFFLINE (since Linux 2.6.33) โ€” soft offline the pages in the range specified by addr and size. the memory of each page in the specified range is preserved (i.e., when next accessed, the same content will be visible, but in a new physical page frame), and the original page is offlined (i.e., no longer used, and taken out of normal memory management). the effect of the MADV_SOFT_OFFLINE operation is invisible to (i.e., does not change the semantics of) the calling process. ๐Ÿซฅ

this feature is intended for testing of memory error-handling code; it is available only if the kernel was configured with CONFIG_MEMORY_FAILURE.

  • MADV_HUGEPAGE (since Linux 2.6.38) โ€” enable Transparent Huge Pages (THP) for pages in the range specified by addr and size. the kernel will regularly scan the areas marked as huge page candidates to replace them with huge pages. the kernel will also allocate huge pages directly when the region is naturally aligned to the huge page size (see posix_memalign(2)). ๐Ÿ˜

this feature is primarily aimed at applications that use large mappings of data and access large regions of that memory at a time (e.g., virtualization systems such as QEMU). it can very easily waste memory (e.g., a 2 MB mapping that only ever accesses 1 byte will result in 2 MB of wired memory instead of one 4 KB page). see the Linux kernel source file Documentation/admin-guide/mm/transhuge.rst for more details. ๐Ÿ˜ญ

most common kernel configurations provide MADV_HUGEPAGE-style behavior by default, and thus MADV_HUGEPAGE is normally not necessary. it is mostly intended for embedded systems, where MADV_HUGEPAGE-style behavior may not be enabled by default in the kernel. on such systems, this flag can be used in order to selectively enable THP. whenever MADV_HUGEPAGE is used, it should always be in regions of memory with an access pattern that the developer knows in advance won't risk increasing the memory footprint of the application when transparent hugepages are enabled. ๐Ÿง 

since Linux 5.4, automatic scan of eligible areas and replacement by huge pages works with private anonymous pages (see mmap(2)), shmem pages, and file-backed pages. for all memory types, memory may only be replaced by huge pages on hugepage-aligned boundaries. for file-mapped memory โ€”including tmpfs (see tmpfs(2))โ€” the mapping must also be naturally hugepage-aligned within the file. additionally, for file-backed, non-tmpfs memory, the file must not be open for write and the mapping must be executable. ๐Ÿ“

the VMA must not be marked VM_NOHUGEPAGE, VM_HUGETLB, VM_IO, VM_DONTEXPAND, VM_MIXEDMAP, or VM_PFNMAP, nor can it be stack memory or backed by a DAX-enabled device (unless the DAX device is hot-plugged as System RAM). the process can have PR_SET_THP_DISABLE set only if PR_THP_DISABLE_EXCEPT_ADVISED is set (see prctl(2)). ๐Ÿšซ


The MADV_HUGEPAGE, MADV_NOHUGEPAGE, and MADV_COLLAPSE operations are only available if the kernel was configured with CONFIG_TRANSPARENT_HUGEPAGE, and file/shmem memory is only supported if the kernel was configured with CONFIG_READ_ONLY_THP_FOR_FS. no config, no vibes, that's just how it is bestie ๐Ÿ’…

๐ŸŽ€ MADV_NOHUGEPAGE (since Linux 2.6.38)

Ensures that the memory in the address range given by addr and size will not be backed by transparent hugepages. that's the whole thing. it's the off switch ๐Ÿšซ

โœจ MADV_COLLAPSE (since Linux 6.1)

Does a best-effort synchronous collapse of the native pages mapped by the memory range into Transparent Huge Pages (THPs). MADV_COLLAPSE operates on the current state of memory of the calling process, and it makes no persistent changes or guarantees about how pages will be mapped, constructed, or faulted in the future. so like, it does the thing right now, it does not pinky-promise you anything about later ๐Ÿ™ˆ

MADV_COLLAPSE supports private anonymous pages (see mmap(2)), shmem pages, and file-backed pages. See MADV_HUGEPAGE for the general rundown on memory requirements for THP. If the range you hand it spans multiple VMAs, the semantics of the collapse over each VMA is independent from the others. And if collapsing one given huge page-aligned/sized region fails, the operation may still keep going and try to collapse whatever's left of the memory you specified. Oh, and it will automatically clamp the range you gave it so it's hugepage-aligned. she fixes your alignment for you, icon behavior โœจ

All non-resident pages covered by the range will first be swapped/faulted-in, before being copied onto a freshly allocated hugepage. If the native pages already compose the same PTE-mapped hugepage, and they're suitably aligned, then allocating a new hugepage may be elided and the collapse may happen in-place. Unmapped pages get their data directly initialized to 0 in the new hugepage. BUT โ€” and this is the catch โ€” for every eligible hugepage-aligned/sized region to be collapsed, at least one page must currently be backed by physical memory. not zero. one. minimum. ๐Ÿ˜ค

MADV_COLLAPSE is independent of any sysfs (see sysfs(5)) setting under /sys/kernel/mm/transparent_hugepage, both for determining THP eligibility and for allocation semantics. See the Linux kernel source file Documentation/admin-guide/mm/transhuge.rst for more info. MADV_COLLAPSE also ignores the huge= tmpfs mount option when it's operating on tmpfs files. Allocation for the new hugepage may enter direct reclaim and/or compaction, regardless of VMA flags (though VM_NOHUGEPAGE is still respected โ€” she's not that reckless). ๐Ÿ”ฅ

When the system has multiple NUMA nodes, the hugepage will be allocated from the node that's providing the most native pages. very "go where the people are" of her ๐Ÿซถ

If all hugepage-sized/aligned regions covered by the range you provided were either successfully collapsed, or were already PMD-mapped THPs, then this operation is deemed successful. Note that this doesn't guarantee anything about other possible mappings of the memory. And in the event that multiple hugepage-aligned/sized areas fail to collapse, only the most-recentlyโ€“failed code will be set in errno. yeah. just the last one. the earlier ones are lost to the group chat ๐Ÿ’€

๐Ÿ“ MADV_DONTDUMP (since Linux 3.4)

Excludes from a core dump those pages in the range specified by addr and size. This is handy for applications that have big areas of memory which are known not to be useful in a core dump โ€” you know, the ones that just make your core file enormous for no reason ๐Ÿ˜ญ The effect of MADV_DONTDUMP takes precedence over the bit mask that is set via the /proc/pid/coredump_filter file (see core(5)).

๐ŸŒธ MADV_DODUMP (since Linux 3.4)

Undoes the effect of an earlier MADV_DONTDUMP. the take-backsies operation ๐ŸŽ€

๐Ÿฆ‹ MADV_FREE (since Linux 4.5)

The application no longer requires the pages in the range specified by addr and size. So the kernel can free these pages, but the freeing could be delayed until memory pressure occurs. For each of the pages that has been marked to be freed but has not yet actually been freed, the free operation will be canceled if the caller writes into the page. So after a successful MADV_FREE operation, any stale data (i.e., dirty, unwritten pages) will be lost when the kernel frees the pages. However, subsequent writes to pages in the range will succeed, and then the kernel cannot free those dirtied pages โ€” so the caller can always see just-written data. If there is no subsequent write, the kernel can free the pages at any time. Once the pages in the range have been freed, the caller will see zero-fill-on-demand pages upon subsequent page references. very "you snooze you lose" but make it memory management ๐Ÿ˜Œ

The MADV_FREE operation can be applied only to private anonymous pages (see mmap(2)). Before Linux 4.12, when freeing pages on a swapless system, the pages in the given range are freed instantly, regardless of memory pressure. no chill pre-4.12, apparently ๐Ÿ’€

๐Ÿงš MADV_WIPEONFORK (since Linux 4.14)

Presents the child process with zero-filled memory in this range after a fork(2). This is super useful in forking servers to make sure that sensitive per-process data (for example, PRNG seeds, cryptographic secrets, and so on) is not handed to child processes. keep your secrets, babe ๐Ÿ”

The MADV_WIPEONFORK operation can be applied only to private anonymous pages (see mmap(2)).

Within the child created by fork(2), the MADV_WIPEONFORK setting remains in place on the specified address range. This setting is cleared during execve(2).

๐Ÿ‘‘ MADV_KEEPONFORK (since Linux 4.14)

Undoes the effect of an earlier MADV_WIPEONFORK.

๐Ÿ’œ MADV_COLD (since Linux 5.4)

Deactivates a given range of pages. This makes the pages a more probable reclaim target should there be memory pressure. It's a nondestructive operation, so you're not losing anything โ€” you're just moving these pages to the back of the line. And the advice might be ignored for some pages in the range when it isn't applicable. she's best-effort, not contractual ๐Ÿ’…

๐ŸŒˆ MADV_PAGEOUT (since Linux 5.4)

Reclaims a given range of pages. This is done to free up the memory occupied by these pages. If a page is anonymous, it will be swapped out. If a page is file-backed and dirty, it will be written back to the backing storage. The advice might be ignored for some pages in the range when it is not applicable.

โญ MADV_POPULATE_READ (since Linux 5.14)

Populates (prefaults) page tables readable, faulting in all pages in the range just as if you were manually reading from each page; however, it avoids the actual memory access that would have been performed after handling the fault. so the hypothetical read happens, the real read does not. very efficient of her ๐Ÿ’…

In contrast to MAP_POPULATE, MADV_POPULATE_READ does not hide errors, can be applied to (parts of) existing mappings, and will always populate (prefault) page tables readable. One example use case is prefaulting a file mapping and reading all the file content from disk; however, the pages won't be dirtied and consequently won't have to be written back to disk when evicting the pages from memory. ate, honestly ๐Ÿ”ฅ

Depending on the underlying mapping, this can map the shared zeropage, preallocate memory, or read the underlying file; files with holes might or might not preallocate blocks. If populating fails, a SIGBUS signal is not generated; instead, an error is returned. good news actually, no random signal jumpscare ๐Ÿซถ

If MADV_POPULATE_READ succeeds, all page tables have been populated (prefaulted) readable once. If MADV_POPULATE_READ fails, some page tables might have been populated. so it's a "no refunds, partial progress possible" kind of deal.

MADV_POPULATE_READ cannot be applied to mappings without read permissions and special mappings โ€” for example, mappings marked with kernel-internal flags such as VM_PFNMAP or VM_IO, or secret memory regions created using memfd_secret(2). not those, not ever ๐Ÿšซ

โš ๏ธ Note that with MADV_POPULATE_READ, the process can be killed at any moment when the system runs out of memory. like, literally any moment. bookmark that one bestie ๐Ÿ’€

๐ŸŒธ MADV_POPULATE_WRITE (since Linux 5.14)

Populates (prefaults) page tables writable, faulting in all pages in the range just as if you were manually writing to each page; however, it avoids the actual memory access that would have been performed after handling the fault.

In contrast to MAP_POPULATE, MADV_POPULATE_WRITE does not hide errors, can be applied to (parts of) existing mappings, and will always populate (prefault) page tables writable. One example use case is preallocating memory, breaking any CoW (Copy on Write). breaking up with CoW, respectfully ๐Ÿ’…

Depending on the underlying mapping, this can preallocate memory or read the underlying file; files with holes will preallocate blocks. If populating fails, a SIGBUS signal is not generated; instead, an error is returned.

If MADV_POPULATE_WRITE succeeds, all page tables have been populated (prefaulted) writable once. If MADV_POPULATE_WRITE fails, some page tables might have been populated.

MADV_POPULATE_WRITE cannot be applied to mappings without write permissions and special mappings โ€” for example, mappings marked with kernel-internal flags such as VM_PFNMAP or VM_IO, or secret memory regions created using memfd_secret(2).

โš ๏ธ Note that with MADV_POPULATE_WRITE, the process can be killed at any moment when the system runs out of memory. same warning, same drama ๐Ÿ˜ญ

๐Ÿ›ก๏ธ MADV_GUARD_INSTALL (since Linux 6.13)

Installs a lightweight guard region into the range specified by addr and size, causing any read or write in the range to result in a SIGSEGV signal being raised. it's a force field. a very official one ๐Ÿ›ก๏ธโœจ

If the region maps memory pages, those mappings will be replaced as part of the operation โ€” though if MADV_GUARD_INSTALL is applied to regions containing pre-existing lightweight guard regions, those are left in place. she doesn't touch the guard she already installed.

Prior to Linux 6.15, this operation was supported only for writable anonymous private mappings. Since Linux 6.15, both anonymous and file-backed mappings are supported, including read-only mappings. glow up ๐Ÿฆ‹

The mapping must not be mlock'd, must not map hugetlb ranges, and must not contain special mappings โ€” for example, mappings marked with kernel-internal flags such as VM_PFNMAP or VM_IO, or secret memory regions created using memfd_secret(2).

An EINVAL error is returned if it is attempted on any other kind of mapping. so rude of you tbh, she said no ๐Ÿšซ

This operation is more efficient than mapping a new region of memory PROT_NONE, since it does not require the establishment of new mappings. Instead, regions of an existing mapping simply have their page tables manipulated to establish the desired behavior. No additional memory is used. zero. none. iconic ๐Ÿ’…

Lightweight guard regions remain on fork (except for any parts which have had MADV_WIPEONFORK applied to them), and they are not removed by MADV_DONTNEED, MADV_FREE, MADV_PAGEOUT, or MADV_COLD. she's committed. she's not leaving just because you tried to page her out ๐Ÿ’œ

  • Trying to mlock(2) a lightweight guard region? nah, that fails. Same energy for MADV_POPULATE_READ and MADV_POPULATE_WRITE โ€” they will not work on them either. ๐Ÿ’€
  • If the mapping gets its attributes changed, or gets split, or is partially unmapped, any guard regions that already exist stay exactly where they are (unless they get unmapped, obviously).
  • If a mapping gets moved with mremap(2), the lightweight guard regions get moved right along with it. ride or die ๐Ÿซถ
  • Lightweight guard regions dip out when they get unmapped, when the process gets torn down, or when you hit them with the MADV_GUARD_REMOVE operation. โœจ

MADV_GUARD_REMOVE (since Linux 6.13)

Okay so this one removes any lightweight guard regions living in the range you gave with addr and size. ๐Ÿ‘‘

Everything else in the range โ€” like, all the mappings that are not lightweight guard regions โ€” gets left alone, untouched, unbothered. This operation works on the mappings that MADV_GUARD_INSTALL permits, plus mlock()'d mappings, and if it's not one of those it returns an EINVAL error instead.

So when lightweight guard regions get removed, they act like empty regions of the mapping they're inside. Which means: anonymous private mappings become zero-fill-on-demand pages ๐ŸŽ€, and file-backed mappings get repopulated with the memory contents from the up-to-date contents of the underlying mapped file.

And if the operation runs into any transparent huge pages? They just stay in place. not me, not my problem ๐Ÿ’…


โœจ RETURN VALUE โœจ

When it works, madvise() returns zero. ๐ŸŽ‰ When it doesn't, it returns -1 and errno gets set to say what went wrong.


๐Ÿ˜ญ ERRORS ๐Ÿ˜ญ

Bestie, here's the full rundown of every way this can go sideways:

  • EACCES โ€” advice is MADV_REMOVE, but the address range you specified isn't a shared writable mapping.
  • EAGAIN โ€” a kernel resource was, like, temporarily unavailable.
  • EBADF โ€” the map exists, but the area is mapping something that isn't a file.
  • EBUSY โ€” (for MADV_COLLAPSE) couldn't charge the hugepage to the cgroup, because the cgroup limit was exceeded.
  • EBUSY โ€” (for MADV_SOFT_OFFLINE) some pages within the specified address range couldn't be offlined. This can happen if the page is currently in use or locked.
  • EFAULT โ€” advice is MADV_POPULATE_READ or MADV_POPULATE_WRITE, and populating (prefaulting) the page tables failed because a SIGBUS would've been generated on actual memory access, and the reason is not a HW poisoned page (HW poisoned pages can, for example, be created using the MADV_HWPOISON flag described elsewhere in this page).
  • EINVAL โ€” addr is not page-aligned, or size is negative.
  • EINVAL โ€” advice is not a valid.
  • EINVAL โ€” advice is MADV_COLD or MADV_PAGEOUT, and the specified address range includes locked, Huge TLB pages, or VM_PFNMAP pages.
  • EINVAL โ€” advice is MADV_DONTNEED or MADV_REMOVE, and the specified address range includes locked, Huge TLB pages, or VM_PFNMAP pages.
  • EINVAL โ€” advice is MADV_MERGEABLE or MADV_UNMERGEABLE, but the kernel was not configured with CONFIG_KSM.
  • EINVAL โ€” advice is MADV_FREE or MADV_WIPEONFORK, but the specified address range includes file, Huge TLB, MAP_SHARED, or VM_PFNMAP ranges.
  • EINVAL โ€” advice is MADV_POPULATE_READ or MADV_POPULATE_WRITE, but the specified address range includes ranges with insufficient permissions or special mappings โ€” for example, mappings marked with kernel-internal flags such a VM_IO or VM_PFNMAP, or secret memory regions created using memfd_secret(2).
  • EINVAL โ€” advice is MADV_GUARD_INSTALL or MADV_GUARD_REMOVE, but the specified address range contains an unsupported mapping.
  • EIO โ€” (for MADV_WILLNEED) paging in this area would exceed the process's maximum resident set size.
  • ENOMEM โ€” (for MADV_WILLNEED) not enough memory: paging in failed.
  • ENOMEM โ€” (for MADV_COLLAPSE) not enough memory: could not allocate hugepage.
  • ENOMEM โ€” addresses in the specified range are not currently mapped, or they're outside the address space of the process.
  • ENOMEM โ€” advice is MADV_POPULATE_READ or MADV_POPULATE_WRITE, and populating (prefaulting) the page tables failed because there wasn't enough memory.
  • EPERM โ€” advice is MADV_HWPOISON, but the caller does not have the CAP_SYS_ADMIN capability.
  • EHWPOISON โ€” advice is MADV_POPULATE_READ or MADV_POPULATE_WRITE, and populating (prefaulting) the page tables failed because a HW poisoned page was encountered (HW poisoned pages can, for example, be created using the MADV_HWPOISON flag described elsewhere in this page).

๐ŸŒˆ VERSIONS ๐ŸŒˆ

Other implementations out here have versions of this syscall too, implementing a whole wide variety of advice values. Those other implementations typically implement at least the flags listed above under Conventional advice flags, even if the semantics wobble a little between them.

POSIX.1-2001 describes posix_madvise(3) with the constants POSIX_MADV_NORMAL, POSIX_MADV_RANDOM, POSIX_MADV_SEQUENTIAL, POSIX_MADV_WILLNEED, and POSIX_MADV_DONTNEED, and so on, and its behavior is close to the similarly named flags listed above. ๐Ÿ’ซ

๐Ÿง Linux ๐Ÿง

The Linux implementation requires that the address addr be page-aligned, and it allows size to be zero. And if some parts of the specified address range aren't mapped, the Linux version of madvise() just ignores them and applies the call to the rest โ€” but yeah, it still returns ENOMEM from the system call, as it should. ๐Ÿ™ƒ

And get this: madvise(0, 0, advice) will return zero if and only if advice is supported by the kernel โ€” so you can totally rely on it to probe for support. iconic. โญ


๐Ÿ“œ STANDARDS ๐Ÿ“œ

None. literally none. ๐Ÿ’€


๐Ÿ•ฐ๏ธ HISTORY ๐Ÿ•ฐ๏ธ

  • First appeared in 4.4BSD.
  • Since Linux 3.18, support for this system call is optional, and it depends on the setting of the CONFIG_ADVISE_SYSCALLS configuration option.

๐Ÿ‘€ SEE ALSO ๐Ÿ‘€

getrlimit(2), memfd_secret(2), mincore(2), mmap(2), mprotect(2), msync(2), munmap(2), prctl(2), process_madvise(2), posix_madvise(3), core(5) ๐Ÿฆ‹


okay that's the whole thing bestie, you made it to the end ๐ŸŽ€ this page is from Linux man-pages 6.20, dated 2026-02-08, and it's the madvise(2) page. go forth and advise your memory wisely, mwah ๐Ÿ’–

๐Ÿ“ฆ 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: Linux-man-pages-copyleft
  • ๐Ÿ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms