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