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