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