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