xref: /openbsd-src/sys/uvm/uvm_pdaemon.c (revision c1a45aed656e7d5627c30c92421893a76f370ccb)
1 /*	$OpenBSD: uvm_pdaemon.c,v 1.96 2022/04/11 16:43:49 mpi 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. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)vm_pageout.c        8.5 (Berkeley) 2/14/94
38  * from: Id: uvm_pdaemon.c,v 1.1.2.32 1998/02/06 05:26:30 chs Exp
39  *
40  *
41  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42  * All rights reserved.
43  *
44  * Permission to use, copy, modify and distribute this software and
45  * its documentation is hereby granted, provided that both the copyright
46  * notice and this permission notice appear in all copies of the
47  * software, derivative works or modified versions, and any portions
48  * thereof, and that both notices appear in supporting documentation.
49  *
50  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
53  *
54  * Carnegie Mellon requests users of this software to return to
55  *
56  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
57  *  School of Computer Science
58  *  Carnegie Mellon University
59  *  Pittsburgh PA 15213-3890
60  *
61  * any improvements or extensions that they make and grant Carnegie the
62  * rights to redistribute these changes.
63  */
64 
65 /*
66  * uvm_pdaemon.c: the page daemon
67  */
68 
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/kernel.h>
72 #include <sys/pool.h>
73 #include <sys/proc.h>
74 #include <sys/buf.h>
75 #include <sys/mount.h>
76 #include <sys/atomic.h>
77 
78 #ifdef HIBERNATE
79 #include <sys/hibernate.h>
80 #endif
81 
82 #include <uvm/uvm.h>
83 
84 #include "drm.h"
85 
86 #if NDRM > 0
87 extern void drmbackoff(long);
88 #endif
89 
90 /*
91  * UVMPD_NUMDIRTYREACTS is how many dirty pages the pagedaemon will reactivate
92  * in a pass thru the inactive list when swap is full.  the value should be
93  * "small"... if it's too large we'll cycle the active pages thru the inactive
94  * queue too quickly to for them to be referenced and avoid being freed.
95  */
96 
97 #define UVMPD_NUMDIRTYREACTS 16
98 
99 
100 /*
101  * local prototypes
102  */
103 
104 void		uvmpd_scan(void);
105 boolean_t	uvmpd_scan_inactive(struct pglist *);
106 void		uvmpd_tune(void);
107 void		uvmpd_drop(struct pglist *);
108 
109 /*
110  * uvm_wait: wait (sleep) for the page daemon to free some pages
111  *
112  * => should be called with all locks released
113  * => should _not_ be called by the page daemon (to avoid deadlock)
114  */
115 
116 void
117 uvm_wait(const char *wmsg)
118 {
119 	uint64_t timo = INFSLP;
120 
121 #ifdef DIAGNOSTIC
122 	if (curproc == &proc0)
123 		panic("%s: cannot sleep for memory during boot", __func__);
124 #endif
125 
126 	/*
127 	 * check for page daemon going to sleep (waiting for itself)
128 	 */
129 	if (curproc == uvm.pagedaemon_proc) {
130 		printf("uvm_wait emergency bufbackoff\n");
131 		if (bufbackoff(NULL, 4) == 0)
132 			return;
133 		/*
134 		 * now we have a problem: the pagedaemon wants to go to
135 		 * sleep until it frees more memory.   but how can it
136 		 * free more memory if it is asleep?  that is a deadlock.
137 		 * we have two options:
138 		 *  [1] panic now
139 		 *  [2] put a timeout on the sleep, thus causing the
140 		 *      pagedaemon to only pause (rather than sleep forever)
141 		 *
142 		 * note that option [2] will only help us if we get lucky
143 		 * and some other process on the system breaks the deadlock
144 		 * by exiting or freeing memory (thus allowing the pagedaemon
145 		 * to continue).  for now we panic if DEBUG is defined,
146 		 * otherwise we hope for the best with option [2] (better
147 		 * yet, this should never happen in the first place!).
148 		 */
149 
150 		printf("pagedaemon: deadlock detected!\n");
151 		timo = MSEC_TO_NSEC(125);	/* set timeout */
152 #if defined(DEBUG)
153 		/* DEBUG: panic so we can debug it */
154 		panic("pagedaemon deadlock");
155 #endif
156 	}
157 
158 	uvm_lock_fpageq();
159 	wakeup(&uvm.pagedaemon);		/* wake the daemon! */
160 	msleep_nsec(&uvmexp.free, &uvm.fpageqlock, PVM | PNORELOCK, wmsg, timo);
161 }
162 
163 /*
164  * uvmpd_tune: tune paging parameters
165  *
166  * => called whenever memory is added to (or removed from?) the system
167  * => caller must call with page queues locked
168  */
169 
170 void
171 uvmpd_tune(void)
172 {
173 
174 	uvmexp.freemin = uvmexp.npages / 30;
175 
176 	/* between 16k and 512k */
177 	/* XXX:  what are these values good for? */
178 	uvmexp.freemin = max(uvmexp.freemin, (16*1024) >> PAGE_SHIFT);
179 #if 0
180 	uvmexp.freemin = min(uvmexp.freemin, (512*1024) >> PAGE_SHIFT);
181 #endif
182 
183 	/* Make sure there's always a user page free. */
184 	if (uvmexp.freemin < uvmexp.reserve_kernel + 1)
185 		uvmexp.freemin = uvmexp.reserve_kernel + 1;
186 
187 	uvmexp.freetarg = (uvmexp.freemin * 4) / 3;
188 	if (uvmexp.freetarg <= uvmexp.freemin)
189 		uvmexp.freetarg = uvmexp.freemin + 1;
190 
191 	/* uvmexp.inactarg: computed in main daemon loop */
192 
193 	uvmexp.wiredmax = uvmexp.npages / 3;
194 }
195 
196 /*
197  * Indicate to the page daemon that a nowait call failed and it should
198  * recover at least some memory in the most restricted region (assumed
199  * to be dma_constraint).
200  */
201 volatile int uvm_nowait_failed;
202 
203 /*
204  * uvm_pageout: the main loop for the pagedaemon
205  */
206 void
207 uvm_pageout(void *arg)
208 {
209 	struct uvm_constraint_range constraint;
210 	struct uvm_pmalloc *pma;
211 	int npages = 0;
212 
213 	/* ensure correct priority and set paging parameters... */
214 	uvm.pagedaemon_proc = curproc;
215 	(void) spl0();
216 	uvm_lock_pageq();
217 	npages = uvmexp.npages;
218 	uvmpd_tune();
219 	uvm_unlock_pageq();
220 
221 	for (;;) {
222 		long size;
223 
224 		uvm_lock_fpageq();
225 		if (!uvm_nowait_failed && TAILQ_EMPTY(&uvm.pmr_control.allocs)) {
226 			msleep_nsec(&uvm.pagedaemon, &uvm.fpageqlock, PVM,
227 			    "pgdaemon", INFSLP);
228 			uvmexp.pdwoke++;
229 		}
230 
231 		if ((pma = TAILQ_FIRST(&uvm.pmr_control.allocs)) != NULL) {
232 			pma->pm_flags |= UVM_PMA_BUSY;
233 			constraint = pma->pm_constraint;
234 		} else {
235 			if (uvm_nowait_failed) {
236 				/*
237 				 * XXX realisticly, this is what our
238 				 * nowait callers probably care about
239 				 */
240 				constraint = dma_constraint;
241 				uvm_nowait_failed = 0;
242 			} else
243 				constraint = no_constraint;
244 		}
245 
246 		uvm_unlock_fpageq();
247 
248 		/*
249 		 * now lock page queues and recompute inactive count
250 		 */
251 		uvm_lock_pageq();
252 		if (npages != uvmexp.npages) {	/* check for new pages? */
253 			npages = uvmexp.npages;
254 			uvmpd_tune();
255 		}
256 
257 		uvmexp.inactarg = (uvmexp.active + uvmexp.inactive) / 3;
258 		if (uvmexp.inactarg <= uvmexp.freetarg) {
259 			uvmexp.inactarg = uvmexp.freetarg + 1;
260 		}
261 
262 		/* Reclaim pages from the buffer cache if possible. */
263 		size = 0;
264 		if (pma != NULL)
265 			size += pma->pm_size >> PAGE_SHIFT;
266 		if (uvmexp.free - BUFPAGES_DEFICIT < uvmexp.freetarg)
267 			size += uvmexp.freetarg - (uvmexp.free -
268 			    BUFPAGES_DEFICIT);
269 		if (size == 0)
270 			size = 16; /* XXX */
271 		uvm_unlock_pageq();
272 		(void) bufbackoff(&constraint, size * 2);
273 #if NDRM > 0
274 		drmbackoff(size * 2);
275 #endif
276 		uvm_lock_pageq();
277 
278 		/*
279 		 * scan if needed
280 		 */
281 		if (pma != NULL ||
282 		    ((uvmexp.free - BUFPAGES_DEFICIT) < uvmexp.freetarg) ||
283 		    ((uvmexp.inactive + BUFPAGES_INACT) < uvmexp.inactarg)) {
284 			uvmpd_scan();
285 		}
286 
287 		/*
288 		 * if there's any free memory to be had,
289 		 * wake up any waiters.
290 		 */
291 		uvm_lock_fpageq();
292 		if (uvmexp.free > uvmexp.reserve_kernel ||
293 		    uvmexp.paging == 0) {
294 			wakeup(&uvmexp.free);
295 		}
296 
297 		if (pma != NULL) {
298 			/*
299 			 * XXX If UVM_PMA_FREED isn't set, no pages
300 			 * were freed.  Should we set UVM_PMA_FAIL in
301 			 * that case?
302 			 */
303 			pma->pm_flags &= ~UVM_PMA_BUSY;
304 			if (pma->pm_flags & UVM_PMA_FREED) {
305 				pma->pm_flags &= ~UVM_PMA_LINKED;
306 				TAILQ_REMOVE(&uvm.pmr_control.allocs, pma,
307 				    pmq);
308 				wakeup(pma);
309 			}
310 		}
311 		uvm_unlock_fpageq();
312 
313 		/*
314 		 * scan done.  unlock page queues (the only lock we are holding)
315 		 */
316 		uvm_unlock_pageq();
317 
318 		sched_pause(yield);
319 	}
320 	/*NOTREACHED*/
321 }
322 
323 
324 /*
325  * uvm_aiodone_daemon:  main loop for the aiodone daemon.
326  */
327 void
328 uvm_aiodone_daemon(void *arg)
329 {
330 	int s, free;
331 	struct buf *bp, *nbp;
332 
333 	uvm.aiodoned_proc = curproc;
334 
335 	for (;;) {
336 		/*
337 		 * Check for done aio structures. If we've got structures to
338 		 * process, do so. Otherwise sleep while avoiding races.
339 		 */
340 		mtx_enter(&uvm.aiodoned_lock);
341 		while ((bp = TAILQ_FIRST(&uvm.aio_done)) == NULL)
342 			msleep_nsec(&uvm.aiodoned, &uvm.aiodoned_lock,
343 			    PVM, "aiodoned", INFSLP);
344 		/* Take the list for ourselves. */
345 		TAILQ_INIT(&uvm.aio_done);
346 		mtx_leave(&uvm.aiodoned_lock);
347 
348 		/* process each i/o that's done. */
349 		free = uvmexp.free;
350 		while (bp != NULL) {
351 			if (bp->b_flags & B_PDAEMON) {
352 				uvmexp.paging -= bp->b_bufsize >> PAGE_SHIFT;
353 			}
354 			nbp = TAILQ_NEXT(bp, b_freelist);
355 			s = splbio();	/* b_iodone must by called at splbio */
356 			(*bp->b_iodone)(bp);
357 			splx(s);
358 			bp = nbp;
359 
360 			sched_pause(yield);
361 		}
362 		uvm_lock_fpageq();
363 		wakeup(free <= uvmexp.reserve_kernel ? &uvm.pagedaemon :
364 		    &uvmexp.free);
365 		uvm_unlock_fpageq();
366 	}
367 }
368 
369 
370 
371 /*
372  * uvmpd_scan_inactive: scan an inactive list for pages to clean or free.
373  *
374  * => called with page queues locked
375  * => we work on meeting our free target by converting inactive pages
376  *    into free pages.
377  * => we handle the building of swap-backed clusters
378  * => we return TRUE if we are exiting because we met our target
379  */
380 
381 boolean_t
382 uvmpd_scan_inactive(struct pglist *pglst)
383 {
384 	boolean_t retval = FALSE;	/* assume we haven't hit target */
385 	int free, result;
386 	struct vm_page *p, *nextpg;
387 	struct uvm_object *uobj;
388 	struct vm_page *pps[MAXBSIZE >> PAGE_SHIFT], **ppsp;
389 	int npages;
390 	struct vm_page *swpps[MAXBSIZE >> PAGE_SHIFT]; 	/* XXX: see below */
391 	int swnpages, swcpages;				/* XXX: see below */
392 	int swslot;
393 	struct vm_anon *anon;
394 	boolean_t swap_backed;
395 	vaddr_t start;
396 	int dirtyreacts;
397 
398 	/*
399 	 * note: we currently keep swap-backed pages on a separate inactive
400 	 * list from object-backed pages.   however, merging the two lists
401 	 * back together again hasn't been ruled out.   thus, we keep our
402 	 * swap cluster in "swpps" rather than in pps (allows us to mix
403 	 * clustering types in the event of a mixed inactive queue).
404 	 */
405 	/*
406 	 * swslot is non-zero if we are building a swap cluster.  we want
407 	 * to stay in the loop while we have a page to scan or we have
408 	 * a swap-cluster to build.
409 	 */
410 	swslot = 0;
411 	swnpages = swcpages = 0;
412 	free = 0;
413 	dirtyreacts = 0;
414 
415 	for (p = TAILQ_FIRST(pglst); p != NULL || swslot != 0; p = nextpg) {
416 		/*
417 		 * note that p can be NULL iff we have traversed the whole
418 		 * list and need to do one final swap-backed clustered pageout.
419 		 */
420 		uobj = NULL;
421 		anon = NULL;
422 
423 		if (p) {
424 			/*
425 			 * update our copy of "free" and see if we've met
426 			 * our target
427 			 */
428 			free = uvmexp.free - BUFPAGES_DEFICIT;
429 
430 			if (free + uvmexp.paging >= uvmexp.freetarg << 2 ||
431 			    dirtyreacts == UVMPD_NUMDIRTYREACTS) {
432 				retval = TRUE;
433 
434 				if (swslot == 0) {
435 					/* exit now if no swap-i/o pending */
436 					break;
437 				}
438 
439 				/* set p to null to signal final swap i/o */
440 				p = NULL;
441 			}
442 		}
443 
444 		if (p) {	/* if (we have a new page to consider) */
445 			/*
446 			 * we are below target and have a new page to consider.
447 			 */
448 			uvmexp.pdscans++;
449 			nextpg = TAILQ_NEXT(p, pageq);
450 
451 			if (p->pg_flags & PQ_ANON) {
452 				anon = p->uanon;
453 				KASSERT(anon != NULL);
454 				if (rw_enter(anon->an_lock,
455 				    RW_WRITE|RW_NOSLEEP)) {
456 					/* lock failed, skip this page */
457 					continue;
458 				}
459 				/*
460 				 * move referenced pages back to active queue
461 				 * and skip to next page.
462 				 */
463 				if (pmap_is_referenced(p)) {
464 					uvm_pageactivate(p);
465 					rw_exit(anon->an_lock);
466 					uvmexp.pdreact++;
467 					continue;
468 				}
469 				if (p->pg_flags & PG_BUSY) {
470 					rw_exit(anon->an_lock);
471 					uvmexp.pdbusy++;
472 					/* someone else owns page, skip it */
473 					continue;
474 				}
475 				uvmexp.pdanscan++;
476 			} else {
477 				uobj = p->uobject;
478 				KASSERT(uobj != NULL);
479 				if (rw_enter(uobj->vmobjlock,
480 				    RW_WRITE|RW_NOSLEEP)) {
481 					/* lock failed, skip this page */
482 					continue;
483 				}
484 				/*
485 				 * move referenced pages back to active queue
486 				 * and skip to next page.
487 				 */
488 				if (pmap_is_referenced(p)) {
489 					uvm_pageactivate(p);
490 					rw_exit(uobj->vmobjlock);
491 					uvmexp.pdreact++;
492 					continue;
493 				}
494 				if (p->pg_flags & PG_BUSY) {
495 					rw_exit(uobj->vmobjlock);
496 					uvmexp.pdbusy++;
497 					/* someone else owns page, skip it */
498 					continue;
499 				}
500 				uvmexp.pdobscan++;
501 			}
502 
503 			/*
504 			 * we now have the page queues locked.
505 			 * the page is not busy.   if the page is clean we
506 			 * can free it now and continue.
507 			 */
508 			if (p->pg_flags & PG_CLEAN) {
509 				if (p->pg_flags & PQ_SWAPBACKED) {
510 					/* this page now lives only in swap */
511 					atomic_inc_int(&uvmexp.swpgonly);
512 				}
513 
514 				/* zap all mappings with pmap_page_protect... */
515 				pmap_page_protect(p, PROT_NONE);
516 				uvm_pagefree(p);
517 				uvmexp.pdfreed++;
518 
519 				if (anon) {
520 
521 					/*
522 					 * an anonymous page can only be clean
523 					 * if it has backing store assigned.
524 					 */
525 
526 					KASSERT(anon->an_swslot != 0);
527 
528 					/* remove from object */
529 					anon->an_page = NULL;
530 					rw_exit(anon->an_lock);
531 				} else {
532 					rw_exit(uobj->vmobjlock);
533 				}
534 				continue;
535 			}
536 
537 			/*
538 			 * this page is dirty, skip it if we'll have met our
539 			 * free target when all the current pageouts complete.
540 			 */
541 			if (free + uvmexp.paging > uvmexp.freetarg << 2) {
542 				if (anon) {
543 					rw_exit(anon->an_lock);
544 				} else {
545 					rw_exit(uobj->vmobjlock);
546 				}
547 				continue;
548 			}
549 
550 			/*
551 			 * this page is dirty, but we can't page it out
552 			 * since all pages in swap are only in swap.
553 			 * reactivate it so that we eventually cycle
554 			 * all pages thru the inactive queue.
555 			 */
556 			if ((p->pg_flags & PQ_SWAPBACKED) && uvm_swapisfull()) {
557 				dirtyreacts++;
558 				uvm_pageactivate(p);
559 				if (anon) {
560 					rw_exit(anon->an_lock);
561 				} else {
562 					rw_exit(uobj->vmobjlock);
563 				}
564 				continue;
565 			}
566 
567 			/*
568 			 * if the page is swap-backed and dirty and swap space
569 			 * is full, free any swap allocated to the page
570 			 * so that other pages can be paged out.
571 			 */
572 			KASSERT(uvmexp.swpginuse <= uvmexp.swpages);
573 			if ((p->pg_flags & PQ_SWAPBACKED) &&
574 			    uvmexp.swpginuse == uvmexp.swpages) {
575 
576 				if ((p->pg_flags & PQ_ANON) &&
577 				    p->uanon->an_swslot) {
578 					uvm_swap_free(p->uanon->an_swslot, 1);
579 					p->uanon->an_swslot = 0;
580 				}
581 				if (p->pg_flags & PQ_AOBJ) {
582 					uao_dropswap(p->uobject,
583 						     p->offset >> PAGE_SHIFT);
584 				}
585 			}
586 
587 			/*
588 			 * the page we are looking at is dirty.   we must
589 			 * clean it before it can be freed.  to do this we
590 			 * first mark the page busy so that no one else will
591 			 * touch the page.   we write protect all the mappings
592 			 * of the page so that no one touches it while it is
593 			 * in I/O.
594 			 */
595 
596 			swap_backed = ((p->pg_flags & PQ_SWAPBACKED) != 0);
597 			atomic_setbits_int(&p->pg_flags, PG_BUSY);
598 			UVM_PAGE_OWN(p, "scan_inactive");
599 			pmap_page_protect(p, PROT_READ);
600 			uvmexp.pgswapout++;
601 
602 			/*
603 			 * for swap-backed pages we need to (re)allocate
604 			 * swap space.
605 			 */
606 			if (swap_backed) {
607 				/* free old swap slot (if any) */
608 				if (anon) {
609 					if (anon->an_swslot) {
610 						uvm_swap_free(anon->an_swslot,
611 						    1);
612 						anon->an_swslot = 0;
613 					}
614 				} else {
615 					uao_dropswap(uobj,
616 						     p->offset >> PAGE_SHIFT);
617 				}
618 
619 				/* start new cluster (if necessary) */
620 				if (swslot == 0) {
621 					swnpages = MAXBSIZE >> PAGE_SHIFT;
622 					swslot = uvm_swap_alloc(&swnpages,
623 					    TRUE);
624 					if (swslot == 0) {
625 						/* no swap?  give up! */
626 						atomic_clearbits_int(
627 						    &p->pg_flags,
628 						    PG_BUSY);
629 						UVM_PAGE_OWN(p, NULL);
630 						if (anon)
631 							rw_exit(anon->an_lock);
632 						else
633 							rw_exit(
634 							    uobj->vmobjlock);
635 						continue;
636 					}
637 					swcpages = 0;	/* cluster is empty */
638 				}
639 
640 				/* add block to cluster */
641 				swpps[swcpages] = p;
642 				if (anon)
643 					anon->an_swslot = swslot + swcpages;
644 				else
645 					uao_set_swslot(uobj,
646 					    p->offset >> PAGE_SHIFT,
647 					    swslot + swcpages);
648 				swcpages++;
649 			}
650 		} else {
651 			/* if p == NULL we must be doing a last swap i/o */
652 			swap_backed = TRUE;
653 		}
654 
655 		/*
656 		 * now consider doing the pageout.
657 		 *
658 		 * for swap-backed pages, we do the pageout if we have either
659 		 * filled the cluster (in which case (swnpages == swcpages) or
660 		 * run out of pages (p == NULL).
661 		 *
662 		 * for object pages, we always do the pageout.
663 		 */
664 		if (swap_backed) {
665 			if (p) {	/* if we just added a page to cluster */
666 				if (anon)
667 					rw_exit(anon->an_lock);
668 				else
669 					rw_exit(uobj->vmobjlock);
670 
671 				/* cluster not full yet? */
672 				if (swcpages < swnpages)
673 					continue;
674 			}
675 
676 			/* starting I/O now... set up for it */
677 			npages = swcpages;
678 			ppsp = swpps;
679 			/* for swap-backed pages only */
680 			start = (vaddr_t) swslot;
681 
682 			/* if this is final pageout we could have a few
683 			 * extra swap blocks */
684 			if (swcpages < swnpages) {
685 				uvm_swap_free(swslot + swcpages,
686 				    (swnpages - swcpages));
687 			}
688 		} else {
689 			/* normal object pageout */
690 			ppsp = pps;
691 			npages = sizeof(pps) / sizeof(struct vm_page *);
692 			/* not looked at because PGO_ALLPAGES is set */
693 			start = 0;
694 		}
695 
696 		/*
697 		 * now do the pageout.
698 		 *
699 		 * for swap_backed pages we have already built the cluster.
700 		 * for !swap_backed pages, uvm_pager_put will call the object's
701 		 * "make put cluster" function to build a cluster on our behalf.
702 		 *
703 		 * we pass the PGO_PDFREECLUST flag to uvm_pager_put to instruct
704 		 * it to free the cluster pages for us on a successful I/O (it
705 		 * always does this for un-successful I/O requests).  this
706 		 * allows us to do clustered pageout without having to deal
707 		 * with cluster pages at this level.
708 		 *
709 		 * note locking semantics of uvm_pager_put with PGO_PDFREECLUST:
710 		 *  IN: locked: page queues
711 		 * OUT: locked:
712 		 *     !locked: pageqs
713 		 */
714 
715 		uvmexp.pdpageouts++;
716 		result = uvm_pager_put(swap_backed ? NULL : uobj, p,
717 		    &ppsp, &npages, PGO_ALLPAGES|PGO_PDFREECLUST, start, 0);
718 
719 		/*
720 		 * if we did i/o to swap, zero swslot to indicate that we are
721 		 * no longer building a swap-backed cluster.
722 		 */
723 
724 		if (swap_backed)
725 			swslot = 0;		/* done with this cluster */
726 
727 		/*
728 		 * first, we check for VM_PAGER_PEND which means that the
729 		 * async I/O is in progress and the async I/O done routine
730 		 * will clean up after us.   in this case we move on to the
731 		 * next page.
732 		 *
733 		 * there is a very remote chance that the pending async i/o can
734 		 * finish _before_ we get here.   if that happens, our page "p"
735 		 * may no longer be on the inactive queue.   so we verify this
736 		 * when determining the next page (starting over at the head if
737 		 * we've lost our inactive page).
738 		 */
739 
740 		if (result == VM_PAGER_PEND) {
741 			uvmexp.paging += npages;
742 			uvm_lock_pageq();
743 			uvmexp.pdpending++;
744 			if (p) {
745 				if (p->pg_flags & PQ_INACTIVE)
746 					nextpg = TAILQ_NEXT(p, pageq);
747 				else
748 					nextpg = TAILQ_FIRST(pglst);
749 			} else {
750 				nextpg = NULL;
751 			}
752 			continue;
753 		}
754 
755 		/* clean up "p" if we have one */
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 			/* !swap_backed case: already locked... */
780 			if (swap_backed) {
781 				if (anon)
782 					rw_enter(anon->an_lock, RW_WRITE);
783 				else
784 					rw_enter(uobj->vmobjlock, RW_WRITE);
785 			}
786 
787 #ifdef DIAGNOSTIC
788 			if (result == VM_PAGER_UNLOCK)
789 				panic("pagedaemon: pageout returned "
790 				    "invalid 'unlock' code");
791 #endif
792 
793 			/* handle PG_WANTED now */
794 			if (p->pg_flags & PG_WANTED)
795 				wakeup(p);
796 
797 			atomic_clearbits_int(&p->pg_flags, PG_BUSY|PG_WANTED);
798 			UVM_PAGE_OWN(p, NULL);
799 
800 			/* released during I/O? Can only happen for anons */
801 			if (p->pg_flags & PG_RELEASED) {
802 				KASSERT(anon != NULL);
803 				/*
804 				 * remove page so we can get nextpg,
805 				 * also zero out anon so we don't use
806 				 * it after the free.
807 				 */
808 				anon->an_page = NULL;
809 				p->uanon = NULL;
810 
811 				rw_exit(anon->an_lock);
812 				uvm_anfree(anon);	/* kills anon */
813 				pmap_page_protect(p, PROT_NONE);
814 				anon = NULL;
815 				uvm_lock_pageq();
816 				nextpg = TAILQ_NEXT(p, pageq);
817 				/* free released page */
818 				uvm_pagefree(p);
819 			} else {	/* page was not released during I/O */
820 				uvm_lock_pageq();
821 				nextpg = TAILQ_NEXT(p, pageq);
822 				if (result != VM_PAGER_OK) {
823 					/* pageout was a failure... */
824 					if (result != VM_PAGER_AGAIN)
825 						uvm_pageactivate(p);
826 					pmap_clear_reference(p);
827 					/* XXXCDC: if (swap_backed) FREE p's
828 					 * swap block? */
829 				} else {
830 					/* pageout was a success... */
831 					pmap_clear_reference(p);
832 					pmap_clear_modify(p);
833 					atomic_setbits_int(&p->pg_flags,
834 					    PG_CLEAN);
835 				}
836 			}
837 
838 			/*
839 			 * drop object lock (if there is an object left).   do
840 			 * a safety check of nextpg to make sure it is on the
841 			 * inactive queue (it should be since PG_BUSY pages on
842 			 * the inactive queue can't be re-queued [note: not
843 			 * true for active queue]).
844 			 */
845 			if (anon)
846 				rw_exit(anon->an_lock);
847 			else if (uobj)
848 				rw_exit(uobj->vmobjlock);
849 
850 			if (nextpg && (nextpg->pg_flags & PQ_INACTIVE) == 0) {
851 				nextpg = TAILQ_FIRST(pglst);	/* reload! */
852 			}
853 		} else {
854 			/*
855 			 * if p is null in this loop, make sure it stays null
856 			 * in the next loop.
857 			 */
858 			nextpg = NULL;
859 
860 			/*
861 			 * lock page queues here just so they're always locked
862 			 * at the end of the loop.
863 			 */
864 			uvm_lock_pageq();
865 		}
866 	}
867 	return (retval);
868 }
869 
870 /*
871  * uvmpd_scan: scan the page queues and attempt to meet our targets.
872  *
873  * => called with pageq's locked
874  */
875 
876 void
877 uvmpd_scan(void)
878 {
879 	int free, inactive_shortage, swap_shortage, pages_freed;
880 	struct vm_page *p, *nextpg;
881 	struct uvm_object *uobj;
882 	boolean_t got_it;
883 
884 	MUTEX_ASSERT_LOCKED(&uvm.pageqlock);
885 
886 	uvmexp.pdrevs++;		/* counter */
887 	uobj = NULL;
888 
889 	/*
890 	 * get current "free" page count
891 	 */
892 	free = uvmexp.free - BUFPAGES_DEFICIT;
893 
894 #ifndef __SWAP_BROKEN
895 	/*
896 	 * swap out some processes if we are below our free target.
897 	 * we need to unlock the page queues for this.
898 	 */
899 	if (free < uvmexp.freetarg) {
900 		uvmexp.pdswout++;
901 		uvm_unlock_pageq();
902 		uvm_swapout_threads();
903 		uvm_lock_pageq();
904 	}
905 #endif
906 
907 	/*
908 	 * now we want to work on meeting our targets.   first we work on our
909 	 * free target by converting inactive pages into free pages.  then
910 	 * we work on meeting our inactive target by converting active pages
911 	 * to inactive ones.
912 	 */
913 
914 	/*
915 	 * alternate starting queue between swap and object based on the
916 	 * low bit of uvmexp.pdrevs (which we bump by one each call).
917 	 */
918 	got_it = FALSE;
919 	pages_freed = uvmexp.pdfreed;	/* XXX - int */
920 	if ((uvmexp.pdrevs & 1) != 0 && uvmexp.nswapdev != 0)
921 		got_it = uvmpd_scan_inactive(&uvm.page_inactive_swp);
922 	if (!got_it)
923 		got_it = uvmpd_scan_inactive(&uvm.page_inactive_obj);
924 	if (!got_it && (uvmexp.pdrevs & 1) == 0 && uvmexp.nswapdev != 0)
925 		(void) uvmpd_scan_inactive(&uvm.page_inactive_swp);
926 	pages_freed = uvmexp.pdfreed - pages_freed;
927 
928 	/*
929 	 * we have done the scan to get free pages.   now we work on meeting
930 	 * our inactive target.
931 	 */
932 	inactive_shortage = uvmexp.inactarg - uvmexp.inactive - BUFPAGES_INACT;
933 
934 	/*
935 	 * detect if we're not going to be able to page anything out
936 	 * until we free some swap resources from active pages.
937 	 */
938 	swap_shortage = 0;
939 	if (uvmexp.free < uvmexp.freetarg &&
940 	    uvmexp.swpginuse == uvmexp.swpages &&
941 	    !uvm_swapisfull() &&
942 	    pages_freed == 0) {
943 		swap_shortage = uvmexp.freetarg - uvmexp.free;
944 	}
945 
946 	for (p = TAILQ_FIRST(&uvm.page_active);
947 	     p != NULL && (inactive_shortage > 0 || swap_shortage > 0);
948 	     p = nextpg) {
949 		nextpg = TAILQ_NEXT(p, pageq);
950 
951 		/* skip this page if it's busy. */
952 		if (p->pg_flags & PG_BUSY)
953 			continue;
954 
955 		if (p->pg_flags & PQ_ANON) {
956 			KASSERT(p->uanon != NULL);
957 			if (rw_enter(p->uanon->an_lock, RW_WRITE|RW_NOSLEEP))
958 				continue;
959 		} else {
960 			KASSERT(p->uobject != NULL);
961 			if (rw_enter(p->uobject->vmobjlock,
962 			    RW_WRITE|RW_NOSLEEP))
963 				continue;
964 		}
965 
966 		/*
967 		 * if there's a shortage of swap, free any swap allocated
968 		 * to this page so that other pages can be paged out.
969 		 */
970 		if (swap_shortage > 0) {
971 			if ((p->pg_flags & PQ_ANON) && p->uanon->an_swslot) {
972 				uvm_swap_free(p->uanon->an_swslot, 1);
973 				p->uanon->an_swslot = 0;
974 				atomic_clearbits_int(&p->pg_flags, PG_CLEAN);
975 				swap_shortage--;
976 			}
977 			if (p->pg_flags & PQ_AOBJ) {
978 				int slot = uao_set_swslot(p->uobject,
979 					p->offset >> PAGE_SHIFT, 0);
980 				if (slot) {
981 					uvm_swap_free(slot, 1);
982 					atomic_clearbits_int(&p->pg_flags,
983 					    PG_CLEAN);
984 					swap_shortage--;
985 				}
986 			}
987 		}
988 
989 		/*
990 		 * deactivate this page if there's a shortage of
991 		 * inactive pages.
992 		 */
993 		if (inactive_shortage > 0) {
994 			pmap_page_protect(p, 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 		if (p->pg_flags & PQ_ANON)
1001 			rw_exit(p->uanon->an_lock);
1002 		else
1003 			rw_exit(p->uobject->vmobjlock);
1004 	}
1005 }
1006 
1007 #ifdef HIBERNATE
1008 
1009 /*
1010  * uvmpd_drop: drop clean pages from list
1011  */
1012 void
1013 uvmpd_drop(struct pglist *pglst)
1014 {
1015 	struct vm_page *p, *nextpg;
1016 
1017 	for (p = TAILQ_FIRST(pglst); p != NULL; p = nextpg) {
1018 		nextpg = TAILQ_NEXT(p, pageq);
1019 
1020 		if (p->pg_flags & PQ_ANON || p->uobject == NULL)
1021 			continue;
1022 
1023 		if (p->pg_flags & PG_BUSY)
1024 			continue;
1025 
1026 		if (p->pg_flags & PG_CLEAN) {
1027 			struct uvm_object * uobj = p->uobject;
1028 
1029 			rw_enter(uobj->vmobjlock, RW_WRITE);
1030 			uvm_lock_pageq();
1031 			/*
1032 			 * we now have the page queues locked.
1033 			 * the page is not busy.   if the page is clean we
1034 			 * can free it now and continue.
1035 			 */
1036 			if (p->pg_flags & PG_CLEAN) {
1037 				if (p->pg_flags & PQ_SWAPBACKED) {
1038 					/* this page now lives only in swap */
1039 					atomic_inc_int(&uvmexp.swpgonly);
1040 				}
1041 
1042 				/* zap all mappings with pmap_page_protect... */
1043 				pmap_page_protect(p, PROT_NONE);
1044 				uvm_pagefree(p);
1045 			}
1046 			uvm_unlock_pageq();
1047 			rw_exit(uobj->vmobjlock);
1048 		}
1049 	}
1050 }
1051 
1052 void
1053 uvmpd_hibernate(void)
1054 {
1055 	uvmpd_drop(&uvm.page_inactive_swp);
1056 	uvmpd_drop(&uvm.page_inactive_obj);
1057 	uvmpd_drop(&uvm.page_active);
1058 }
1059 
1060 #endif
1061