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