xref: /freebsd/sys/vm/vm_pageout.c (revision 277fbb92d5e4cd0938c67f77b08d9ba4ac9d54a6)
1 /*-
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 1994 John S. Dyson
5  * All rights reserved.
6  * Copyright (c) 1994 David Greenman
7  * All rights reserved.
8  * Copyright (c) 2005 Yahoo! Technologies Norway AS
9  * All rights reserved.
10  *
11  * This code is derived from software contributed to Berkeley by
12  * The Mach Operating System project at Carnegie-Mellon University.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. All advertising materials mentioning features or use of this software
23  *    must display the following acknowledgement:
24  *	This product includes software developed by the University of
25  *	California, Berkeley and 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  *	from: @(#)vm_pageout.c	7.4 (Berkeley) 5/7/91
43  *
44  *
45  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
46  * All rights reserved.
47  *
48  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
49  *
50  * Permission to use, copy, modify and distribute this software and
51  * its documentation is hereby granted, provided that both the copyright
52  * notice and this permission notice appear in all copies of the
53  * software, derivative works or modified versions, and any portions
54  * thereof, and that both notices appear in supporting documentation.
55  *
56  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
57  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
58  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
59  *
60  * Carnegie Mellon requests users of this software to return to
61  *
62  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
63  *  School of Computer Science
64  *  Carnegie Mellon University
65  *  Pittsburgh PA 15213-3890
66  *
67  * any improvements or extensions that they make and grant Carnegie the
68  * rights to redistribute these changes.
69  */
70 
71 /*
72  *	The proverbial page-out daemon.
73  */
74 
75 #include <sys/cdefs.h>
76 __FBSDID("$FreeBSD$");
77 
78 #include "opt_vm.h"
79 
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/kernel.h>
83 #include <sys/eventhandler.h>
84 #include <sys/lock.h>
85 #include <sys/mutex.h>
86 #include <sys/proc.h>
87 #include <sys/kthread.h>
88 #include <sys/ktr.h>
89 #include <sys/mount.h>
90 #include <sys/racct.h>
91 #include <sys/resourcevar.h>
92 #include <sys/sched.h>
93 #include <sys/sdt.h>
94 #include <sys/signalvar.h>
95 #include <sys/smp.h>
96 #include <sys/time.h>
97 #include <sys/vnode.h>
98 #include <sys/vmmeter.h>
99 #include <sys/rwlock.h>
100 #include <sys/sx.h>
101 #include <sys/sysctl.h>
102 
103 #include <vm/vm.h>
104 #include <vm/vm_param.h>
105 #include <vm/vm_object.h>
106 #include <vm/vm_page.h>
107 #include <vm/vm_map.h>
108 #include <vm/vm_pageout.h>
109 #include <vm/vm_pager.h>
110 #include <vm/vm_phys.h>
111 #include <vm/swap_pager.h>
112 #include <vm/vm_extern.h>
113 #include <vm/uma.h>
114 
115 /*
116  * System initialization
117  */
118 
119 /* the kernel process "vm_pageout"*/
120 static void vm_pageout(void);
121 static void vm_pageout_init(void);
122 static int vm_pageout_clean(vm_page_t m);
123 static int vm_pageout_cluster(vm_page_t m);
124 static void vm_pageout_scan(struct vm_domain *vmd, int pass);
125 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
126     int starting_page_shortage);
127 
128 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
129     NULL);
130 
131 struct proc *pageproc;
132 
133 static struct kproc_desc page_kp = {
134 	"pagedaemon",
135 	vm_pageout,
136 	&pageproc
137 };
138 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
139     &page_kp);
140 
141 SDT_PROVIDER_DEFINE(vm);
142 SDT_PROBE_DEFINE(vm, , , vm__lowmem_cache);
143 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan);
144 
145 #if !defined(NO_SWAPPING)
146 /* the kernel process "vm_daemon"*/
147 static void vm_daemon(void);
148 static struct	proc *vmproc;
149 
150 static struct kproc_desc vm_kp = {
151 	"vmdaemon",
152 	vm_daemon,
153 	&vmproc
154 };
155 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
156 #endif
157 
158 
159 int vm_pages_needed;		/* Event on which pageout daemon sleeps */
160 int vm_pageout_deficit;		/* Estimated number of pages deficit */
161 int vm_pageout_wakeup_thresh;
162 static int vm_pageout_oom_seq = 12;
163 
164 #if !defined(NO_SWAPPING)
165 static int vm_pageout_req_swapout;	/* XXX */
166 static int vm_daemon_needed;
167 static struct mtx vm_daemon_mtx;
168 /* Allow for use by vm_pageout before vm_daemon is initialized. */
169 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
170 #endif
171 static int vm_max_launder = 32;
172 static int vm_pageout_update_period;
173 static int defer_swap_pageouts;
174 static int disable_swap_pageouts;
175 static int lowmem_period = 10;
176 static time_t lowmem_uptime;
177 
178 #if defined(NO_SWAPPING)
179 static int vm_swap_enabled = 0;
180 static int vm_swap_idle_enabled = 0;
181 #else
182 static int vm_swap_enabled = 1;
183 static int vm_swap_idle_enabled = 0;
184 #endif
185 
186 static int vm_panic_on_oom = 0;
187 
188 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
189 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
190 	"panic on out of memory instead of killing the largest process");
191 
192 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
193 	CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
194 	"free page threshold for waking up the pageout daemon");
195 
196 SYSCTL_INT(_vm, OID_AUTO, max_launder,
197 	CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
198 
199 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
200 	CTLFLAG_RW, &vm_pageout_update_period, 0,
201 	"Maximum active LRU update period");
202 
203 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
204 	"Low memory callback period");
205 
206 #if defined(NO_SWAPPING)
207 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
208 	CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
209 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
210 	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
211 #else
212 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
213 	CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
214 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
215 	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
216 #endif
217 
218 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
219 	CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
220 
221 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
222 	CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
223 
224 static int pageout_lock_miss;
225 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
226 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
227 
228 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
229 	CTLFLAG_RW, &vm_pageout_oom_seq, 0,
230 	"back-to-back calls to oom detector to start OOM");
231 
232 #define VM_PAGEOUT_PAGE_COUNT 16
233 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
234 
235 int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
236 SYSCTL_INT(_vm, OID_AUTO, max_wired,
237 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
238 
239 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
240 static boolean_t vm_pageout_launder(struct vm_pagequeue *pq, int, vm_paddr_t,
241     vm_paddr_t);
242 #if !defined(NO_SWAPPING)
243 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
244 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
245 static void vm_req_vmdaemon(int req);
246 #endif
247 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
248 
249 /*
250  * Initialize a dummy page for marking the caller's place in the specified
251  * paging queue.  In principle, this function only needs to set the flag
252  * PG_MARKER.  Nonetheless, it wirte busies and initializes the hold count
253  * to one as safety precautions.
254  */
255 static void
256 vm_pageout_init_marker(vm_page_t marker, u_short queue)
257 {
258 
259 	bzero(marker, sizeof(*marker));
260 	marker->flags = PG_MARKER;
261 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
262 	marker->queue = queue;
263 	marker->hold_count = 1;
264 }
265 
266 /*
267  * vm_pageout_fallback_object_lock:
268  *
269  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
270  * known to have failed and page queue must be either PQ_ACTIVE or
271  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queues
272  * while locking the vm object.  Use marker page to detect page queue
273  * changes and maintain notion of next page on page queue.  Return
274  * TRUE if no changes were detected, FALSE otherwise.  vm object is
275  * locked on return.
276  *
277  * This function depends on both the lock portion of struct vm_object
278  * and normal struct vm_page being type stable.
279  */
280 static boolean_t
281 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
282 {
283 	struct vm_page marker;
284 	struct vm_pagequeue *pq;
285 	boolean_t unchanged;
286 	u_short queue;
287 	vm_object_t object;
288 
289 	queue = m->queue;
290 	vm_pageout_init_marker(&marker, queue);
291 	pq = vm_page_pagequeue(m);
292 	object = m->object;
293 
294 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
295 	vm_pagequeue_unlock(pq);
296 	vm_page_unlock(m);
297 	VM_OBJECT_WLOCK(object);
298 	vm_page_lock(m);
299 	vm_pagequeue_lock(pq);
300 
301 	/*
302 	 * The page's object might have changed, and/or the page might
303 	 * have moved from its original position in the queue.  If the
304 	 * page's object has changed, then the caller should abandon
305 	 * processing the page because the wrong object lock was
306 	 * acquired.  Use the marker's plinks.q, not the page's, to
307 	 * determine if the page has been moved.  The state of the
308 	 * page's plinks.q can be indeterminate; whereas, the marker's
309 	 * plinks.q must be valid.
310 	 */
311 	*next = TAILQ_NEXT(&marker, plinks.q);
312 	unchanged = m->object == object &&
313 	    m == TAILQ_PREV(&marker, pglist, plinks.q);
314 	KASSERT(!unchanged || m->queue == queue,
315 	    ("page %p queue %d %d", m, queue, m->queue));
316 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
317 	return (unchanged);
318 }
319 
320 /*
321  * Lock the page while holding the page queue lock.  Use marker page
322  * to detect page queue changes and maintain notion of next page on
323  * page queue.  Return TRUE if no changes were detected, FALSE
324  * otherwise.  The page is locked on return. The page queue lock might
325  * be dropped and reacquired.
326  *
327  * This function depends on normal struct vm_page being type stable.
328  */
329 static boolean_t
330 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
331 {
332 	struct vm_page marker;
333 	struct vm_pagequeue *pq;
334 	boolean_t unchanged;
335 	u_short queue;
336 
337 	vm_page_lock_assert(m, MA_NOTOWNED);
338 	if (vm_page_trylock(m))
339 		return (TRUE);
340 
341 	queue = m->queue;
342 	vm_pageout_init_marker(&marker, queue);
343 	pq = vm_page_pagequeue(m);
344 
345 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
346 	vm_pagequeue_unlock(pq);
347 	vm_page_lock(m);
348 	vm_pagequeue_lock(pq);
349 
350 	/* Page queue might have changed. */
351 	*next = TAILQ_NEXT(&marker, plinks.q);
352 	unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
353 	KASSERT(!unchanged || m->queue == queue,
354 	    ("page %p queue %d %d", m, queue, m->queue));
355 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
356 	return (unchanged);
357 }
358 
359 /*
360  * vm_pageout_clean:
361  *
362  * Clean the page and remove it from the laundry.
363  *
364  * We set the busy bit to cause potential page faults on this page to
365  * block.  Note the careful timing, however, the busy bit isn't set till
366  * late and we cannot do anything that will mess with the page.
367  */
368 static int
369 vm_pageout_cluster(vm_page_t m)
370 {
371 	vm_object_t object;
372 	vm_page_t mc[2*vm_pageout_page_count], pb, ps;
373 	int pageout_count;
374 	int ib, is, page_base;
375 	vm_pindex_t pindex = m->pindex;
376 
377 	vm_page_lock_assert(m, MA_OWNED);
378 	object = m->object;
379 	VM_OBJECT_ASSERT_WLOCKED(object);
380 
381 	/*
382 	 * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
383 	 * with the new swapper, but we could have serious problems paging
384 	 * out other object types if there is insufficient memory.
385 	 *
386 	 * Unfortunately, checking free memory here is far too late, so the
387 	 * check has been moved up a procedural level.
388 	 */
389 
390 	/*
391 	 * Can't clean the page if it's busy or held.
392 	 */
393 	vm_page_assert_unbusied(m);
394 	KASSERT(m->hold_count == 0, ("vm_pageout_clean: page %p is held", m));
395 	vm_page_unlock(m);
396 
397 	mc[vm_pageout_page_count] = pb = ps = m;
398 	pageout_count = 1;
399 	page_base = vm_pageout_page_count;
400 	ib = 1;
401 	is = 1;
402 
403 	/*
404 	 * Scan object for clusterable pages.
405 	 *
406 	 * We can cluster ONLY if: ->> the page is NOT
407 	 * clean, wired, busy, held, or mapped into a
408 	 * buffer, and one of the following:
409 	 * 1) The page is inactive, or a seldom used
410 	 *    active page.
411 	 * -or-
412 	 * 2) we force the issue.
413 	 *
414 	 * During heavy mmap/modification loads the pageout
415 	 * daemon can really fragment the underlying file
416 	 * due to flushing pages out of order and not trying
417 	 * align the clusters (which leave sporatic out-of-order
418 	 * holes).  To solve this problem we do the reverse scan
419 	 * first and attempt to align our cluster, then do a
420 	 * forward scan if room remains.
421 	 */
422 more:
423 	while (ib && pageout_count < vm_pageout_page_count) {
424 		vm_page_t p;
425 
426 		if (ib > pindex) {
427 			ib = 0;
428 			break;
429 		}
430 
431 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
432 			ib = 0;
433 			break;
434 		}
435 		vm_page_test_dirty(p);
436 		if (p->dirty == 0) {
437 			ib = 0;
438 			break;
439 		}
440 		vm_page_lock(p);
441 		if (p->queue != PQ_INACTIVE ||
442 		    p->hold_count != 0) {	/* may be undergoing I/O */
443 			vm_page_unlock(p);
444 			ib = 0;
445 			break;
446 		}
447 		vm_page_unlock(p);
448 		mc[--page_base] = pb = p;
449 		++pageout_count;
450 		++ib;
451 		/*
452 		 * alignment boundry, stop here and switch directions.  Do
453 		 * not clear ib.
454 		 */
455 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
456 			break;
457 	}
458 
459 	while (pageout_count < vm_pageout_page_count &&
460 	    pindex + is < object->size) {
461 		vm_page_t p;
462 
463 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
464 			break;
465 		vm_page_test_dirty(p);
466 		if (p->dirty == 0)
467 			break;
468 		vm_page_lock(p);
469 		if (p->queue != PQ_INACTIVE ||
470 		    p->hold_count != 0) {	/* may be undergoing I/O */
471 			vm_page_unlock(p);
472 			break;
473 		}
474 		vm_page_unlock(p);
475 		mc[page_base + pageout_count] = ps = p;
476 		++pageout_count;
477 		++is;
478 	}
479 
480 	/*
481 	 * If we exhausted our forward scan, continue with the reverse scan
482 	 * when possible, even past a page boundry.  This catches boundry
483 	 * conditions.
484 	 */
485 	if (ib && pageout_count < vm_pageout_page_count)
486 		goto more;
487 
488 	/*
489 	 * we allow reads during pageouts...
490 	 */
491 	return (vm_pageout_flush(&mc[page_base], pageout_count, 0, 0, NULL,
492 	    NULL));
493 }
494 
495 /*
496  * vm_pageout_flush() - launder the given pages
497  *
498  *	The given pages are laundered.  Note that we setup for the start of
499  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
500  *	reference count all in here rather then in the parent.  If we want
501  *	the parent to do more sophisticated things we may have to change
502  *	the ordering.
503  *
504  *	Returned runlen is the count of pages between mreq and first
505  *	page after mreq with status VM_PAGER_AGAIN.
506  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
507  *	for any page in runlen set.
508  */
509 int
510 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
511     boolean_t *eio)
512 {
513 	vm_object_t object = mc[0]->object;
514 	int pageout_status[count];
515 	int numpagedout = 0;
516 	int i, runlen;
517 
518 	VM_OBJECT_ASSERT_WLOCKED(object);
519 
520 	/*
521 	 * Initiate I/O.  Bump the vm_page_t->busy counter and
522 	 * mark the pages read-only.
523 	 *
524 	 * We do not have to fixup the clean/dirty bits here... we can
525 	 * allow the pager to do it after the I/O completes.
526 	 *
527 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
528 	 * edge case with file fragments.
529 	 */
530 	for (i = 0; i < count; i++) {
531 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
532 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
533 			mc[i], i, count));
534 		vm_page_sbusy(mc[i]);
535 		pmap_remove_write(mc[i]);
536 	}
537 	vm_object_pip_add(object, count);
538 
539 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
540 
541 	runlen = count - mreq;
542 	if (eio != NULL)
543 		*eio = FALSE;
544 	for (i = 0; i < count; i++) {
545 		vm_page_t mt = mc[i];
546 
547 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
548 		    !pmap_page_is_write_mapped(mt),
549 		    ("vm_pageout_flush: page %p is not write protected", mt));
550 		switch (pageout_status[i]) {
551 		case VM_PAGER_OK:
552 		case VM_PAGER_PEND:
553 			numpagedout++;
554 			break;
555 		case VM_PAGER_BAD:
556 			/*
557 			 * Page outside of range of object. Right now we
558 			 * essentially lose the changes by pretending it
559 			 * worked.
560 			 */
561 			vm_page_undirty(mt);
562 			break;
563 		case VM_PAGER_ERROR:
564 		case VM_PAGER_FAIL:
565 			/*
566 			 * If page couldn't be paged out, then reactivate the
567 			 * page so it doesn't clog the inactive list.  (We
568 			 * will try paging out it again later).
569 			 */
570 			vm_page_lock(mt);
571 			vm_page_activate(mt);
572 			vm_page_unlock(mt);
573 			if (eio != NULL && i >= mreq && i - mreq < runlen)
574 				*eio = TRUE;
575 			break;
576 		case VM_PAGER_AGAIN:
577 			if (i >= mreq && i - mreq < runlen)
578 				runlen = i - mreq;
579 			break;
580 		}
581 
582 		/*
583 		 * If the operation is still going, leave the page busy to
584 		 * block all other accesses. Also, leave the paging in
585 		 * progress indicator set so that we don't attempt an object
586 		 * collapse.
587 		 */
588 		if (pageout_status[i] != VM_PAGER_PEND) {
589 			vm_object_pip_wakeup(object);
590 			vm_page_sunbusy(mt);
591 		}
592 	}
593 	if (prunlen != NULL)
594 		*prunlen = runlen;
595 	return (numpagedout);
596 }
597 
598 static boolean_t
599 vm_pageout_launder(struct vm_pagequeue *pq, int tries, vm_paddr_t low,
600     vm_paddr_t high)
601 {
602 	struct mount *mp;
603 	struct vnode *vp;
604 	vm_object_t object;
605 	vm_paddr_t pa;
606 	vm_page_t m, m_tmp, next;
607 	int lockmode;
608 
609 	vm_pagequeue_lock(pq);
610 	TAILQ_FOREACH_SAFE(m, &pq->pq_pl, plinks.q, next) {
611 		if ((m->flags & PG_MARKER) != 0)
612 			continue;
613 		pa = VM_PAGE_TO_PHYS(m);
614 		if (pa < low || pa + PAGE_SIZE > high)
615 			continue;
616 		if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
617 			vm_page_unlock(m);
618 			continue;
619 		}
620 		object = m->object;
621 		if ((!VM_OBJECT_TRYWLOCK(object) &&
622 		    (!vm_pageout_fallback_object_lock(m, &next) ||
623 		    m->hold_count != 0)) || vm_page_busied(m)) {
624 			vm_page_unlock(m);
625 			VM_OBJECT_WUNLOCK(object);
626 			continue;
627 		}
628 		vm_page_test_dirty(m);
629 		if (m->dirty == 0 && object->ref_count != 0)
630 			pmap_remove_all(m);
631 		if (m->dirty != 0) {
632 			vm_page_unlock(m);
633 			if (tries == 0 || (object->flags & OBJ_DEAD) != 0) {
634 				VM_OBJECT_WUNLOCK(object);
635 				continue;
636 			}
637 			if (object->type == OBJT_VNODE) {
638 				vm_pagequeue_unlock(pq);
639 				vp = object->handle;
640 				vm_object_reference_locked(object);
641 				VM_OBJECT_WUNLOCK(object);
642 				(void)vn_start_write(vp, &mp, V_WAIT);
643 				lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
644 				    LK_SHARED : LK_EXCLUSIVE;
645 				vn_lock(vp, lockmode | LK_RETRY);
646 				VM_OBJECT_WLOCK(object);
647 				vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
648 				VM_OBJECT_WUNLOCK(object);
649 				VOP_UNLOCK(vp, 0);
650 				vm_object_deallocate(object);
651 				vn_finished_write(mp);
652 				return (TRUE);
653 			} else if (object->type == OBJT_SWAP ||
654 			    object->type == OBJT_DEFAULT) {
655 				vm_pagequeue_unlock(pq);
656 				m_tmp = m;
657 				vm_pageout_flush(&m_tmp, 1, VM_PAGER_PUT_SYNC,
658 				    0, NULL, NULL);
659 				VM_OBJECT_WUNLOCK(object);
660 				return (TRUE);
661 			}
662 		} else {
663 			/*
664 			 * Dequeue here to prevent lock recursion in
665 			 * vm_page_cache().
666 			 */
667 			vm_page_dequeue_locked(m);
668 			vm_page_cache(m);
669 			vm_page_unlock(m);
670 		}
671 		VM_OBJECT_WUNLOCK(object);
672 	}
673 	vm_pagequeue_unlock(pq);
674 	return (FALSE);
675 }
676 
677 /*
678  * Increase the number of cached pages.  The specified value, "tries",
679  * determines which categories of pages are cached:
680  *
681  *  0: All clean, inactive pages within the specified physical address range
682  *     are cached.  Will not sleep.
683  *  1: The vm_lowmem handlers are called.  All inactive pages within
684  *     the specified physical address range are cached.  May sleep.
685  *  2: The vm_lowmem handlers are called.  All inactive and active pages
686  *     within the specified physical address range are cached.  May sleep.
687  */
688 void
689 vm_pageout_grow_cache(int tries, vm_paddr_t low, vm_paddr_t high)
690 {
691 	int actl, actmax, inactl, inactmax, dom, initial_dom;
692 	static int start_dom = 0;
693 
694 	if (tries > 0) {
695 		/*
696 		 * Decrease registered cache sizes.  The vm_lowmem handlers
697 		 * may acquire locks and/or sleep, so they can only be invoked
698 		 * when "tries" is greater than zero.
699 		 */
700 		SDT_PROBE0(vm, , , vm__lowmem_cache);
701 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
702 
703 		/*
704 		 * We do this explicitly after the caches have been drained
705 		 * above.
706 		 */
707 		uma_reclaim();
708 	}
709 
710 	/*
711 	 * Make the next scan start on the next domain.
712 	 */
713 	initial_dom = atomic_fetchadd_int(&start_dom, 1) % vm_ndomains;
714 
715 	inactl = 0;
716 	inactmax = vm_cnt.v_inactive_count;
717 	actl = 0;
718 	actmax = tries < 2 ? 0 : vm_cnt.v_active_count;
719 	dom = initial_dom;
720 
721 	/*
722 	 * Scan domains in round-robin order, first inactive queues,
723 	 * then active.  Since domain usually owns large physically
724 	 * contiguous chunk of memory, it makes sense to completely
725 	 * exhaust one domain before switching to next, while growing
726 	 * the pool of contiguous physical pages.
727 	 *
728 	 * Do not even start launder a domain which cannot contain
729 	 * the specified address range, as indicated by segments
730 	 * constituting the domain.
731 	 */
732 again:
733 	if (inactl < inactmax) {
734 		if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
735 		    low, high) &&
736 		    vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_INACTIVE],
737 		    tries, low, high)) {
738 			inactl++;
739 			goto again;
740 		}
741 		if (++dom == vm_ndomains)
742 			dom = 0;
743 		if (dom != initial_dom)
744 			goto again;
745 	}
746 	if (actl < actmax) {
747 		if (vm_phys_domain_intersects(vm_dom[dom].vmd_segs,
748 		    low, high) &&
749 		    vm_pageout_launder(&vm_dom[dom].vmd_pagequeues[PQ_ACTIVE],
750 		      tries, low, high)) {
751 			actl++;
752 			goto again;
753 		}
754 		if (++dom == vm_ndomains)
755 			dom = 0;
756 		if (dom != initial_dom)
757 			goto again;
758 	}
759 }
760 
761 #if !defined(NO_SWAPPING)
762 /*
763  *	vm_pageout_object_deactivate_pages
764  *
765  *	Deactivate enough pages to satisfy the inactive target
766  *	requirements.
767  *
768  *	The object and map must be locked.
769  */
770 static void
771 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
772     long desired)
773 {
774 	vm_object_t backing_object, object;
775 	vm_page_t p;
776 	int act_delta, remove_mode;
777 
778 	VM_OBJECT_ASSERT_LOCKED(first_object);
779 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
780 		return;
781 	for (object = first_object;; object = backing_object) {
782 		if (pmap_resident_count(pmap) <= desired)
783 			goto unlock_return;
784 		VM_OBJECT_ASSERT_LOCKED(object);
785 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
786 		    object->paging_in_progress != 0)
787 			goto unlock_return;
788 
789 		remove_mode = 0;
790 		if (object->shadow_count > 1)
791 			remove_mode = 1;
792 		/*
793 		 * Scan the object's entire memory queue.
794 		 */
795 		TAILQ_FOREACH(p, &object->memq, listq) {
796 			if (pmap_resident_count(pmap) <= desired)
797 				goto unlock_return;
798 			if (vm_page_busied(p))
799 				continue;
800 			PCPU_INC(cnt.v_pdpages);
801 			vm_page_lock(p);
802 			if (p->wire_count != 0 || p->hold_count != 0 ||
803 			    !pmap_page_exists_quick(pmap, p)) {
804 				vm_page_unlock(p);
805 				continue;
806 			}
807 			act_delta = pmap_ts_referenced(p);
808 			if ((p->aflags & PGA_REFERENCED) != 0) {
809 				if (act_delta == 0)
810 					act_delta = 1;
811 				vm_page_aflag_clear(p, PGA_REFERENCED);
812 			}
813 			if (p->queue != PQ_ACTIVE && act_delta != 0) {
814 				vm_page_activate(p);
815 				p->act_count += act_delta;
816 			} else if (p->queue == PQ_ACTIVE) {
817 				if (act_delta == 0) {
818 					p->act_count -= min(p->act_count,
819 					    ACT_DECLINE);
820 					if (!remove_mode && p->act_count == 0) {
821 						pmap_remove_all(p);
822 						vm_page_deactivate(p);
823 					} else
824 						vm_page_requeue(p);
825 				} else {
826 					vm_page_activate(p);
827 					if (p->act_count < ACT_MAX -
828 					    ACT_ADVANCE)
829 						p->act_count += ACT_ADVANCE;
830 					vm_page_requeue(p);
831 				}
832 			} else if (p->queue == PQ_INACTIVE)
833 				pmap_remove_all(p);
834 			vm_page_unlock(p);
835 		}
836 		if ((backing_object = object->backing_object) == NULL)
837 			goto unlock_return;
838 		VM_OBJECT_RLOCK(backing_object);
839 		if (object != first_object)
840 			VM_OBJECT_RUNLOCK(object);
841 	}
842 unlock_return:
843 	if (object != first_object)
844 		VM_OBJECT_RUNLOCK(object);
845 }
846 
847 /*
848  * deactivate some number of pages in a map, try to do it fairly, but
849  * that is really hard to do.
850  */
851 static void
852 vm_pageout_map_deactivate_pages(map, desired)
853 	vm_map_t map;
854 	long desired;
855 {
856 	vm_map_entry_t tmpe;
857 	vm_object_t obj, bigobj;
858 	int nothingwired;
859 
860 	if (!vm_map_trylock(map))
861 		return;
862 
863 	bigobj = NULL;
864 	nothingwired = TRUE;
865 
866 	/*
867 	 * first, search out the biggest object, and try to free pages from
868 	 * that.
869 	 */
870 	tmpe = map->header.next;
871 	while (tmpe != &map->header) {
872 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
873 			obj = tmpe->object.vm_object;
874 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
875 				if (obj->shadow_count <= 1 &&
876 				    (bigobj == NULL ||
877 				     bigobj->resident_page_count < obj->resident_page_count)) {
878 					if (bigobj != NULL)
879 						VM_OBJECT_RUNLOCK(bigobj);
880 					bigobj = obj;
881 				} else
882 					VM_OBJECT_RUNLOCK(obj);
883 			}
884 		}
885 		if (tmpe->wired_count > 0)
886 			nothingwired = FALSE;
887 		tmpe = tmpe->next;
888 	}
889 
890 	if (bigobj != NULL) {
891 		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
892 		VM_OBJECT_RUNLOCK(bigobj);
893 	}
894 	/*
895 	 * Next, hunt around for other pages to deactivate.  We actually
896 	 * do this search sort of wrong -- .text first is not the best idea.
897 	 */
898 	tmpe = map->header.next;
899 	while (tmpe != &map->header) {
900 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
901 			break;
902 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
903 			obj = tmpe->object.vm_object;
904 			if (obj != NULL) {
905 				VM_OBJECT_RLOCK(obj);
906 				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
907 				VM_OBJECT_RUNLOCK(obj);
908 			}
909 		}
910 		tmpe = tmpe->next;
911 	}
912 
913 	/*
914 	 * Remove all mappings if a process is swapped out, this will free page
915 	 * table pages.
916 	 */
917 	if (desired == 0 && nothingwired) {
918 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
919 		    vm_map_max(map));
920 	}
921 
922 	vm_map_unlock(map);
923 }
924 #endif		/* !defined(NO_SWAPPING) */
925 
926 /*
927  * Attempt to acquire all of the necessary locks to launder a page and
928  * then call through the clustering layer to PUTPAGES.  Wait a short
929  * time for a vnode lock.
930  *
931  * Requires the page and object lock on entry, releases both before return.
932  * Returns 0 on success and an errno otherwise.
933  */
934 static int
935 vm_pageout_clean(vm_page_t m)
936 {
937 	struct vnode *vp;
938 	struct mount *mp;
939 	vm_object_t object;
940 	vm_pindex_t pindex;
941 	int error, lockmode;
942 
943 	vm_page_assert_locked(m);
944 	object = m->object;
945 	VM_OBJECT_ASSERT_WLOCKED(object);
946 	error = 0;
947 	vp = NULL;
948 	mp = NULL;
949 
950 	/*
951 	 * The object is already known NOT to be dead.   It
952 	 * is possible for the vget() to block the whole
953 	 * pageout daemon, but the new low-memory handling
954 	 * code should prevent it.
955 	 *
956 	 * We can't wait forever for the vnode lock, we might
957 	 * deadlock due to a vn_read() getting stuck in
958 	 * vm_wait while holding this vnode.  We skip the
959 	 * vnode if we can't get it in a reasonable amount
960 	 * of time.
961 	 */
962 	if (object->type == OBJT_VNODE) {
963 		vm_page_unlock(m);
964 		vp = object->handle;
965 		if (vp->v_type == VREG &&
966 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
967 			mp = NULL;
968 			error = EDEADLK;
969 			goto unlock_all;
970 		}
971 		KASSERT(mp != NULL,
972 		    ("vp %p with NULL v_mount", vp));
973 		vm_object_reference_locked(object);
974 		pindex = m->pindex;
975 		VM_OBJECT_WUNLOCK(object);
976 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
977 		    LK_SHARED : LK_EXCLUSIVE;
978 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
979 			vp = NULL;
980 			error = EDEADLK;
981 			goto unlock_mp;
982 		}
983 		VM_OBJECT_WLOCK(object);
984 		vm_page_lock(m);
985 		/*
986 		 * While the object and page were unlocked, the page
987 		 * may have been:
988 		 * (1) moved to a different queue,
989 		 * (2) reallocated to a different object,
990 		 * (3) reallocated to a different offset, or
991 		 * (4) cleaned.
992 		 */
993 		if (m->queue != PQ_INACTIVE || m->object != object ||
994 		    m->pindex != pindex || m->dirty == 0) {
995 			vm_page_unlock(m);
996 			error = ENXIO;
997 			goto unlock_all;
998 		}
999 
1000 		/*
1001 		 * The page may have been busied or held while the object
1002 		 * and page locks were released.
1003 		 */
1004 		if (vm_page_busied(m) || m->hold_count != 0) {
1005 			vm_page_unlock(m);
1006 			error = EBUSY;
1007 			goto unlock_all;
1008 		}
1009 	}
1010 
1011 	/*
1012 	 * If a page is dirty, then it is either being washed
1013 	 * (but not yet cleaned) or it is still in the
1014 	 * laundry.  If it is still in the laundry, then we
1015 	 * start the cleaning operation.
1016 	 */
1017 	if (vm_pageout_cluster(m) == 0)
1018 		error = EIO;
1019 
1020 unlock_all:
1021 	VM_OBJECT_WUNLOCK(object);
1022 
1023 unlock_mp:
1024 	vm_page_lock_assert(m, MA_NOTOWNED);
1025 	if (mp != NULL) {
1026 		if (vp != NULL)
1027 			vput(vp);
1028 		vm_object_deallocate(object);
1029 		vn_finished_write(mp);
1030 	}
1031 
1032 	return (error);
1033 }
1034 
1035 /*
1036  *	vm_pageout_scan does the dirty work for the pageout daemon.
1037  *
1038  *	pass 0 - Update active LRU/deactivate pages
1039  *	pass 1 - Move inactive to cache or free
1040  *	pass 2 - Launder dirty pages
1041  */
1042 static void
1043 vm_pageout_scan(struct vm_domain *vmd, int pass)
1044 {
1045 	vm_page_t m, next;
1046 	struct vm_pagequeue *pq;
1047 	vm_object_t object;
1048 	long min_scan;
1049 	int act_delta, addl_page_shortage, deficit, error, maxlaunder, maxscan;
1050 	int page_shortage, scan_tick, scanned, starting_page_shortage;
1051 	int vnodes_skipped;
1052 	boolean_t pageout_ok, queues_locked;
1053 
1054 	/*
1055 	 * If we need to reclaim memory ask kernel caches to return
1056 	 * some.  We rate limit to avoid thrashing.
1057 	 */
1058 	if (vmd == &vm_dom[0] && pass > 0 &&
1059 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
1060 		/*
1061 		 * Decrease registered cache sizes.
1062 		 */
1063 		SDT_PROBE0(vm, , , vm__lowmem_scan);
1064 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
1065 		/*
1066 		 * We do this explicitly after the caches have been
1067 		 * drained above.
1068 		 */
1069 		uma_reclaim();
1070 		lowmem_uptime = time_uptime;
1071 	}
1072 
1073 	/*
1074 	 * The addl_page_shortage is the number of temporarily
1075 	 * stuck pages in the inactive queue.  In other words, the
1076 	 * number of pages from the inactive count that should be
1077 	 * discounted in setting the target for the active queue scan.
1078 	 */
1079 	addl_page_shortage = 0;
1080 
1081 	/*
1082 	 * Calculate the number of pages we want to either free or move
1083 	 * to the cache.
1084 	 */
1085 	if (pass > 0) {
1086 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
1087 		page_shortage = vm_paging_target() + deficit;
1088 	} else
1089 		page_shortage = deficit = 0;
1090 	starting_page_shortage = page_shortage;
1091 
1092 	/*
1093 	 * maxlaunder limits the number of dirty pages we flush per scan.
1094 	 * For most systems a smaller value (16 or 32) is more robust under
1095 	 * extreme memory and disk pressure because any unnecessary writes
1096 	 * to disk can result in extreme performance degredation.  However,
1097 	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
1098 	 * used) will die horribly with limited laundering.  If the pageout
1099 	 * daemon cannot clean enough pages in the first pass, we let it go
1100 	 * all out in succeeding passes.
1101 	 */
1102 	if ((maxlaunder = vm_max_launder) <= 1)
1103 		maxlaunder = 1;
1104 	if (pass > 1)
1105 		maxlaunder = 10000;
1106 
1107 	vnodes_skipped = 0;
1108 
1109 	/*
1110 	 * Start scanning the inactive queue for pages we can move to the
1111 	 * cache or free.  The scan will stop when the target is reached or
1112 	 * we have scanned the entire inactive queue.  Note that m->act_count
1113 	 * is not used to form decisions for the inactive queue, only for the
1114 	 * active queue.
1115 	 */
1116 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1117 	maxscan = pq->pq_cnt;
1118 	vm_pagequeue_lock(pq);
1119 	queues_locked = TRUE;
1120 	for (m = TAILQ_FIRST(&pq->pq_pl);
1121 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
1122 	     m = next) {
1123 		vm_pagequeue_assert_locked(pq);
1124 		KASSERT(queues_locked, ("unlocked queues"));
1125 		KASSERT(m->queue == PQ_INACTIVE, ("Inactive queue %p", m));
1126 
1127 		PCPU_INC(cnt.v_pdpages);
1128 		next = TAILQ_NEXT(m, plinks.q);
1129 
1130 		/*
1131 		 * skip marker pages
1132 		 */
1133 		if (m->flags & PG_MARKER)
1134 			continue;
1135 
1136 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
1137 		    ("Fictitious page %p cannot be in inactive queue", m));
1138 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1139 		    ("Unmanaged page %p cannot be in inactive queue", m));
1140 
1141 		/*
1142 		 * The page or object lock acquisitions fail if the
1143 		 * page was removed from the queue or moved to a
1144 		 * different position within the queue.  In either
1145 		 * case, addl_page_shortage should not be incremented.
1146 		 */
1147 		if (!vm_pageout_page_lock(m, &next))
1148 			goto unlock_page;
1149 		else if (m->hold_count != 0) {
1150 			/*
1151 			 * Held pages are essentially stuck in the
1152 			 * queue.  So, they ought to be discounted
1153 			 * from the inactive count.  See the
1154 			 * calculation of the page_shortage for the
1155 			 * loop over the active queue below.
1156 			 */
1157 			addl_page_shortage++;
1158 			goto unlock_page;
1159 		}
1160 		object = m->object;
1161 		if (!VM_OBJECT_TRYWLOCK(object)) {
1162 			if (!vm_pageout_fallback_object_lock(m, &next))
1163 				goto unlock_object;
1164 			else if (m->hold_count != 0) {
1165 				addl_page_shortage++;
1166 				goto unlock_object;
1167 			}
1168 		}
1169 		if (vm_page_busied(m)) {
1170 			/*
1171 			 * Don't mess with busy pages.  Leave them at
1172 			 * the front of the queue.  Most likely, they
1173 			 * are being paged out and will leave the
1174 			 * queue shortly after the scan finishes.  So,
1175 			 * they ought to be discounted from the
1176 			 * inactive count.
1177 			 */
1178 			addl_page_shortage++;
1179 unlock_object:
1180 			VM_OBJECT_WUNLOCK(object);
1181 unlock_page:
1182 			vm_page_unlock(m);
1183 			continue;
1184 		}
1185 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1186 
1187 		/*
1188 		 * We unlock the inactive page queue, invalidating the
1189 		 * 'next' pointer.  Use our marker to remember our
1190 		 * place.
1191 		 */
1192 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1193 		vm_pagequeue_unlock(pq);
1194 		queues_locked = FALSE;
1195 
1196 		/*
1197 		 * Invalid pages can be easily freed. They cannot be
1198 		 * mapped, vm_page_free() asserts this.
1199 		 */
1200 		if (m->valid == 0)
1201 			goto free_page;
1202 
1203 		/*
1204 		 * If the page has been referenced and the object is not dead,
1205 		 * reactivate or requeue the page depending on whether the
1206 		 * object is mapped.
1207 		 */
1208 		if ((m->aflags & PGA_REFERENCED) != 0) {
1209 			vm_page_aflag_clear(m, PGA_REFERENCED);
1210 			act_delta = 1;
1211 		} else
1212 			act_delta = 0;
1213 		if (object->ref_count != 0) {
1214 			act_delta += pmap_ts_referenced(m);
1215 		} else {
1216 			KASSERT(!pmap_page_is_mapped(m),
1217 			    ("vm_pageout_scan: page %p is mapped", m));
1218 		}
1219 		if (act_delta != 0) {
1220 			if (object->ref_count != 0) {
1221 				vm_page_activate(m);
1222 
1223 				/*
1224 				 * Increase the activation count if the page
1225 				 * was referenced while in the inactive queue.
1226 				 * This makes it less likely that the page will
1227 				 * be returned prematurely to the inactive
1228 				 * queue.
1229  				 */
1230 				m->act_count += act_delta + ACT_ADVANCE;
1231 				goto drop_page;
1232 			} else if ((object->flags & OBJ_DEAD) == 0)
1233 				goto requeue_page;
1234 		}
1235 
1236 		/*
1237 		 * If the page appears to be clean at the machine-independent
1238 		 * layer, then remove all of its mappings from the pmap in
1239 		 * anticipation of placing it onto the cache queue.  If,
1240 		 * however, any of the page's mappings allow write access,
1241 		 * then the page may still be modified until the last of those
1242 		 * mappings are removed.
1243 		 */
1244 		if (object->ref_count != 0) {
1245 			vm_page_test_dirty(m);
1246 			if (m->dirty == 0)
1247 				pmap_remove_all(m);
1248 		}
1249 
1250 		if (m->dirty == 0) {
1251 			/*
1252 			 * Clean pages can be freed.
1253 			 */
1254 free_page:
1255 			vm_page_free(m);
1256 			PCPU_INC(cnt.v_dfree);
1257 			--page_shortage;
1258 		} else if ((object->flags & OBJ_DEAD) != 0) {
1259 			/*
1260 			 * Leave dirty pages from dead objects at the front of
1261 			 * the queue.  They are being paged out and freed by
1262 			 * the thread that destroyed the object.  They will
1263 			 * leave the queue shortly after the scan finishes, so
1264 			 * they should be discounted from the inactive count.
1265 			 */
1266 			addl_page_shortage++;
1267 		} else if ((m->flags & PG_WINATCFLS) == 0 && pass < 2) {
1268 			/*
1269 			 * Dirty pages need to be paged out, but flushing
1270 			 * a page is extremely expensive versus freeing
1271 			 * a clean page.  Rather then artificially limiting
1272 			 * the number of pages we can flush, we instead give
1273 			 * dirty pages extra priority on the inactive queue
1274 			 * by forcing them to be cycled through the queue
1275 			 * twice before being flushed, after which the
1276 			 * (now clean) page will cycle through once more
1277 			 * before being freed.  This significantly extends
1278 			 * the thrash point for a heavily loaded machine.
1279 			 */
1280 			m->flags |= PG_WINATCFLS;
1281 requeue_page:
1282 			vm_pagequeue_lock(pq);
1283 			queues_locked = TRUE;
1284 			vm_page_requeue_locked(m);
1285 		} else if (maxlaunder > 0) {
1286 			/*
1287 			 * We always want to try to flush some dirty pages if
1288 			 * we encounter them, to keep the system stable.
1289 			 * Normally this number is small, but under extreme
1290 			 * pressure where there are insufficient clean pages
1291 			 * on the inactive queue, we may have to go all out.
1292 			 */
1293 
1294 			if (object->type != OBJT_SWAP &&
1295 			    object->type != OBJT_DEFAULT)
1296 				pageout_ok = TRUE;
1297 			else if (disable_swap_pageouts)
1298 				pageout_ok = FALSE;
1299 			else if (defer_swap_pageouts)
1300 				pageout_ok = vm_page_count_min();
1301 			else
1302 				pageout_ok = TRUE;
1303 			if (!pageout_ok)
1304 				goto requeue_page;
1305 			error = vm_pageout_clean(m);
1306 			/*
1307 			 * Decrement page_shortage on success to account for
1308 			 * the (future) cleaned page.  Otherwise we could wind
1309 			 * up laundering or cleaning too many pages.
1310 			 */
1311 			if (error == 0) {
1312 				page_shortage--;
1313 				maxlaunder--;
1314 			} else if (error == EDEADLK) {
1315 				pageout_lock_miss++;
1316 				vnodes_skipped++;
1317 			} else if (error == EBUSY) {
1318 				addl_page_shortage++;
1319 			}
1320 			vm_page_lock_assert(m, MA_NOTOWNED);
1321 			goto relock_queues;
1322 		}
1323 drop_page:
1324 		vm_page_unlock(m);
1325 		VM_OBJECT_WUNLOCK(object);
1326 relock_queues:
1327 		if (!queues_locked) {
1328 			vm_pagequeue_lock(pq);
1329 			queues_locked = TRUE;
1330 		}
1331 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1332 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1333 	}
1334 	vm_pagequeue_unlock(pq);
1335 
1336 #if !defined(NO_SWAPPING)
1337 	/*
1338 	 * Wakeup the swapout daemon if we didn't cache or free the targeted
1339 	 * number of pages.
1340 	 */
1341 	if (vm_swap_enabled && page_shortage > 0)
1342 		vm_req_vmdaemon(VM_SWAP_NORMAL);
1343 #endif
1344 
1345 	/*
1346 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1347 	 * and we didn't cache or free enough pages.
1348 	 */
1349 	if (vnodes_skipped > 0 && page_shortage > vm_cnt.v_free_target -
1350 	    vm_cnt.v_free_min)
1351 		(void)speedup_syncer();
1352 
1353 	/*
1354 	 * If the inactive queue scan fails repeatedly to meet its
1355 	 * target, kill the largest process.
1356 	 */
1357 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1358 
1359 	/*
1360 	 * Compute the number of pages we want to try to move from the
1361 	 * active queue to the inactive queue.
1362 	 */
1363 	page_shortage = vm_cnt.v_inactive_target - vm_cnt.v_inactive_count +
1364 	    vm_paging_target() + deficit + addl_page_shortage;
1365 
1366 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1367 	vm_pagequeue_lock(pq);
1368 	maxscan = pq->pq_cnt;
1369 
1370 	/*
1371 	 * If we're just idle polling attempt to visit every
1372 	 * active page within 'update_period' seconds.
1373 	 */
1374 	scan_tick = ticks;
1375 	if (vm_pageout_update_period != 0) {
1376 		min_scan = pq->pq_cnt;
1377 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
1378 		min_scan /= hz * vm_pageout_update_period;
1379 	} else
1380 		min_scan = 0;
1381 	if (min_scan > 0 || (page_shortage > 0 && maxscan > 0))
1382 		vmd->vmd_last_active_scan = scan_tick;
1383 
1384 	/*
1385 	 * Scan the active queue for pages that can be deactivated.  Update
1386 	 * the per-page activity counter and use it to identify deactivation
1387 	 * candidates.
1388 	 */
1389 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1390 	    min_scan || (page_shortage > 0 && scanned < maxscan)); m = next,
1391 	    scanned++) {
1392 
1393 		KASSERT(m->queue == PQ_ACTIVE,
1394 		    ("vm_pageout_scan: page %p isn't active", m));
1395 
1396 		next = TAILQ_NEXT(m, plinks.q);
1397 		if ((m->flags & PG_MARKER) != 0)
1398 			continue;
1399 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
1400 		    ("Fictitious page %p cannot be in active queue", m));
1401 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1402 		    ("Unmanaged page %p cannot be in active queue", m));
1403 		if (!vm_pageout_page_lock(m, &next)) {
1404 			vm_page_unlock(m);
1405 			continue;
1406 		}
1407 
1408 		/*
1409 		 * The count for pagedaemon pages is done after checking the
1410 		 * page for eligibility...
1411 		 */
1412 		PCPU_INC(cnt.v_pdpages);
1413 
1414 		/*
1415 		 * Check to see "how much" the page has been used.
1416 		 */
1417 		if ((m->aflags & PGA_REFERENCED) != 0) {
1418 			vm_page_aflag_clear(m, PGA_REFERENCED);
1419 			act_delta = 1;
1420 		} else
1421 			act_delta = 0;
1422 
1423 		/*
1424 		 * Unlocked object ref count check.  Two races are possible.
1425 		 * 1) The ref was transitioning to zero and we saw non-zero,
1426 		 *    the pmap bits will be checked unnecessarily.
1427 		 * 2) The ref was transitioning to one and we saw zero.
1428 		 *    The page lock prevents a new reference to this page so
1429 		 *    we need not check the reference bits.
1430 		 */
1431 		if (m->object->ref_count != 0)
1432 			act_delta += pmap_ts_referenced(m);
1433 
1434 		/*
1435 		 * Advance or decay the act_count based on recent usage.
1436 		 */
1437 		if (act_delta != 0) {
1438 			m->act_count += ACT_ADVANCE + act_delta;
1439 			if (m->act_count > ACT_MAX)
1440 				m->act_count = ACT_MAX;
1441 		} else
1442 			m->act_count -= min(m->act_count, ACT_DECLINE);
1443 
1444 		/*
1445 		 * Move this page to the tail of the active or inactive
1446 		 * queue depending on usage.
1447 		 */
1448 		if (m->act_count == 0) {
1449 			/* Dequeue to avoid later lock recursion. */
1450 			vm_page_dequeue_locked(m);
1451 			vm_page_deactivate(m);
1452 			page_shortage--;
1453 		} else
1454 			vm_page_requeue_locked(m);
1455 		vm_page_unlock(m);
1456 	}
1457 	vm_pagequeue_unlock(pq);
1458 #if !defined(NO_SWAPPING)
1459 	/*
1460 	 * Idle process swapout -- run once per second.
1461 	 */
1462 	if (vm_swap_idle_enabled) {
1463 		static long lsec;
1464 		if (time_second != lsec) {
1465 			vm_req_vmdaemon(VM_SWAP_IDLE);
1466 			lsec = time_second;
1467 		}
1468 	}
1469 #endif
1470 }
1471 
1472 static int vm_pageout_oom_vote;
1473 
1474 /*
1475  * The pagedaemon threads randlomly select one to perform the
1476  * OOM.  Trying to kill processes before all pagedaemons
1477  * failed to reach free target is premature.
1478  */
1479 static void
1480 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1481     int starting_page_shortage)
1482 {
1483 	int old_vote;
1484 
1485 	if (starting_page_shortage <= 0 || starting_page_shortage !=
1486 	    page_shortage)
1487 		vmd->vmd_oom_seq = 0;
1488 	else
1489 		vmd->vmd_oom_seq++;
1490 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1491 		if (vmd->vmd_oom) {
1492 			vmd->vmd_oom = FALSE;
1493 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1494 		}
1495 		return;
1496 	}
1497 
1498 	/*
1499 	 * Do not follow the call sequence until OOM condition is
1500 	 * cleared.
1501 	 */
1502 	vmd->vmd_oom_seq = 0;
1503 
1504 	if (vmd->vmd_oom)
1505 		return;
1506 
1507 	vmd->vmd_oom = TRUE;
1508 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1509 	if (old_vote != vm_ndomains - 1)
1510 		return;
1511 
1512 	/*
1513 	 * The current pagedaemon thread is the last in the quorum to
1514 	 * start OOM.  Initiate the selection and signaling of the
1515 	 * victim.
1516 	 */
1517 	vm_pageout_oom(VM_OOM_MEM);
1518 
1519 	/*
1520 	 * After one round of OOM terror, recall our vote.  On the
1521 	 * next pass, current pagedaemon would vote again if the low
1522 	 * memory condition is still there, due to vmd_oom being
1523 	 * false.
1524 	 */
1525 	vmd->vmd_oom = FALSE;
1526 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1527 }
1528 
1529 /*
1530  * The OOM killer is the page daemon's action of last resort when
1531  * memory allocation requests have been stalled for a prolonged period
1532  * of time because it cannot reclaim memory.  This function computes
1533  * the approximate number of physical pages that could be reclaimed if
1534  * the specified address space is destroyed.
1535  *
1536  * Private, anonymous memory owned by the address space is the
1537  * principal resource that we expect to recover after an OOM kill.
1538  * Since the physical pages mapped by the address space's COW entries
1539  * are typically shared pages, they are unlikely to be released and so
1540  * they are not counted.
1541  *
1542  * To get to the point where the page daemon runs the OOM killer, its
1543  * efforts to write-back vnode-backed pages may have stalled.  This
1544  * could be caused by a memory allocation deadlock in the write path
1545  * that might be resolved by an OOM kill.  Therefore, physical pages
1546  * belonging to vnode-backed objects are counted, because they might
1547  * be freed without being written out first if the address space holds
1548  * the last reference to an unlinked vnode.
1549  *
1550  * Similarly, physical pages belonging to OBJT_PHYS objects are
1551  * counted because the address space might hold the last reference to
1552  * the object.
1553  */
1554 static long
1555 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1556 {
1557 	vm_map_t map;
1558 	vm_map_entry_t entry;
1559 	vm_object_t obj;
1560 	long res;
1561 
1562 	map = &vmspace->vm_map;
1563 	KASSERT(!map->system_map, ("system map"));
1564 	sx_assert(&map->lock, SA_LOCKED);
1565 	res = 0;
1566 	for (entry = map->header.next; entry != &map->header;
1567 	    entry = entry->next) {
1568 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1569 			continue;
1570 		obj = entry->object.vm_object;
1571 		if (obj == NULL)
1572 			continue;
1573 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1574 		    obj->ref_count != 1)
1575 			continue;
1576 		switch (obj->type) {
1577 		case OBJT_DEFAULT:
1578 		case OBJT_SWAP:
1579 		case OBJT_PHYS:
1580 		case OBJT_VNODE:
1581 			res += obj->resident_page_count;
1582 			break;
1583 		}
1584 	}
1585 	return (res);
1586 }
1587 
1588 void
1589 vm_pageout_oom(int shortage)
1590 {
1591 	struct proc *p, *bigproc;
1592 	vm_offset_t size, bigsize;
1593 	struct thread *td;
1594 	struct vmspace *vm;
1595 
1596 	/*
1597 	 * We keep the process bigproc locked once we find it to keep anyone
1598 	 * from messing with it; however, there is a possibility of
1599 	 * deadlock if process B is bigproc and one of it's child processes
1600 	 * attempts to propagate a signal to B while we are waiting for A's
1601 	 * lock while walking this list.  To avoid this, we don't block on
1602 	 * the process lock but just skip a process if it is already locked.
1603 	 */
1604 	bigproc = NULL;
1605 	bigsize = 0;
1606 	sx_slock(&allproc_lock);
1607 	FOREACH_PROC_IN_SYSTEM(p) {
1608 		int breakout;
1609 
1610 		PROC_LOCK(p);
1611 
1612 		/*
1613 		 * If this is a system, protected or killed process, skip it.
1614 		 */
1615 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1616 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1617 		    p->p_pid == 1 || P_KILLED(p) ||
1618 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
1619 			PROC_UNLOCK(p);
1620 			continue;
1621 		}
1622 		/*
1623 		 * If the process is in a non-running type state,
1624 		 * don't touch it.  Check all the threads individually.
1625 		 */
1626 		breakout = 0;
1627 		FOREACH_THREAD_IN_PROC(p, td) {
1628 			thread_lock(td);
1629 			if (!TD_ON_RUNQ(td) &&
1630 			    !TD_IS_RUNNING(td) &&
1631 			    !TD_IS_SLEEPING(td) &&
1632 			    !TD_IS_SUSPENDED(td) &&
1633 			    !TD_IS_SWAPPED(td)) {
1634 				thread_unlock(td);
1635 				breakout = 1;
1636 				break;
1637 			}
1638 			thread_unlock(td);
1639 		}
1640 		if (breakout) {
1641 			PROC_UNLOCK(p);
1642 			continue;
1643 		}
1644 		/*
1645 		 * get the process size
1646 		 */
1647 		vm = vmspace_acquire_ref(p);
1648 		if (vm == NULL) {
1649 			PROC_UNLOCK(p);
1650 			continue;
1651 		}
1652 		_PHOLD(p);
1653 		if (!vm_map_trylock_read(&vm->vm_map)) {
1654 			_PRELE(p);
1655 			PROC_UNLOCK(p);
1656 			vmspace_free(vm);
1657 			continue;
1658 		}
1659 		PROC_UNLOCK(p);
1660 		size = vmspace_swap_count(vm);
1661 		if (shortage == VM_OOM_MEM)
1662 			size += vm_pageout_oom_pagecount(vm);
1663 		vm_map_unlock_read(&vm->vm_map);
1664 		vmspace_free(vm);
1665 
1666 		/*
1667 		 * If this process is bigger than the biggest one,
1668 		 * remember it.
1669 		 */
1670 		if (size > bigsize) {
1671 			if (bigproc != NULL)
1672 				PRELE(bigproc);
1673 			bigproc = p;
1674 			bigsize = size;
1675 		} else {
1676 			PRELE(p);
1677 		}
1678 	}
1679 	sx_sunlock(&allproc_lock);
1680 	if (bigproc != NULL) {
1681 		if (vm_panic_on_oom != 0)
1682 			panic("out of swap space");
1683 		PROC_LOCK(bigproc);
1684 		killproc(bigproc, "out of swap space");
1685 		sched_nice(bigproc, PRIO_MIN);
1686 		_PRELE(bigproc);
1687 		PROC_UNLOCK(bigproc);
1688 		wakeup(&vm_cnt.v_free_count);
1689 	}
1690 }
1691 
1692 static void
1693 vm_pageout_worker(void *arg)
1694 {
1695 	struct vm_domain *domain;
1696 	int domidx;
1697 
1698 	domidx = (uintptr_t)arg;
1699 	domain = &vm_dom[domidx];
1700 
1701 	/*
1702 	 * XXXKIB It could be useful to bind pageout daemon threads to
1703 	 * the cores belonging to the domain, from which vm_page_array
1704 	 * is allocated.
1705 	 */
1706 
1707 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1708 	domain->vmd_last_active_scan = ticks;
1709 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1710 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
1711 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
1712 	    &domain->vmd_inacthead, plinks.q);
1713 
1714 	/*
1715 	 * The pageout daemon worker is never done, so loop forever.
1716 	 */
1717 	while (TRUE) {
1718 		/*
1719 		 * If we have enough free memory, wakeup waiters.  Do
1720 		 * not clear vm_pages_needed until we reach our target,
1721 		 * otherwise we may be woken up over and over again and
1722 		 * waste a lot of cpu.
1723 		 */
1724 		mtx_lock(&vm_page_queue_free_mtx);
1725 		if (vm_pages_needed && !vm_page_count_min()) {
1726 			if (!vm_paging_needed())
1727 				vm_pages_needed = 0;
1728 			wakeup(&vm_cnt.v_free_count);
1729 		}
1730 		if (vm_pages_needed) {
1731 			/*
1732 			 * We're still not done.  Either vm_pages_needed was
1733 			 * set by another thread during the previous scan
1734 			 * (typically, this happens during a level 0 scan) or
1735 			 * vm_pages_needed was already set and the scan failed
1736 			 * to free enough pages.  If we haven't yet performed
1737 			 * a level >= 2 scan (unlimited dirty cleaning), then
1738 			 * upgrade the level and scan again now.  Otherwise,
1739 			 * sleep a bit and try again later.  While sleeping,
1740 			 * vm_pages_needed can be cleared.
1741 			 */
1742 			if (domain->vmd_pass > 1)
1743 				msleep(&vm_pages_needed,
1744 				    &vm_page_queue_free_mtx, PVM, "psleep",
1745 				    hz / 2);
1746 		} else {
1747 			/*
1748 			 * Good enough, sleep until required to refresh
1749 			 * stats.
1750 			 */
1751 			msleep(&vm_pages_needed, &vm_page_queue_free_mtx,
1752 			    PVM, "psleep", hz);
1753 		}
1754 		if (vm_pages_needed) {
1755 			vm_cnt.v_pdwakeups++;
1756 			domain->vmd_pass++;
1757 		} else
1758 			domain->vmd_pass = 0;
1759 		mtx_unlock(&vm_page_queue_free_mtx);
1760 		vm_pageout_scan(domain, domain->vmd_pass);
1761 	}
1762 }
1763 
1764 /*
1765  *	vm_pageout_init initialises basic pageout daemon settings.
1766  */
1767 static void
1768 vm_pageout_init(void)
1769 {
1770 	/*
1771 	 * Initialize some paging parameters.
1772 	 */
1773 	vm_cnt.v_interrupt_free_min = 2;
1774 	if (vm_cnt.v_page_count < 2000)
1775 		vm_pageout_page_count = 8;
1776 
1777 	/*
1778 	 * v_free_reserved needs to include enough for the largest
1779 	 * swap pager structures plus enough for any pv_entry structs
1780 	 * when paging.
1781 	 */
1782 	if (vm_cnt.v_page_count > 1024)
1783 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
1784 	else
1785 		vm_cnt.v_free_min = 4;
1786 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1787 	    vm_cnt.v_interrupt_free_min;
1788 	vm_cnt.v_free_reserved = vm_pageout_page_count +
1789 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
1790 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
1791 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
1792 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
1793 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
1794 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
1795 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
1796 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
1797 
1798 	/*
1799 	 * Set the default wakeup threshold to be 10% above the minimum
1800 	 * page limit.  This keeps the steady state out of shortfall.
1801 	 */
1802 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
1803 
1804 	/*
1805 	 * Set interval in seconds for active scan.  We want to visit each
1806 	 * page at least once every ten minutes.  This is to prevent worst
1807 	 * case paging behaviors with stale active LRU.
1808 	 */
1809 	if (vm_pageout_update_period == 0)
1810 		vm_pageout_update_period = 600;
1811 
1812 	/* XXX does not really belong here */
1813 	if (vm_page_max_wired == 0)
1814 		vm_page_max_wired = vm_cnt.v_free_count / 3;
1815 }
1816 
1817 /*
1818  *     vm_pageout is the high level pageout daemon.
1819  */
1820 static void
1821 vm_pageout(void)
1822 {
1823 	int error;
1824 #if MAXMEMDOM > 1
1825 	int i;
1826 #endif
1827 
1828 	swap_pager_swap_init();
1829 #if MAXMEMDOM > 1
1830 	for (i = 1; i < vm_ndomains; i++) {
1831 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
1832 		    curproc, NULL, 0, 0, "dom%d", i);
1833 		if (error != 0) {
1834 			panic("starting pageout for domain %d, error %d\n",
1835 			    i, error);
1836 		}
1837 	}
1838 #endif
1839 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
1840 	    0, 0, "uma");
1841 	if (error != 0)
1842 		panic("starting uma_reclaim helper, error %d\n", error);
1843 	vm_pageout_worker((void *)(uintptr_t)0);
1844 }
1845 
1846 /*
1847  * Unless the free page queue lock is held by the caller, this function
1848  * should be regarded as advisory.  Specifically, the caller should
1849  * not msleep() on &vm_cnt.v_free_count following this function unless
1850  * the free page queue lock is held until the msleep() is performed.
1851  */
1852 void
1853 pagedaemon_wakeup(void)
1854 {
1855 
1856 	if (!vm_pages_needed && curthread->td_proc != pageproc) {
1857 		vm_pages_needed = 1;
1858 		wakeup(&vm_pages_needed);
1859 	}
1860 }
1861 
1862 #if !defined(NO_SWAPPING)
1863 static void
1864 vm_req_vmdaemon(int req)
1865 {
1866 	static int lastrun = 0;
1867 
1868 	mtx_lock(&vm_daemon_mtx);
1869 	vm_pageout_req_swapout |= req;
1870 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1871 		wakeup(&vm_daemon_needed);
1872 		lastrun = ticks;
1873 	}
1874 	mtx_unlock(&vm_daemon_mtx);
1875 }
1876 
1877 static void
1878 vm_daemon(void)
1879 {
1880 	struct rlimit rsslim;
1881 	struct proc *p;
1882 	struct thread *td;
1883 	struct vmspace *vm;
1884 	int breakout, swapout_flags, tryagain, attempts;
1885 #ifdef RACCT
1886 	uint64_t rsize, ravailable;
1887 #endif
1888 
1889 	while (TRUE) {
1890 		mtx_lock(&vm_daemon_mtx);
1891 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
1892 #ifdef RACCT
1893 		    racct_enable ? hz : 0
1894 #else
1895 		    0
1896 #endif
1897 		);
1898 		swapout_flags = vm_pageout_req_swapout;
1899 		vm_pageout_req_swapout = 0;
1900 		mtx_unlock(&vm_daemon_mtx);
1901 		if (swapout_flags)
1902 			swapout_procs(swapout_flags);
1903 
1904 		/*
1905 		 * scan the processes for exceeding their rlimits or if
1906 		 * process is swapped out -- deactivate pages
1907 		 */
1908 		tryagain = 0;
1909 		attempts = 0;
1910 again:
1911 		attempts++;
1912 		sx_slock(&allproc_lock);
1913 		FOREACH_PROC_IN_SYSTEM(p) {
1914 			vm_pindex_t limit, size;
1915 
1916 			/*
1917 			 * if this is a system process or if we have already
1918 			 * looked at this process, skip it.
1919 			 */
1920 			PROC_LOCK(p);
1921 			if (p->p_state != PRS_NORMAL ||
1922 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1923 				PROC_UNLOCK(p);
1924 				continue;
1925 			}
1926 			/*
1927 			 * if the process is in a non-running type state,
1928 			 * don't touch it.
1929 			 */
1930 			breakout = 0;
1931 			FOREACH_THREAD_IN_PROC(p, td) {
1932 				thread_lock(td);
1933 				if (!TD_ON_RUNQ(td) &&
1934 				    !TD_IS_RUNNING(td) &&
1935 				    !TD_IS_SLEEPING(td) &&
1936 				    !TD_IS_SUSPENDED(td)) {
1937 					thread_unlock(td);
1938 					breakout = 1;
1939 					break;
1940 				}
1941 				thread_unlock(td);
1942 			}
1943 			if (breakout) {
1944 				PROC_UNLOCK(p);
1945 				continue;
1946 			}
1947 			/*
1948 			 * get a limit
1949 			 */
1950 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
1951 			limit = OFF_TO_IDX(
1952 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
1953 
1954 			/*
1955 			 * let processes that are swapped out really be
1956 			 * swapped out set the limit to nothing (will force a
1957 			 * swap-out.)
1958 			 */
1959 			if ((p->p_flag & P_INMEM) == 0)
1960 				limit = 0;	/* XXX */
1961 			vm = vmspace_acquire_ref(p);
1962 			PROC_UNLOCK(p);
1963 			if (vm == NULL)
1964 				continue;
1965 
1966 			size = vmspace_resident_count(vm);
1967 			if (size >= limit) {
1968 				vm_pageout_map_deactivate_pages(
1969 				    &vm->vm_map, limit);
1970 			}
1971 #ifdef RACCT
1972 			if (racct_enable) {
1973 				rsize = IDX_TO_OFF(size);
1974 				PROC_LOCK(p);
1975 				racct_set(p, RACCT_RSS, rsize);
1976 				ravailable = racct_get_available(p, RACCT_RSS);
1977 				PROC_UNLOCK(p);
1978 				if (rsize > ravailable) {
1979 					/*
1980 					 * Don't be overly aggressive; this
1981 					 * might be an innocent process,
1982 					 * and the limit could've been exceeded
1983 					 * by some memory hog.  Don't try
1984 					 * to deactivate more than 1/4th
1985 					 * of process' resident set size.
1986 					 */
1987 					if (attempts <= 8) {
1988 						if (ravailable < rsize -
1989 						    (rsize / 4)) {
1990 							ravailable = rsize -
1991 							    (rsize / 4);
1992 						}
1993 					}
1994 					vm_pageout_map_deactivate_pages(
1995 					    &vm->vm_map,
1996 					    OFF_TO_IDX(ravailable));
1997 					/* Update RSS usage after paging out. */
1998 					size = vmspace_resident_count(vm);
1999 					rsize = IDX_TO_OFF(size);
2000 					PROC_LOCK(p);
2001 					racct_set(p, RACCT_RSS, rsize);
2002 					PROC_UNLOCK(p);
2003 					if (rsize > ravailable)
2004 						tryagain = 1;
2005 				}
2006 			}
2007 #endif
2008 			vmspace_free(vm);
2009 		}
2010 		sx_sunlock(&allproc_lock);
2011 		if (tryagain != 0 && attempts <= 10)
2012 			goto again;
2013 	}
2014 }
2015 #endif			/* !defined(NO_SWAPPING) */
2016