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