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