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