Home | History | Annotate | Line # | Download | only in uvm
uvm_pdaemon.c revision 1.115
      1 /*	$NetBSD: uvm_pdaemon.c,v 1.115 2019/12/14 21:36:00 ad 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.115 2019/12/14 21:36:00 ad Exp $");
     70 
     71 #include "opt_uvmhist.h"
     72 #include "opt_readahead.h"
     73 
     74 #include <sys/param.h>
     75 #include <sys/proc.h>
     76 #include <sys/systm.h>
     77 #include <sys/kernel.h>
     78 #include <sys/pool.h>
     79 #include <sys/buf.h>
     80 #include <sys/module.h>
     81 #include <sys/atomic.h>
     82 #include <sys/kthread.h>
     83 
     84 #include <uvm/uvm.h>
     85 #include <uvm/uvm_pdpolicy.h>
     86 
     87 #ifdef UVMHIST
     88 UVMHIST_DEFINE(pdhist);
     89 #endif
     90 
     91 /*
     92  * UVMPD_NUMDIRTYREACTS is how many dirty pages the pagedaemon will reactivate
     93  * in a pass thru the inactive list when swap is full.  the value should be
     94  * "small"... if it's too large we'll cycle the active pages thru the inactive
     95  * queue too quickly to for them to be referenced and avoid being freed.
     96  */
     97 
     98 #define	UVMPD_NUMDIRTYREACTS	16
     99 
    100 #define	UVMPD_NUMTRYLOCKOWNER	128
    101 
    102 /*
    103  * local prototypes
    104  */
    105 
    106 static void	uvmpd_scan(void);
    107 static void	uvmpd_scan_queue(void);
    108 static void	uvmpd_tune(void);
    109 static void	uvmpd_pool_drain_thread(void *);
    110 static void	uvmpd_pool_drain_wakeup(void);
    111 
    112 static unsigned int uvm_pagedaemon_waiters;
    113 
    114 /* State for the pool drainer thread */
    115 static kmutex_t uvmpd_pool_drain_lock __cacheline_aligned;
    116 static kcondvar_t uvmpd_pool_drain_cv;
    117 static bool uvmpd_pool_drain_run = false;
    118 
    119 /*
    120  * XXX hack to avoid hangs when large processes fork.
    121  */
    122 u_int uvm_extrapages;
    123 
    124 /*
    125  * uvm_wait: wait (sleep) for the page daemon to free some pages
    126  *
    127  * => should be called with all locks released
    128  * => should _not_ be called by the page daemon (to avoid deadlock)
    129  */
    130 
    131 void
    132 uvm_wait(const char *wmsg)
    133 {
    134 	int timo = 0;
    135 
    136 	if (uvm.pagedaemon_lwp == NULL)
    137 		panic("out of memory before the pagedaemon thread exists");
    138 
    139 	mutex_spin_enter(&uvm_fpageqlock);
    140 
    141 	/*
    142 	 * check for page daemon going to sleep (waiting for itself)
    143 	 */
    144 
    145 	if (curlwp == uvm.pagedaemon_lwp && uvmexp.paging == 0) {
    146 		/*
    147 		 * now we have a problem: the pagedaemon wants to go to
    148 		 * sleep until it frees more memory.   but how can it
    149 		 * free more memory if it is asleep?  that is a deadlock.
    150 		 * we have two options:
    151 		 *  [1] panic now
    152 		 *  [2] put a timeout on the sleep, thus causing the
    153 		 *      pagedaemon to only pause (rather than sleep forever)
    154 		 *
    155 		 * note that option [2] will only help us if we get lucky
    156 		 * and some other process on the system breaks the deadlock
    157 		 * by exiting or freeing memory (thus allowing the pagedaemon
    158 		 * to continue).  for now we panic if DEBUG is defined,
    159 		 * otherwise we hope for the best with option [2] (better
    160 		 * yet, this should never happen in the first place!).
    161 		 */
    162 
    163 		printf("pagedaemon: deadlock detected!\n");
    164 		timo = hz >> 3;		/* set timeout */
    165 #if defined(DEBUG)
    166 		/* DEBUG: panic so we can debug it */
    167 		panic("pagedaemon deadlock");
    168 #endif
    169 	}
    170 
    171 	uvm_pagedaemon_waiters++;
    172 	wakeup(&uvm.pagedaemon);		/* wake the daemon! */
    173 	UVM_UNLOCK_AND_WAIT(&uvmexp.free, &uvm_fpageqlock, false, wmsg, timo);
    174 }
    175 
    176 /*
    177  * uvm_kick_pdaemon: perform checks to determine if we need to
    178  * give the pagedaemon a nudge, and do so if necessary.
    179  *
    180  * => called with uvm_fpageqlock held.
    181  */
    182 
    183 void
    184 uvm_kick_pdaemon(void)
    185 {
    186 
    187 	KASSERT(mutex_owned(&uvm_fpageqlock));
    188 
    189 	if (uvmexp.free + uvmexp.paging < uvmexp.freemin ||
    190 	    (uvmexp.free + uvmexp.paging < uvmexp.freetarg &&
    191 	     uvmpdpol_needsscan_p()) ||
    192 	     uvm_km_va_starved_p()) {
    193 		wakeup(&uvm.pagedaemon);
    194 	}
    195 }
    196 
    197 /*
    198  * uvmpd_tune: tune paging parameters
    199  *
    200  * => called when ever memory is added (or removed?) to the system
    201  */
    202 
    203 static void
    204 uvmpd_tune(void)
    205 {
    206 	int val;
    207 
    208 	UVMHIST_FUNC("uvmpd_tune"); UVMHIST_CALLED(pdhist);
    209 
    210 	/*
    211 	 * try to keep 0.5% of available RAM free, but limit to between
    212 	 * 128k and 1024k per-CPU.  XXX: what are these values good for?
    213 	 */
    214 	val = uvmexp.npages / 200;
    215 	val = MAX(val, (128*1024) >> PAGE_SHIFT);
    216 	val = MIN(val, (1024*1024) >> PAGE_SHIFT);
    217 	val *= ncpu;
    218 
    219 	/* Make sure there's always a user page free. */
    220 	if (val < uvmexp.reserve_kernel + 1)
    221 		val = uvmexp.reserve_kernel + 1;
    222 	uvmexp.freemin = val;
    223 
    224 	/* Calculate free target. */
    225 	val = (uvmexp.freemin * 4) / 3;
    226 	if (val <= uvmexp.freemin)
    227 		val = uvmexp.freemin + 1;
    228 	uvmexp.freetarg = val + atomic_swap_uint(&uvm_extrapages, 0);
    229 
    230 	uvmexp.wiredmax = uvmexp.npages / 3;
    231 	UVMHIST_LOG(pdhist, "<- done, freemin=%jd, freetarg=%jd, wiredmax=%jd",
    232 	      uvmexp.freemin, uvmexp.freetarg, uvmexp.wiredmax, 0);
    233 }
    234 
    235 /*
    236  * uvm_pageout: the main loop for the pagedaemon
    237  */
    238 
    239 void
    240 uvm_pageout(void *arg)
    241 {
    242 	int npages = 0;
    243 	int extrapages = 0;
    244 
    245 	UVMHIST_FUNC("uvm_pageout"); UVMHIST_CALLED(pdhist);
    246 
    247 	UVMHIST_LOG(pdhist,"<starting uvm pagedaemon>", 0, 0, 0, 0);
    248 
    249 	mutex_init(&uvmpd_pool_drain_lock, MUTEX_DEFAULT, IPL_VM);
    250 	cv_init(&uvmpd_pool_drain_cv, "pooldrain");
    251 
    252 	/* Create the pool drainer kernel thread. */
    253 	if (kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL,
    254 	    uvmpd_pool_drain_thread, NULL, NULL, "pooldrain"))
    255 		panic("fork pooldrain");
    256 
    257 	/*
    258 	 * ensure correct priority and set paging parameters...
    259 	 */
    260 
    261 	uvm.pagedaemon_lwp = curlwp;
    262 	npages = uvmexp.npages;
    263 	uvmpd_tune();
    264 
    265 	/*
    266 	 * main loop
    267 	 */
    268 
    269 	for (;;) {
    270 		bool needsscan, needsfree, kmem_va_starved;
    271 
    272 		kmem_va_starved = uvm_km_va_starved_p();
    273 
    274 		mutex_spin_enter(&uvm_fpageqlock);
    275 		if ((uvm_pagedaemon_waiters == 0 || uvmexp.paging > 0) &&
    276 		    !kmem_va_starved) {
    277 			UVMHIST_LOG(pdhist,"  <<SLEEPING>>",0,0,0,0);
    278 			UVM_UNLOCK_AND_WAIT(&uvm.pagedaemon,
    279 			    &uvm_fpageqlock, false, "pgdaemon", 0);
    280 			uvmexp.pdwoke++;
    281 			UVMHIST_LOG(pdhist,"  <<WOKE UP>>",0,0,0,0);
    282 		} else {
    283 			mutex_spin_exit(&uvm_fpageqlock);
    284 		}
    285 
    286 		/*
    287 		 * now recompute inactive count
    288 		 */
    289 
    290 		if (npages != uvmexp.npages || extrapages != uvm_extrapages) {
    291 			npages = uvmexp.npages;
    292 			extrapages = uvm_extrapages;
    293 			mutex_spin_enter(&uvm_fpageqlock);
    294 			uvmpd_tune();
    295 			mutex_spin_exit(&uvm_fpageqlock);
    296 		}
    297 
    298 		uvmpdpol_tune();
    299 
    300 		/*
    301 		 * Estimate a hint.  Note that bufmem are returned to
    302 		 * system only when entire pool page is empty.
    303 		 */
    304 		mutex_spin_enter(&uvm_fpageqlock);
    305 
    306 		UVMHIST_LOG(pdhist,"  free/ftarg=%jd/%jd",
    307 		    uvmexp.free, uvmexp.freetarg, 0,0);
    308 
    309 		needsfree = uvmexp.free + uvmexp.paging < uvmexp.freetarg;
    310 		needsscan = needsfree || uvmpdpol_needsscan_p();
    311 
    312 		/*
    313 		 * scan if needed
    314 		 */
    315 		if (needsscan) {
    316 			mutex_spin_exit(&uvm_fpageqlock);
    317 			uvmpd_scan();
    318 			mutex_spin_enter(&uvm_fpageqlock);
    319 		}
    320 
    321 		/*
    322 		 * if there's any free memory to be had,
    323 		 * wake up any waiters.
    324 		 */
    325 		if (uvmexp.free > uvmexp.reserve_kernel ||
    326 		    uvmexp.paging == 0) {
    327 			wakeup(&uvmexp.free);
    328 			uvm_pagedaemon_waiters = 0;
    329 		}
    330 		mutex_spin_exit(&uvm_fpageqlock);
    331 
    332 		/*
    333 		 * scan done.  if we don't need free memory, we're done.
    334 		 */
    335 
    336 		if (!needsfree && !kmem_va_starved)
    337 			continue;
    338 
    339 		/*
    340 		 * kick the pool drainer thread.
    341 		 */
    342 
    343 		uvmpd_pool_drain_wakeup();
    344 	}
    345 	/*NOTREACHED*/
    346 }
    347 
    348 
    349 /*
    350  * uvm_aiodone_worker: a workqueue callback for the aiodone daemon.
    351  */
    352 
    353 void
    354 uvm_aiodone_worker(struct work *wk, void *dummy)
    355 {
    356 	struct buf *bp = (void *)wk;
    357 
    358 	KASSERT(&bp->b_work == wk);
    359 
    360 	/*
    361 	 * process an i/o that's done.
    362 	 */
    363 
    364 	(*bp->b_iodone)(bp);
    365 }
    366 
    367 void
    368 uvm_pageout_start(int npages)
    369 {
    370 
    371 	atomic_add_int(&uvmexp.paging, npages);
    372 }
    373 
    374 void
    375 uvm_pageout_done(int npages)
    376 {
    377 
    378 	KASSERT(uvmexp.paging >= npages);
    379 	atomic_add_int(&uvmexp.paging, -npages);
    380 
    381 	/*
    382 	 * wake up either of pagedaemon or LWPs waiting for it.
    383 	 */
    384 
    385 	mutex_spin_enter(&uvm_fpageqlock);
    386 	if (uvmexp.free <= uvmexp.reserve_kernel) {
    387 		wakeup(&uvm.pagedaemon);
    388 	} else {
    389 		wakeup(&uvmexp.free);
    390 		uvm_pagedaemon_waiters = 0;
    391 	}
    392 	mutex_spin_exit(&uvm_fpageqlock);
    393 }
    394 
    395 /*
    396  * uvmpd_trylockowner: trylock the page's owner.
    397  *
    398  * => called with page interlock held.
    399  * => resolve orphaned O->A loaned page.
    400  * => return the locked mutex on success.  otherwise, return NULL.
    401  */
    402 
    403 kmutex_t *
    404 uvmpd_trylockowner(struct vm_page *pg)
    405 {
    406 	struct uvm_object *uobj = pg->uobject;
    407 	struct vm_anon *anon = pg->uanon;
    408 	int tries, count;
    409 	bool running;
    410 	kmutex_t *slock;
    411 
    412 	KASSERT(mutex_owned(&pg->interlock));
    413 
    414 	if (uobj != NULL) {
    415 		slock = uobj->vmobjlock;
    416 		KASSERTMSG(slock != NULL, "pg %p uobj %p, NULL lock", pg, uobj);
    417 	} else if (anon != NULL) {
    418 		slock = anon->an_lock;
    419 		KASSERTMSG(slock != NULL, "pg %p anon %p, NULL lock", pg, anon);
    420 	} else {
    421 		/* Page may be in state of flux - ignore. */
    422 		mutex_exit(&pg->interlock);
    423 		return NULL;
    424 	}
    425 
    426 	/*
    427 	 * Now try to lock the objects.  We'll try hard, but don't really
    428 	 * plan on spending more than a millisecond or so here.
    429 	 */
    430 	tries = (curlwp == uvm.pagedaemon_lwp ? UVMPD_NUMTRYLOCKOWNER : 1);
    431 	for (;;) {
    432 		if (mutex_tryenter(slock)) {
    433 			if (uobj == NULL) {
    434 				/*
    435 				 * set PG_ANON if it isn't set already.
    436 				 */
    437 				if ((pg->flags & PG_ANON) == 0) {
    438 					KASSERT(pg->loan_count > 0);
    439 					pg->loan_count--;
    440 					pg->flags |= PG_ANON;
    441 					/* anon now owns it */
    442 				}
    443 			}
    444 			mutex_exit(&pg->interlock);
    445 			return slock;
    446 		}
    447 		running = mutex_owner_running(slock);
    448 		if (!running || --tries <= 0) {
    449 			break;
    450 		}
    451 		count = SPINLOCK_BACKOFF_MAX;
    452 		SPINLOCK_BACKOFF(count);
    453 	}
    454 
    455 	/*
    456 	 * We didn't get the lock; chances are the very next page on the
    457 	 * queue also has the same lock, so if the lock owner is not running
    458 	 * take a breather and allow them to make progress.  There could be
    459 	 * only 1 CPU in the system, or the pagedaemon could have preempted
    460 	 * the owner in kernel, or any number of other things could be going
    461 	 * on.
    462 	 */
    463 	mutex_exit(&pg->interlock);
    464 	if (curlwp == uvm.pagedaemon_lwp) {
    465 		if (!running) {
    466 			(void)kpause("pdpglock", false, 1, NULL);
    467 		}
    468 		uvmexp.pdbusy++;
    469 	}
    470 	return NULL;
    471 }
    472 
    473 #if defined(VMSWAP)
    474 struct swapcluster {
    475 	int swc_slot;
    476 	int swc_nallocated;
    477 	int swc_nused;
    478 	struct vm_page *swc_pages[howmany(MAXPHYS, MIN_PAGE_SIZE)];
    479 };
    480 
    481 static void
    482 swapcluster_init(struct swapcluster *swc)
    483 {
    484 
    485 	swc->swc_slot = 0;
    486 	swc->swc_nused = 0;
    487 }
    488 
    489 static int
    490 swapcluster_allocslots(struct swapcluster *swc)
    491 {
    492 	int slot;
    493 	int npages;
    494 
    495 	if (swc->swc_slot != 0) {
    496 		return 0;
    497 	}
    498 
    499 	/* Even with strange MAXPHYS, the shift
    500 	   implicitly rounds down to a page. */
    501 	npages = MAXPHYS >> PAGE_SHIFT;
    502 	slot = uvm_swap_alloc(&npages, true);
    503 	if (slot == 0) {
    504 		return ENOMEM;
    505 	}
    506 	swc->swc_slot = slot;
    507 	swc->swc_nallocated = npages;
    508 	swc->swc_nused = 0;
    509 
    510 	return 0;
    511 }
    512 
    513 static int
    514 swapcluster_add(struct swapcluster *swc, struct vm_page *pg)
    515 {
    516 	int slot;
    517 	struct uvm_object *uobj;
    518 
    519 	KASSERT(swc->swc_slot != 0);
    520 	KASSERT(swc->swc_nused < swc->swc_nallocated);
    521 	KASSERT((pg->flags & PG_SWAPBACKED) != 0);
    522 
    523 	slot = swc->swc_slot + swc->swc_nused;
    524 	uobj = pg->uobject;
    525 	if (uobj == NULL) {
    526 		KASSERT(mutex_owned(pg->uanon->an_lock));
    527 		pg->uanon->an_swslot = slot;
    528 	} else {
    529 		int result;
    530 
    531 		KASSERT(mutex_owned(uobj->vmobjlock));
    532 		result = uao_set_swslot(uobj, pg->offset >> PAGE_SHIFT, slot);
    533 		if (result == -1) {
    534 			return ENOMEM;
    535 		}
    536 	}
    537 	swc->swc_pages[swc->swc_nused] = pg;
    538 	swc->swc_nused++;
    539 
    540 	return 0;
    541 }
    542 
    543 static void
    544 swapcluster_flush(struct swapcluster *swc, bool now)
    545 {
    546 	int slot;
    547 	int nused;
    548 	int nallocated;
    549 	int error __diagused;
    550 
    551 	if (swc->swc_slot == 0) {
    552 		return;
    553 	}
    554 	KASSERT(swc->swc_nused <= swc->swc_nallocated);
    555 
    556 	slot = swc->swc_slot;
    557 	nused = swc->swc_nused;
    558 	nallocated = swc->swc_nallocated;
    559 
    560 	/*
    561 	 * if this is the final pageout we could have a few
    562 	 * unused swap blocks.  if so, free them now.
    563 	 */
    564 
    565 	if (nused < nallocated) {
    566 		if (!now) {
    567 			return;
    568 		}
    569 		uvm_swap_free(slot + nused, nallocated - nused);
    570 	}
    571 
    572 	/*
    573 	 * now start the pageout.
    574 	 */
    575 
    576 	if (nused > 0) {
    577 		uvmexp.pdpageouts++;
    578 		uvm_pageout_start(nused);
    579 		error = uvm_swap_put(slot, swc->swc_pages, nused, 0);
    580 		KASSERT(error == 0 || error == ENOMEM);
    581 	}
    582 
    583 	/*
    584 	 * zero swslot to indicate that we are
    585 	 * no longer building a swap-backed cluster.
    586 	 */
    587 
    588 	swc->swc_slot = 0;
    589 	swc->swc_nused = 0;
    590 }
    591 
    592 static int
    593 swapcluster_nused(struct swapcluster *swc)
    594 {
    595 
    596 	return swc->swc_nused;
    597 }
    598 
    599 /*
    600  * uvmpd_dropswap: free any swap allocated to this page.
    601  *
    602  * => called with owner locked.
    603  * => return true if a page had an associated slot.
    604  */
    605 
    606 static bool
    607 uvmpd_dropswap(struct vm_page *pg)
    608 {
    609 	bool result = false;
    610 	struct vm_anon *anon = pg->uanon;
    611 
    612 	if ((pg->flags & PG_ANON) && anon->an_swslot) {
    613 		uvm_swap_free(anon->an_swslot, 1);
    614 		anon->an_swslot = 0;
    615 		pg->flags &= ~PG_CLEAN;
    616 		result = true;
    617 	} else if (pg->flags & PG_AOBJ) {
    618 		int slot = uao_set_swslot(pg->uobject,
    619 		    pg->offset >> PAGE_SHIFT, 0);
    620 		if (slot) {
    621 			uvm_swap_free(slot, 1);
    622 			pg->flags &= ~PG_CLEAN;
    623 			result = true;
    624 		}
    625 	}
    626 
    627 	return result;
    628 }
    629 
    630 /*
    631  * uvmpd_trydropswap: try to free any swap allocated to this page.
    632  *
    633  * => return true if a slot is successfully freed.
    634  * => page interlock must be held, and will be dropped.
    635  */
    636 
    637 bool
    638 uvmpd_trydropswap(struct vm_page *pg)
    639 {
    640 	kmutex_t *slock;
    641 	bool result;
    642 
    643 	if ((pg->flags & PG_BUSY) != 0) {
    644 		mutex_exit(&pg->interlock);
    645 		return false;
    646 	}
    647 
    648 	/*
    649 	 * lock the page's owner.
    650 	 * this will drop pg->interlock.
    651 	 */
    652 
    653 	slock = uvmpd_trylockowner(pg);
    654 	if (slock == NULL) {
    655 		return false;
    656 	}
    657 
    658 	/*
    659 	 * skip this page if it's busy.
    660 	 */
    661 
    662 	if ((pg->flags & PG_BUSY) != 0) {
    663 		mutex_exit(slock);
    664 		return false;
    665 	}
    666 
    667 	result = uvmpd_dropswap(pg);
    668 
    669 	mutex_exit(slock);
    670 
    671 	return result;
    672 }
    673 
    674 #endif /* defined(VMSWAP) */
    675 
    676 /*
    677  * uvmpd_scan_queue: scan an replace candidate list for pages
    678  * to clean or free.
    679  *
    680  * => we work on meeting our free target by converting inactive pages
    681  *    into free pages.
    682  * => we handle the building of swap-backed clusters
    683  */
    684 
    685 static void
    686 uvmpd_scan_queue(void)
    687 {
    688 	struct vm_page *p;
    689 	struct uvm_object *uobj;
    690 	struct vm_anon *anon;
    691 #if defined(VMSWAP)
    692 	struct swapcluster swc;
    693 #endif /* defined(VMSWAP) */
    694 	int dirtyreacts;
    695 	kmutex_t *slock;
    696 	UVMHIST_FUNC("uvmpd_scan_queue"); UVMHIST_CALLED(pdhist);
    697 
    698 	/*
    699 	 * swslot is non-zero if we are building a swap cluster.  we want
    700 	 * to stay in the loop while we have a page to scan or we have
    701 	 * a swap-cluster to build.
    702 	 */
    703 
    704 #if defined(VMSWAP)
    705 	swapcluster_init(&swc);
    706 #endif /* defined(VMSWAP) */
    707 
    708 	dirtyreacts = 0;
    709 	uvmpdpol_scaninit();
    710 
    711 	while (/* CONSTCOND */ 1) {
    712 
    713 		/*
    714 		 * see if we've met the free target.
    715 		 */
    716 
    717 		if (uvmexp.free + uvmexp.paging
    718 #if defined(VMSWAP)
    719 		    + swapcluster_nused(&swc)
    720 #endif /* defined(VMSWAP) */
    721 		    >= uvmexp.freetarg << 2 ||
    722 		    dirtyreacts == UVMPD_NUMDIRTYREACTS) {
    723 			UVMHIST_LOG(pdhist,"  met free target: "
    724 				    "exit loop", 0, 0, 0, 0);
    725 			break;
    726 		}
    727 
    728 		/*
    729 		 * first we have the pdpolicy select a victim page
    730 		 * and attempt to lock the object that the page
    731 		 * belongs to.  if our attempt fails we skip on to
    732 		 * the next page (no harm done).  it is important to
    733 		 * "try" locking the object as we are locking in the
    734 		 * wrong order (pageq -> object) and we don't want to
    735 		 * deadlock.
    736 		 *
    737 		 * the only time we expect to see an ownerless page
    738 		 * (i.e. a page with no uobject and !PG_ANON) is if an
    739 		 * anon has loaned a page from a uvm_object and the
    740 		 * uvm_object has dropped the ownership.  in that
    741 		 * case, the anon can "take over" the loaned page
    742 		 * and make it its own.
    743 		 */
    744 
    745 		p = uvmpdpol_selectvictim(&slock);
    746 		if (p == NULL) {
    747 			break;
    748 		}
    749 		KASSERT(uvmpdpol_pageisqueued_p(p));
    750 		KASSERT(uvm_page_locked_p(p));
    751 		KASSERT(p->wire_count == 0);
    752 
    753 		/*
    754 		 * we are below target and have a new page to consider.
    755 		 */
    756 
    757 		anon = p->uanon;
    758 		uobj = p->uobject;
    759 
    760 		if (p->flags & PG_BUSY) {
    761 			mutex_exit(slock);
    762 			uvmexp.pdbusy++;
    763 			continue;
    764 		}
    765 
    766 		/* does the page belong to an object? */
    767 		if (uobj != NULL) {
    768 			uvmexp.pdobscan++;
    769 		} else {
    770 #if defined(VMSWAP)
    771 			KASSERT(anon != NULL);
    772 			uvmexp.pdanscan++;
    773 #else /* defined(VMSWAP) */
    774 			panic("%s: anon", __func__);
    775 #endif /* defined(VMSWAP) */
    776 		}
    777 
    778 
    779 		/*
    780 		 * we now have the object locked.
    781 		 * if the page is not swap-backed, call the object's
    782 		 * pager to flush and free the page.
    783 		 */
    784 
    785 #if defined(READAHEAD_STATS)
    786 		if ((p->flags & PG_READAHEAD) != 0) {
    787 			p->flags &= ~PG_READAHEAD;
    788 			uvm_ra_miss.ev_count++;
    789 		}
    790 #endif /* defined(READAHEAD_STATS) */
    791 
    792 		if ((p->flags & PG_SWAPBACKED) == 0) {
    793 			KASSERT(uobj != NULL);
    794 			(void) (uobj->pgops->pgo_put)(uobj, p->offset,
    795 			    p->offset + PAGE_SIZE, PGO_CLEANIT|PGO_FREE);
    796 			continue;
    797 		}
    798 
    799 		/*
    800 		 * the page is swap-backed.  remove all the permissions
    801 		 * from the page so we can sync the modified info
    802 		 * without any race conditions.  if the page is clean
    803 		 * we can free it now and continue.
    804 		 */
    805 
    806 		pmap_page_protect(p, VM_PROT_NONE);
    807 		if ((p->flags & PG_CLEAN) && pmap_clear_modify(p)) {
    808 			p->flags &= ~(PG_CLEAN);
    809 		}
    810 		if (p->flags & PG_CLEAN) {
    811 			int slot;
    812 			int pageidx;
    813 
    814 			pageidx = p->offset >> PAGE_SHIFT;
    815 			uvm_pagefree(p);
    816 			atomic_inc_uint(&uvmexp.pdfreed);
    817 
    818 			/*
    819 			 * for anons, we need to remove the page
    820 			 * from the anon ourselves.  for aobjs,
    821 			 * pagefree did that for us.
    822 			 */
    823 
    824 			if (anon) {
    825 				KASSERT(anon->an_swslot != 0);
    826 				anon->an_page = NULL;
    827 				slot = anon->an_swslot;
    828 			} else {
    829 				slot = uao_find_swslot(uobj, pageidx);
    830 			}
    831 			if (slot > 0) {
    832 				/* this page is now only in swap. */
    833 				KASSERT(uvmexp.swpgonly < uvmexp.swpginuse);
    834 				atomic_inc_uint(&uvmexp.swpgonly);
    835 			}
    836 			mutex_exit(slock);
    837 			continue;
    838 		}
    839 
    840 #if defined(VMSWAP)
    841 		/*
    842 		 * this page is dirty, skip it if we'll have met our
    843 		 * free target when all the current pageouts complete.
    844 		 */
    845 
    846 		if (uvmexp.free + uvmexp.paging > uvmexp.freetarg << 2) {
    847 			mutex_exit(slock);
    848 			continue;
    849 		}
    850 
    851 		/*
    852 		 * free any swap space allocated to the page since
    853 		 * we'll have to write it again with its new data.
    854 		 */
    855 
    856 		uvmpd_dropswap(p);
    857 
    858 		/*
    859 		 * start new swap pageout cluster (if necessary).
    860 		 *
    861 		 * if swap is full reactivate this page so that
    862 		 * we eventually cycle all pages through the
    863 		 * inactive queue.
    864 		 */
    865 
    866 		if (swapcluster_allocslots(&swc)) {
    867 			dirtyreacts++;
    868 			uvm_pageactivate(p);
    869 			mutex_exit(slock);
    870 			continue;
    871 		}
    872 
    873 		/*
    874 		 * at this point, we're definitely going reuse this
    875 		 * page.  mark the page busy and delayed-free.
    876 		 * we should remove the page from the page queues
    877 		 * so we don't ever look at it again.
    878 		 * adjust counters and such.
    879 		 */
    880 
    881 		p->flags |= PG_BUSY;
    882 		UVM_PAGE_OWN(p, "scan_queue");
    883 		p->flags |= PG_PAGEOUT;
    884 		uvmexp.pgswapout++;
    885 
    886 		uvm_pagedequeue(p);
    887 
    888 		/*
    889 		 * add the new page to the cluster.
    890 		 */
    891 
    892 		if (swapcluster_add(&swc, p)) {
    893 			p->flags &= ~(PG_BUSY|PG_PAGEOUT);
    894 			UVM_PAGE_OWN(p, NULL);
    895 			dirtyreacts++;
    896 			uvm_pageactivate(p);
    897 			mutex_exit(slock);
    898 			continue;
    899 		}
    900 		mutex_exit(slock);
    901 
    902 		swapcluster_flush(&swc, false);
    903 
    904 		/*
    905 		 * the pageout is in progress.  bump counters and set up
    906 		 * for the next loop.
    907 		 */
    908 
    909 		atomic_inc_uint(&uvmexp.pdpending);
    910 
    911 #else /* defined(VMSWAP) */
    912 		uvm_pageactivate(p);
    913 		mutex_exit(slock);
    914 #endif /* defined(VMSWAP) */
    915 	}
    916 
    917 #if defined(VMSWAP)
    918 	swapcluster_flush(&swc, true);
    919 #endif /* defined(VMSWAP) */
    920 }
    921 
    922 /*
    923  * uvmpd_scan: scan the page queues and attempt to meet our targets.
    924  */
    925 
    926 static void
    927 uvmpd_scan(void)
    928 {
    929 	int swap_shortage, pages_freed;
    930 	UVMHIST_FUNC("uvmpd_scan"); UVMHIST_CALLED(pdhist);
    931 
    932 	uvmexp.pdrevs++;
    933 
    934 	/*
    935 	 * work on meeting our targets.   first we work on our free target
    936 	 * by converting inactive pages into free pages.  then we work on
    937 	 * meeting our inactive target by converting active pages to
    938 	 * inactive ones.
    939 	 */
    940 
    941 	UVMHIST_LOG(pdhist, "  starting 'free' loop",0,0,0,0);
    942 
    943 	pages_freed = uvmexp.pdfreed;
    944 	uvmpd_scan_queue();
    945 	pages_freed = uvmexp.pdfreed - pages_freed;
    946 
    947 	/*
    948 	 * detect if we're not going to be able to page anything out
    949 	 * until we free some swap resources from active pages.
    950 	 */
    951 
    952 	swap_shortage = 0;
    953 	if (uvmexp.free < uvmexp.freetarg &&
    954 	    uvmexp.swpginuse >= uvmexp.swpgavail &&
    955 	    !uvm_swapisfull() &&
    956 	    pages_freed == 0) {
    957 		swap_shortage = uvmexp.freetarg - uvmexp.free;
    958 	}
    959 
    960 	uvmpdpol_balancequeue(swap_shortage);
    961 
    962 	/*
    963 	 * if still below the minimum target, try unloading kernel
    964 	 * modules.
    965 	 */
    966 
    967 	if (uvmexp.free < uvmexp.freemin) {
    968 		module_thread_kick();
    969 	}
    970 }
    971 
    972 /*
    973  * uvm_reclaimable: decide whether to wait for pagedaemon.
    974  *
    975  * => return true if it seems to be worth to do uvm_wait.
    976  *
    977  * XXX should be tunable.
    978  * XXX should consider pools, etc?
    979  */
    980 
    981 bool
    982 uvm_reclaimable(void)
    983 {
    984 	int filepages;
    985 	int active, inactive;
    986 
    987 	/*
    988 	 * if swap is not full, no problem.
    989 	 */
    990 
    991 	if (!uvm_swapisfull()) {
    992 		return true;
    993 	}
    994 
    995 	/*
    996 	 * file-backed pages can be reclaimed even when swap is full.
    997 	 * if we have more than 1/16 of pageable memory or 5MB, try to reclaim.
    998 	 *
    999 	 * XXX assume the worst case, ie. all wired pages are file-backed.
   1000 	 *
   1001 	 * XXX should consider about other reclaimable memory.
   1002 	 * XXX ie. pools, traditional buffer cache.
   1003 	 */
   1004 
   1005 	filepages = uvmexp.filepages + uvmexp.execpages - uvmexp.wired;
   1006 	uvm_estimatepageable(&active, &inactive);
   1007 	if (filepages >= MIN((active + inactive) >> 4,
   1008 	    5 * 1024 * 1024 >> PAGE_SHIFT)) {
   1009 		return true;
   1010 	}
   1011 
   1012 	/*
   1013 	 * kill the process, fail allocation, etc..
   1014 	 */
   1015 
   1016 	return false;
   1017 }
   1018 
   1019 void
   1020 uvm_estimatepageable(int *active, int *inactive)
   1021 {
   1022 
   1023 	uvmpdpol_estimatepageable(active, inactive);
   1024 }
   1025 
   1026 
   1027 /*
   1028  * Use a separate thread for draining pools.
   1029  * This work can't done from the main pagedaemon thread because
   1030  * some pool allocators need to take vm_map locks.
   1031  */
   1032 
   1033 static void
   1034 uvmpd_pool_drain_thread(void *arg)
   1035 {
   1036 	int bufcnt;
   1037 
   1038 	for (;;) {
   1039 		mutex_enter(&uvmpd_pool_drain_lock);
   1040 		if (!uvmpd_pool_drain_run) {
   1041 			cv_wait(&uvmpd_pool_drain_cv, &uvmpd_pool_drain_lock);
   1042 		}
   1043 		uvmpd_pool_drain_run = false;
   1044 		mutex_exit(&uvmpd_pool_drain_lock);
   1045 
   1046 		/*
   1047 		 * kill unused metadata buffers.
   1048 		 */
   1049 		mutex_spin_enter(&uvm_fpageqlock);
   1050 		bufcnt = uvmexp.freetarg - uvmexp.free;
   1051 		mutex_spin_exit(&uvm_fpageqlock);
   1052 		if (bufcnt < 0)
   1053 			bufcnt = 0;
   1054 
   1055 		mutex_enter(&bufcache_lock);
   1056 		buf_drain(bufcnt << PAGE_SHIFT);
   1057 		mutex_exit(&bufcache_lock);
   1058 
   1059 		/*
   1060 		 * drain a pool.
   1061 		 */
   1062 		pool_drain(NULL);
   1063 	}
   1064 	/*NOTREACHED*/
   1065 }
   1066 
   1067 static void
   1068 uvmpd_pool_drain_wakeup(void)
   1069 {
   1070 
   1071 	mutex_enter(&uvmpd_pool_drain_lock);
   1072 	uvmpd_pool_drain_run = true;
   1073 	cv_signal(&uvmpd_pool_drain_cv);
   1074 	mutex_exit(&uvmpd_pool_drain_lock);
   1075 }
   1076