xref: /openbsd-src/sys/uvm/uvm_pdaemon.c (revision 43003dfe3ad45d1698bed8a37f2b0f5b14f20d4f)
1 /*	$OpenBSD: uvm_pdaemon.c,v 1.54 2009/08/08 13:43:59 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 		int scanned = 0;
216 		uvm_lock_fpageq();
217 		UVMHIST_LOG(pdhist,"  <<SLEEPING>>",0,0,0,0);
218 		msleep(&uvm.pagedaemon, &uvm.fpageqlock, PVM | PNORELOCK,
219 		    "pgdaemon", 0);
220 		uvmexp.pdwoke++;
221 		UVMHIST_LOG(pdhist,"  <<WOKE UP>>",0,0,0,0);
222 
223 		/*
224 		 * now lock page queues and recompute inactive count
225 		 */
226 
227 		uvm_lock_pageq();
228 		if (npages != uvmexp.npages) {	/* check for new pages? */
229 			npages = uvmexp.npages;
230 			uvmpd_tune();
231 		}
232 
233 		uvmexp.inactarg = (uvmexp.active + uvmexp.inactive) / 3;
234 		if (uvmexp.inactarg <= uvmexp.freetarg) {
235 			uvmexp.inactarg = uvmexp.freetarg + 1;
236 		}
237 
238 		UVMHIST_LOG(pdhist,"  free/ftarg=%ld/%ld, inact/itarg=%ld/%ld",
239 		    uvmexp.free, uvmexp.freetarg, uvmexp.inactive,
240 		    uvmexp.inactarg);
241 
242 		/*
243 		 * get pages from the buffer cache, or scan if needed
244 		 */
245 		if ((uvmexp.free - BUFPAGES_DEFICIT) < uvmexp.freetarg) {
246 			if (bufbackoff() == -1) {
247 				uvmpd_scan();
248 				scanned = 1;
249 			} else
250 				scanned = 0;
251 		}
252 
253 		if (!scanned && (uvmexp.inactive < uvmexp.inactarg))
254 			uvmpd_scan();
255 
256 
257 		/*
258 		 * if there's any free memory to be had,
259 		 * wake up any waiters.
260 		 */
261 		uvm_lock_fpageq();
262 		if (uvmexp.free > uvmexp.reserve_kernel ||
263 		    uvmexp.paging == 0) {
264 			wakeup(&uvmexp.free);
265 		}
266 		uvm_unlock_fpageq();
267 
268 		/*
269 		 * scan done.  unlock page queues (the only lock we are holding)
270 		 */
271 
272 		uvm_unlock_pageq();
273 	}
274 	/*NOTREACHED*/
275 }
276 
277 
278 /*
279  * uvm_aiodone_daemon:  main loop for the aiodone daemon.
280  */
281 
282 void
283 uvm_aiodone_daemon(void *arg)
284 {
285 	int s, free;
286 	struct buf *bp, *nbp;
287 	UVMHIST_FUNC("uvm_aiodoned"); UVMHIST_CALLED(pdhist);
288 
289 	uvm.aiodoned_proc = curproc;
290 
291 	for (;;) {
292 
293 		/*
294 		 * Check for done aio structures. If we've got structures to
295 		 * process, do so. Otherwise sleep while avoiding races.
296 		 */
297 		mtx_enter(&uvm.aiodoned_lock);
298 		while ((bp = TAILQ_FIRST(&uvm.aio_done)) == NULL)
299 			msleep(&uvm.aiodoned, &uvm.aiodoned_lock,
300 			    PVM, "aiodoned", 0);
301 		/* Take the list for ourselves. */
302 		TAILQ_INIT(&uvm.aio_done);
303 		mtx_leave(&uvm.aiodoned_lock);
304 
305 		/*
306 		 * process each i/o that's done.
307 		 */
308 
309 		free = uvmexp.free;
310 		while (bp != NULL) {
311 			if (bp->b_flags & B_PDAEMON) {
312 				uvmexp.paging -= bp->b_bufsize >> PAGE_SHIFT;
313 			}
314 			nbp = TAILQ_NEXT(bp, b_freelist);
315 			s = splbio();	/* b_iodone must by called at splbio */
316 			(*bp->b_iodone)(bp);
317 			splx(s);
318 			bp = nbp;
319 		}
320 		uvm_lock_fpageq();
321 		wakeup(free <= uvmexp.reserve_kernel ? &uvm.pagedaemon :
322 		    &uvmexp.free);
323 		uvm_unlock_fpageq();
324 	}
325 }
326 
327 
328 
329 /*
330  * uvmpd_scan_inactive: scan an inactive list for pages to clean or free.
331  *
332  * => called with page queues locked
333  * => we work on meeting our free target by converting inactive pages
334  *    into free pages.
335  * => we handle the building of swap-backed clusters
336  * => we return TRUE if we are exiting because we met our target
337  */
338 
339 static boolean_t
340 uvmpd_scan_inactive(struct pglist *pglst)
341 {
342 	boolean_t retval = FALSE;	/* assume we haven't hit target */
343 	int free, result;
344 	struct vm_page *p, *nextpg;
345 	struct uvm_object *uobj;
346 	struct vm_page *pps[MAXBSIZE >> PAGE_SHIFT], **ppsp;
347 	int npages;
348 	struct vm_page *swpps[MAXBSIZE >> PAGE_SHIFT]; 	/* XXX: see below */
349 	int swnpages, swcpages;				/* XXX: see below */
350 	int swslot;
351 	struct vm_anon *anon;
352 	boolean_t swap_backed;
353 	vaddr_t start;
354 	int dirtyreacts;
355 	UVMHIST_FUNC("uvmpd_scan_inactive"); UVMHIST_CALLED(pdhist);
356 
357 	/*
358 	 * note: we currently keep swap-backed pages on a separate inactive
359 	 * list from object-backed pages.   however, merging the two lists
360 	 * back together again hasn't been ruled out.   thus, we keep our
361 	 * swap cluster in "swpps" rather than in pps (allows us to mix
362 	 * clustering types in the event of a mixed inactive queue).
363 	 */
364 
365 	/*
366 	 * swslot is non-zero if we are building a swap cluster.  we want
367 	 * to stay in the loop while we have a page to scan or we have
368 	 * a swap-cluster to build.
369 	 */
370 
371 	swslot = 0;
372 	swnpages = swcpages = 0;
373 	free = 0;
374 	dirtyreacts = 0;
375 
376 	for (p = TAILQ_FIRST(pglst); p != NULL || swslot != 0; p = nextpg) {
377 
378 		/*
379 		 * note that p can be NULL iff we have traversed the whole
380 		 * list and need to do one final swap-backed clustered pageout.
381 		 */
382 
383 		uobj = NULL;
384 		anon = NULL;
385 
386 		if (p) {
387 
388 			/*
389 			 * update our copy of "free" and see if we've met
390 			 * our target
391 			 */
392 			free = uvmexp.free - BUFPAGES_DEFICIT;
393 
394 			if (free + uvmexp.paging >= uvmexp.freetarg << 2 ||
395 			    dirtyreacts == UVMPD_NUMDIRTYREACTS) {
396 				UVMHIST_LOG(pdhist,"  met free target: "
397 					    "exit loop", 0, 0, 0, 0);
398 				retval = TRUE;
399 
400 				if (swslot == 0) {
401 					/* exit now if no swap-i/o pending */
402 					break;
403 				}
404 
405 				/* set p to null to signal final swap i/o */
406 				p = NULL;
407 			}
408 		}
409 
410 		if (p) {	/* if (we have a new page to consider) */
411 
412 			/*
413 			 * we are below target and have a new page to consider.
414 			 */
415 			uvmexp.pdscans++;
416 			nextpg = TAILQ_NEXT(p, pageq);
417 
418 			/*
419 			 * move referenced pages back to active queue and
420 			 * skip to next page (unlikely to happen since
421 			 * inactive pages shouldn't have any valid mappings
422 			 * and we cleared reference before deactivating).
423 			 */
424 
425 			if (pmap_is_referenced(p)) {
426 				uvm_pageactivate(p);
427 				uvmexp.pdreact++;
428 				continue;
429 			}
430 
431 			/*
432 			 * first we attempt to lock the object that this page
433 			 * belongs to.  if our attempt fails we skip on to
434 			 * the next page (no harm done).  it is important to
435 			 * "try" locking the object as we are locking in the
436 			 * wrong order (pageq -> object) and we don't want to
437 			 * deadlock.
438 			 *
439 			 * the only time we expect to see an ownerless page
440 			 * (i.e. a page with no uobject and !PQ_ANON) is if an
441 			 * anon has loaned a page from a uvm_object and the
442 			 * uvm_object has dropped the ownership.  in that
443 			 * case, the anon can "take over" the loaned page
444 			 * and make it its own.
445 			 */
446 
447 			/* is page part of an anon or ownerless ? */
448 			if ((p->pg_flags & PQ_ANON) || p->uobject == NULL) {
449 				anon = p->uanon;
450 				KASSERT(anon != NULL);
451 				if (!simple_lock_try(&anon->an_lock)) {
452 					/* lock failed, skip this page */
453 					continue;
454 				}
455 
456 				/*
457 				 * if the page is ownerless, claim it in the
458 				 * name of "anon"!
459 				 */
460 
461 				if ((p->pg_flags & PQ_ANON) == 0) {
462 					KASSERT(p->loan_count > 0);
463 					p->loan_count--;
464 					atomic_setbits_int(&p->pg_flags,
465 					    PQ_ANON);
466 					/* anon now owns it */
467 				}
468 				if (p->pg_flags & PG_BUSY) {
469 					simple_unlock(&anon->an_lock);
470 					uvmexp.pdbusy++;
471 					/* someone else owns page, skip it */
472 					continue;
473 				}
474 				uvmexp.pdanscan++;
475 			} else {
476 				uobj = p->uobject;
477 				KASSERT(uobj != NULL);
478 				if (!simple_lock_try(&uobj->vmobjlock)) {
479 					/* lock failed, skip this page */
480 					continue;
481 				}
482 				if (p->pg_flags & PG_BUSY) {
483 					simple_unlock(&uobj->vmobjlock);
484 					uvmexp.pdbusy++;
485 					/* someone else owns page, skip it */
486 					continue;
487 				}
488 				uvmexp.pdobscan++;
489 			}
490 
491 			/*
492 			 * we now have the object and the page queues locked.
493 			 * the page is not busy.   if the page is clean we
494 			 * can free it now and continue.
495 			 */
496 
497 			if (p->pg_flags & PG_CLEAN) {
498 				if (p->pg_flags & PQ_SWAPBACKED) {
499 					/* this page now lives only in swap */
500 					simple_lock(&uvm.swap_data_lock);
501 					uvmexp.swpgonly++;
502 					simple_unlock(&uvm.swap_data_lock);
503 				}
504 
505 				/* zap all mappings with pmap_page_protect... */
506 				pmap_page_protect(p, VM_PROT_NONE);
507 				uvm_pagefree(p);
508 				uvmexp.pdfreed++;
509 
510 				if (anon) {
511 
512 					/*
513 					 * an anonymous page can only be clean
514 					 * if it has backing store assigned.
515 					 */
516 
517 					KASSERT(anon->an_swslot != 0);
518 
519 					/* remove from object */
520 					anon->an_page = NULL;
521 					simple_unlock(&anon->an_lock);
522 				} else {
523 					/* pagefree has already removed the
524 					 * page from the object */
525 					simple_unlock(&uobj->vmobjlock);
526 				}
527 				continue;
528 			}
529 
530 			/*
531 			 * this page is dirty, skip it if we'll have met our
532 			 * free target when all the current pageouts complete.
533 			 */
534 
535 			if (free + uvmexp.paging > uvmexp.freetarg << 2) {
536 				if (anon) {
537 					simple_unlock(&anon->an_lock);
538 				} else {
539 					simple_unlock(&uobj->vmobjlock);
540 				}
541 				continue;
542 			}
543 
544 			/*
545 			 * this page is dirty, but we can't page it out
546 			 * since all pages in swap are only in swap.
547 			 * reactivate it so that we eventually cycle
548 			 * all pages thru the inactive queue.
549 			 */
550 
551 			KASSERT(uvmexp.swpgonly <= uvmexp.swpages);
552 			if ((p->pg_flags & PQ_SWAPBACKED) &&
553 			    uvmexp.swpgonly == uvmexp.swpages) {
554 				dirtyreacts++;
555 				uvm_pageactivate(p);
556 				if (anon) {
557 					simple_unlock(&anon->an_lock);
558 				} else {
559 					simple_unlock(&uobj->vmobjlock);
560 				}
561 				continue;
562 			}
563 
564 			/*
565 			 * if the page is swap-backed and dirty and swap space
566 			 * is full, free any swap allocated to the page
567 			 * so that other pages can be paged out.
568 			 */
569 
570 			KASSERT(uvmexp.swpginuse <= uvmexp.swpages);
571 			if ((p->pg_flags & PQ_SWAPBACKED) &&
572 			    uvmexp.swpginuse == uvmexp.swpages) {
573 
574 				if ((p->pg_flags & PQ_ANON) &&
575 				    p->uanon->an_swslot) {
576 					uvm_swap_free(p->uanon->an_swslot, 1);
577 					p->uanon->an_swslot = 0;
578 				}
579 				if (p->pg_flags & PQ_AOBJ) {
580 					uao_dropswap(p->uobject,
581 						     p->offset >> PAGE_SHIFT);
582 				}
583 			}
584 
585 			/*
586 			 * the page we are looking at is dirty.   we must
587 			 * clean it before it can be freed.  to do this we
588 			 * first mark the page busy so that no one else will
589 			 * touch the page.   we write protect all the mappings
590 			 * of the page so that no one touches it while it is
591 			 * in I/O.
592 			 */
593 
594 			swap_backed = ((p->pg_flags & PQ_SWAPBACKED) != 0);
595 			atomic_setbits_int(&p->pg_flags, PG_BUSY);
596 			UVM_PAGE_OWN(p, "scan_inactive");
597 			pmap_page_protect(p, VM_PROT_READ);
598 			uvmexp.pgswapout++;
599 
600 			/*
601 			 * for swap-backed pages we need to (re)allocate
602 			 * swap space.
603 			 */
604 
605 			if (swap_backed) {
606 
607 				/*
608 				 * free old swap slot (if any)
609 				 */
610 
611 				if (anon) {
612 					if (anon->an_swslot) {
613 						uvm_swap_free(anon->an_swslot,
614 						    1);
615 						anon->an_swslot = 0;
616 					}
617 				} else {
618 					uao_dropswap(uobj,
619 						     p->offset >> PAGE_SHIFT);
620 				}
621 
622 				/*
623 				 * start new cluster (if necessary)
624 				 */
625 
626 				if (swslot == 0) {
627 					swnpages = MAXBSIZE >> PAGE_SHIFT;
628 					swslot = uvm_swap_alloc(&swnpages,
629 					    TRUE);
630 					if (swslot == 0) {
631 						/* no swap?  give up! */
632 						atomic_clearbits_int(
633 						    &p->pg_flags,
634 						    PG_BUSY);
635 						UVM_PAGE_OWN(p, NULL);
636 						if (anon)
637 							simple_unlock(
638 							    &anon->an_lock);
639 						else
640 							simple_unlock(
641 							    &uobj->vmobjlock);
642 						continue;
643 					}
644 					swcpages = 0;	/* cluster is empty */
645 				}
646 
647 				/*
648 				 * add block to cluster
649 				 */
650 
651 				swpps[swcpages] = p;
652 				if (anon)
653 					anon->an_swslot = swslot + swcpages;
654 				else
655 					uao_set_swslot(uobj,
656 					    p->offset >> PAGE_SHIFT,
657 					    swslot + swcpages);
658 				swcpages++;
659 			}
660 		} else {
661 
662 			/* if p == NULL we must be doing a last swap i/o */
663 			swap_backed = TRUE;
664 		}
665 
666 		/*
667 		 * now consider doing the pageout.
668 		 *
669 		 * for swap-backed pages, we do the pageout if we have either
670 		 * filled the cluster (in which case (swnpages == swcpages) or
671 		 * run out of pages (p == NULL).
672 		 *
673 		 * for object pages, we always do the pageout.
674 		 */
675 
676 		if (swap_backed) {
677 			if (p) {	/* if we just added a page to cluster */
678 				if (anon)
679 					simple_unlock(&anon->an_lock);
680 				else
681 					simple_unlock(&uobj->vmobjlock);
682 
683 				/* cluster not full yet? */
684 				if (swcpages < swnpages)
685 					continue;
686 			}
687 
688 			/* starting I/O now... set up for it */
689 			npages = swcpages;
690 			ppsp = swpps;
691 			/* for swap-backed pages only */
692 			start = (vaddr_t) swslot;
693 
694 			/* if this is final pageout we could have a few
695 			 * extra swap blocks */
696 			if (swcpages < swnpages) {
697 				uvm_swap_free(swslot + swcpages,
698 				    (swnpages - swcpages));
699 			}
700 		} else {
701 			/* normal object pageout */
702 			ppsp = pps;
703 			npages = sizeof(pps) / sizeof(struct vm_page *);
704 			/* not looked at because PGO_ALLPAGES is set */
705 			start = 0;
706 		}
707 
708 		/*
709 		 * now do the pageout.
710 		 *
711 		 * for swap_backed pages we have already built the cluster.
712 		 * for !swap_backed pages, uvm_pager_put will call the object's
713 		 * "make put cluster" function to build a cluster on our behalf.
714 		 *
715 		 * we pass the PGO_PDFREECLUST flag to uvm_pager_put to instruct
716 		 * it to free the cluster pages for us on a successful I/O (it
717 		 * always does this for un-successful I/O requests).  this
718 		 * allows us to do clustered pageout without having to deal
719 		 * with cluster pages at this level.
720 		 *
721 		 * note locking semantics of uvm_pager_put with PGO_PDFREECLUST:
722 		 *  IN: locked: uobj (if !swap_backed), page queues
723 		 * OUT: locked: uobj (if !swap_backed && result !=VM_PAGER_PEND)
724 		 *     !locked: pageqs, uobj (if swap_backed || VM_PAGER_PEND)
725 		 *
726 		 * [the bit about VM_PAGER_PEND saves us one lock-unlock pair]
727 		 */
728 
729 		/* locked: uobj (if !swap_backed), page queues */
730 		uvmexp.pdpageouts++;
731 		result = uvm_pager_put(swap_backed ? NULL : uobj, p,
732 		    &ppsp, &npages, PGO_ALLPAGES|PGO_PDFREECLUST, start, 0);
733 		/* locked: uobj (if !swap_backed && result != PEND) */
734 		/* unlocked: pageqs, object (if swap_backed ||result == PEND) */
735 
736 		/*
737 		 * if we did i/o to swap, zero swslot to indicate that we are
738 		 * no longer building a swap-backed cluster.
739 		 */
740 
741 		if (swap_backed)
742 			swslot = 0;		/* done with this cluster */
743 
744 		/*
745 		 * first, we check for VM_PAGER_PEND which means that the
746 		 * async I/O is in progress and the async I/O done routine
747 		 * will clean up after us.   in this case we move on to the
748 		 * next page.
749 		 *
750 		 * there is a very remote chance that the pending async i/o can
751 		 * finish _before_ we get here.   if that happens, our page "p"
752 		 * may no longer be on the inactive queue.   so we verify this
753 		 * when determining the next page (starting over at the head if
754 		 * we've lost our inactive page).
755 		 */
756 
757 		if (result == VM_PAGER_PEND) {
758 			uvmexp.paging += npages;
759 			uvm_lock_pageq();
760 			uvmexp.pdpending++;
761 			if (p) {
762 				if (p->pg_flags & PQ_INACTIVE)
763 					nextpg = TAILQ_NEXT(p, pageq);
764 				else
765 					nextpg = TAILQ_FIRST(pglst);
766 			} else {
767 				nextpg = NULL;
768 			}
769 			continue;
770 		}
771 
772 #ifdef UBC
773 		if (result == VM_PAGER_ERROR &&
774 		    curproc == uvm.pagedaemon_proc) {
775 			uvm_lock_pageq();
776 			nextpg = TAILQ_NEXT(p, pageq);
777 			uvm_pageactivate(p);
778 			continue;
779 		}
780 #endif
781 
782 		/*
783 		 * clean up "p" if we have one
784 		 */
785 
786 		if (p) {
787 			/*
788 			 * the I/O request to "p" is done and uvm_pager_put
789 			 * has freed any cluster pages it may have allocated
790 			 * during I/O.  all that is left for us to do is
791 			 * clean up page "p" (which is still PG_BUSY).
792 			 *
793 			 * our result could be one of the following:
794 			 *   VM_PAGER_OK: successful pageout
795 			 *
796 			 *   VM_PAGER_AGAIN: tmp resource shortage, we skip
797 			 *     to next page
798 			 *   VM_PAGER_{FAIL,ERROR,BAD}: an error.   we
799 			 *     "reactivate" page to get it out of the way (it
800 			 *     will eventually drift back into the inactive
801 			 *     queue for a retry).
802 			 *   VM_PAGER_UNLOCK: should never see this as it is
803 			 *     only valid for "get" operations
804 			 */
805 
806 			/* relock p's object: page queues not lock yet, so
807 			 * no need for "try" */
808 
809 			/* !swap_backed case: already locked... */
810 			if (swap_backed) {
811 				if (anon)
812 					simple_lock(&anon->an_lock);
813 				else
814 					simple_lock(&uobj->vmobjlock);
815 			}
816 
817 #ifdef DIAGNOSTIC
818 			if (result == VM_PAGER_UNLOCK)
819 				panic("pagedaemon: pageout returned "
820 				    "invalid 'unlock' code");
821 #endif
822 
823 			/* handle PG_WANTED now */
824 			if (p->pg_flags & PG_WANTED)
825 				/* still holding object lock */
826 				wakeup(p);
827 
828 			atomic_clearbits_int(&p->pg_flags, PG_BUSY|PG_WANTED);
829 			UVM_PAGE_OWN(p, NULL);
830 
831 			/* released during I/O? Can only happen for anons */
832 			if (p->pg_flags & PG_RELEASED) {
833 				KASSERT(anon != NULL);
834 				/*
835 				 * remove page so we can get nextpg,
836 				 * also zero out anon so we don't use
837 				 * it after the free.
838 				 */
839 				anon->an_page = NULL;
840 				p->uanon = NULL;
841 
842 				simple_unlock(&anon->an_lock);
843 				uvm_anfree(anon);	/* kills anon */
844 				pmap_page_protect(p, VM_PROT_NONE);
845 				anon = NULL;
846 				uvm_lock_pageq();
847 				nextpg = TAILQ_NEXT(p, pageq);
848 				/* free released page */
849 				uvm_pagefree(p);
850 			} else {	/* page was not released during I/O */
851 				uvm_lock_pageq();
852 				nextpg = TAILQ_NEXT(p, pageq);
853 				if (result != VM_PAGER_OK) {
854 					/* pageout was a failure... */
855 					if (result != VM_PAGER_AGAIN)
856 						uvm_pageactivate(p);
857 					pmap_clear_reference(p);
858 					/* XXXCDC: if (swap_backed) FREE p's
859 					 * swap block? */
860 				} else {
861 					/* pageout was a success... */
862 					pmap_clear_reference(p);
863 					pmap_clear_modify(p);
864 					atomic_setbits_int(&p->pg_flags,
865 					    PG_CLEAN);
866 				}
867 			}
868 
869 			/*
870 			 * drop object lock (if there is an object left).   do
871 			 * a safety check of nextpg to make sure it is on the
872 			 * inactive queue (it should be since PG_BUSY pages on
873 			 * the inactive queue can't be re-queued [note: not
874 			 * true for active queue]).
875 			 */
876 
877 			if (anon)
878 				simple_unlock(&anon->an_lock);
879 			else if (uobj)
880 				simple_unlock(&uobj->vmobjlock);
881 
882 			if (nextpg && (nextpg->pg_flags & PQ_INACTIVE) == 0) {
883 				nextpg = TAILQ_FIRST(pglst);	/* reload! */
884 			}
885 		} else {
886 
887 			/*
888 			 * if p is null in this loop, make sure it stays null
889 			 * in the next loop.
890 			 */
891 
892 			nextpg = NULL;
893 
894 			/*
895 			 * lock page queues here just so they're always locked
896 			 * at the end of the loop.
897 			 */
898 
899 			uvm_lock_pageq();
900 		}
901 	}
902 	return (retval);
903 }
904 
905 /*
906  * uvmpd_scan: scan the page queues and attempt to meet our targets.
907  *
908  * => called with pageq's locked
909  */
910 
911 void
912 uvmpd_scan(void)
913 {
914 	int free, inactive_shortage, swap_shortage, pages_freed;
915 	struct vm_page *p, *nextpg;
916 	struct uvm_object *uobj;
917 	boolean_t got_it;
918 	UVMHIST_FUNC("uvmpd_scan"); UVMHIST_CALLED(pdhist);
919 
920 	uvmexp.pdrevs++;		/* counter */
921 	uobj = NULL;
922 
923 	/*
924 	 * get current "free" page count
925 	 */
926 	free = uvmexp.free - BUFPAGES_DEFICIT;
927 
928 #ifndef __SWAP_BROKEN
929 	/*
930 	 * swap out some processes if we are below our free target.
931 	 * we need to unlock the page queues for this.
932 	 */
933 	if (free < uvmexp.freetarg) {
934 		uvmexp.pdswout++;
935 		UVMHIST_LOG(pdhist,"  free %ld < target %ld: swapout", free,
936 		    uvmexp.freetarg, 0, 0);
937 		uvm_unlock_pageq();
938 		uvm_swapout_threads();
939 		uvm_lock_pageq();
940 	}
941 #endif
942 
943 	/*
944 	 * now we want to work on meeting our targets.   first we work on our
945 	 * free target by converting inactive pages into free pages.  then
946 	 * we work on meeting our inactive target by converting active pages
947 	 * to inactive ones.
948 	 */
949 
950 	UVMHIST_LOG(pdhist, "  starting 'free' loop",0,0,0,0);
951 
952 	/*
953 	 * alternate starting queue between swap and object based on the
954 	 * low bit of uvmexp.pdrevs (which we bump by one each call).
955 	 */
956 
957 	got_it = FALSE;
958 	pages_freed = uvmexp.pdfreed;	/* XXX - int */
959 	if ((uvmexp.pdrevs & 1) != 0 && uvmexp.nswapdev != 0)
960 		got_it = uvmpd_scan_inactive(&uvm.page_inactive_swp);
961 	if (!got_it)
962 		got_it = uvmpd_scan_inactive(&uvm.page_inactive_obj);
963 	if (!got_it && (uvmexp.pdrevs & 1) == 0 && uvmexp.nswapdev != 0)
964 		(void) uvmpd_scan_inactive(&uvm.page_inactive_swp);
965 	pages_freed = uvmexp.pdfreed - pages_freed;
966 
967 	/*
968 	 * we have done the scan to get free pages.   now we work on meeting
969 	 * our inactive target.
970 	 */
971 
972 	inactive_shortage = uvmexp.inactarg - uvmexp.inactive;
973 
974 	/*
975 	 * detect if we're not going to be able to page anything out
976 	 * until we free some swap resources from active pages.
977 	 */
978 
979 	swap_shortage = 0;
980 	if (uvmexp.free < uvmexp.freetarg &&
981 	    uvmexp.swpginuse == uvmexp.swpages &&
982 	    uvmexp.swpgonly < uvmexp.swpages &&
983 	    pages_freed == 0) {
984 		swap_shortage = uvmexp.freetarg - uvmexp.free;
985 	}
986 
987 	UVMHIST_LOG(pdhist, "  loop 2: inactive_shortage=%ld swap_shortage=%ld",
988 		    inactive_shortage, swap_shortage,0,0);
989 	for (p = TAILQ_FIRST(&uvm.page_active);
990 	     p != NULL && (inactive_shortage > 0 || swap_shortage > 0);
991 	     p = nextpg) {
992 		nextpg = TAILQ_NEXT(p, pageq);
993 		if (p->pg_flags & PG_BUSY)
994 			continue;	/* quick check before trying to lock */
995 
996 		/*
997 		 * lock the page's owner.
998 		 */
999 		/* is page anon owned or ownerless? */
1000 		if ((p->pg_flags & PQ_ANON) || p->uobject == NULL) {
1001 			KASSERT(p->uanon != NULL);
1002 			if (!simple_lock_try(&p->uanon->an_lock))
1003 				continue;
1004 
1005 			/* take over the page? */
1006 			if ((p->pg_flags & PQ_ANON) == 0) {
1007 				KASSERT(p->loan_count > 0);
1008 				p->loan_count--;
1009 				atomic_setbits_int(&p->pg_flags, PQ_ANON);
1010 			}
1011 		} else {
1012 			if (!simple_lock_try(&p->uobject->vmobjlock))
1013 				continue;
1014 		}
1015 
1016 		/*
1017 		 * skip this page if it's busy.
1018 		 */
1019 
1020 		if ((p->pg_flags & PG_BUSY) != 0) {
1021 			if (p->pg_flags & PQ_ANON)
1022 				simple_unlock(&p->uanon->an_lock);
1023 			else
1024 				simple_unlock(&p->uobject->vmobjlock);
1025 			continue;
1026 		}
1027 
1028 		/*
1029 		 * if there's a shortage of swap, free any swap allocated
1030 		 * to this page so that other pages can be paged out.
1031 		 */
1032 
1033 		if (swap_shortage > 0) {
1034 			if ((p->pg_flags & PQ_ANON) && p->uanon->an_swslot) {
1035 				uvm_swap_free(p->uanon->an_swslot, 1);
1036 				p->uanon->an_swslot = 0;
1037 				atomic_clearbits_int(&p->pg_flags, PG_CLEAN);
1038 				swap_shortage--;
1039 			}
1040 			if (p->pg_flags & PQ_AOBJ) {
1041 				int slot = uao_set_swslot(p->uobject,
1042 					p->offset >> PAGE_SHIFT, 0);
1043 				if (slot) {
1044 					uvm_swap_free(slot, 1);
1045 					atomic_clearbits_int(&p->pg_flags,
1046 					    PG_CLEAN);
1047 					swap_shortage--;
1048 				}
1049 			}
1050 		}
1051 
1052 		/*
1053 		 * deactivate this page if there's a shortage of
1054 		 * inactive pages.
1055 		 */
1056 
1057 		if (inactive_shortage > 0) {
1058 			pmap_page_protect(p, VM_PROT_NONE);
1059 			/* no need to check wire_count as pg is "active" */
1060 			uvm_pagedeactivate(p);
1061 			uvmexp.pddeact++;
1062 			inactive_shortage--;
1063 		}
1064 		if (p->pg_flags & PQ_ANON)
1065 			simple_unlock(&p->uanon->an_lock);
1066 		else
1067 			simple_unlock(&p->uobject->vmobjlock);
1068 	}
1069 }
1070