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