/*-1* SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)2*3* Copyright (c) 1991, 19934* The Regents of the University of California. All rights reserved.5*6* This code is derived from software contributed to Berkeley by7* The Mach Operating System project at Carnegie-Mellon University.8*9* Redistribution and use in source and binary forms, with or without10* modification, are permitted provided that the following conditions11* are met:12* 1. Redistributions of source code must retain the above copyright13* notice, this list of conditions and the following disclaimer.14* 2. Redistributions in binary form must reproduce the above copyright15* notice, this list of conditions and the following disclaimer in the16* documentation and/or other materials provided with the distribution.17* 3. Neither the name of the University nor the names of its contributors18* may be used to endorse or promote products derived from this software19* without specific prior written permission.20*21* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND22* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE23* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE24* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE25* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL26* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS27* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)28* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT29* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY30* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF31* SUCH DAMAGE.32*33*34* Copyright (c) 1987, 1990 Carnegie-Mellon University.35* All rights reserved.36*37* Authors: Avadis Tevanian, Jr., Michael Wayne Young38*39* Permission to use, copy, modify and distribute this software and40* its documentation is hereby granted, provided that both the copyright41* notice and this permission notice appear in all copies of the42* software, derivative works or modified versions, and any portions43* thereof, and that both notices appear in supporting documentation.44*45* CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"46* CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND47* FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.48*49* Carnegie Mellon requests users of this software to return to50*51* Software Distribution Coordinator or [email protected]52* School of Computer Science53* Carnegie Mellon University54* Pittsburgh PA 15213-389055*56* any improvements or extensions that they make and grant Carnegie the57* rights to redistribute these changes.58*/5960#ifndef _VM_PAGEQUEUE_61#define _VM_PAGEQUEUE_6263#ifdef _KERNEL64struct vm_pagequeue {65struct mtx pq_mutex;66struct pglist pq_pl;67int pq_cnt;68const char * const pq_name;69uint64_t pq_pdpages;70} __aligned(CACHE_LINE_SIZE);7172#if __SIZEOF_LONG__ == 873#define VM_BATCHQUEUE_SIZE 6374#else75#define VM_BATCHQUEUE_SIZE 1576#endif7778struct vm_batchqueue {79vm_page_t bq_pa[VM_BATCHQUEUE_SIZE];80int bq_cnt;81} __aligned(CACHE_LINE_SIZE);8283#include <vm/uma.h>84#include <sys/_blockcount.h>85#include <sys/pidctrl.h>86struct sysctl_oid;8788/*89* One vm_domain per NUMA domain. Contains pagequeues, free page structures,90* and accounting.91*92* Lock Key:93* f vmd_free_mtx94* p vmd_pageout_mtx95* d vm_domainset_lock96* a atomic97* c const after boot98* q page queue lock99*100* A unique page daemon thread manages each vm_domain structure and is101* responsible for ensuring that some free memory is available by freeing102* inactive pages and aging active pages. To decide how many pages to process,103* it uses thresholds derived from the number of pages in the domain:104*105* vmd_page_count106* ---107* |108* |-> vmd_inactive_target (~3%)109* | - The active queue scan target is given by110* | (vmd_inactive_target + vmd_free_target - vmd_free_count).111* |112* |113* |-> vmd_free_target (~2%)114* | - Target for page reclamation.115* |116* |-> vmd_pageout_wakeup_thresh (~1.8%)117* | - Threshold for waking up the page daemon.118* |119* |120* |-> vmd_free_min (~0.5%)121* | - First low memory threshold.122* | - Causes per-CPU caching to be lazily disabled in UMA.123* | - vm_wait() sleeps below this threshold.124* |125* |-> vmd_free_severe (~0.25%)126* | - Second low memory threshold.127* | - Triggers aggressive UMA reclamation, disables delayed buffer128* | writes.129* |130* |-> vmd_free_reserved (~0.13%)131* | - Minimum for VM_ALLOC_NORMAL page allocations.132* |-> vmd_pageout_free_min (32 + 2 pages)133* | - Minimum for waking a page daemon thread sleeping in vm_wait().134* |-> vmd_interrupt_free_min (2 pages)135* | - Minimum for VM_ALLOC_SYSTEM page allocations.136* ---137*138*--139* Free page count regulation:140*141* The page daemon attempts to ensure that the free page count is above the free142* target. It wakes up periodically (every 100ms) to input the current free143* page shortage (free_target - free_count) to a PID controller, which in144* response outputs the number of pages to attempt to reclaim. The shortage's145* current magnitude, rate of change, and cumulative value are together used to146* determine the controller's output. The page daemon target thus adapts147* dynamically to the system's demand for free pages, resulting in less148* burstiness than a simple hysteresis loop.149*150* When the free page count drops below the wakeup threshold,151* vm_domain_allocate() proactively wakes up the page daemon. This helps ensure152* that the system responds promptly to a large instantaneous free page153* shortage.154*155* The page daemon also attempts to ensure that some fraction of the system's156* memory is present in the inactive (I) and laundry (L) page queues, so that it157* can respond promptly to a sudden free page shortage. In particular, the page158* daemon thread aggressively scans active pages so long as the following159* condition holds:160*161* len(I) + len(L) + free_target - free_count < inactive_target162*163* Otherwise, when the inactive target is met, the page daemon periodically164* scans a small portion of the active queue in order to maintain up-to-date165* per-page access history. Unreferenced pages in the active queue thus166* eventually migrate to the inactive queue.167*168* The per-domain laundry thread periodically launders dirty pages based on the169* number of clean pages freed by the page daemon since the last laundering. If170* the page daemon fails to meet its scan target (i.e., the PID controller171* output) because of a shortage of clean inactive pages, the laundry thread172* attempts to launder enough pages to meet the free page target.173*174*--175* Page allocation priorities:176*177* The system defines three page allocation priorities: VM_ALLOC_NORMAL,178* VM_ALLOC_SYSTEM and VM_ALLOC_INTERRUPT. An interrupt-priority allocation can179* claim any free page. This priority is used in the pmap layer when attempting180* to allocate a page for the kernel page tables; in such cases an allocation181* failure will usually result in a kernel panic. The system priority is used182* for most other kernel memory allocations, for instance by UMA's slab183* allocator or the buffer cache. Such allocations will fail if the free count184* is below interrupt_free_min. All other allocations occur at the normal185* priority, which is typically used for allocation of user pages, for instance186* in the page fault handler or when allocating page table pages or pv_entry187* structures for user pmaps. Such allocations fail if the free count is below188* the free_reserved threshold.189*190*--191* Free memory shortages:192*193* The system uses the free_min and free_severe thresholds to apply194* back-pressure and give the page daemon a chance to recover. When a page195* allocation fails due to a shortage and the allocating thread cannot handle196* failure, it may call vm_wait() to sleep until free pages are available.197* vm_domain_freecnt_inc() wakes sleeping threads once the free page count rises198* above the free_min threshold; the page daemon and laundry threads are given199* priority and will wake up once free_count reaches the (much smaller)200* pageout_free_min threshold.201*202* On NUMA systems, the domainset iterators always prefer NUMA domains where the203* free page count is above the free_min threshold. This means that given the204* choice between two NUMA domains, one above the free_min threshold and one205* below, the former will be used to satisfy the allocation request regardless206* of the domain selection policy.207*208* In addition to reclaiming memory from the page queues, the vm_lowmem event209* fires every ten seconds so long as the system is under memory pressure (i.e.,210* vmd_free_count < vmd_free_target). This allows kernel subsystems to register211* for notifications of free page shortages, upon which they may shrink their212* caches. Following a vm_lowmem event, UMA's caches are pruned to ensure that213* they do not contain an excess of unused memory. When a domain is below the214* free_min threshold, UMA limits the population of per-CPU caches. When a215* domain falls below the free_severe threshold, UMA's caches are completely216* drained.217*218* If the system encounters a global memory shortage, it may resort to the219* out-of-memory (OOM) killer, which selects a process and delivers SIGKILL in a220* last-ditch attempt to free up some pages. Either of the two following221* conditions will activate the OOM killer:222*223* 1. The page daemons collectively fail to reclaim any pages during their224* inactive queue scans. After vm_pageout_oom_seq consecutive scans fail,225* the page daemon thread votes for an OOM kill, and an OOM kill is226* triggered when all page daemons have voted. This heuristic is strict and227* may fail to trigger even when the system is effectively deadlocked.228*229* 2. Threads in the user fault handler are repeatedly unable to make progress230* while allocating a page to satisfy the fault. After231* vm_pfault_oom_attempts page allocation failures with intervening232* vm_wait() calls, the faulting thread will trigger an OOM kill.233*/234struct vm_domain {235struct vm_pagequeue vmd_pagequeues[PQ_COUNT];236struct mtx_padalign vmd_free_mtx;237struct mtx_padalign vmd_pageout_mtx;238struct vm_pgcache {239int domain;240int pool;241uma_zone_t zone;242} vmd_pgcache[VM_NFREEPOOL];243struct vmem *vmd_kernel_arena; /* (c) per-domain kva R/W arena. */244struct vmem *vmd_kernel_rwx_arena; /* (c) per-domain kva R/W/X arena. */245struct vmem *vmd_kernel_nofree_arena; /* (c) per-domain kva NOFREE arena. */246u_int vmd_domain; /* (c) Domain number. */247u_int vmd_page_count; /* (c) Total page count. */248long vmd_segs; /* (c) bitmask of the segments */249struct pglist vmd_nofreeq; /* (f) NOFREE page bump allocator. */250u_int __aligned(CACHE_LINE_SIZE) vmd_free_count; /* (a,f) free page count */251u_int vmd_pageout_deficit; /* (a) Estimated number of pages deficit */252uint8_t vmd_pad[CACHE_LINE_SIZE - (sizeof(u_int) * 2)];253254/* Paging control variables, used within single threaded page daemon. */255struct pidctrl vmd_pid; /* Pageout controller. */256bool vmd_oom; /* An OOM kill was requested. */257bool vmd_helper_threads_enabled;/* Use multiple threads to scan. */258u_int vmd_inactive_threads; /* Number of extra helper threads. */259u_int vmd_inactive_shortage; /* Per-thread shortage. */260blockcount_t vmd_inactive_running; /* Number of inactive threads. */261blockcount_t vmd_inactive_starting; /* Number of threads started. */262u_int vmd_addl_shortage; /* (a) Shortage accumulator. */263u_int vmd_inactive_freed; /* (a) Successful inactive frees. */264u_int vmd_inactive_us; /* (a) Microseconds for above. */265u_int vmd_inactive_pps; /* Exponential decay frees/second. */266int vmd_oom_seq;267int vmd_last_active_scan;268struct vm_page vmd_markers[PQ_COUNT]; /* (q) markers for queue scans */269struct vm_page vmd_inacthead; /* marker for LRU-defeating insertions */270struct vm_page vmd_clock[2]; /* markers for active queue scan */271272int vmd_pageout_wanted; /* (a, p) pageout daemon wait channel */273int vmd_pageout_pages_needed; /* (d) page daemon waiting for pages? */274bool vmd_minset; /* (d) Are we in vm_min_domains? */275bool vmd_severeset; /* (d) Are we in vm_severe_domains? */276enum {277VM_LAUNDRY_IDLE = 0,278VM_LAUNDRY_BACKGROUND,279VM_LAUNDRY_SHORTFALL280} vmd_laundry_request;281282/* Paging thresholds and targets. */283u_int vmd_clean_pages_freed; /* (q) accumulator for laundry thread */284u_int vmd_background_launder_target; /* (c) */285u_int vmd_free_reserved; /* (c) pages reserved for deadlock */286u_int vmd_free_target; /* (c) pages desired free */287u_int vmd_free_min; /* (c) pages desired free */288u_int vmd_inactive_target; /* (c) pages desired inactive */289u_int vmd_pageout_free_min; /* (c) min pages reserved for kernel */290u_int vmd_pageout_wakeup_thresh;/* (c) min pages to wake pagedaemon */291u_int vmd_interrupt_free_min; /* (c) reserved pages for int code */292u_int vmd_free_severe; /* (c) severe page depletion point */293294/* Name for sysctl etc. */295struct sysctl_oid *vmd_oid;296char vmd_name[sizeof(__XSTRING(MAXMEMDOM))];297} __aligned(CACHE_LINE_SIZE);298299extern struct vm_domain vm_dom[MAXMEMDOM];300301#define VM_DOMAIN(n) (&vm_dom[(n)])302#define VM_DOMAIN_EMPTY(n) (vm_dom[(n)].vmd_page_count == 0)303304#define vm_pagequeue_assert_locked(pq) mtx_assert(&(pq)->pq_mutex, MA_OWNED)305#define vm_pagequeue_lock(pq) mtx_lock(&(pq)->pq_mutex)306#define vm_pagequeue_lockptr(pq) (&(pq)->pq_mutex)307#define vm_pagequeue_trylock(pq) mtx_trylock(&(pq)->pq_mutex)308#define vm_pagequeue_unlock(pq) mtx_unlock(&(pq)->pq_mutex)309310#define vm_domain_free_assert_locked(n) \311mtx_assert(vm_domain_free_lockptr((n)), MA_OWNED)312#define vm_domain_free_assert_unlocked(n) \313mtx_assert(vm_domain_free_lockptr((n)), MA_NOTOWNED)314#define vm_domain_free_lock(d) \315mtx_lock(vm_domain_free_lockptr((d)))316#define vm_domain_free_lockptr(d) \317(&(d)->vmd_free_mtx)318#define vm_domain_free_trylock(d) \319mtx_trylock(vm_domain_free_lockptr((d)))320#define vm_domain_free_unlock(d) \321mtx_unlock(vm_domain_free_lockptr((d)))322323#define vm_domain_pageout_lockptr(d) \324(&(d)->vmd_pageout_mtx)325#define vm_domain_pageout_assert_locked(n) \326mtx_assert(vm_domain_pageout_lockptr((n)), MA_OWNED)327#define vm_domain_pageout_assert_unlocked(n) \328mtx_assert(vm_domain_pageout_lockptr((n)), MA_NOTOWNED)329#define vm_domain_pageout_lock(d) \330mtx_lock(vm_domain_pageout_lockptr((d)))331#define vm_domain_pageout_unlock(d) \332mtx_unlock(vm_domain_pageout_lockptr((d)))333334static __inline void335vm_pagequeue_cnt_add(struct vm_pagequeue *pq, int addend)336{337338vm_pagequeue_assert_locked(pq);339pq->pq_cnt += addend;340}341#define vm_pagequeue_cnt_inc(pq) vm_pagequeue_cnt_add((pq), 1)342#define vm_pagequeue_cnt_dec(pq) vm_pagequeue_cnt_add((pq), -1)343344static inline void345vm_pagequeue_remove(struct vm_pagequeue *pq, vm_page_t m)346{347348TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);349vm_pagequeue_cnt_dec(pq);350}351352static inline void353vm_batchqueue_init(struct vm_batchqueue *bq)354{355356bq->bq_cnt = 0;357}358359static inline bool360vm_batchqueue_empty(const struct vm_batchqueue *bq)361{362return (bq->bq_cnt == 0);363}364365static inline int366vm_batchqueue_insert(struct vm_batchqueue *bq, vm_page_t m)367{368int slots_free;369370slots_free = nitems(bq->bq_pa) - bq->bq_cnt;371if (slots_free > 0) {372bq->bq_pa[bq->bq_cnt++] = m;373return (slots_free);374}375return (slots_free);376}377378static inline vm_page_t379vm_batchqueue_pop(struct vm_batchqueue *bq)380{381382if (bq->bq_cnt == 0)383return (NULL);384return (bq->bq_pa[--bq->bq_cnt]);385}386387void vm_domain_set(struct vm_domain *vmd);388void vm_domain_clear(struct vm_domain *vmd);389int vm_domain_allocate(struct vm_domain *vmd, int req, int npages);390391/*392* vm_pagequeue_domain:393*394* Return the memory domain the page belongs to.395*/396static inline struct vm_domain *397vm_pagequeue_domain(vm_page_t m)398{399400return (VM_DOMAIN(vm_page_domain(m)));401}402403/*404* Return the number of pages we need to free-up or cache405* A positive number indicates that we do not have enough free pages.406*/407static inline int408vm_paging_target(struct vm_domain *vmd)409{410411return (vmd->vmd_free_target - vmd->vmd_free_count);412}413414/*415* Returns TRUE if the pagedaemon needs to be woken up.416*/417static inline int418vm_paging_needed(struct vm_domain *vmd, u_int free_count)419{420421return (free_count < vmd->vmd_pageout_wakeup_thresh);422}423424/*425* Returns TRUE if the domain is below the min paging target.426*/427static inline int428vm_paging_min(struct vm_domain *vmd)429{430431return (vmd->vmd_free_min > vmd->vmd_free_count);432}433434/*435* Returns TRUE if the domain is below the severe paging target.436*/437static inline int438vm_paging_severe(struct vm_domain *vmd)439{440441return (vmd->vmd_free_severe > vmd->vmd_free_count);442}443444/*445* Return the number of pages we need to launder.446* A positive number indicates that we have a shortfall of clean pages.447*/448static inline int449vm_laundry_target(struct vm_domain *vmd)450{451452return (vm_paging_target(vmd));453}454455void pagedaemon_wakeup(int domain);456457static inline void458vm_domain_freecnt_inc(struct vm_domain *vmd, int adj)459{460u_int old, new;461462old = atomic_fetchadd_int(&vmd->vmd_free_count, adj);463new = old + adj;464/*465* Only update bitsets on transitions. Notice we short-circuit the466* rest of the checks if we're above min already.467*/468if (old < vmd->vmd_free_min && (new >= vmd->vmd_free_min ||469(old < vmd->vmd_free_severe && new >= vmd->vmd_free_severe) ||470(old < vmd->vmd_pageout_free_min &&471new >= vmd->vmd_pageout_free_min)))472vm_domain_clear(vmd);473}474475#endif /* _KERNEL */476#endif /* !_VM_PAGEQUEUE_ */477478479