xref: /openbsd-src/sys/uvm/uvm_pdaemon.c (revision 7bbe964f6b7d22ad07ca46292495604f942eba4e)
1 /*	$OpenBSD: uvm_pdaemon.c,v 1.55 2009/10/14 17:53:30 beck Exp $	*/
2 /*	$NetBSD: uvm_pdaemon.c,v 1.23 2000/08/20 10:24:14 bjh21 Exp $	*/
3 
4 /*
5  * Copyright (c) 1997 Charles D. Cranor and Washington University.
6  * Copyright (c) 1991, 1993, The Regents of the University of California.
7  *
8  * All rights reserved.
9  *
10  * This code is derived from software contributed to Berkeley by
11  * The Mach Operating System project at Carnegie-Mellon University.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *	This product includes software developed by Charles D. Cranor,
24  *      Washington University, the University of California, Berkeley and
25  *      its contributors.
26  * 4. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *	@(#)vm_pageout.c        8.5 (Berkeley) 2/14/94
43  * from: Id: uvm_pdaemon.c,v 1.1.2.32 1998/02/06 05:26:30 chs Exp
44  *
45  *
46  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
47  * All rights reserved.
48  *
49  * Permission to use, copy, modify and distribute this software and
50  * its documentation is hereby granted, provided that both the copyright
51  * notice and this permission notice appear in all copies of the
52  * software, derivative works or modified versions, and any portions
53  * thereof, and that both notices appear in supporting documentation.
54  *
55  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58  *
59  * Carnegie Mellon requests users of this software to return to
60  *
61  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
62  *  School of Computer Science
63  *  Carnegie Mellon University
64  *  Pittsburgh PA 15213-3890
65  *
66  * any improvements or extensions that they make and grant Carnegie the
67  * rights to redistribute these changes.
68  */
69 
70 /*
71  * uvm_pdaemon.c: the page daemon
72  */
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/vnode.h>
81 #include <sys/mount.h>
82 
83 #include <uvm/uvm.h>
84 
85 /*
86  * UVMPD_NUMDIRTYREACTS is how many dirty pages the pagedaemon will reactivate
87  * in a pass thru the inactive list when swap is full.  the value should be
88  * "small"... if it's too large we'll cycle the active pages thru the inactive
89  * queue too quickly to for them to be referenced and avoid being freed.
90  */
91 
92 #define UVMPD_NUMDIRTYREACTS 16
93 
94 
95 /*
96  * local prototypes
97  */
98 
99 static void		uvmpd_scan(void);
100 static boolean_t	uvmpd_scan_inactive(struct pglist *);
101 static void		uvmpd_tune(void);
102 
103 /*
104  * uvm_wait: wait (sleep) for the page daemon to free some pages
105  *
106  * => should be called with all locks released
107  * => should _not_ be called by the page daemon (to avoid deadlock)
108  */
109 
110 void
111 uvm_wait(const char *wmsg)
112 {
113 	int	timo = 0;
114 
115 	/*
116 	 * check for page daemon going to sleep (waiting for itself)
117 	 */
118 
119 	if (curproc == uvm.pagedaemon_proc) {
120 		/*
121 		 * now we have a problem: the pagedaemon wants to go to
122 		 * sleep until it frees more memory.   but how can it
123 		 * free more memory if it is asleep?  that is a deadlock.
124 		 * we have two options:
125 		 *  [1] panic now
126 		 *  [2] put a timeout on the sleep, thus causing the
127 		 *      pagedaemon to only pause (rather than sleep forever)
128 		 *
129 		 * note that option [2] will only help us if we get lucky
130 		 * and some other process on the system breaks the deadlock
131 		 * by exiting or freeing memory (thus allowing the pagedaemon
132 		 * to continue).  for now we panic if DEBUG is defined,
133 		 * otherwise we hope for the best with option [2] (better
134 		 * yet, this should never happen in the first place!).
135 		 */
136 
137 		printf("pagedaemon: deadlock detected!\n");
138 		timo = hz >> 3;		/* set timeout */
139 #if defined(DEBUG)
140 		/* DEBUG: panic so we can debug it */
141 		panic("pagedaemon deadlock");
142 #endif
143 	}
144 
145 	uvm_lock_fpageq();
146 	wakeup(&uvm.pagedaemon);		/* wake the daemon! */
147 	msleep(&uvmexp.free, &uvm.fpageqlock, PVM | PNORELOCK, wmsg, timo);
148 }
149 
150 
151 /*
152  * uvmpd_tune: tune paging parameters
153  *
154  * => called when ever memory is added (or removed?) to the system
155  * => caller must call with page queues locked
156  */
157 
158 static void
159 uvmpd_tune(void)
160 {
161 	UVMHIST_FUNC("uvmpd_tune"); UVMHIST_CALLED(pdhist);
162 
163 	uvmexp.freemin = uvmexp.npages / 30;
164 
165 	/* between 16k and 512k */
166 	/* XXX:  what are these values good for? */
167 	uvmexp.freemin = max(uvmexp.freemin, (16*1024) >> PAGE_SHIFT);
168 #if 0
169 	uvmexp.freemin = min(uvmexp.freemin, (512*1024) >> PAGE_SHIFT);
170 #endif
171 
172 	/* Make sure there's always a user page free. */
173 	if (uvmexp.freemin < uvmexp.reserve_kernel + 1)
174 		uvmexp.freemin = uvmexp.reserve_kernel + 1;
175 
176 	uvmexp.freetarg = (uvmexp.freemin * 4) / 3;
177 	if (uvmexp.freetarg <= uvmexp.freemin)
178 		uvmexp.freetarg = uvmexp.freemin + 1;
179 
180 	/* uvmexp.inactarg: computed in main daemon loop */
181 
182 	uvmexp.wiredmax = uvmexp.npages / 3;
183 	UVMHIST_LOG(pdhist, "<- done, freemin=%ld, freetarg=%ld, wiredmax=%ld",
184 	      uvmexp.freemin, uvmexp.freetarg, uvmexp.wiredmax, 0);
185 }
186 
187 /*
188  * uvm_pageout: the main loop for the pagedaemon
189  */
190 
191 void
192 uvm_pageout(void *arg)
193 {
194 	int npages = 0;
195 	UVMHIST_FUNC("uvm_pageout"); UVMHIST_CALLED(pdhist);
196 
197 	UVMHIST_LOG(pdhist,"<starting uvm pagedaemon>", 0, 0, 0, 0);
198 
199 	/*
200 	 * ensure correct priority and set paging parameters...
201 	 */
202 
203 	uvm.pagedaemon_proc = curproc;
204 	(void) spl0();
205 	uvm_lock_pageq();
206 	npages = uvmexp.npages;
207 	uvmpd_tune();
208 	uvm_unlock_pageq();
209 
210 	/*
211 	 * main loop
212 	 */
213 
214 	for (;;) {
215 		uvm_lock_fpageq();
216 		UVMHIST_LOG(pdhist,"  <<SLEEPING>>",0,0,0,0);
217 		msleep(&uvm.pagedaemon, &uvm.fpageqlock, PVM | PNORELOCK,
218 		    "pgdaemon", 0);
219 		uvmexp.pdwoke++;
220 		UVMHIST_LOG(pdhist,"  <<WOKE UP>>",0,0,0,0);
221 
222 		/*
223 		 * now lock page queues and recompute inactive count
224 		 */
225 
226 		uvm_lock_pageq();
227 		if (npages != uvmexp.npages) {	/* check for new pages? */
228 			npages = uvmexp.npages;
229 			uvmpd_tune();
230 		}
231 
232 		uvmexp.inactarg = (uvmexp.active + uvmexp.inactive) / 3;
233 		if (uvmexp.inactarg <= uvmexp.freetarg) {
234 			uvmexp.inactarg = uvmexp.freetarg + 1;
235 		}
236 
237 		UVMHIST_LOG(pdhist,"  free/ftarg=%ld/%ld, inact/itarg=%ld/%ld",
238 		    uvmexp.free, uvmexp.freetarg, uvmexp.inactive,
239 		    uvmexp.inactarg);
240 
241 		/*
242 		 * get pages from the buffer cache, or scan if needed
243 		 */
244 		if (((uvmexp.free - BUFPAGES_DEFICIT) < uvmexp.freetarg) ||
245 		    ((uvmexp.inactive + BUFPAGES_INACT) < uvmexp.inactarg)) {
246 			if (bufbackoff() == -1)
247 				uvmpd_scan();
248 		}
249 
250 		/*
251 		 * if there's any free memory to be had,
252 		 * wake up any waiters.
253 		 */
254 		uvm_lock_fpageq();
255 		if (uvmexp.free > uvmexp.reserve_kernel ||
256 		    uvmexp.paging == 0) {
257 			wakeup(&uvmexp.free);
258 		}
259 		uvm_unlock_fpageq();
260 
261 		/*
262 		 * scan done.  unlock page queues (the only lock we are holding)
263 		 */
264 
265 		uvm_unlock_pageq();
266 	}
267 	/*NOTREACHED*/
268 }
269 
270 
271 /*
272  * uvm_aiodone_daemon:  main loop for the aiodone daemon.
273  */
274 
275 void
276 uvm_aiodone_daemon(void *arg)
277 {
278 	int s, free;
279 	struct buf *bp, *nbp;
280 	UVMHIST_FUNC("uvm_aiodoned"); UVMHIST_CALLED(pdhist);
281 
282 	uvm.aiodoned_proc = curproc;
283 
284 	for (;;) {
285 
286 		/*
287 		 * Check for done aio structures. If we've got structures to
288 		 * process, do so. Otherwise sleep while avoiding races.
289 		 */
290 		mtx_enter(&uvm.aiodoned_lock);
291 		while ((bp = TAILQ_FIRST(&uvm.aio_done)) == NULL)
292 			msleep(&uvm.aiodoned, &uvm.aiodoned_lock,
293 			    PVM, "aiodoned", 0);
294 		/* Take the list for ourselves. */
295 		TAILQ_INIT(&uvm.aio_done);
296 		mtx_leave(&uvm.aiodoned_lock);
297 
298 		/*
299 		 * process each i/o that's done.
300 		 */
301 
302 		free = uvmexp.free;
303 		while (bp != NULL) {
304 			if (bp->b_flags & B_PDAEMON) {
305 				uvmexp.paging -= bp->b_bufsize >> PAGE_SHIFT;
306 			}
307 			nbp = TAILQ_NEXT(bp, b_freelist);
308 			s = splbio();	/* b_iodone must by called at splbio */
309 			(*bp->b_iodone)(bp);
310 			splx(s);
311 			bp = nbp;
312 		}
313 		uvm_lock_fpageq();
314 		wakeup(free <= uvmexp.reserve_kernel ? &uvm.pagedaemon :
315 		    &uvmexp.free);
316 		uvm_unlock_fpageq();
317 	}
318 }
319 
320 
321 
322 /*
323  * uvmpd_scan_inactive: scan an inactive list for pages to clean or free.
324  *
325  * => called with page queues locked
326  * => we work on meeting our free target by converting inactive pages
327  *    into free pages.
328  * => we handle the building of swap-backed clusters
329  * => we return TRUE if we are exiting because we met our target
330  */
331 
332 static boolean_t
333 uvmpd_scan_inactive(struct pglist *pglst)
334 {
335 	boolean_t retval = FALSE;	/* assume we haven't hit target */
336 	int free, result;
337 	struct vm_page *p, *nextpg;
338 	struct uvm_object *uobj;
339 	struct vm_page *pps[MAXBSIZE >> PAGE_SHIFT], **ppsp;
340 	int npages;
341 	struct vm_page *swpps[MAXBSIZE >> PAGE_SHIFT]; 	/* XXX: see below */
342 	int swnpages, swcpages;				/* XXX: see below */
343 	int swslot;
344 	struct vm_anon *anon;
345 	boolean_t swap_backed;
346 	vaddr_t start;
347 	int dirtyreacts;
348 	UVMHIST_FUNC("uvmpd_scan_inactive"); UVMHIST_CALLED(pdhist);
349 
350 	/*
351 	 * note: we currently keep swap-backed pages on a separate inactive
352 	 * list from object-backed pages.   however, merging the two lists
353 	 * back together again hasn't been ruled out.   thus, we keep our
354 	 * swap cluster in "swpps" rather than in pps (allows us to mix
355 	 * clustering types in the event of a mixed inactive queue).
356 	 */
357 
358 	/*
359 	 * swslot is non-zero if we are building a swap cluster.  we want
360 	 * to stay in the loop while we have a page to scan or we have
361 	 * a swap-cluster to build.
362 	 */
363 
364 	swslot = 0;
365 	swnpages = swcpages = 0;
366 	free = 0;
367 	dirtyreacts = 0;
368 
369 	for (p = TAILQ_FIRST(pglst); p != NULL || swslot != 0; p = nextpg) {
370 
371 		/*
372 		 * note that p can be NULL iff we have traversed the whole
373 		 * list and need to do one final swap-backed clustered pageout.
374 		 */
375 
376 		uobj = NULL;
377 		anon = NULL;
378 
379 		if (p) {
380 
381 			/*
382 			 * update our copy of "free" and see if we've met
383 			 * our target
384 			 */
385 			free = uvmexp.free - BUFPAGES_DEFICIT;
386 
387 			if (free + uvmexp.paging >= uvmexp.freetarg << 2 ||
388 			    dirtyreacts == UVMPD_NUMDIRTYREACTS) {
389 				UVMHIST_LOG(pdhist,"  met free target: "
390 					    "exit loop", 0, 0, 0, 0);
391 				retval = TRUE;
392 
393 				if (swslot == 0) {
394 					/* exit now if no swap-i/o pending */
395 					break;
396 				}
397 
398 				/* set p to null to signal final swap i/o */
399 				p = NULL;
400 			}
401 		}
402 
403 		if (p) {	/* if (we have a new page to consider) */
404 
405 			/*
406 			 * we are below target and have a new page to consider.
407 			 */
408 			uvmexp.pdscans++;
409 			nextpg = TAILQ_NEXT(p, pageq);
410 
411 			/*
412 			 * move referenced pages back to active queue and
413 			 * skip to next page (unlikely to happen since
414 			 * inactive pages shouldn't have any valid mappings
415 			 * and we cleared reference before deactivating).
416 			 */
417 
418 			if (pmap_is_referenced(p)) {
419 				uvm_pageactivate(p);
420 				uvmexp.pdreact++;
421 				continue;
422 			}
423 
424 			/*
425 			 * first we attempt to lock the object that this page
426 			 * belongs to.  if our attempt fails we skip on to
427 			 * the next page (no harm done).  it is important to
428 			 * "try" locking the object as we are locking in the
429 			 * wrong order (pageq -> object) and we don't want to
430 			 * deadlock.
431 			 *
432 			 * the only time we expect to see an ownerless page
433 			 * (i.e. a page with no uobject and !PQ_ANON) is if an
434 			 * anon has loaned a page from a uvm_object and the
435 			 * uvm_object has dropped the ownership.  in that
436 			 * case, the anon can "take over" the loaned page
437 			 * and make it its own.
438 			 */
439 
440 			/* is page part of an anon or ownerless ? */
441 			if ((p->pg_flags & PQ_ANON) || p->uobject == NULL) {
442 				anon = p->uanon;
443 				KASSERT(anon != NULL);
444 				if (!simple_lock_try(&anon->an_lock)) {
445 					/* lock failed, skip this page */
446 					continue;
447 				}
448 
449 				/*
450 				 * if the page is ownerless, claim it in the
451 				 * name of "anon"!
452 				 */
453 
454 				if ((p->pg_flags & PQ_ANON) == 0) {
455 					KASSERT(p->loan_count > 0);
456 					p->loan_count--;
457 					atomic_setbits_int(&p->pg_flags,
458 					    PQ_ANON);
459 					/* anon now owns it */
460 				}
461 				if (p->pg_flags & PG_BUSY) {
462 					simple_unlock(&anon->an_lock);
463 					uvmexp.pdbusy++;
464 					/* someone else owns page, skip it */
465 					continue;
466 				}
467 				uvmexp.pdanscan++;
468 			} else {
469 				uobj = p->uobject;
470 				KASSERT(uobj != NULL);
471 				if (!simple_lock_try(&uobj->vmobjlock)) {
472 					/* lock failed, skip this page */
473 					continue;
474 				}
475 				if (p->pg_flags & PG_BUSY) {
476 					simple_unlock(&uobj->vmobjlock);
477 					uvmexp.pdbusy++;
478 					/* someone else owns page, skip it */
479 					continue;
480 				}
481 				uvmexp.pdobscan++;
482 			}
483 
484 			/*
485 			 * we now have the object and the page queues locked.
486 			 * the page is not busy.   if the page is clean we
487 			 * can free it now and continue.
488 			 */
489 
490 			if (p->pg_flags & PG_CLEAN) {
491 				if (p->pg_flags & PQ_SWAPBACKED) {
492 					/* this page now lives only in swap */
493 					simple_lock(&uvm.swap_data_lock);
494 					uvmexp.swpgonly++;
495 					simple_unlock(&uvm.swap_data_lock);
496 				}
497 
498 				/* zap all mappings with pmap_page_protect... */
499 				pmap_page_protect(p, VM_PROT_NONE);
500 				uvm_pagefree(p);
501 				uvmexp.pdfreed++;
502 
503 				if (anon) {
504 
505 					/*
506 					 * an anonymous page can only be clean
507 					 * if it has backing store assigned.
508 					 */
509 
510 					KASSERT(anon->an_swslot != 0);
511 
512 					/* remove from object */
513 					anon->an_page = NULL;
514 					simple_unlock(&anon->an_lock);
515 				} else {
516 					/* pagefree has already removed the
517 					 * page from the object */
518 					simple_unlock(&uobj->vmobjlock);
519 				}
520 				continue;
521 			}
522 
523 			/*
524 			 * this page is dirty, skip it if we'll have met our
525 			 * free target when all the current pageouts complete.
526 			 */
527 
528 			if (free + uvmexp.paging > uvmexp.freetarg << 2) {
529 				if (anon) {
530 					simple_unlock(&anon->an_lock);
531 				} else {
532 					simple_unlock(&uobj->vmobjlock);
533 				}
534 				continue;
535 			}
536 
537 			/*
538 			 * this page is dirty, but we can't page it out
539 			 * since all pages in swap are only in swap.
540 			 * reactivate it so that we eventually cycle
541 			 * all pages thru the inactive queue.
542 			 */
543 
544 			KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
545 			if ((p->pg_flags & PQ_SWAPBACKED) &&
546 			    uvmexp.swpgonly == uvmexp.swpages) {
547 				dirtyreacts++;
548 				uvm_pageactivate(p);
549 				if (anon) {
550 					simple_unlock(&anon->an_lock);
551 				} else {
552 					simple_unlock(&uobj->vmobjlock);
553 				}
554 				continue;
555 			}
556 
557 			/*
558 			 * if the page is swap-backed and dirty and swap space
559 			 * is full, free any swap allocated to the page
560 			 * so that other pages can be paged out.
561 			 */
562 
563 			KASSERT(uvmexp.swpginuse <= uvmexp.swpages);
564 			if ((p->pg_flags & PQ_SWAPBACKED) &&
565 			    uvmexp.swpginuse == uvmexp.swpages) {
566 
567 				if ((p->pg_flags & PQ_ANON) &&
568 				    p->uanon->an_swslot) {
569 					uvm_swap_free(p->uanon->an_swslot, 1);
570 					p->uanon->an_swslot = 0;
571 				}
572 				if (p->pg_flags & PQ_AOBJ) {
573 					uao_dropswap(p->uobject,
574 						     p->offset >> PAGE_SHIFT);
575 				}
576 			}
577 
578 			/*
579 			 * the page we are looking at is dirty.   we must
580 			 * clean it before it can be freed.  to do this we
581 			 * first mark the page busy so that no one else will
582 			 * touch the page.   we write protect all the mappings
583 			 * of the page so that no one touches it while it is
584 			 * in I/O.
585 			 */
586 
587 			swap_backed = ((p->pg_flags & PQ_SWAPBACKED) != 0);
588 			atomic_setbits_int(&p->pg_flags, PG_BUSY);
589 			UVM_PAGE_OWN(p, "scan_inactive");
590 			pmap_page_protect(p, VM_PROT_READ);
591 			uvmexp.pgswapout++;
592 
593 			/*
594 			 * for swap-backed pages we need to (re)allocate
595 			 * swap space.
596 			 */
597 
598 			if (swap_backed) {
599 
600 				/*
601 				 * free old swap slot (if any)
602 				 */
603 
604 				if (anon) {
605 					if (anon->an_swslot) {
606 						uvm_swap_free(anon->an_swslot,
607 						    1);
608 						anon->an_swslot = 0;
609 					}
610 				} else {
611 					uao_dropswap(uobj,
612 						     p->offset >> PAGE_SHIFT);
613 				}
614 
615 				/*
616 				 * start new cluster (if necessary)
617 				 */
618 
619 				if (swslot == 0) {
620 					swnpages = MAXBSIZE >> PAGE_SHIFT;
621 					swslot = uvm_swap_alloc(&swnpages,
622 					    TRUE);
623 					if (swslot == 0) {
624 						/* no swap?  give up! */
625 						atomic_clearbits_int(
626 						    &p->pg_flags,
627 						    PG_BUSY);
628 						UVM_PAGE_OWN(p, NULL);
629 						if (anon)
630 							simple_unlock(
631 							    &anon->an_lock);
632 						else
633 							simple_unlock(
634 							    &uobj->vmobjlock);
635 						continue;
636 					}
637 					swcpages = 0;	/* cluster is empty */
638 				}
639 
640 				/*
641 				 * add block to cluster
642 				 */
643 
644 				swpps[swcpages] = p;
645 				if (anon)
646 					anon->an_swslot = swslot + swcpages;
647 				else
648 					uao_set_swslot(uobj,
649 					    p->offset >> PAGE_SHIFT,
650 					    swslot + swcpages);
651 				swcpages++;
652 			}
653 		} else {
654 
655 			/* if p == NULL we must be doing a last swap i/o */
656 			swap_backed = TRUE;
657 		}
658 
659 		/*
660 		 * now consider doing the pageout.
661 		 *
662 		 * for swap-backed pages, we do the pageout if we have either
663 		 * filled the cluster (in which case (swnpages == swcpages) or
664 		 * run out of pages (p == NULL).
665 		 *
666 		 * for object pages, we always do the pageout.
667 		 */
668 
669 		if (swap_backed) {
670 			if (p) {	/* if we just added a page to cluster */
671 				if (anon)
672 					simple_unlock(&anon->an_lock);
673 				else
674 					simple_unlock(&uobj->vmobjlock);
675 
676 				/* cluster not full yet? */
677 				if (swcpages < swnpages)
678 					continue;
679 			}
680 
681 			/* starting I/O now... set up for it */
682 			npages = swcpages;
683 			ppsp = swpps;
684 			/* for swap-backed pages only */
685 			start = (vaddr_t) swslot;
686 
687 			/* if this is final pageout we could have a few
688 			 * extra swap blocks */
689 			if (swcpages < swnpages) {
690 				uvm_swap_free(swslot + swcpages,
691 				    (swnpages - swcpages));
692 			}
693 		} else {
694 			/* normal object pageout */
695 			ppsp = pps;
696 			npages = sizeof(pps) / sizeof(struct vm_page *);
697 			/* not looked at because PGO_ALLPAGES is set */
698 			start = 0;
699 		}
700 
701 		/*
702 		 * now do the pageout.
703 		 *
704 		 * for swap_backed pages we have already built the cluster.
705 		 * for !swap_backed pages, uvm_pager_put will call the object's
706 		 * "make put cluster" function to build a cluster on our behalf.
707 		 *
708 		 * we pass the PGO_PDFREECLUST flag to uvm_pager_put to instruct
709 		 * it to free the cluster pages for us on a successful I/O (it
710 		 * always does this for un-successful I/O requests).  this
711 		 * allows us to do clustered pageout without having to deal
712 		 * with cluster pages at this level.
713 		 *
714 		 * note locking semantics of uvm_pager_put with PGO_PDFREECLUST:
715 		 *  IN: locked: uobj (if !swap_backed), page queues
716 		 * OUT: locked: uobj (if !swap_backed && result !=VM_PAGER_PEND)
717 		 *     !locked: pageqs, uobj (if swap_backed || VM_PAGER_PEND)
718 		 *
719 		 * [the bit about VM_PAGER_PEND saves us one lock-unlock pair]
720 		 */
721 
722 		/* locked: uobj (if !swap_backed), page queues */
723 		uvmexp.pdpageouts++;
724 		result = uvm_pager_put(swap_backed ? NULL : uobj, p,
725 		    &ppsp, &npages, PGO_ALLPAGES|PGO_PDFREECLUST, start, 0);
726 		/* locked: uobj (if !swap_backed && result != PEND) */
727 		/* unlocked: pageqs, object (if swap_backed ||result == PEND) */
728 
729 		/*
730 		 * if we did i/o to swap, zero swslot to indicate that we are
731 		 * no longer building a swap-backed cluster.
732 		 */
733 
734 		if (swap_backed)
735 			swslot = 0;		/* done with this cluster */
736 
737 		/*
738 		 * first, we check for VM_PAGER_PEND which means that the
739 		 * async I/O is in progress and the async I/O done routine
740 		 * will clean up after us.   in this case we move on to the
741 		 * next page.
742 		 *
743 		 * there is a very remote chance that the pending async i/o can
744 		 * finish _before_ we get here.   if that happens, our page "p"
745 		 * may no longer be on the inactive queue.   so we verify this
746 		 * when determining the next page (starting over at the head if
747 		 * we've lost our inactive page).
748 		 */
749 
750 		if (result == VM_PAGER_PEND) {
751 			uvmexp.paging += npages;
752 			uvm_lock_pageq();
753 			uvmexp.pdpending++;
754 			if (p) {
755 				if (p->pg_flags & PQ_INACTIVE)
756 					nextpg = TAILQ_NEXT(p, pageq);
757 				else
758 					nextpg = TAILQ_FIRST(pglst);
759 			} else {
760 				nextpg = NULL;
761 			}
762 			continue;
763 		}
764 
765 #ifdef UBC
766 		if (result == VM_PAGER_ERROR &&
767 		    curproc == uvm.pagedaemon_proc) {
768 			uvm_lock_pageq();
769 			nextpg = TAILQ_NEXT(p, pageq);
770 			uvm_pageactivate(p);
771 			continue;
772 		}
773 #endif
774 
775 		/*
776 		 * clean up "p" if we have one
777 		 */
778 
779 		if (p) {
780 			/*
781 			 * the I/O request to "p" is done and uvm_pager_put
782 			 * has freed any cluster pages it may have allocated
783 			 * during I/O.  all that is left for us to do is
784 			 * clean up page "p" (which is still PG_BUSY).
785 			 *
786 			 * our result could be one of the following:
787 			 *   VM_PAGER_OK: successful pageout
788 			 *
789 			 *   VM_PAGER_AGAIN: tmp resource shortage, we skip
790 			 *     to next page
791 			 *   VM_PAGER_{FAIL,ERROR,BAD}: an error.   we
792 			 *     "reactivate" page to get it out of the way (it
793 			 *     will eventually drift back into the inactive
794 			 *     queue for a retry).
795 			 *   VM_PAGER_UNLOCK: should never see this as it is
796 			 *     only valid for "get" operations
797 			 */
798 
799 			/* relock p's object: page queues not lock yet, so
800 			 * no need for "try" */
801 
802 			/* !swap_backed case: already locked... */
803 			if (swap_backed) {
804 				if (anon)
805 					simple_lock(&anon->an_lock);
806 				else
807 					simple_lock(&uobj->vmobjlock);
808 			}
809 
810 #ifdef DIAGNOSTIC
811 			if (result == VM_PAGER_UNLOCK)
812 				panic("pagedaemon: pageout returned "
813 				    "invalid 'unlock' code");
814 #endif
815 
816 			/* handle PG_WANTED now */
817 			if (p->pg_flags & PG_WANTED)
818 				/* still holding object lock */
819 				wakeup(p);
820 
821 			atomic_clearbits_int(&p->pg_flags, PG_BUSY|PG_WANTED);
822 			UVM_PAGE_OWN(p, NULL);
823 
824 			/* released during I/O? Can only happen for anons */
825 			if (p->pg_flags & PG_RELEASED) {
826 				KASSERT(anon != NULL);
827 				/*
828 				 * remove page so we can get nextpg,
829 				 * also zero out anon so we don't use
830 				 * it after the free.
831 				 */
832 				anon->an_page = NULL;
833 				p->uanon = NULL;
834 
835 				simple_unlock(&anon->an_lock);
836 				uvm_anfree(anon);	/* kills anon */
837 				pmap_page_protect(p, VM_PROT_NONE);
838 				anon = NULL;
839 				uvm_lock_pageq();
840 				nextpg = TAILQ_NEXT(p, pageq);
841 				/* free released page */
842 				uvm_pagefree(p);
843 			} else {	/* page was not released during I/O */
844 				uvm_lock_pageq();
845 				nextpg = TAILQ_NEXT(p, pageq);
846 				if (result != VM_PAGER_OK) {
847 					/* pageout was a failure... */
848 					if (result != VM_PAGER_AGAIN)
849 						uvm_pageactivate(p);
850 					pmap_clear_reference(p);
851 					/* XXXCDC: if (swap_backed) FREE p's
852 					 * swap block? */
853 				} else {
854 					/* pageout was a success... */
855 					pmap_clear_reference(p);
856 					pmap_clear_modify(p);
857 					atomic_setbits_int(&p->pg_flags,
858 					    PG_CLEAN);
859 				}
860 			}
861 
862 			/*
863 			 * drop object lock (if there is an object left).   do
864 			 * a safety check of nextpg to make sure it is on the
865 			 * inactive queue (it should be since PG_BUSY pages on
866 			 * the inactive queue can't be re-queued [note: not
867 			 * true for active queue]).
868 			 */
869 
870 			if (anon)
871 				simple_unlock(&anon->an_lock);
872 			else if (uobj)
873 				simple_unlock(&uobj->vmobjlock);
874 
875 			if (nextpg && (nextpg->pg_flags & PQ_INACTIVE) == 0) {
876 				nextpg = TAILQ_FIRST(pglst);	/* reload! */
877 			}
878 		} else {
879 
880 			/*
881 			 * if p is null in this loop, make sure it stays null
882 			 * in the next loop.
883 			 */
884 
885 			nextpg = NULL;
886 
887 			/*
888 			 * lock page queues here just so they're always locked
889 			 * at the end of the loop.
890 			 */
891 
892 			uvm_lock_pageq();
893 		}
894 	}
895 	return (retval);
896 }
897 
898 /*
899  * uvmpd_scan: scan the page queues and attempt to meet our targets.
900  *
901  * => called with pageq's locked
902  */
903 
904 void
905 uvmpd_scan(void)
906 {
907 	int free, inactive_shortage, swap_shortage, pages_freed;
908 	struct vm_page *p, *nextpg;
909 	struct uvm_object *uobj;
910 	boolean_t got_it;
911 	UVMHIST_FUNC("uvmpd_scan"); UVMHIST_CALLED(pdhist);
912 
913 	uvmexp.pdrevs++;		/* counter */
914 	uobj = NULL;
915 
916 	/*
917 	 * get current "free" page count
918 	 */
919 	free = uvmexp.free - BUFPAGES_DEFICIT;
920 
921 #ifndef __SWAP_BROKEN
922 	/*
923 	 * swap out some processes if we are below our free target.
924 	 * we need to unlock the page queues for this.
925 	 */
926 	if (free < uvmexp.freetarg) {
927 		uvmexp.pdswout++;
928 		UVMHIST_LOG(pdhist,"  free %ld < target %ld: swapout", free,
929 		    uvmexp.freetarg, 0, 0);
930 		uvm_unlock_pageq();
931 		uvm_swapout_threads();
932 		uvm_lock_pageq();
933 	}
934 #endif
935 
936 	/*
937 	 * now we want to work on meeting our targets.   first we work on our
938 	 * free target by converting inactive pages into free pages.  then
939 	 * we work on meeting our inactive target by converting active pages
940 	 * to inactive ones.
941 	 */
942 
943 	UVMHIST_LOG(pdhist, "  starting 'free' loop",0,0,0,0);
944 
945 	/*
946 	 * alternate starting queue between swap and object based on the
947 	 * low bit of uvmexp.pdrevs (which we bump by one each call).
948 	 */
949 
950 	got_it = FALSE;
951 	pages_freed = uvmexp.pdfreed;	/* XXX - int */
952 	if ((uvmexp.pdrevs & 1) != 0 && uvmexp.nswapdev != 0)
953 		got_it = uvmpd_scan_inactive(&uvm.page_inactive_swp);
954 	if (!got_it)
955 		got_it = uvmpd_scan_inactive(&uvm.page_inactive_obj);
956 	if (!got_it && (uvmexp.pdrevs & 1) == 0 && uvmexp.nswapdev != 0)
957 		(void) uvmpd_scan_inactive(&uvm.page_inactive_swp);
958 	pages_freed = uvmexp.pdfreed - pages_freed;
959 
960 	/*
961 	 * we have done the scan to get free pages.   now we work on meeting
962 	 * our inactive target.
963 	 */
964 
965 	inactive_shortage = uvmexp.inactarg - uvmexp.inactive;
966 
967 	/*
968 	 * detect if we're not going to be able to page anything out
969 	 * until we free some swap resources from active pages.
970 	 */
971 
972 	swap_shortage = 0;
973 	if (uvmexp.free < uvmexp.freetarg &&
974 	    uvmexp.swpginuse == uvmexp.swpages &&
975 	    uvmexp.swpgonly < uvmexp.swpages &&
976 	    pages_freed == 0) {
977 		swap_shortage = uvmexp.freetarg - uvmexp.free;
978 	}
979 
980 	UVMHIST_LOG(pdhist, "  loop 2: inactive_shortage=%ld swap_shortage=%ld",
981 		    inactive_shortage, swap_shortage,0,0);
982 	for (p = TAILQ_FIRST(&uvm.page_active);
983 	     p != NULL && (inactive_shortage > 0 || swap_shortage > 0);
984 	     p = nextpg) {
985 		nextpg = TAILQ_NEXT(p, pageq);
986 		if (p->pg_flags & PG_BUSY)
987 			continue;	/* quick check before trying to lock */
988 
989 		/*
990 		 * lock the page's owner.
991 		 */
992 		/* is page anon owned or ownerless? */
993 		if ((p->pg_flags & PQ_ANON) || p->uobject == NULL) {
994 			KASSERT(p->uanon != NULL);
995 			if (!simple_lock_try(&p->uanon->an_lock))
996 				continue;
997 
998 			/* take over the page? */
999 			if ((p->pg_flags & PQ_ANON) == 0) {
1000 				KASSERT(p->loan_count > 0);
1001 				p->loan_count--;
1002 				atomic_setbits_int(&p->pg_flags, PQ_ANON);
1003 			}
1004 		} else {
1005 			if (!simple_lock_try(&p->uobject->vmobjlock))
1006 				continue;
1007 		}
1008 
1009 		/*
1010 		 * skip this page if it's busy.
1011 		 */
1012 
1013 		if ((p->pg_flags & PG_BUSY) != 0) {
1014 			if (p->pg_flags & PQ_ANON)
1015 				simple_unlock(&p->uanon->an_lock);
1016 			else
1017 				simple_unlock(&p->uobject->vmobjlock);
1018 			continue;
1019 		}
1020 
1021 		/*
1022 		 * if there's a shortage of swap, free any swap allocated
1023 		 * to this page so that other pages can be paged out.
1024 		 */
1025 
1026 		if (swap_shortage > 0) {
1027 			if ((p->pg_flags & PQ_ANON) && p->uanon->an_swslot) {
1028 				uvm_swap_free(p->uanon->an_swslot, 1);
1029 				p->uanon->an_swslot = 0;
1030 				atomic_clearbits_int(&p->pg_flags, PG_CLEAN);
1031 				swap_shortage--;
1032 			}
1033 			if (p->pg_flags & PQ_AOBJ) {
1034 				int slot = uao_set_swslot(p->uobject,
1035 					p->offset >> PAGE_SHIFT, 0);
1036 				if (slot) {
1037 					uvm_swap_free(slot, 1);
1038 					atomic_clearbits_int(&p->pg_flags,
1039 					    PG_CLEAN);
1040 					swap_shortage--;
1041 				}
1042 			}
1043 		}
1044 
1045 		/*
1046 		 * deactivate this page if there's a shortage of
1047 		 * inactive pages.
1048 		 */
1049 
1050 		if (inactive_shortage > 0) {
1051 			pmap_page_protect(p, VM_PROT_NONE);
1052 			/* no need to check wire_count as pg is "active" */
1053 			uvm_pagedeactivate(p);
1054 			uvmexp.pddeact++;
1055 			inactive_shortage--;
1056 		}
1057 		if (p->pg_flags & PQ_ANON)
1058 			simple_unlock(&p->uanon->an_lock);
1059 		else
1060 			simple_unlock(&p->uobject->vmobjlock);
1061 	}
1062 }
1063