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