Home | History | Annotate | Line # | Download | only in uvm
      1 /*	$NetBSD: uvm_pdaemon.c,v 1.141 2026/08/23 22:08:41 riastradh Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997 Charles D. Cranor and Washington University.
      5  * Copyright (c) 1991, 1993, The Regents of the University of California.
      6  *
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * The Mach Operating System project at Carnegie-Mellon University.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  *
     36  *	@(#)vm_pageout.c        8.5 (Berkeley) 2/14/94
     37  * from: Id: uvm_pdaemon.c,v 1.1.2.32 1998/02/06 05:26:30 chs Exp
     38  *
     39  *
     40  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
     41  * All rights reserved.
     42  *
     43  * Permission to use, copy, modify and distribute this software and
     44  * its documentation is hereby granted, provided that both the copyright
     45  * notice and this permission notice appear in all copies of the
     46  * software, derivative works or modified versions, and any portions
     47  * thereof, and that both notices appear in supporting documentation.
     48  *
     49  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     50  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
     51  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     52  *
     53  * Carnegie Mellon requests users of this software to return to
     54  *
     55  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     56  *  School of Computer Science
     57  *  Carnegie Mellon University
     58  *  Pittsburgh PA 15213-3890
     59  *
     60  * any improvements or extensions that they make and grant Carnegie the
     61  * rights to redistribute these changes.
     62  */
     63 
     64 /*
     65  * uvm_pdaemon.c: the page daemon
     66  */
     67 
     68 #include <sys/cdefs.h>
     69 __KERNEL_RCSID(0, "$NetBSD: uvm_pdaemon.c,v 1.141 2026/08/23 22:08:41 riastradh Exp $");
     70 
     71 #include "opt_uvmhist.h"
     72 #include "opt_readahead.h"
     73 
     74 #define	__RWLOCK_PRIVATE
     75 
     76 #include <sys/param.h>
     77 #include <sys/proc.h>
     78 #include <sys/systm.h>
     79 #include <sys/kernel.h>
     80 #include <sys/pool.h>
     81 #include <sys/buf.h>
     82 #include <sys/module.h>
     83 #include <sys/atomic.h>
     84 #include <sys/kthread.h>
     85 
     86 #include <uvm/uvm.h>
     87 #include <uvm/uvm_pdpolicy.h>
     88 #include <uvm/uvm_pgflcache.h>
     89 
     90 #ifdef UVMHIST
     91 #ifndef UVMHIST_PDHIST_SIZE
     92 #define UVMHIST_PDHIST_SIZE 100
     93 #endif
     94 static struct kern_history_ent pdhistbuf[UVMHIST_PDHIST_SIZE];
     95 UVMHIST_DEFINE(pdhist) = UVMHIST_INITIALIZER(pdhisthist, pdhistbuf);
     96 #endif
     97 
     98 /*
     99  * UVMPD_NUMDIRTYREACTS is how many dirty pages the pagedaemon will reactivate
    100  * in a pass thru the inactive list when swap is full.  the value should be
    101  * "small"... if it's too large we'll cycle the active pages thru the inactive
    102  * queue too quickly to for them to be referenced and avoid being freed.
    103  */
    104 
    105 #define	UVMPD_NUMDIRTYREACTS	16
    106 
    107 /*
    108  * local prototypes
    109  */
    110 
    111 static void	uvmpd_scan(void);
    112 static void	uvmpd_scan_queue(void);
    113 static void	uvmpd_tune(void);
    114 static void	uvmpd_pool_drain_thread(void *);
    115 static void	uvmpd_pool_drain_wakeup(void);
    116 
    117 /*
    118  * State coordinating sleeping in uvm_wait with wakeups in uvm_pageout
    119  * (page daemon) and uvm_pageout_done (paging completion handler)
    120  */
    121 static kmutex_t uvmpd_waiter_lock __cacheline_aligned; /* IPL_SOFTBIO */
    122 static volatile unsigned uvm_pagedaemon_waiters __cacheline_aligned;
    123 static volatile unsigned uvm_waiter_wakeup __cacheline_aligned;
    124 
    125 /* State for the pool drainer thread */
    126 static kmutex_t uvmpd_pool_drain_lock; /* IPL_NONE */
    127 static kcondvar_t uvmpd_pool_drain_cv;
    128 static bool uvmpd_pool_drain_run = false;
    129 
    130 /*
    131  * State for requesting page daemon wakeups, which may be triggered
    132  * from:
    133  *
    134  * - hard interrupt context when NOSLEEP allocations fail
    135  * - soft interrupt context when uvm_pageout_done hasn't done enough
    136  * - thread context in uvm_wait when SLEEP allocations fail
    137  */
    138 static kmutex_t uvmpd_kick_lock __cacheline_aligned; /* IPL_VM */
    139 static volatile unsigned uvmpd_sleeping __cacheline_aligned;
    140 static volatile unsigned uvmpd_wakeup __cacheline_aligned;
    141 
    142 /*
    143  * XXX hack to avoid hangs when large processes fork.
    144  */
    145 u_int uvm_extrapages;
    146 
    147 #if __HAVE_ATOMIC64_LOADSTORE
    148 
    149 static volatile uint64_t uvmpd_gen;
    150 
    151 static uint64_t
    152 uvmpd_read_gen(void)
    153 {
    154 
    155 	return atomic_load_acquire(&uvmpd_gen);
    156 }
    157 
    158 static void
    159 uvmpd_advance_gen(void)
    160 {
    161 
    162 	KASSERT(mutex_owned(&uvmpd_waiter_lock));
    163 	atomic_store_release(&uvmpd_gen, atomic_load_relaxed(&uvmpd_gen) + 1);
    164 }
    165 
    166 #else  /* !__HAVE_ATOMIC64_LOADSTORE */
    167 
    168 static volatile struct {
    169 #if _BYTE_ORDER == _BIG_ENDIAN
    170 	uint32_t	hi, lo;
    171 #else
    172 	uint32_t	lo, hi;
    173 #endif
    174 } uvmpd_gen;
    175 
    176 static uint64_t
    177 uvmpd_read_gen(void)
    178 {
    179 	uint32_t hi, lo;
    180 
    181 top:	while (__predict_false((hi = atomic_load_relaxed(&uvmpd_gen.hi)) ==
    182 		0xffffffff))
    183 		SPINLOCK_BACKOFF_HOOK;
    184 	membar_consumer();	/* membar_producer in uvmpd_advance_gen */
    185 	/* load-acquire matches store-release in uvmpd_advance_gen */
    186 	lo = atomic_load_acquire(&uvmpd_gen.lo);
    187 	if (__predict_false(hi != atomic_load_relaxed(&uvmpd_gen.hi)))
    188 		goto top;
    189 
    190 	return (uint64_t)hi << 32 | lo;
    191 }
    192 
    193 static void
    194 uvmpd_advance_gen(void)
    195 {
    196 	uint32_t hi, lo;
    197 
    198 	KASSERT(mutex_owned(&uvmpd_waiter_lock));
    199 
    200 	lo = atomic_load_relaxed(&uvmpd_gen.lo);
    201 	if (__predict_false(++lo == 0)) {
    202 		hi = atomic_load_relaxed(&uvmpd_gen.hi) + 1; /* carry */
    203 		atomic_store_relaxed(&uvmpd_gen.hi, 0xffffffff);
    204 		/* store-release matches load-acquire in uvmpd_read_gen */
    205 		atomic_store_release(&uvmpd_gen.lo, lo);
    206 		membar_producer(); /* membar_consumer in uvmpd_read_gen */
    207 		atomic_store_relaxed(&uvmpd_gen.hi, hi);
    208 	} else {
    209 		/* store-release matches load-acquire in uvmpd_read_gen */
    210 		atomic_store_release(&uvmpd_gen.lo, lo);
    211 	}
    212 }
    213 
    214 #endif
    215 
    216 static void
    217 uvmpd_wake_pagedaemon(void)
    218 {
    219 
    220 	/*
    221 	 * Record that a wakeup is pending.  If there was already a
    222 	 * wakeup pending, some other thread will take care of the
    223 	 * rest, so stop here.
    224 	 *
    225 	 * membar_release matches membar_acquire in uvm_pageout.
    226 	 */
    227 	membar_release();
    228 	if (atomic_swap_uint(&uvmpd_wakeup, 1))
    229 		return;
    230 
    231 	/*
    232 	 * Ensure store-before-load ordering so we announce intent to
    233 	 * wake up before we check whether the page daemon has
    234 	 * announced intent to sleep.
    235 	 *
    236 	 * Matches membar_sync in uvm_pageout between storing
    237 	 * uvmpd_sleeping := 1 and loading uvmpd_wakeup.
    238 	 */
    239 	membar_sync();
    240 
    241 	/*
    242 	 * If _after_ we have told the page daemon to wake up, it has
    243 	 * still not announced intent to sleep, nothing more to do --
    244 	 * it's busy working, and it will read uvmpd_wakeup on the next
    245 	 * iteration and avoid going to sleep.
    246 	 */
    247 	if (!atomic_load_relaxed(&uvmpd_sleeping))
    248 		return;
    249 
    250 	/*
    251 	 * The page daemon has already decided to go to sleep, and it
    252 	 * may be too late for us to stop it.  Wake it up.
    253 	 */
    254 	mutex_spin_enter(&uvmpd_kick_lock);
    255 	wakeup(&uvm.pagedaemon);
    256 	mutex_spin_exit(&uvmpd_kick_lock);
    257 }
    258 
    259 static void
    260 uvmpd_wake_waiters(void)
    261 {
    262 
    263 	/*
    264 	 * Record that a wakeup is pending.  If there was already a
    265 	 * wakeup pending, some other thread will take care of the
    266 	 * rest, so stop here.
    267 	 *
    268 	 * membar_release matches membar_acquire in uvm_wait.
    269 	 */
    270 	membar_release();
    271 	if (atomic_swap_uint(&uvm_waiter_wakeup, 1))
    272 		return;
    273 
    274 	/*
    275 	 * Ensure store-before-load ordering so we announce intent to
    276 	 * wake up before we check whether there are any waiters
    277 	 * waiting.
    278 	 *
    279 	 * Matches membar_sync in uvm_wait.
    280 	 */
    281 	membar_sync();
    282 
    283 	/*
    284 	 * If _after_ we have told the waiters to wake up, there still
    285 	 * are none, nothing more to do -- whoever calls uvm_wait next
    286 	 * will read uvm_waiter_wakeup and avoid going to sleep.
    287 	 */
    288 	if (atomic_load_relaxed(&uvm_pagedaemon_waiters) == 0)
    289 		return;
    290 
    291 	/*
    292 	 * uvm_wait waiters are either asleep or about to go to sleep,
    293 	 * and it may be too late to stop them, so we have to take the
    294 	 * lock to wake them up.
    295 	 *
    296 	 * Make sure to advance the generation so that logic still in
    297 	 * the ellipsis of
    298 	 *
    299 	 * top:	ticket = uvm_wait_prepare();
    300 	 *	...
    301 	 *	if (allocfailed) {
    302 	 *		uvm_wait("wmesg", ticket);
    303 	 *		goto top;
    304 	 *	}
    305 	 *
    306 	 * will wake up and not sleep forever when it hits uvm_wait.
    307 	 */
    308 	mutex_enter(&uvmpd_waiter_lock);
    309 	uvmpd_advance_gen();
    310 	if (atomic_load_relaxed(&uvm_pagedaemon_waiters) != 0) {
    311 		atomic_store_relaxed(&uvm_pagedaemon_waiters, 0);
    312 		wakeup(&uvmexp.free);
    313 	}
    314 	mutex_exit(&uvmpd_waiter_lock);
    315 }
    316 
    317 /*
    318  * uvm_wait_prepare: return a ticket for uvm_wait
    319  *
    320  * => caller must:
    321  *    1. get a ticket _first_,
    322  *    2. _then_ try allocation, and
    323  *    3. uvm_wait with the ticket if it fails
    324  */
    325 
    326 uint64_t
    327 uvm_wait_prepare(void)
    328 {
    329 	uint64_t ticket;
    330 
    331 	ticket = uvmpd_read_gen();
    332 
    333 	return ticket;
    334 }
    335 
    336 /*
    337  * uvm_wait: wait (sleep) for the page daemon to free some pages
    338  *
    339  * => should be called with all locks released
    340  * => should _not_ be called by the page daemon (to avoid deadlock)
    341  * => caller must have acquired a ticket with uvm_wait_prepare,
    342  *    before trying an allocation that we now wait for
    343  */
    344 
    345 void
    346 uvm_wait(const char *wmsg, uint64_t ticket)
    347 {
    348 	uint64_t gen = ticket;
    349 	int timo = 0;
    350 
    351 	if (uvm.pagedaemon_lwp == NULL)
    352 		panic("out of memory before the pagedaemon thread exists");
    353 
    354 	/*
    355 	 * Fast path: if the page daemon wakeup generation has already
    356 	 * advanced since the caller began uvm_wait_prepare, don't add
    357 	 * to contention on uvmpd_waiter_lock; we already know the
    358 	 * caller can retry its allocation.
    359 	 */
    360 	if (gen != uvmpd_read_gen())
    361 		return;
    362 
    363 	mutex_enter(&uvmpd_waiter_lock);
    364 
    365 	/*
    366 	 * If the page daemon wakeup generation has advanced since the
    367 	 * caller began uvm_wait_prepare, don't sleep; the caller can
    368 	 * already retry its allocation.
    369 	 */
    370 	if (gen != uvmpd_read_gen()) {
    371 		mutex_exit(&uvmpd_waiter_lock);
    372 		return;
    373 	}
    374 
    375 	/*
    376 	 * check for page daemon going to sleep (waiting for itself)
    377 	 */
    378 	if (uvm_lwp_is_pagedaemon(curlwp) && uvmexp.paging == 0) {
    379 		/*
    380 		 * now we have a problem: the pagedaemon wants to go to
    381 		 * sleep until it frees more memory.   but how can it
    382 		 * free more memory if it is asleep?  that is a deadlock.
    383 		 * we have two options:
    384 		 *  [1] panic now
    385 		 *  [2] put a timeout on the sleep, thus causing the
    386 		 *      pagedaemon to only pause (rather than sleep forever)
    387 		 *
    388 		 * note that option [2] will only help us if we get lucky
    389 		 * and some other process on the system breaks the deadlock
    390 		 * by exiting or freeing memory (thus allowing the pagedaemon
    391 		 * to continue).  for now we panic if DEBUG is defined,
    392 		 * otherwise we hope for the best with option [2] (better
    393 		 * yet, this should never happen in the first place!).
    394 		 */
    395 
    396 		printf("pagedaemon: deadlock detected!\n");
    397 		timo = hz >> 3;		/* set timeout */
    398 #if defined(DEBUG)
    399 		/* DEBUG: panic so we can debug it */
    400 		panic("pagedaemon deadlock");
    401 #endif
    402 	}
    403 
    404 	/*
    405 	 * Notify uvmpd_wake_waiters that there are waiters before we
    406 	 * check whether there's a pending unlocked wakeup.
    407 	 *
    408 	 * membar_sync here matches membar_sync in uvmpd_wake_waiters.
    409 	 *
    410 	 * If there's pending unlocked wakeup, consume it by advancing
    411 	 * the wakeup generation and waking any other waiters -- that
    412 	 * can be done only with the lock.  Generally there should be
    413 	 * no other waiters at this point -- if there is a pending
    414 	 * wakeup, any other call to uvm_wait would have consumed it
    415 	 * and so can't be waiting; if another call to uvm_wait didn't
    416 	 * find a pending wakeup, then any subsequent uvm_pageout or
    417 	 * uvm_pageout_done wakeup should have noticed that call and
    418 	 * issued wakeup(&uvmexp.free) -- but it takes a more effort to
    419 	 * prove that it is safe to elide wakeup(&uvmexp.free) than it
    420 	 * takes to just call it anyway here.
    421 	 *
    422 	 * The wakeup might be spurious by now, but the caller has to
    423 	 * cope with spurious wakeups anyway.
    424 	 */
    425 	atomic_store_relaxed(&uvm_pagedaemon_waiters,
    426 	    atomic_load_relaxed(&uvm_pagedaemon_waiters) + 1);
    427 	membar_sync();
    428 	if (atomic_swap_uint(&uvm_waiter_wakeup, 0)) {
    429 		/*
    430 		 * membar_acquire matches membar_release in
    431 		 * uvmpd_wake_waiters.
    432 		 */
    433 		membar_acquire();
    434 		uvmpd_advance_gen();
    435 		atomic_store_relaxed(&uvm_pagedaemon_waiters, 0);
    436 		wakeup(&uvmexp.free);
    437 		mutex_exit(&uvmpd_waiter_lock);
    438 		return;
    439 	}
    440 
    441 	uvmpd_wake_pagedaemon();	/* wake the daemon! */
    442 	UVM_UNLOCK_AND_WAIT(&uvmexp.free, &uvmpd_waiter_lock, false, wmsg,
    443 	    timo);
    444 }
    445 
    446 /*
    447  * uvm_kick_pdaemon: perform checks to determine if we need to
    448  * give the pagedaemon a nudge, and do so if necessary.
    449  */
    450 
    451 void
    452 uvm_kick_pdaemon(void)
    453 {
    454 	int fpages = uvm_availmem(false);
    455 
    456 	if (fpages + uvmexp.paging < uvmexp.freemin ||
    457 	    (fpages + uvmexp.paging < uvmexp.freetarg &&
    458 	     uvmpdpol_needsscan_p()) ||
    459 	     uvm_km_va_starved_p()) {
    460 		uvmpd_wake_pagedaemon();
    461 	}
    462 }
    463 
    464 /*
    465  * _uvm_lwp_is_pagedaemon: returns true of the specified lwp is
    466  * a pagedaemon lwp.
    467  */
    468 
    469 bool
    470 _uvm_lwp_is_pagedaemon(struct lwp *l)
    471 {
    472 	return _uvm_lwp_is_pagedaemon_test(l);
    473 }
    474 
    475 /*
    476  * uvmpd_tune: tune paging parameters
    477  *
    478  * => called when ever memory is added (or removed?) to the system
    479  */
    480 
    481 static void
    482 uvmpd_tune(void)
    483 {
    484 	int val;
    485 
    486 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
    487 
    488 	/*
    489 	 * try to keep 0.5% of available RAM free, but limit to between
    490 	 * 128k and 1024k per-CPU.  XXX: what are these values good for?
    491 	 */
    492 	val = uvmexp.npages / 200;
    493 	val = MAX(val, (128*1024) >> PAGE_SHIFT);
    494 	val = MIN(val, (1024*1024) >> PAGE_SHIFT);
    495 	val *= ncpu;
    496 
    497 	/* Make sure there's always a user page free. */
    498 	if (val < uvmexp.reserve_kernel + 1)
    499 		val = uvmexp.reserve_kernel + 1;
    500 	uvmexp.freemin = val;
    501 
    502 	/* Calculate free target. */
    503 	val = (uvmexp.freemin * 4) / 3;
    504 	if (val <= uvmexp.freemin)
    505 		val = uvmexp.freemin + 1;
    506 	uvmexp.freetarg = val + atomic_swap_uint(&uvm_extrapages, 0);
    507 
    508 	uvmexp.wiredmax = uvmexp.npages / 3;
    509 	UVMHIST_LOG(pdhist, "<- done, freemin=%jd, freetarg=%jd, wiredmax=%jd",
    510 	      uvmexp.freemin, uvmexp.freetarg, uvmexp.wiredmax, 0);
    511 }
    512 
    513 /*
    514  * uvm_pageout: the main loop for the pagedaemon
    515  */
    516 
    517 void
    518 uvm_pageout(void *arg)
    519 {
    520 	int npages = 0;
    521 	int extrapages = 0;
    522 	int fpages;
    523 
    524 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
    525 
    526 	UVMHIST_LOG(pdhist,"<starting uvm pagedaemon>", 0, 0, 0, 0);
    527 
    528 	mutex_init(&uvmpd_kick_lock, MUTEX_DEFAULT, IPL_VM);
    529 	mutex_init(&uvmpd_waiter_lock, MUTEX_DEFAULT, IPL_SOFTBIO);
    530 	mutex_init(&uvmpd_pool_drain_lock, MUTEX_DEFAULT, IPL_NONE);
    531 	cv_init(&uvmpd_pool_drain_cv, "pooldrain");
    532 
    533 	/* Create the pool drainer kernel thread. */
    534 	if (kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL,
    535 	    uvmpd_pool_drain_thread, NULL, NULL, "pooldrain"))
    536 		panic("fork pooldrain");
    537 
    538 	/*
    539 	 * ensure correct priority and set paging parameters...
    540 	 */
    541 
    542 	uvm.pagedaemon_lwp = curlwp;
    543 	npages = uvmexp.npages;
    544 	uvmpd_tune();
    545 
    546 	/*
    547 	 * main loop
    548 	 */
    549 
    550 	for (;;) {
    551 		bool needsscan, needsfree, kmem_va_starved;
    552 
    553 		kmem_va_starved = uvm_km_va_starved_p();
    554 
    555 		mutex_spin_enter(&uvmpd_kick_lock);
    556 		if ((atomic_load_relaxed(&uvm_pagedaemon_waiters) == 0 ||
    557 			uvmexp.paging > 0) &&
    558 		    !kmem_va_starved) {
    559 			UVMHIST_LOG(pdhist,"  <<SLEEPING>>",0,0,0,0);
    560 
    561 			/*
    562 			 * Notify uvm_kick_pdaemon that we're about to
    563 			 * go to sleep.  Then check whether it has
    564 			 * already asked us to wake up again before it
    565 			 * puts contention on uvmpd_kick_lock.  If,
    566 			 * after we have announced our intent to sleep,
    567 			 * there's still no pending wakeup, go to sleep
    568 			 * and release uvm_pdlock.
    569 			 *
    570 			 * membar_sync here matches membar_sync in
    571 			 * uvmpd_wake_pagedaemon.
    572 			 *
    573 			 * Once we're not asleep -- either because
    574 			 * uvmpd_wakeup = 1 or because of a concurrent
    575 			 * wakeup(&uvm.pagedaemon) -- set
    576 			 * uvmpd_sleeping back to 0 again so that while
    577 			 * we work, uvmpd_wake_pagedaemon need not take
    578 			 * uvmpd_kick_lock in order to make sure we
    579 			 * wake up next time.
    580 			 */
    581 			atomic_store_relaxed(&uvmpd_sleeping, 1);
    582 			membar_sync();
    583 			if (atomic_swap_uint(&uvmpd_wakeup, 0)) {
    584 				/*
    585 				 * membar_release matches
    586 				 * membar_acquire in
    587 				 * uvmpd_wake_pagedaemon.
    588 				 */
    589 				membar_acquire();
    590 				mutex_spin_exit(&uvmpd_kick_lock);
    591 			} else {
    592 				UVM_UNLOCK_AND_WAIT(&uvm.pagedaemon,
    593 				    &uvmpd_kick_lock, false, "pgdaemon", 0);
    594 			}
    595 			atomic_store_relaxed(&uvmpd_sleeping, 0);
    596 			uvmexp.pdwoke++;
    597 
    598 			UVMHIST_LOG(pdhist,"  <<WOKE UP>>",0,0,0,0);
    599 		} else {
    600 			mutex_spin_exit(&uvmpd_kick_lock);
    601 		}
    602 
    603 		/*
    604 		 * now recompute inactive count
    605 		 */
    606 
    607 		if (npages != uvmexp.npages || extrapages != uvm_extrapages) {
    608 			npages = uvmexp.npages;
    609 			extrapages = uvm_extrapages;
    610 			uvmpd_tune();
    611 		}
    612 
    613 		uvmpdpol_tune();
    614 
    615 		/*
    616 		 * Estimate a hint.  Note that bufmem are returned to
    617 		 * system only when entire pool page is empty.
    618 		 */
    619 		fpages = uvm_availmem(false);
    620 		UVMHIST_LOG(pdhist,"  free/ftarg=%jd/%jd",
    621 		    fpages, uvmexp.freetarg, 0,0);
    622 
    623 		needsfree = fpages + uvmexp.paging < uvmexp.freetarg;
    624 		needsscan = needsfree || uvmpdpol_needsscan_p();
    625 
    626 		/*
    627 		 * scan if needed
    628 		 */
    629 		if (needsscan) {
    630 			uvmpd_scan();
    631 		}
    632 
    633 		/*
    634 		 * if there's any free memory to be had,
    635 		 * wake up any waiters.
    636 		 */
    637 		if (uvm_availmem(false) > uvmexp.reserve_kernel ||
    638 		    uvmexp.paging == 0) {
    639 			uvmpd_wake_waiters();
    640 		}
    641 
    642 		/*
    643 		 * scan done.  if we don't need free memory, we're done.
    644 		 */
    645 
    646 		if (!needsfree && !kmem_va_starved)
    647 			continue;
    648 
    649 		/*
    650 		 * kick the pool drainer thread.
    651 		 */
    652 
    653 		uvmpd_pool_drain_wakeup();
    654 	}
    655 	/*NOTREACHED*/
    656 }
    657 
    658 void
    659 uvm_pageout_start(int npages)
    660 {
    661 
    662 	atomic_add_int(&uvmexp.paging, npages);
    663 }
    664 
    665 void
    666 uvm_pageout_done(int npages)
    667 {
    668 
    669 	KASSERT(atomic_load_relaxed(&uvmexp.paging) >= npages);
    670 
    671 	if (npages == 0) {
    672 		return;
    673 	}
    674 
    675 	atomic_add_int(&uvmexp.paging, -npages);
    676 
    677 	/*
    678 	 * wake up either of pagedaemon or LWPs waiting for it.
    679 	 */
    680 	if (uvm_availmem(false) <= uvmexp.reserve_kernel) {
    681 		uvmpd_wake_pagedaemon();
    682 	} else {
    683 		uvmpd_wake_waiters();
    684 	}
    685 }
    686 
    687 static krwlock_t *
    688 uvmpd_page_owner_lock(struct vm_page *pg)
    689 {
    690 	struct uvm_object *uobj = pg->uobject;
    691 	struct vm_anon *anon = pg->uanon;
    692 	krwlock_t *slock;
    693 
    694 	KASSERT(mutex_owned(&pg->interlock));
    695 
    696 #ifdef DEBUG
    697 	if (uobj == (void *)0xdeadbeef || anon == (void *)0xdeadbeef) {
    698 		return NULL;
    699 	}
    700 #endif
    701 	if (uobj != NULL) {
    702 		slock = uobj->vmobjlock;
    703 		KASSERTMSG(slock != NULL, "pg %p uobj %p, NULL lock", pg, uobj);
    704 	} else if (anon != NULL) {
    705 		slock = anon->an_lock;
    706 		KASSERTMSG(slock != NULL, "pg %p anon %p, NULL lock", pg, anon);
    707 	} else {
    708 		slock = NULL;
    709 	}
    710 	return slock;
    711 }
    712 
    713 /*
    714  * uvmpd_trylockowner: trylock the page's owner.
    715  *
    716  * => called with page interlock held.
    717  * => resolve orphaned O->A loaned page.
    718  * => return the locked mutex on success.  otherwise, return NULL.
    719  */
    720 
    721 krwlock_t *
    722 uvmpd_trylockowner(struct vm_page *pg)
    723 {
    724 	krwlock_t *slock, *heldslock = NULL;
    725 
    726 	KASSERT(mutex_owned(&pg->interlock));
    727 
    728 	slock = uvmpd_page_owner_lock(pg);
    729 	if (slock == NULL) {
    730 		/* Page may be in state of flux - ignore. */
    731 		mutex_exit(&pg->interlock);
    732 		return NULL;
    733 	}
    734 
    735 	if (rw_tryenter(slock, RW_WRITER)) {
    736 		goto success;
    737 	}
    738 
    739 	/*
    740 	 * The try-lock didn't work, so now do a blocking lock after
    741 	 * dropping the page interlock.  Prevent the owner lock from
    742 	 * being freed by taking a hold on it first.
    743 	 */
    744 
    745 	rw_obj_hold(slock);
    746 	mutex_exit(&pg->interlock);
    747 	rw_enter(slock, RW_WRITER);
    748 	heldslock = slock;
    749 
    750 	/*
    751 	 * Now we hold some owner lock.  Check if the lock we hold
    752 	 * is still the lock for the owner of the page.
    753 	 * If it is then return it, otherwise release it and return NULL.
    754 	 */
    755 
    756 	mutex_enter(&pg->interlock);
    757 	slock = uvmpd_page_owner_lock(pg);
    758 	if (heldslock != slock) {
    759 		rw_exit(heldslock);
    760 		slock = NULL;
    761 	} else {
    762 success:
    763 		/*
    764 		 * Set PG_ANON if it isn't set already.
    765 		 */
    766 		if (pg->uobject == NULL && (pg->flags & PG_ANON) == 0) {
    767 			KASSERT(pg->loan_count > 0);
    768 			pg->loan_count--;
    769 			pg->flags |= PG_ANON;
    770 			/* anon now owns it */
    771 		}
    772 	}
    773 	mutex_exit(&pg->interlock);
    774 	if (heldslock != NULL) {
    775 		rw_obj_free(heldslock);
    776 	}
    777 	return slock;
    778 }
    779 
    780 #if defined(VMSWAP)
    781 struct swapcluster {
    782 	int swc_slot;
    783 	int swc_nallocated;
    784 	int swc_nused;
    785 	struct vm_page *swc_pages[howmany(MAXPHYS, MIN_PAGE_SIZE)];
    786 };
    787 
    788 static void
    789 swapcluster_init(struct swapcluster *swc)
    790 {
    791 
    792 	swc->swc_slot = 0;
    793 	swc->swc_nused = 0;
    794 }
    795 
    796 static int
    797 swapcluster_allocslots(struct swapcluster *swc)
    798 {
    799 	int slot;
    800 	int npages;
    801 
    802 	if (swc->swc_slot != 0) {
    803 		return 0;
    804 	}
    805 
    806 	/* Even with strange MAXPHYS, the shift
    807 	   implicitly rounds down to a page. */
    808 	npages = MAXPHYS >> PAGE_SHIFT;
    809 	slot = uvm_swap_alloc(&npages, true);
    810 	if (slot == 0) {
    811 		return ENOMEM;
    812 	}
    813 	swc->swc_slot = slot;
    814 	swc->swc_nallocated = npages;
    815 	swc->swc_nused = 0;
    816 
    817 	return 0;
    818 }
    819 
    820 static int
    821 swapcluster_add(struct swapcluster *swc, struct vm_page *pg)
    822 {
    823 	int slot;
    824 	struct uvm_object *uobj;
    825 
    826 	KASSERT(swc->swc_slot != 0);
    827 	KASSERT(swc->swc_nused < swc->swc_nallocated);
    828 	KASSERT((pg->flags & PG_SWAPBACKED) != 0);
    829 
    830 	slot = swc->swc_slot + swc->swc_nused;
    831 	uobj = pg->uobject;
    832 	if (uobj == NULL) {
    833 		KASSERT(rw_write_held(pg->uanon->an_lock));
    834 		pg->uanon->an_swslot = slot;
    835 	} else {
    836 		int result;
    837 
    838 		KASSERT(rw_write_held(uobj->vmobjlock));
    839 		result = uao_set_swslot(uobj, pg->offset >> PAGE_SHIFT, slot);
    840 		if (result == -1) {
    841 			return ENOMEM;
    842 		}
    843 	}
    844 	swc->swc_pages[swc->swc_nused] = pg;
    845 	swc->swc_nused++;
    846 
    847 	return 0;
    848 }
    849 
    850 static void
    851 swapcluster_flush(struct swapcluster *swc, bool now)
    852 {
    853 	int slot;
    854 	int nused;
    855 	int nallocated;
    856 	int error __diagused;
    857 
    858 	if (swc->swc_slot == 0) {
    859 		return;
    860 	}
    861 	KASSERT(swc->swc_nused <= swc->swc_nallocated);
    862 
    863 	slot = swc->swc_slot;
    864 	nused = swc->swc_nused;
    865 	nallocated = swc->swc_nallocated;
    866 
    867 	/*
    868 	 * if this is the final pageout we could have a few
    869 	 * unused swap blocks.  if so, free them now.
    870 	 */
    871 
    872 	if (nused < nallocated) {
    873 		if (!now) {
    874 			return;
    875 		}
    876 		uvm_swap_free(slot + nused, nallocated - nused);
    877 	}
    878 
    879 	/*
    880 	 * now start the pageout.
    881 	 */
    882 
    883 	if (nused > 0) {
    884 		uvmexp.pdpageouts++;
    885 		uvm_pageout_start(nused);
    886 		error = uvm_swap_put(slot, swc->swc_pages, nused, 0);
    887 		KASSERT(error == 0 || error == ENOMEM);
    888 	}
    889 
    890 	/*
    891 	 * zero swslot to indicate that we are
    892 	 * no longer building a swap-backed cluster.
    893 	 */
    894 
    895 	swc->swc_slot = 0;
    896 	swc->swc_nused = 0;
    897 }
    898 
    899 static int
    900 swapcluster_nused(struct swapcluster *swc)
    901 {
    902 
    903 	return swc->swc_nused;
    904 }
    905 
    906 /*
    907  * uvmpd_dropswap: free any swap allocated to this page.
    908  *
    909  * => called with owner locked.
    910  * => return true if a page had an associated slot.
    911  */
    912 
    913 bool
    914 uvmpd_dropswap(struct vm_page *pg)
    915 {
    916 	bool result = false;
    917 	struct vm_anon *anon = pg->uanon;
    918 
    919 	if ((pg->flags & PG_ANON) && anon->an_swslot) {
    920 		uvm_swap_free(anon->an_swslot, 1);
    921 		anon->an_swslot = 0;
    922 		uvm_pagemarkdirty(pg, UVM_PAGE_STATUS_DIRTY);
    923 		result = true;
    924 	} else if (pg->flags & PG_AOBJ) {
    925 		int slot = uao_set_swslot(pg->uobject,
    926 		    pg->offset >> PAGE_SHIFT, 0);
    927 		if (slot) {
    928 			uvm_swap_free(slot, 1);
    929 			uvm_pagemarkdirty(pg, UVM_PAGE_STATUS_DIRTY);
    930 			result = true;
    931 		}
    932 	}
    933 
    934 	return result;
    935 }
    936 
    937 #endif /* defined(VMSWAP) */
    938 
    939 /*
    940  * uvmpd_scan_queue: scan an replace candidate list for pages
    941  * to clean or free.
    942  *
    943  * => we work on meeting our free target by converting inactive pages
    944  *    into free pages.
    945  * => we handle the building of swap-backed clusters
    946  */
    947 
    948 static void
    949 uvmpd_scan_queue(void)
    950 {
    951 	struct vm_page *p;
    952 	struct uvm_object *uobj;
    953 	struct vm_anon *anon;
    954 #if defined(VMSWAP)
    955 	struct swapcluster swc;
    956 #endif /* defined(VMSWAP) */
    957 	int dirtyreacts;
    958 	krwlock_t *slock;
    959 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
    960 
    961 	/*
    962 	 * swslot is non-zero if we are building a swap cluster.  we want
    963 	 * to stay in the loop while we have a page to scan or we have
    964 	 * a swap-cluster to build.
    965 	 */
    966 
    967 #if defined(VMSWAP)
    968 	swapcluster_init(&swc);
    969 #endif /* defined(VMSWAP) */
    970 
    971 	dirtyreacts = 0;
    972 	uvmpdpol_scaninit();
    973 
    974 	while (/* CONSTCOND */ 1) {
    975 
    976 		/*
    977 		 * see if we've met the free target.
    978 		 */
    979 
    980 		if (uvm_availmem(false) + uvmexp.paging
    981 #if defined(VMSWAP)
    982 		    + swapcluster_nused(&swc)
    983 #endif /* defined(VMSWAP) */
    984 		    >= uvmexp.freetarg << 2 ||
    985 		    dirtyreacts == UVMPD_NUMDIRTYREACTS) {
    986 			UVMHIST_LOG(pdhist,"  met free target: "
    987 				    "exit loop", 0, 0, 0, 0);
    988 			break;
    989 		}
    990 
    991 		/*
    992 		 * first we have the pdpolicy select a victim page
    993 		 * and attempt to lock the object that the page
    994 		 * belongs to.  if our attempt fails we skip on to
    995 		 * the next page (no harm done).  it is important to
    996 		 * "try" locking the object as we are locking in the
    997 		 * wrong order (pageq -> object) and we don't want to
    998 		 * deadlock.
    999 		 *
   1000 		 * the only time we expect to see an ownerless page
   1001 		 * (i.e. a page with no uobject and !PG_ANON) is if an
   1002 		 * anon has loaned a page from a uvm_object and the
   1003 		 * uvm_object has dropped the ownership.  in that
   1004 		 * case, the anon can "take over" the loaned page
   1005 		 * and make it its own.
   1006 		 */
   1007 
   1008 		p = uvmpdpol_selectvictim(&slock);
   1009 		if (p == NULL) {
   1010 			break;
   1011 		}
   1012 		KASSERT(uvmpdpol_pageisqueued_p(p));
   1013 		KASSERT(uvm_page_owner_locked_p(p, true));
   1014 		KASSERT(p->wire_count == 0);
   1015 
   1016 		/*
   1017 		 * we are below target and have a new page to consider.
   1018 		 */
   1019 
   1020 		anon = p->uanon;
   1021 		uobj = p->uobject;
   1022 
   1023 		if (p->flags & PG_BUSY) {
   1024 			rw_exit(slock);
   1025 			uvmexp.pdbusy++;
   1026 			continue;
   1027 		}
   1028 
   1029 		/* does the page belong to an object? */
   1030 		if (uobj != NULL) {
   1031 			uvmexp.pdobscan++;
   1032 		} else {
   1033 #if defined(VMSWAP)
   1034 			KASSERT(anon != NULL);
   1035 			uvmexp.pdanscan++;
   1036 #else /* defined(VMSWAP) */
   1037 			panic("%s: anon", __func__);
   1038 #endif /* defined(VMSWAP) */
   1039 		}
   1040 
   1041 
   1042 		/*
   1043 		 * we now have the object locked.
   1044 		 * if the page is not swap-backed, call the object's
   1045 		 * pager to flush and free the page.
   1046 		 */
   1047 
   1048 #if defined(READAHEAD_STATS)
   1049 		if ((p->flags & PG_READAHEAD) != 0) {
   1050 			p->flags &= ~PG_READAHEAD;
   1051 			uvm_ra_miss.ev_count++;
   1052 		}
   1053 #endif /* defined(READAHEAD_STATS) */
   1054 
   1055 		if ((p->flags & PG_SWAPBACKED) == 0) {
   1056 			KASSERT(uobj != NULL);
   1057 			(void) (uobj->pgops->pgo_put)(uobj, p->offset,
   1058 			    p->offset + PAGE_SIZE, PGO_CLEANIT|PGO_FREE);
   1059 			continue;
   1060 		}
   1061 
   1062 		/*
   1063 		 * the page is swap-backed.  remove all the permissions
   1064 		 * from the page so we can sync the modified info
   1065 		 * without any race conditions.  if the page is clean
   1066 		 * we can free it now and continue.
   1067 		 */
   1068 
   1069 		pmap_page_protect(p, VM_PROT_NONE);
   1070 		if (uvm_pagegetdirty(p) == UVM_PAGE_STATUS_UNKNOWN) {
   1071 			if (pmap_clear_modify(p)) {
   1072 				uvm_pagemarkdirty(p, UVM_PAGE_STATUS_DIRTY);
   1073 			} else {
   1074 				uvm_pagemarkdirty(p, UVM_PAGE_STATUS_CLEAN);
   1075 			}
   1076 		}
   1077 		if (uvm_pagegetdirty(p) != UVM_PAGE_STATUS_DIRTY) {
   1078 			int slot;
   1079 			int pageidx;
   1080 
   1081 			pageidx = p->offset >> PAGE_SHIFT;
   1082 			uvm_pagefree(p);
   1083 			atomic_inc_uint(&uvmexp.pdfreed);
   1084 
   1085 			/*
   1086 			 * for anons, we need to remove the page
   1087 			 * from the anon ourselves.  for aobjs,
   1088 			 * pagefree did that for us.
   1089 			 */
   1090 
   1091 			if (anon) {
   1092 				KASSERT(anon->an_swslot != 0);
   1093 				anon->an_page = NULL;
   1094 				slot = anon->an_swslot;
   1095 			} else {
   1096 				slot = uao_find_swslot(uobj, pageidx);
   1097 			}
   1098 			if (slot > 0) {
   1099 				/* this page is now only in swap. */
   1100 				atomic_inc_uint(&uvmexp.swpgonly);
   1101 			}
   1102 			rw_exit(slock);
   1103 			continue;
   1104 		}
   1105 
   1106 #if defined(VMSWAP)
   1107 		/*
   1108 		 * this page is dirty, skip it if we'll have met our
   1109 		 * free target when all the current pageouts complete.
   1110 		 */
   1111 
   1112 		if (uvm_availmem(false) + uvmexp.paging >
   1113 		    uvmexp.freetarg << 2) {
   1114 			rw_exit(slock);
   1115 			continue;
   1116 		}
   1117 
   1118 		/*
   1119 		 * free any swap space allocated to the page since
   1120 		 * we'll have to write it again with its new data.
   1121 		 */
   1122 
   1123 		uvmpd_dropswap(p);
   1124 
   1125 		/*
   1126 		 * start new swap pageout cluster (if necessary).
   1127 		 *
   1128 		 * if swap is full reactivate this page so that
   1129 		 * we eventually cycle all pages through the
   1130 		 * inactive queue.
   1131 		 */
   1132 
   1133 		if (swapcluster_allocslots(&swc)) {
   1134 			dirtyreacts++;
   1135 			uvm_pagelock(p);
   1136 			uvm_pageactivate(p);
   1137 			uvm_pageunlock(p);
   1138 			rw_exit(slock);
   1139 			continue;
   1140 		}
   1141 
   1142 		/*
   1143 		 * at this point, we're definitely going reuse this
   1144 		 * page.  mark the page busy and delayed-free.
   1145 		 * we should remove the page from the page queues
   1146 		 * so we don't ever look at it again.
   1147 		 * adjust counters and such.
   1148 		 */
   1149 
   1150 		p->flags |= PG_BUSY;
   1151 		UVM_PAGE_OWN(p, "scan_queue");
   1152 		p->flags |= PG_PAGEOUT;
   1153 		uvmexp.pgswapout++;
   1154 
   1155 		uvm_pagelock(p);
   1156 		uvm_pagedequeue(p);
   1157 		uvm_pageunlock(p);
   1158 
   1159 		/*
   1160 		 * add the new page to the cluster.
   1161 		 */
   1162 
   1163 		if (swapcluster_add(&swc, p)) {
   1164 			p->flags &= ~(PG_BUSY|PG_PAGEOUT);
   1165 			UVM_PAGE_OWN(p, NULL);
   1166 			dirtyreacts++;
   1167 			uvm_pagelock(p);
   1168 			uvm_pageactivate(p);
   1169 			uvm_pageunlock(p);
   1170 			rw_exit(slock);
   1171 			continue;
   1172 		}
   1173 		rw_exit(slock);
   1174 
   1175 		swapcluster_flush(&swc, false);
   1176 
   1177 #else /* defined(VMSWAP) */
   1178 		uvm_pagelock(p);
   1179 		uvm_pageactivate(p);
   1180 		uvm_pageunlock(p);
   1181 		rw_exit(slock);
   1182 #endif /* defined(VMSWAP) */
   1183 	}
   1184 
   1185 	uvmpdpol_scanfini();
   1186 
   1187 #if defined(VMSWAP)
   1188 	swapcluster_flush(&swc, true);
   1189 #endif /* defined(VMSWAP) */
   1190 }
   1191 
   1192 /*
   1193  * uvmpd_scan: scan the page queues and attempt to meet our targets.
   1194  */
   1195 
   1196 static void
   1197 uvmpd_scan(void)
   1198 {
   1199 	int swap_shortage, pages_freed, fpages;
   1200 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
   1201 
   1202 	uvmexp.pdrevs++;
   1203 
   1204 	/*
   1205 	 * work on meeting our targets.   first we work on our free target
   1206 	 * by converting inactive pages into free pages.  then we work on
   1207 	 * meeting our inactive target by converting active pages to
   1208 	 * inactive ones.
   1209 	 */
   1210 
   1211 	UVMHIST_LOG(pdhist, "  starting 'free' loop",0,0,0,0);
   1212 
   1213 	pages_freed = uvmexp.pdfreed;
   1214 	uvmpd_scan_queue();
   1215 	pages_freed = uvmexp.pdfreed - pages_freed;
   1216 
   1217 	/*
   1218 	 * detect if we're not going to be able to page anything out
   1219 	 * until we free some swap resources from active pages.
   1220 	 */
   1221 
   1222 	swap_shortage = 0;
   1223 	fpages = uvm_availmem(false);
   1224 	if (fpages < uvmexp.freetarg &&
   1225 	    uvmexp.swpginuse >= uvmexp.swpgavail &&
   1226 	    !uvm_swapisfull() &&
   1227 	    pages_freed == 0) {
   1228 		swap_shortage = uvmexp.freetarg - fpages;
   1229 	}
   1230 
   1231 	uvmpdpol_balancequeue(swap_shortage);
   1232 
   1233 	/*
   1234 	 * if still below the minimum target, try unloading kernel
   1235 	 * modules.
   1236 	 */
   1237 
   1238 	if (uvm_availmem(false) < uvmexp.freemin) {
   1239 		module_thread_kick();
   1240 	}
   1241 }
   1242 
   1243 /*
   1244  * uvm_reclaimable: decide whether to wait for pagedaemon.
   1245  *
   1246  * => return true if it seems to be worth to do uvm_wait.
   1247  *
   1248  * XXX should be tunable.
   1249  * XXX should consider pools, etc?
   1250  */
   1251 
   1252 bool
   1253 uvm_reclaimable(void)
   1254 {
   1255 	int filepages;
   1256 	int active, inactive;
   1257 
   1258 	/*
   1259 	 * if swap is not full, no problem.
   1260 	 */
   1261 
   1262 	if (!uvm_swapisfull()) {
   1263 		return true;
   1264 	}
   1265 
   1266 	/*
   1267 	 * file-backed pages can be reclaimed even when swap is full.
   1268 	 * if we have more than 1/16 of pageable memory or 5MB, try to reclaim.
   1269 	 * NB: filepages calculation does not exclude EXECPAGES - intentional.
   1270 	 *
   1271 	 * XXX assume the worst case, ie. all wired pages are file-backed.
   1272 	 *
   1273 	 * XXX should consider about other reclaimable memory.
   1274 	 * XXX ie. pools, traditional buffer cache.
   1275 	 */
   1276 
   1277 	cpu_count_sync(false);
   1278 	filepages = (int)(cpu_count_get(CPU_COUNT_FILECLEAN) +
   1279 	    cpu_count_get(CPU_COUNT_FILEUNKNOWN) +
   1280 	    cpu_count_get(CPU_COUNT_FILEDIRTY) - uvmexp.wired);
   1281 	uvm_estimatepageable(&active, &inactive);
   1282 	if (filepages >= MIN((active + inactive) >> 4,
   1283 	    5 * 1024 * 1024 >> PAGE_SHIFT)) {
   1284 		return true;
   1285 	}
   1286 
   1287 	/*
   1288 	 * kill the process, fail allocation, etc..
   1289 	 */
   1290 
   1291 	return false;
   1292 }
   1293 
   1294 void
   1295 uvm_estimatepageable(int *active, int *inactive)
   1296 {
   1297 
   1298 	uvmpdpol_estimatepageable(active, inactive);
   1299 }
   1300 
   1301 
   1302 /*
   1303  * Use a separate thread for draining pools.
   1304  * This work can't done from the main pagedaemon thread because
   1305  * some pool allocators need to take vm_map locks.
   1306  */
   1307 
   1308 static void
   1309 uvmpd_pool_drain_thread(void *arg)
   1310 {
   1311 	struct pool *firstpool, *curpool;
   1312 	int bufcnt, lastslept;
   1313 	bool cycled;
   1314 
   1315 	firstpool = NULL;
   1316 	cycled = true;
   1317 	for (;;) {
   1318 		/*
   1319 		 * sleep until awoken by the pagedaemon.
   1320 		 */
   1321 		mutex_enter(&uvmpd_pool_drain_lock);
   1322 		if (!uvmpd_pool_drain_run) {
   1323 			lastslept = getticks();
   1324 			cv_wait(&uvmpd_pool_drain_cv, &uvmpd_pool_drain_lock);
   1325 			if (getticks() != lastslept) {
   1326 				cycled = false;
   1327 				firstpool = NULL;
   1328 			}
   1329 		}
   1330 		uvmpd_pool_drain_run = false;
   1331 		mutex_exit(&uvmpd_pool_drain_lock);
   1332 
   1333 		/*
   1334 		 * rate limit draining, otherwise in desperate circumstances
   1335 		 * this can totally saturate the system with xcall activity.
   1336 		 */
   1337 		if (cycled) {
   1338 			kpause("uvmpdlmt", false, 1, NULL);
   1339 			cycled = false;
   1340 			firstpool = NULL;
   1341 		}
   1342 
   1343 		/*
   1344 		 * drain and temporarily disable the freelist cache.
   1345 		 */
   1346 		uvm_pgflcache_pause();
   1347 
   1348 		/*
   1349 		 * kill unused metadata buffers.
   1350 		 */
   1351 		bufcnt = uvmexp.freetarg - uvm_availmem(false);
   1352 		if (bufcnt < 0)
   1353 			bufcnt = 0;
   1354 
   1355 		mutex_enter(&bufcache_lock);
   1356 		buf_drain(bufcnt << PAGE_SHIFT);
   1357 		mutex_exit(&bufcache_lock);
   1358 
   1359 		/*
   1360 		 * drain a pool, and then re-enable the freelist cache.
   1361 		 */
   1362 		(void)pool_drain(&curpool);
   1363 		KASSERT(curpool != NULL);
   1364 		if (firstpool == NULL) {
   1365 			firstpool = curpool;
   1366 		} else if (firstpool == curpool) {
   1367 			cycled = true;
   1368 		}
   1369 		uvm_pgflcache_resume();
   1370 	}
   1371 	/*NOTREACHED*/
   1372 }
   1373 
   1374 static void
   1375 uvmpd_pool_drain_wakeup(void)
   1376 {
   1377 
   1378 	mutex_enter(&uvmpd_pool_drain_lock);
   1379 	uvmpd_pool_drain_run = true;
   1380 	cv_signal(&uvmpd_pool_drain_cv);
   1381 	mutex_exit(&uvmpd_pool_drain_lock);
   1382 }
   1383