xref: /netbsd-src/sys/uvm/uvm_pdaemon.c (revision 627f7eb200a4419d89b531d55fccd2ee3ffdcde0)
1 /*	$NetBSD: uvm_pdaemon.c,v 1.131 2020/11/04 01:30:19 chs Exp $	*/
2 
3 /*
4  * Copyright (c) 1997 Charles D. Cranor and Washington University.
5  * Copyright (c) 1991, 1993, The Regents of the University of California.
6  *
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * The Mach Operating System project at Carnegie-Mellon University.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)vm_pageout.c        8.5 (Berkeley) 2/14/94
37  * from: Id: uvm_pdaemon.c,v 1.1.2.32 1998/02/06 05:26:30 chs Exp
38  *
39  *
40  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
41  * All rights reserved.
42  *
43  * Permission to use, copy, modify and distribute this software and
44  * its documentation is hereby granted, provided that both the copyright
45  * notice and this permission notice appear in all copies of the
46  * software, derivative works or modified versions, and any portions
47  * thereof, and that both notices appear in supporting documentation.
48  *
49  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
50  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
51  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52  *
53  * Carnegie Mellon requests users of this software to return to
54  *
55  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
56  *  School of Computer Science
57  *  Carnegie Mellon University
58  *  Pittsburgh PA 15213-3890
59  *
60  * any improvements or extensions that they make and grant Carnegie the
61  * rights to redistribute these changes.
62  */
63 
64 /*
65  * uvm_pdaemon.c: the page daemon
66  */
67 
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: uvm_pdaemon.c,v 1.131 2020/11/04 01:30:19 chs Exp $");
70 
71 #include "opt_uvmhist.h"
72 #include "opt_readahead.h"
73 
74 #define	__RWLOCK_PRIVATE
75 
76 #include <sys/param.h>
77 #include <sys/proc.h>
78 #include <sys/systm.h>
79 #include <sys/kernel.h>
80 #include <sys/pool.h>
81 #include <sys/buf.h>
82 #include <sys/module.h>
83 #include <sys/atomic.h>
84 #include <sys/kthread.h>
85 
86 #include <uvm/uvm.h>
87 #include <uvm/uvm_pdpolicy.h>
88 #include <uvm/uvm_pgflcache.h>
89 
90 #ifdef UVMHIST
91 UVMHIST_DEFINE(pdhist);
92 #endif
93 
94 /*
95  * UVMPD_NUMDIRTYREACTS is how many dirty pages the pagedaemon will reactivate
96  * in a pass thru the inactive list when swap is full.  the value should be
97  * "small"... if it's too large we'll cycle the active pages thru the inactive
98  * queue too quickly to for them to be referenced and avoid being freed.
99  */
100 
101 #define	UVMPD_NUMDIRTYREACTS	16
102 
103 /*
104  * local prototypes
105  */
106 
107 static void	uvmpd_scan(void);
108 static void	uvmpd_scan_queue(void);
109 static void	uvmpd_tune(void);
110 static void	uvmpd_pool_drain_thread(void *);
111 static void	uvmpd_pool_drain_wakeup(void);
112 
113 static unsigned int uvm_pagedaemon_waiters;
114 
115 /* State for the pool drainer thread */
116 static kmutex_t uvmpd_lock __cacheline_aligned;
117 static kcondvar_t uvmpd_pool_drain_cv;
118 static bool uvmpd_pool_drain_run = false;
119 
120 /*
121  * XXX hack to avoid hangs when large processes fork.
122  */
123 u_int uvm_extrapages;
124 
125 /*
126  * uvm_wait: wait (sleep) for the page daemon to free some pages
127  *
128  * => should be called with all locks released
129  * => should _not_ be called by the page daemon (to avoid deadlock)
130  */
131 
132 void
133 uvm_wait(const char *wmsg)
134 {
135 	int timo = 0;
136 
137 	if (uvm.pagedaemon_lwp == NULL)
138 		panic("out of memory before the pagedaemon thread exists");
139 
140 	mutex_spin_enter(&uvmpd_lock);
141 
142 	/*
143 	 * check for page daemon going to sleep (waiting for itself)
144 	 */
145 
146 	if (curlwp == uvm.pagedaemon_lwp && uvmexp.paging == 0) {
147 		/*
148 		 * now we have a problem: the pagedaemon wants to go to
149 		 * sleep until it frees more memory.   but how can it
150 		 * free more memory if it is asleep?  that is a deadlock.
151 		 * we have two options:
152 		 *  [1] panic now
153 		 *  [2] put a timeout on the sleep, thus causing the
154 		 *      pagedaemon to only pause (rather than sleep forever)
155 		 *
156 		 * note that option [2] will only help us if we get lucky
157 		 * and some other process on the system breaks the deadlock
158 		 * by exiting or freeing memory (thus allowing the pagedaemon
159 		 * to continue).  for now we panic if DEBUG is defined,
160 		 * otherwise we hope for the best with option [2] (better
161 		 * yet, this should never happen in the first place!).
162 		 */
163 
164 		printf("pagedaemon: deadlock detected!\n");
165 		timo = hz >> 3;		/* set timeout */
166 #if defined(DEBUG)
167 		/* DEBUG: panic so we can debug it */
168 		panic("pagedaemon deadlock");
169 #endif
170 	}
171 
172 	uvm_pagedaemon_waiters++;
173 	wakeup(&uvm.pagedaemon);		/* wake the daemon! */
174 	UVM_UNLOCK_AND_WAIT(&uvmexp.free, &uvmpd_lock, false, wmsg, timo);
175 }
176 
177 /*
178  * uvm_kick_pdaemon: perform checks to determine if we need to
179  * give the pagedaemon a nudge, and do so if necessary.
180  */
181 
182 void
183 uvm_kick_pdaemon(void)
184 {
185 	int fpages = uvm_availmem(false);
186 
187 	if (fpages + uvmexp.paging < uvmexp.freemin ||
188 	    (fpages + uvmexp.paging < uvmexp.freetarg &&
189 	     uvmpdpol_needsscan_p()) ||
190 	     uvm_km_va_starved_p()) {
191 	     	mutex_spin_enter(&uvmpd_lock);
192 		wakeup(&uvm.pagedaemon);
193 	     	mutex_spin_exit(&uvmpd_lock);
194 	}
195 }
196 
197 /*
198  * uvmpd_tune: tune paging parameters
199  *
200  * => called when ever memory is added (or removed?) to the system
201  */
202 
203 static void
204 uvmpd_tune(void)
205 {
206 	int val;
207 
208 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
209 
210 	/*
211 	 * try to keep 0.5% of available RAM free, but limit to between
212 	 * 128k and 1024k per-CPU.  XXX: what are these values good for?
213 	 */
214 	val = uvmexp.npages / 200;
215 	val = MAX(val, (128*1024) >> PAGE_SHIFT);
216 	val = MIN(val, (1024*1024) >> PAGE_SHIFT);
217 	val *= ncpu;
218 
219 	/* Make sure there's always a user page free. */
220 	if (val < uvmexp.reserve_kernel + 1)
221 		val = uvmexp.reserve_kernel + 1;
222 	uvmexp.freemin = val;
223 
224 	/* Calculate free target. */
225 	val = (uvmexp.freemin * 4) / 3;
226 	if (val <= uvmexp.freemin)
227 		val = uvmexp.freemin + 1;
228 	uvmexp.freetarg = val + atomic_swap_uint(&uvm_extrapages, 0);
229 
230 	uvmexp.wiredmax = uvmexp.npages / 3;
231 	UVMHIST_LOG(pdhist, "<- done, freemin=%jd, freetarg=%jd, wiredmax=%jd",
232 	      uvmexp.freemin, uvmexp.freetarg, uvmexp.wiredmax, 0);
233 }
234 
235 /*
236  * uvm_pageout: the main loop for the pagedaemon
237  */
238 
239 void
240 uvm_pageout(void *arg)
241 {
242 	int npages = 0;
243 	int extrapages = 0;
244 	int fpages;
245 
246 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
247 
248 	UVMHIST_LOG(pdhist,"<starting uvm pagedaemon>", 0, 0, 0, 0);
249 
250 	mutex_init(&uvmpd_lock, MUTEX_DEFAULT, IPL_VM);
251 	cv_init(&uvmpd_pool_drain_cv, "pooldrain");
252 
253 	/* Create the pool drainer kernel thread. */
254 	if (kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL,
255 	    uvmpd_pool_drain_thread, NULL, NULL, "pooldrain"))
256 		panic("fork pooldrain");
257 
258 	/*
259 	 * ensure correct priority and set paging parameters...
260 	 */
261 
262 	uvm.pagedaemon_lwp = curlwp;
263 	npages = uvmexp.npages;
264 	uvmpd_tune();
265 
266 	/*
267 	 * main loop
268 	 */
269 
270 	for (;;) {
271 		bool needsscan, needsfree, kmem_va_starved;
272 
273 		kmem_va_starved = uvm_km_va_starved_p();
274 
275 		mutex_spin_enter(&uvmpd_lock);
276 		if ((uvm_pagedaemon_waiters == 0 || uvmexp.paging > 0) &&
277 		    !kmem_va_starved) {
278 			UVMHIST_LOG(pdhist,"  <<SLEEPING>>",0,0,0,0);
279 			UVM_UNLOCK_AND_WAIT(&uvm.pagedaemon,
280 			    &uvmpd_lock, false, "pgdaemon", 0);
281 			uvmexp.pdwoke++;
282 			UVMHIST_LOG(pdhist,"  <<WOKE UP>>",0,0,0,0);
283 		} else {
284 			mutex_spin_exit(&uvmpd_lock);
285 		}
286 
287 		/*
288 		 * now recompute inactive count
289 		 */
290 
291 		if (npages != uvmexp.npages || extrapages != uvm_extrapages) {
292 			npages = uvmexp.npages;
293 			extrapages = uvm_extrapages;
294 			uvmpd_tune();
295 		}
296 
297 		uvmpdpol_tune();
298 
299 		/*
300 		 * Estimate a hint.  Note that bufmem are returned to
301 		 * system only when entire pool page is empty.
302 		 */
303 		fpages = uvm_availmem(false);
304 		UVMHIST_LOG(pdhist,"  free/ftarg=%jd/%jd",
305 		    fpages, uvmexp.freetarg, 0,0);
306 
307 		needsfree = fpages + uvmexp.paging < uvmexp.freetarg;
308 		needsscan = needsfree || uvmpdpol_needsscan_p();
309 
310 		/*
311 		 * scan if needed
312 		 */
313 		if (needsscan) {
314 			uvmpd_scan();
315 		}
316 
317 		/*
318 		 * if there's any free memory to be had,
319 		 * wake up any waiters.
320 		 */
321 		if (uvm_availmem(false) > uvmexp.reserve_kernel ||
322 		    uvmexp.paging == 0) {
323 			mutex_spin_enter(&uvmpd_lock);
324 			wakeup(&uvmexp.free);
325 			uvm_pagedaemon_waiters = 0;
326 			mutex_spin_exit(&uvmpd_lock);
327 		}
328 
329 		/*
330 		 * scan done.  if we don't need free memory, we're done.
331 		 */
332 
333 		if (!needsfree && !kmem_va_starved)
334 			continue;
335 
336 		/*
337 		 * kick the pool drainer thread.
338 		 */
339 
340 		uvmpd_pool_drain_wakeup();
341 	}
342 	/*NOTREACHED*/
343 }
344 
345 void
346 uvm_pageout_start(int npages)
347 {
348 
349 	atomic_add_int(&uvmexp.paging, npages);
350 }
351 
352 void
353 uvm_pageout_done(int npages)
354 {
355 
356 	KASSERT(atomic_load_relaxed(&uvmexp.paging) >= npages);
357 
358 	if (npages == 0) {
359 		return;
360 	}
361 
362 	atomic_add_int(&uvmexp.paging, -npages);
363 
364 	/*
365 	 * wake up either of pagedaemon or LWPs waiting for it.
366 	 */
367 
368 	mutex_spin_enter(&uvmpd_lock);
369 	if (uvm_availmem(false) <= uvmexp.reserve_kernel) {
370 		wakeup(&uvm.pagedaemon);
371 	} else if (uvm_pagedaemon_waiters != 0) {
372 		wakeup(&uvmexp.free);
373 		uvm_pagedaemon_waiters = 0;
374 	}
375 	mutex_spin_exit(&uvmpd_lock);
376 }
377 
378 static krwlock_t *
379 uvmpd_page_owner_lock(struct vm_page *pg)
380 {
381 	struct uvm_object *uobj = pg->uobject;
382 	struct vm_anon *anon = pg->uanon;
383 	krwlock_t *slock;
384 
385 	KASSERT(mutex_owned(&pg->interlock));
386 
387 #ifdef DEBUG
388 	if (uobj == (void *)0xdeadbeef || anon == (void *)0xdeadbeef) {
389 		return NULL;
390 	}
391 #endif
392 	if (uobj != NULL) {
393 		slock = uobj->vmobjlock;
394 		KASSERTMSG(slock != NULL, "pg %p uobj %p, NULL lock", pg, uobj);
395 	} else if (anon != NULL) {
396 		slock = anon->an_lock;
397 		KASSERTMSG(slock != NULL, "pg %p anon %p, NULL lock", pg, anon);
398 	} else {
399 		slock = NULL;
400 	}
401 	return slock;
402 }
403 
404 /*
405  * uvmpd_trylockowner: trylock the page's owner.
406  *
407  * => called with page interlock held.
408  * => resolve orphaned O->A loaned page.
409  * => return the locked mutex on success.  otherwise, return NULL.
410  */
411 
412 krwlock_t *
413 uvmpd_trylockowner(struct vm_page *pg)
414 {
415 	krwlock_t *slock, *heldslock;
416 
417 	KASSERT(mutex_owned(&pg->interlock));
418 
419 	slock = uvmpd_page_owner_lock(pg);
420 	if (slock == NULL) {
421 		/* Page may be in state of flux - ignore. */
422 		mutex_exit(&pg->interlock);
423 		return NULL;
424 	}
425 
426 	if (rw_tryenter(slock, RW_WRITER)) {
427 		goto success;
428 	}
429 
430 	/*
431 	 * The try-lock didn't work, so now do a blocking lock after
432 	 * dropping the page interlock.  Prevent the owner lock from
433 	 * being freed by taking a hold on it first.
434 	 */
435 
436 	rw_obj_hold(slock);
437 	mutex_exit(&pg->interlock);
438 	rw_enter(slock, RW_WRITER);
439 	heldslock = slock;
440 
441 	/*
442 	 * Now we hold some owner lock.  Check if the lock we hold
443 	 * is still the lock for the owner of the page.
444 	 * If it is then return it, otherwise release it and return NULL.
445 	 */
446 
447 	mutex_enter(&pg->interlock);
448 	slock = uvmpd_page_owner_lock(pg);
449 	if (heldslock != slock) {
450 		rw_exit(heldslock);
451 		slock = NULL;
452 	}
453 	rw_obj_free(heldslock);
454 	if (slock != NULL) {
455 success:
456 		/*
457 		 * Set PG_ANON if it isn't set already.
458 		 */
459 		if (pg->uobject == NULL && (pg->flags & PG_ANON) == 0) {
460 			KASSERT(pg->loan_count > 0);
461 			pg->loan_count--;
462 			pg->flags |= PG_ANON;
463 			/* anon now owns it */
464 		}
465 	}
466 	mutex_exit(&pg->interlock);
467 	return slock;
468 }
469 
470 #if defined(VMSWAP)
471 struct swapcluster {
472 	int swc_slot;
473 	int swc_nallocated;
474 	int swc_nused;
475 	struct vm_page *swc_pages[howmany(MAXPHYS, MIN_PAGE_SIZE)];
476 };
477 
478 static void
479 swapcluster_init(struct swapcluster *swc)
480 {
481 
482 	swc->swc_slot = 0;
483 	swc->swc_nused = 0;
484 }
485 
486 static int
487 swapcluster_allocslots(struct swapcluster *swc)
488 {
489 	int slot;
490 	int npages;
491 
492 	if (swc->swc_slot != 0) {
493 		return 0;
494 	}
495 
496 	/* Even with strange MAXPHYS, the shift
497 	   implicitly rounds down to a page. */
498 	npages = MAXPHYS >> PAGE_SHIFT;
499 	slot = uvm_swap_alloc(&npages, true);
500 	if (slot == 0) {
501 		return ENOMEM;
502 	}
503 	swc->swc_slot = slot;
504 	swc->swc_nallocated = npages;
505 	swc->swc_nused = 0;
506 
507 	return 0;
508 }
509 
510 static int
511 swapcluster_add(struct swapcluster *swc, struct vm_page *pg)
512 {
513 	int slot;
514 	struct uvm_object *uobj;
515 
516 	KASSERT(swc->swc_slot != 0);
517 	KASSERT(swc->swc_nused < swc->swc_nallocated);
518 	KASSERT((pg->flags & PG_SWAPBACKED) != 0);
519 
520 	slot = swc->swc_slot + swc->swc_nused;
521 	uobj = pg->uobject;
522 	if (uobj == NULL) {
523 		KASSERT(rw_write_held(pg->uanon->an_lock));
524 		pg->uanon->an_swslot = slot;
525 	} else {
526 		int result;
527 
528 		KASSERT(rw_write_held(uobj->vmobjlock));
529 		result = uao_set_swslot(uobj, pg->offset >> PAGE_SHIFT, slot);
530 		if (result == -1) {
531 			return ENOMEM;
532 		}
533 	}
534 	swc->swc_pages[swc->swc_nused] = pg;
535 	swc->swc_nused++;
536 
537 	return 0;
538 }
539 
540 static void
541 swapcluster_flush(struct swapcluster *swc, bool now)
542 {
543 	int slot;
544 	int nused;
545 	int nallocated;
546 	int error __diagused;
547 
548 	if (swc->swc_slot == 0) {
549 		return;
550 	}
551 	KASSERT(swc->swc_nused <= swc->swc_nallocated);
552 
553 	slot = swc->swc_slot;
554 	nused = swc->swc_nused;
555 	nallocated = swc->swc_nallocated;
556 
557 	/*
558 	 * if this is the final pageout we could have a few
559 	 * unused swap blocks.  if so, free them now.
560 	 */
561 
562 	if (nused < nallocated) {
563 		if (!now) {
564 			return;
565 		}
566 		uvm_swap_free(slot + nused, nallocated - nused);
567 	}
568 
569 	/*
570 	 * now start the pageout.
571 	 */
572 
573 	if (nused > 0) {
574 		uvmexp.pdpageouts++;
575 		uvm_pageout_start(nused);
576 		error = uvm_swap_put(slot, swc->swc_pages, nused, 0);
577 		KASSERT(error == 0 || error == ENOMEM);
578 	}
579 
580 	/*
581 	 * zero swslot to indicate that we are
582 	 * no longer building a swap-backed cluster.
583 	 */
584 
585 	swc->swc_slot = 0;
586 	swc->swc_nused = 0;
587 }
588 
589 static int
590 swapcluster_nused(struct swapcluster *swc)
591 {
592 
593 	return swc->swc_nused;
594 }
595 
596 /*
597  * uvmpd_dropswap: free any swap allocated to this page.
598  *
599  * => called with owner locked.
600  * => return true if a page had an associated slot.
601  */
602 
603 bool
604 uvmpd_dropswap(struct vm_page *pg)
605 {
606 	bool result = false;
607 	struct vm_anon *anon = pg->uanon;
608 
609 	if ((pg->flags & PG_ANON) && anon->an_swslot) {
610 		uvm_swap_free(anon->an_swslot, 1);
611 		anon->an_swslot = 0;
612 		uvm_pagemarkdirty(pg, UVM_PAGE_STATUS_DIRTY);
613 		result = true;
614 	} else if (pg->flags & PG_AOBJ) {
615 		int slot = uao_set_swslot(pg->uobject,
616 		    pg->offset >> PAGE_SHIFT, 0);
617 		if (slot) {
618 			uvm_swap_free(slot, 1);
619 			uvm_pagemarkdirty(pg, UVM_PAGE_STATUS_DIRTY);
620 			result = true;
621 		}
622 	}
623 
624 	return result;
625 }
626 
627 #endif /* defined(VMSWAP) */
628 
629 /*
630  * uvmpd_scan_queue: scan an replace candidate list for pages
631  * to clean or free.
632  *
633  * => we work on meeting our free target by converting inactive pages
634  *    into free pages.
635  * => we handle the building of swap-backed clusters
636  */
637 
638 static void
639 uvmpd_scan_queue(void)
640 {
641 	struct vm_page *p;
642 	struct uvm_object *uobj;
643 	struct vm_anon *anon;
644 #if defined(VMSWAP)
645 	struct swapcluster swc;
646 #endif /* defined(VMSWAP) */
647 	int dirtyreacts;
648 	krwlock_t *slock;
649 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
650 
651 	/*
652 	 * swslot is non-zero if we are building a swap cluster.  we want
653 	 * to stay in the loop while we have a page to scan or we have
654 	 * a swap-cluster to build.
655 	 */
656 
657 #if defined(VMSWAP)
658 	swapcluster_init(&swc);
659 #endif /* defined(VMSWAP) */
660 
661 	dirtyreacts = 0;
662 	uvmpdpol_scaninit();
663 
664 	while (/* CONSTCOND */ 1) {
665 
666 		/*
667 		 * see if we've met the free target.
668 		 */
669 
670 		if (uvm_availmem(false) + uvmexp.paging
671 #if defined(VMSWAP)
672 		    + swapcluster_nused(&swc)
673 #endif /* defined(VMSWAP) */
674 		    >= uvmexp.freetarg << 2 ||
675 		    dirtyreacts == UVMPD_NUMDIRTYREACTS) {
676 			UVMHIST_LOG(pdhist,"  met free target: "
677 				    "exit loop", 0, 0, 0, 0);
678 			break;
679 		}
680 
681 		/*
682 		 * first we have the pdpolicy select a victim page
683 		 * and attempt to lock the object that the page
684 		 * belongs to.  if our attempt fails we skip on to
685 		 * the next page (no harm done).  it is important to
686 		 * "try" locking the object as we are locking in the
687 		 * wrong order (pageq -> object) and we don't want to
688 		 * deadlock.
689 		 *
690 		 * the only time we expect to see an ownerless page
691 		 * (i.e. a page with no uobject and !PG_ANON) is if an
692 		 * anon has loaned a page from a uvm_object and the
693 		 * uvm_object has dropped the ownership.  in that
694 		 * case, the anon can "take over" the loaned page
695 		 * and make it its own.
696 		 */
697 
698 		p = uvmpdpol_selectvictim(&slock);
699 		if (p == NULL) {
700 			break;
701 		}
702 		KASSERT(uvmpdpol_pageisqueued_p(p));
703 		KASSERT(uvm_page_owner_locked_p(p, true));
704 		KASSERT(p->wire_count == 0);
705 
706 		/*
707 		 * we are below target and have a new page to consider.
708 		 */
709 
710 		anon = p->uanon;
711 		uobj = p->uobject;
712 
713 		if (p->flags & PG_BUSY) {
714 			rw_exit(slock);
715 			uvmexp.pdbusy++;
716 			continue;
717 		}
718 
719 		/* does the page belong to an object? */
720 		if (uobj != NULL) {
721 			uvmexp.pdobscan++;
722 		} else {
723 #if defined(VMSWAP)
724 			KASSERT(anon != NULL);
725 			uvmexp.pdanscan++;
726 #else /* defined(VMSWAP) */
727 			panic("%s: anon", __func__);
728 #endif /* defined(VMSWAP) */
729 		}
730 
731 
732 		/*
733 		 * we now have the object locked.
734 		 * if the page is not swap-backed, call the object's
735 		 * pager to flush and free the page.
736 		 */
737 
738 #if defined(READAHEAD_STATS)
739 		if ((p->flags & PG_READAHEAD) != 0) {
740 			p->flags &= ~PG_READAHEAD;
741 			uvm_ra_miss.ev_count++;
742 		}
743 #endif /* defined(READAHEAD_STATS) */
744 
745 		if ((p->flags & PG_SWAPBACKED) == 0) {
746 			KASSERT(uobj != NULL);
747 			(void) (uobj->pgops->pgo_put)(uobj, p->offset,
748 			    p->offset + PAGE_SIZE, PGO_CLEANIT|PGO_FREE);
749 			continue;
750 		}
751 
752 		/*
753 		 * the page is swap-backed.  remove all the permissions
754 		 * from the page so we can sync the modified info
755 		 * without any race conditions.  if the page is clean
756 		 * we can free it now and continue.
757 		 */
758 
759 		pmap_page_protect(p, VM_PROT_NONE);
760 		if (uvm_pagegetdirty(p) == UVM_PAGE_STATUS_UNKNOWN) {
761 			if (pmap_clear_modify(p)) {
762 				uvm_pagemarkdirty(p, UVM_PAGE_STATUS_DIRTY);
763 			} else {
764 				uvm_pagemarkdirty(p, UVM_PAGE_STATUS_CLEAN);
765 			}
766 		}
767 		if (uvm_pagegetdirty(p) != UVM_PAGE_STATUS_DIRTY) {
768 			int slot;
769 			int pageidx;
770 
771 			pageidx = p->offset >> PAGE_SHIFT;
772 			uvm_pagefree(p);
773 			atomic_inc_uint(&uvmexp.pdfreed);
774 
775 			/*
776 			 * for anons, we need to remove the page
777 			 * from the anon ourselves.  for aobjs,
778 			 * pagefree did that for us.
779 			 */
780 
781 			if (anon) {
782 				KASSERT(anon->an_swslot != 0);
783 				anon->an_page = NULL;
784 				slot = anon->an_swslot;
785 			} else {
786 				slot = uao_find_swslot(uobj, pageidx);
787 			}
788 			if (slot > 0) {
789 				/* this page is now only in swap. */
790 				KASSERT(uvmexp.swpgonly < uvmexp.swpginuse);
791 				atomic_inc_uint(&uvmexp.swpgonly);
792 			}
793 			rw_exit(slock);
794 			continue;
795 		}
796 
797 #if defined(VMSWAP)
798 		/*
799 		 * this page is dirty, skip it if we'll have met our
800 		 * free target when all the current pageouts complete.
801 		 */
802 
803 		if (uvm_availmem(false) + uvmexp.paging >
804 		    uvmexp.freetarg << 2) {
805 			rw_exit(slock);
806 			continue;
807 		}
808 
809 		/*
810 		 * free any swap space allocated to the page since
811 		 * we'll have to write it again with its new data.
812 		 */
813 
814 		uvmpd_dropswap(p);
815 
816 		/*
817 		 * start new swap pageout cluster (if necessary).
818 		 *
819 		 * if swap is full reactivate this page so that
820 		 * we eventually cycle all pages through the
821 		 * inactive queue.
822 		 */
823 
824 		if (swapcluster_allocslots(&swc)) {
825 			dirtyreacts++;
826 			uvm_pagelock(p);
827 			uvm_pageactivate(p);
828 			uvm_pageunlock(p);
829 			rw_exit(slock);
830 			continue;
831 		}
832 
833 		/*
834 		 * at this point, we're definitely going reuse this
835 		 * page.  mark the page busy and delayed-free.
836 		 * we should remove the page from the page queues
837 		 * so we don't ever look at it again.
838 		 * adjust counters and such.
839 		 */
840 
841 		p->flags |= PG_BUSY;
842 		UVM_PAGE_OWN(p, "scan_queue");
843 		p->flags |= PG_PAGEOUT;
844 		uvmexp.pgswapout++;
845 
846 		uvm_pagelock(p);
847 		uvm_pagedequeue(p);
848 		uvm_pageunlock(p);
849 
850 		/*
851 		 * add the new page to the cluster.
852 		 */
853 
854 		if (swapcluster_add(&swc, p)) {
855 			p->flags &= ~(PG_BUSY|PG_PAGEOUT);
856 			UVM_PAGE_OWN(p, NULL);
857 			dirtyreacts++;
858 			uvm_pagelock(p);
859 			uvm_pageactivate(p);
860 			uvm_pageunlock(p);
861 			rw_exit(slock);
862 			continue;
863 		}
864 		rw_exit(slock);
865 
866 		swapcluster_flush(&swc, false);
867 
868 		/*
869 		 * the pageout is in progress.  bump counters and set up
870 		 * for the next loop.
871 		 */
872 
873 		atomic_inc_uint(&uvmexp.pdpending);
874 
875 #else /* defined(VMSWAP) */
876 		uvm_pagelock(p);
877 		uvm_pageactivate(p);
878 		uvm_pageunlock(p);
879 		rw_exit(slock);
880 #endif /* defined(VMSWAP) */
881 	}
882 
883 	uvmpdpol_scanfini();
884 
885 #if defined(VMSWAP)
886 	swapcluster_flush(&swc, true);
887 #endif /* defined(VMSWAP) */
888 }
889 
890 /*
891  * uvmpd_scan: scan the page queues and attempt to meet our targets.
892  */
893 
894 static void
895 uvmpd_scan(void)
896 {
897 	int swap_shortage, pages_freed, fpages;
898 	UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist);
899 
900 	uvmexp.pdrevs++;
901 
902 	/*
903 	 * work on meeting our targets.   first we work on our free target
904 	 * by converting inactive pages into free pages.  then we work on
905 	 * meeting our inactive target by converting active pages to
906 	 * inactive ones.
907 	 */
908 
909 	UVMHIST_LOG(pdhist, "  starting 'free' loop",0,0,0,0);
910 
911 	pages_freed = uvmexp.pdfreed;
912 	uvmpd_scan_queue();
913 	pages_freed = uvmexp.pdfreed - pages_freed;
914 
915 	/*
916 	 * detect if we're not going to be able to page anything out
917 	 * until we free some swap resources from active pages.
918 	 */
919 
920 	swap_shortage = 0;
921 	fpages = uvm_availmem(false);
922 	if (fpages < uvmexp.freetarg &&
923 	    uvmexp.swpginuse >= uvmexp.swpgavail &&
924 	    !uvm_swapisfull() &&
925 	    pages_freed == 0) {
926 		swap_shortage = uvmexp.freetarg - fpages;
927 	}
928 
929 	uvmpdpol_balancequeue(swap_shortage);
930 
931 	/*
932 	 * if still below the minimum target, try unloading kernel
933 	 * modules.
934 	 */
935 
936 	if (uvm_availmem(false) < uvmexp.freemin) {
937 		module_thread_kick();
938 	}
939 }
940 
941 /*
942  * uvm_reclaimable: decide whether to wait for pagedaemon.
943  *
944  * => return true if it seems to be worth to do uvm_wait.
945  *
946  * XXX should be tunable.
947  * XXX should consider pools, etc?
948  */
949 
950 bool
951 uvm_reclaimable(void)
952 {
953 	int filepages;
954 	int active, inactive;
955 
956 	/*
957 	 * if swap is not full, no problem.
958 	 */
959 
960 	if (!uvm_swapisfull()) {
961 		return true;
962 	}
963 
964 	/*
965 	 * file-backed pages can be reclaimed even when swap is full.
966 	 * if we have more than 1/16 of pageable memory or 5MB, try to reclaim.
967 	 * NB: filepages calculation does not exclude EXECPAGES - intentional.
968 	 *
969 	 * XXX assume the worst case, ie. all wired pages are file-backed.
970 	 *
971 	 * XXX should consider about other reclaimable memory.
972 	 * XXX ie. pools, traditional buffer cache.
973 	 */
974 
975 	cpu_count_sync(false);
976 	filepages = (int)(cpu_count_get(CPU_COUNT_FILECLEAN) +
977 	    cpu_count_get(CPU_COUNT_FILEUNKNOWN) +
978 	    cpu_count_get(CPU_COUNT_FILEDIRTY) - uvmexp.wired);
979 	uvm_estimatepageable(&active, &inactive);
980 	if (filepages >= MIN((active + inactive) >> 4,
981 	    5 * 1024 * 1024 >> PAGE_SHIFT)) {
982 		return true;
983 	}
984 
985 	/*
986 	 * kill the process, fail allocation, etc..
987 	 */
988 
989 	return false;
990 }
991 
992 void
993 uvm_estimatepageable(int *active, int *inactive)
994 {
995 
996 	uvmpdpol_estimatepageable(active, inactive);
997 }
998 
999 
1000 /*
1001  * Use a separate thread for draining pools.
1002  * This work can't done from the main pagedaemon thread because
1003  * some pool allocators need to take vm_map locks.
1004  */
1005 
1006 static void
1007 uvmpd_pool_drain_thread(void *arg)
1008 {
1009 	struct pool *firstpool, *curpool;
1010 	int bufcnt, lastslept;
1011 	bool cycled;
1012 
1013 	firstpool = NULL;
1014 	cycled = true;
1015 	for (;;) {
1016 		/*
1017 		 * sleep until awoken by the pagedaemon.
1018 		 */
1019 		mutex_enter(&uvmpd_lock);
1020 		if (!uvmpd_pool_drain_run) {
1021 			lastslept = getticks();
1022 			cv_wait(&uvmpd_pool_drain_cv, &uvmpd_lock);
1023 			if (getticks() != lastslept) {
1024 				cycled = false;
1025 				firstpool = NULL;
1026 			}
1027 		}
1028 		uvmpd_pool_drain_run = false;
1029 		mutex_exit(&uvmpd_lock);
1030 
1031 		/*
1032 		 * rate limit draining, otherwise in desperate circumstances
1033 		 * this can totally saturate the system with xcall activity.
1034 		 */
1035 		if (cycled) {
1036 			kpause("uvmpdlmt", false, 1, NULL);
1037 			cycled = false;
1038 			firstpool = NULL;
1039 		}
1040 
1041 		/*
1042 		 * drain and temporarily disable the freelist cache.
1043 		 */
1044 		uvm_pgflcache_pause();
1045 
1046 		/*
1047 		 * kill unused metadata buffers.
1048 		 */
1049 		bufcnt = uvmexp.freetarg - uvm_availmem(false);
1050 		if (bufcnt < 0)
1051 			bufcnt = 0;
1052 
1053 		mutex_enter(&bufcache_lock);
1054 		buf_drain(bufcnt << PAGE_SHIFT);
1055 		mutex_exit(&bufcache_lock);
1056 
1057 		/*
1058 		 * drain a pool, and then re-enable the freelist cache.
1059 		 */
1060 		(void)pool_drain(&curpool);
1061 		KASSERT(curpool != NULL);
1062 		if (firstpool == NULL) {
1063 			firstpool = curpool;
1064 		} else if (firstpool == curpool) {
1065 			cycled = true;
1066 		}
1067 		uvm_pgflcache_resume();
1068 	}
1069 	/*NOTREACHED*/
1070 }
1071 
1072 static void
1073 uvmpd_pool_drain_wakeup(void)
1074 {
1075 
1076 	mutex_enter(&uvmpd_lock);
1077 	uvmpd_pool_drain_run = true;
1078 	cv_signal(&uvmpd_pool_drain_cv);
1079 	mutex_exit(&uvmpd_lock);
1080 }
1081