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