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