Unevictable LRU Infrastructure

Introduction

This document describes the Linux memory manager’s “Unevictable LRU”infrastructure and the use of this to manage several types of “unevictable”folios.

The document attempts to provide the overall rationale behind this mechanismand the rationale for some of the design decisions that drove theimplementation. The latter design rationale is discussed in the context of animplementation description. Admittedly, one can obtain the implementationdetails - the “what does it do?” - by reading the code. One hopes that thedescriptions below add value by provide the answer to “why does it do that?”.

The Unevictable LRU

The Unevictable LRU facility adds an additional LRU list to track unevictablefolios and to hide these folios from vmscan. This mechanism is based on a patchby Larry Woodman of Red Hat to address several scalability problems with folioreclaim in Linux. The problems have been observed at customer sites on largememory x86_64 systems.

To illustrate this with an example, a non-NUMA x86_64 platform with 128GB ofmain memory will have over 32 million 4k pages in a single node. When a largefraction of these pages are not evictable for any reason [see below], vmscanwill spend a lot of time scanning the LRU lists looking for the small fractionof pages that are evictable. This can result in a situation where all CPUs arespending 100% of their time in vmscan for hours or days on end, with the systemcompletely unresponsive.

The unevictable list addresses the following classes of unevictable pages:

  • Those owned by ramfs.

  • Those owned by tmpfs with the noswap mount option.

  • Those mapped into SHM_LOCK’d shared memory regions.

  • Those mapped into VM_LOCKED [mlock()ed] VMAs.

The infrastructure may also be able to handle other conditions that make pagesunevictable, either by definition or by circumstance, in the future.

The Unevictable LRU Folio List

The Unevictable LRU folio list is a lie. It was never an LRU-orderedlist, but a companion to the LRU-ordered anonymous and file, active andinactive folio lists; and now it is not even a folio list. But followingfamiliar convention, here in this document and in the source, we oftenimagine it as a fifth LRU folio list.

The Unevictable LRU infrastructure consists of an additional, per-node, LRU listcalled the “unevictable” list and an associated folio flag, PG_unevictable, toindicate that the folio is being managed on the unevictable list.

The PG_unevictable flag is analogous to, and mutually exclusive with, thePG_active flag in that it indicates on which LRU list a folio resides whenPG_lru is set.

The Unevictable LRU infrastructure maintains unevictable folios as if they wereon an additional LRU list for a few reasons:

  1. We get to “treat unevictable folios just like we treat other folios in thesystem - which means we get to use the same code to manipulate them, thesame code to isolate them (for migrate, etc.), the same code to keep trackof the statistics, etc...” [Rik van Riel]

  2. We want to be able to migrate unevictable folios between nodes for memorydefragmentation, workload management and memory hotplug. The Linux kernelcan only migrate folios that it can successfully isolate from the LRUlists (or “Movable” folios: outside of consideration here). If we were tomaintain folios elsewhere than on an LRU-like list, where they can bedetected byfolio_isolate_lru(), we would prevent their migration.

The unevictable list does not differentiate between file-backed andanonymous, swap-backed folios. This differentiation is only importantwhile the folios are, in fact, evictable.

The unevictable list benefits from the “arrayification” of the per-node LRUlists and statistics originally proposed and posted by Christoph Lameter.

Memory Control Group Interaction

The unevictable LRU facility interacts with the memory control group [akamemory controller; seeMemory Resource Controller] byextending the lru_list enum.

The memory controller data structure automatically gets a per-node unevictablelist as a result of the “arrayification” of the per-node LRU lists (one perlru_listenumelement). The memory controller tracks the movement of pages toand from the unevictable list.

When a memory control group comes under memory pressure, the controller willnot attempt to reclaim pages on the unevictable list. This has a couple ofeffects:

  1. Because the pages are “hidden” from reclaim on the unevictable list, thereclaim process can be more efficient, dealing only with pages that have achance of being reclaimed.

  2. On the other hand, if too many of the pages charged to the control groupare unevictable, the evictable portion of the working set of the tasks inthe control group may not fit into the available memory. This can causethe control group to thrash or to OOM-kill tasks.

Marking Address Spaces Unevictable

For facilities such as ramfs none of the pages attached to the address spacemay be evicted. To prevent eviction of any such pages, the AS_UNEVICTABLEaddress space flag is provided, and this can be manipulated by a filesystemusing a number of wrapper functions:

  • voidmapping_set_unevictable(structaddress_space*mapping);

    Mark the address space as being completely unevictable.

  • voidmapping_clear_unevictable(structaddress_space*mapping);

    Mark the address space as being evictable.

  • intmapping_unevictable(structaddress_space*mapping);

    Query the address space, and return true if it is completelyunevictable.

These are currently used in three places in the kernel:

  1. By ramfs to mark the address spaces of its inodes when they are created,and this mark remains for the life of the inode.

  2. By SYSV SHM to mark SHM_LOCK’d address spaces until SHM_UNLOCK is called.Note that SHM_LOCK is not required to page in the locked pages if they’reswapped out; the application must touch the pages manually if it wants toensure they’re in memory.

  3. By the i915 driver to mark pinned address space until it’s unpinned. Theamount of unevictable memory marked by i915 driver is roughly the boundedobject size in debugfs/dri/0/i915_gem_objects.

Detecting Unevictable Pages

The functionfolio_evictable() in mm/internal.h determines whether a folio isevictable or not using the query function outlined above [see sectionMarking address spaces unevictable]to check the AS_UNEVICTABLE flag.

For address spaces that are so marked after being populated (as SHM regionsmight be), the lock action (e.g. SHM_LOCK) can be lazy, and need not populatethe page tables for the region as does, for example,mlock(), nor need it makeany special effort to push any pages in the SHM_LOCK’d area to the unevictablelist. Instead, vmscan will do this if and when it encounters the folios duringa reclamation scan.

On an unlock action (such as SHM_UNLOCK), the unlocker (e.g.shmctl()) must scanthe pages in the region and “rescue” them from the unevictable list if no othercondition is keeping them unevictable. If an unevictable region is destroyed,the pages are also “rescued” from the unevictable list in the process offreeing them.

folio_evictable() also checks for mlocked folios by callingfolio_test_mlocked(), which is set when a folio is faulted into aVM_LOCKED VMA, or found in a VMA being VM_LOCKED.

Vmscan’s Handling of Unevictable Folios

If unevictable folios are culled in the fault path, or moved to the unevictablelist atmlock() or mmap() time, vmscan will not encounter the folios until theyhave become evictable again (viamunlock() for example) and have been “rescued”from the unevictable list. However, there may be situations where we decide,for the sake of expediency, to leave an unevictable folio on one of the regularactive/inactive LRU lists for vmscan to deal with. vmscan checks for suchfolios in all of the shrink_{active|inactive|folio}_list() functions and will“cull” such folios that it encounters: that is, it diverts those folios to theunevictable list for the memory cgroup and node being scanned.

There may be situations where a folio is mapped into a VM_LOCKED VMA,but the folio does not have the mlocked flag set. Such folios will makeit all the way toshrink_active_list() orshrink_folio_list() where theywill be detected when vmscan walks the reverse map infolio_referenced()ortry_to_unmap(). The folio is culled to the unevictable list when itis released by the shrinker.

To “cull” an unevictable folio, vmscan simply puts the folio back onthe LRU list usingfolio_putback_lru() - the inverse operation tofolio_isolate_lru() - after dropping the folio lock. Because thecondition which makes the folio unevictable may change once the foliois unlocked,__pagevec_lru_add_fn() will recheck the unevictable stateof a folio before placing it on the unevictable list.

MLOCKED Pages

The unevictable folio list is also useful formlock(), in addition to ramfs andSYSV SHM. Note thatmlock() is only available in CONFIG_MMU=y situations; inNOMMU situations, all mappings are effectively mlocked.

History

The “Unevictable mlocked Pages” infrastructure is based on work originallyposted by Nick Piggin in an RFC patch entitled “mm: mlocked pages off LRU”.Nick posted his patch as an alternative to a patch posted by Christoph Lameterto achieve the same objective: hiding mlocked pages from vmscan.

In Nick’s patch, he used one of thestructpage LRU list link fields as a countof VM_LOCKED VMAs that map the page (Rik van Riel had the same idea three yearsearlier). But this use of the link field for a count prevented the managementof the pages on an LRU list, and thus mlocked pages were not migratable asfolio_isolate_lru() could not detect them, and the LRU list link field was notavailable to the migration subsystem.

Nick resolved this by putting mlocked pages back on the LRU list beforeattempting to isolate them, thus abandoning the count of VM_LOCKED VMAs. WhenNick’s patch was integrated with the Unevictable LRU work, the count wasreplaced by walking the reverse map when munlocking, to determine whether anyother VM_LOCKED VMAs still mapped the page.

However, walking the reverse map for each page when munlocking was ugly andinefficient, and could lead to catastrophic contention on a file’s rmap lock,when many processes which had it mlocked were trying to exit. In 5.18, theidea of keeping mlock_count in Unevictable LRU list link field was revived andput to work, without preventing the migration of mlocked pages. This is whythe “Unevictable LRU list” cannot be a linked list of pages now; but there wasno use for that linked list anyway - though its size is maintained for meminfo.

Basic Management

mlocked pages - pages mapped into a VM_LOCKED VMA - are a class of unevictablepages. When such a page has been “noticed” by the memory management subsystem,the folio is marked with the PG_mlocked flag. This can be manipulated usingfolio_set_mlocked() andfolio_clear_mlocked() functions.

A PG_mlocked page will be placed on the unevictable list when it is added tothe LRU. Such pages can be “noticed” by memory management in several places:

  1. in themlock()/mlock2()/mlockall() system call handlers;

  2. in the mmap() system call handler when mmapping a region with theMAP_LOCKED flag;

  3. mmapping a region in a task that has calledmlockall() with the MCL_FUTUREflag;

  4. in the fault path and when a VM_LOCKED stack segment is expanded; or

  5. as mentioned above, in vmscan:shrink_folio_list() when attempting toreclaim a page in a VM_LOCKED VMA byfolio_referenced() ortry_to_unmap().

mlocked pages become unlocked and rescued from the unevictable list when:

  1. mapped in a range unlocked via themunlock()/munlockall() system calls;

  2. munmap()’d out of the last VM_LOCKED VMA that maps the page, includingunmapping at task exit;

  3. when the page is truncated from the last VM_LOCKED VMA of an mmapped file;or

  4. before a page is COW’d in a VM_LOCKED VMA.

mlock()/mlock2()/mlockall() System Call Handling

mlock(),mlock2() andmlockall() system call handlers proceed tomlock_fixup()for each VMA in the range specified by the call. In the case ofmlockall(),this is the entire active address space of the task. Note thatmlock_fixup()is used for both mlocking and munlocking a range of memory. A call tomlock()an already VM_LOCKED VMA, or tomunlock() a VMA that is not VM_LOCKED, istreated as a no-op andmlock_fixup() simply returns.

If the VMA passes some filtering as described in “Filtering Special VMAs”below,mlock_fixup() will attempt to merge the VMA with its neighbors or splitoff a subset of the VMA if the range does not cover the entire VMA. Any pagesalready present in the VMA are then marked as mlocked bymlock_folio() viamlock_pte_range() viawalk_page_range() viamlock_vma_pages_range().

Before returning from the system call,do_mlock() ormlockall() will call__mm_populate() to fault in the remaining pages viaget_user_pages() and tomark those pages as mlocked as they are faulted.

Note that the VMA being mlocked might be mapped with PROT_NONE. In this case,get_user_pages() will be unable to fault in the pages. That’s okay. If pagesdo end up getting faulted into this VM_LOCKED VMA, they will be handled in thefault path - which is also howmlock2()’s MLOCK_ONFAULT areas are handled.

For each PTE (or PMD) being faulted into a VMA, the page add rmap functioncallsmlock_vma_folio(), which callsmlock_folio() when the VMA is VM_LOCKED(unless it is a PTE mapping of a part of a transparent huge page). Or whenit is a newly allocated anonymous page,folio_add_lru_vma() callsmlock_new_folio() instead: similar tomlock_folio(), but can make betterjudgments, since this page is held exclusively and known not to be on LRU yet.

mlock_folio() sets PG_mlocked immediately, then places the page on the CPU’smlock folio batch, to batch up the rest of the work to be done under lru_lock by__mlock_folio().__mlock_folio() sets PG_unevictable, initializes mlock_countand moves the page to unevictable state (“the unevictable LRU”, but withmlock_count in place of LRU threading). Or if the page was already PG_lruand PG_unevictable and PG_mlocked, it simply increments the mlock_count.

But in practice that may not work ideally: the page may not yet be on an LRU, orit may have been temporarily isolated from LRU. In such cases the mlock_countfield cannot be touched, but will be set to 0 later when__munlock_folio()returns the page to “LRU”. Races prohibit mlock_count from being set to 1 then:rather than risk stranding a page indefinitely as unevictable, always err withmlock_count on the low side, so that when munlocked the page will be rescued toan evictable LRU, then perhaps be mlocked again later if vmscan finds it in aVM_LOCKED VMA.

Filtering Special VMAs

mlock_fixup() filters several classes of “special” VMAs:

  1. VMAs with VM_IO or VM_PFNMAP set are skipped entirely. The pages behindthese mappings are inherently pinned, so we don’t need to mark them asmlocked. In any case, most of the pages have nostructpage in which to somark the page. Because of this,get_user_pages() will fail for these VMAs,so there is no sense in attempting to visit them.

  2. VMAs mapping hugetlbfs page are already effectively pinned into memory. Weneither need nor want tomlock() these pages. But__mm_populate() includeshugetlbfs ranges, allocating the huge pages and populating the PTEs.

  3. VMAs with VM_DONTEXPAND are generally userspace mappings of kernel pages,such as the VDSO page, relay channel pages, etc. These pages are inherentlyunevictable and are not managed on the LRU lists.__mm_populate() includesthese ranges, populating the PTEs if not already populated.

  4. VMAs with VM_MIXEDMAP set are not marked VM_LOCKED, but__mm_populate()includes these ranges, populating the PTEs if not already populated.

Note that for all of these special VMAs,mlock_fixup() does not set theVM_LOCKED flag. Therefore, we won’t have to deal with them later duringmunlock(),munmap() or task exit. Neither doesmlock_fixup() account theseVMAs against the task’s “locked_vm”.

munlock()/munlockall() System Call Handling

Themunlock() andmunlockall() system calls are handled by the samemlock_fixup() function asmlock(),mlock2() andmlockall() system calls are.If called to munlock an already munlocked VMA,mlock_fixup() simply returns.Because of the VMA filtering discussed above, VM_LOCKED will not be set inany “special” VMAs. So, those VMAs will be ignored for munlock.

If the VMA is VM_LOCKED,mlock_fixup() again attempts to merge or split off thespecified range. All pages in the VMA are then munlocked bymunlock_folio() viamlock_pte_range() viawalk_page_range() viamlock_vma_pages_range() - the samefunction used when mlocking a VMA range, with new flags for the VMA indicatingthat it ismunlock() being performed.

munlock_folio() uses the mlock pagevec to batch up work to be doneunder lru_lock by__munlock_folio().__munlock_folio() decrements thefolio’s mlock_count, and when that reaches 0 it clears the mlocked flagand clears the unevictable flag, moving the folio from unevictable stateto the inactive LRU.

But in practice that may not work ideally: the folio may not yet have reached“the unevictable LRU”, or it may have been temporarily isolated from it. Inthose cases its mlock_count field is unusable and must be assumed to be 0: sothat the folio will be rescued to an evictable LRU, then perhaps be mlockedagain later if vmscan finds it in a VM_LOCKED VMA.

Migrating MLOCKED Pages

A page that is being migrated has been isolated from the LRU lists and is heldlocked across unmapping of the page, updating the page’s address space entryand copying the contents and state, until the page table entry has beenreplaced with an entry that refers to the new page. Linux supports migrationof mlocked pages and other unevictable pages. PG_mlocked is cleared from thethe old page when it is unmapped from the last VM_LOCKED VMA, and set when thenew page is mapped in place of migration entry in a VM_LOCKED VMA. If the pagewas unevictable because mlocked, PG_unevictable follows PG_mlocked; but if thepage was unevictable for other reasons, PG_unevictable is copied explicitly.

Note that page migration can race with mlocking or munlocking of the same page.There is mostly no problem since page migration requires unmapping all PTEs ofthe old page (including munlock where VM_LOCKED), then mapping in the new page(including mlock where VM_LOCKED). The page table locks provide sufficientsynchronization.

However, sincemlock_vma_pages_range() starts by setting VM_LOCKED on a VMA,before mlocking any pages already present, if one of those pages were migratedbeforemlock_pte_range() reached it, it would get counted twice in mlock_count.To prevent that,mlock_vma_pages_range() temporarily marks the VMA as VM_IO,so thatmlock_vma_folio() will skip it.

To complete page migration, we place the old and new pages back onto the LRUafterwards. The “unneeded” page - old page on success, new page on failure -is freed when the reference count held by the migration process is released.

Compacting MLOCKED Pages

The memory map can be scanned for compactable regions and the default behavioris to let unevictable pages be moved. /proc/sys/vm/compact_unevictable_allowedcontrols this behavior (seeDocumentation for /proc/sys/vm/). The workof compaction is mostly handled by the page migration code and the same workflow as described in Migrating MLOCKED Pages will apply.

MLOCKING Transparent Huge Pages

A transparent huge page is represented by a single entry on an LRU list.Therefore, we can only make unevictable an entire compound page, notindividual subpages.

If a user tries tomlock() part of a huge page, and no usermlock()s thewhole of the huge page, we want the rest of the page to be reclaimable.

We cannot just split the page on partialmlock() assplit_huge_page() canfail and a new intermittent failure mode for the syscall is undesirable.

We handle this by keeping PTE-mlocked huge pages on evictable LRU lists:the PMD on the border of a VM_LOCKED VMA will be split into a PTE table.

This way the huge page is accessible for vmscan. Under memory pressure thepage will be split, subpages which belong to VM_LOCKED VMAs will be movedto the unevictable LRU and the rest can be reclaimed.

/proc/meminfo’s Unevictable and Mlocked amounts do not include those partsof a transparent huge page which are mapped only by PTEs in VM_LOCKED VMAs.

mmap(MAP_LOCKED) System Call Handling

In addition to themlock(),mlock2() andmlockall() system calls, an applicationcan request that a region of memory be mlocked by supplying the MAP_LOCKED flagto the mmap() call. There is one important and subtle difference here, though.mmap() +mlock() will fail if the range cannot be faulted in (e.g. becausemm_populate fails) and returns with ENOMEM while mmap(MAP_LOCKED) will not fail.The mmapped area will still have properties of the locked area - pages will notget swapped out - but major page faults to fault memory in might still happen.

Furthermore, any mmap() call orbrk() call that expands the heap by a taskthat has previously calledmlockall() with the MCL_FUTURE flag will resultin the newly mapped memory being mlocked. Before the unevictable/mlockchanges, the kernel simply calledmake_pages_present() to allocate pagesand populate the page table.

To mlock a range of memory under the unevictable/mlock infrastructure,the mmap() handler and task address space expansion functions callpopulate_vma_page_range() specifying the vma and the address range to mlock.

munmap()/exit()/exec() System Call Handling

When unmapping an mlocked region of memory, whether by an explicit call tomunmap() or via an internal unmap fromexit() orexec() processing, we mustmunlock the pages if we’re removing the last VM_LOCKED VMA that maps the pages.Before the unevictable/mlock changes, mlocking did not mark the pages in anyway, so unmapping them required no processing.

For each PTE (or PMD) being unmapped from a VMA, folio_remove_rmap_*() callsmunlock_vma_folio(), which callsmunlock_folio() when the VMA is VM_LOCKED(unless it was a PTE mapping of a part of a transparent huge page).

munlock_folio() uses the mlock pagevec to batch up work to be doneunder lru_lock by__munlock_folio().__munlock_folio() decrements thefolio’s mlock_count, and when that reaches 0 it clears the mlocked flagand clears the unevictable flag, moving the folio from unevictable stateto the inactive LRU.

But in practice that may not work ideally: the folio may not yet have reached“the unevictable LRU”, or it may have been temporarily isolated from it. Inthose cases its mlock_count field is unusable and must be assumed to be 0: sothat the folio will be rescued to an evictable LRU, then perhaps be mlockedagain later if vmscan finds it in a VM_LOCKED VMA.

Truncating MLOCKED Pages

File truncation or hole punching forcibly unmaps the deleted pages fromuserspace; truncation even unmaps and deletes any private anonymous pageswhich had been Copied-On-Write from the file pages now being truncated.

Mlocked pages can be munlocked and deleted in this way: like withmunmap(),for each PTE (or PMD) being unmapped from a VMA, folio_remove_rmap_*() callsmunlock_vma_folio(), which callsmunlock_folio() when the VMA is VM_LOCKED(unless it was a PTE mapping of a part of a transparent huge page).

However, if there is a racingmunlock(), sincemlock_vma_pages_range() startsmunlocking by clearing VM_LOCKED from a VMA, before munlocking all the pagespresent, if one of those pages were unmapped by truncation or hole punch beforemlock_pte_range() reached it, it would not be recognized as mlocked by this VMA,and would not be counted out of mlock_count. In this rare case, a page maystill appear as PG_mlocked after it has been fully unmapped: and it is left torelease_pages() (or__page_cache_release()) to clear it and update statisticsbefore freeing (this event is counted in /proc/vmstat unevictable_pgs_cleared,which is usually 0).

Page Reclaim in shrink_*_list()

vmscan’sshrink_active_list() culls any obviously unevictable pages -i.e. !page_evictable(page) pages - diverting those to the unevictable list.However,shrink_active_list() only sees unevictable pages that made it onto theactive/inactive LRU lists. Note that these pages do not have PG_unevictableset - otherwise they would be on the unevictable list andshrink_active_list()would never see them.

Some examples of these unevictable pages on the LRU lists are:

  1. ramfs pages that have been placed on the LRU lists when first allocated.

  2. SHM_LOCK’d shared memory pages. shmctl(SHM_LOCK) does not attempt toallocate or fault in the pages in the shared memory region. This happenswhen an application accesses the page the first time after SHM_LOCK’ingthe segment.

  3. pages still mapped into VM_LOCKED VMAs, which should be marked mlocked,but events left mlock_count too low, so they were munlocked too early.

vmscan’sshrink_inactive_list() andshrink_folio_list() also divert obviouslyunevictable pages found on the inactive lists to the appropriate memory cgroupand node unevictable list.

rmap’sfolio_referenced_one(), called via vmscan’sshrink_active_list() orshrink_folio_list(), and rmap’stry_to_unmap_one() called viashrink_folio_list(),check for (3) pages still mapped into VM_LOCKED VMAs, and callmlock_vma_folio()to correct them. Such pages are culled to the unevictable list when releasedby the shrinker.