xref: /freebsd/sys/vm/vm_pageout.c (revision 7f9dff23d3092aa33ad45b2b63e52469b3c13a6e)
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 
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, int *numpagedout);
123 static int vm_pageout_cluster(vm_page_t m);
124 static bool vm_pageout_scan(struct vm_domain *vmd, int pass);
125 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
126     int starting_page_shortage);
127 
128 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init,
129     NULL);
130 
131 struct proc *pageproc;
132 
133 static struct kproc_desc page_kp = {
134 	"pagedaemon",
135 	vm_pageout,
136 	&pageproc
137 };
138 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start,
139     &page_kp);
140 
141 SDT_PROVIDER_DEFINE(vm);
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 /* Pagedaemon activity rates, in subdivisions of one second. */
158 #define	VM_LAUNDER_RATE		10
159 #define	VM_INACT_SCAN_RATE	2
160 
161 int vm_pageout_deficit;		/* Estimated number of pages deficit */
162 u_int vm_pageout_wakeup_thresh;
163 static int vm_pageout_oom_seq = 12;
164 bool vm_pageout_wanted;		/* Event on which pageout daemon sleeps */
165 bool vm_pages_needed;		/* Are threads waiting for free pages? */
166 
167 /* Pending request for dirty page laundering. */
168 static enum {
169 	VM_LAUNDRY_IDLE,
170 	VM_LAUNDRY_BACKGROUND,
171 	VM_LAUNDRY_SHORTFALL
172 } vm_laundry_request = VM_LAUNDRY_IDLE;
173 
174 #if !defined(NO_SWAPPING)
175 static int vm_pageout_req_swapout;	/* XXX */
176 static int vm_daemon_needed;
177 static struct mtx vm_daemon_mtx;
178 /* Allow for use by vm_pageout before vm_daemon is initialized. */
179 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
180 #endif
181 static int vm_pageout_update_period;
182 static int disable_swap_pageouts;
183 static int lowmem_period = 10;
184 static time_t lowmem_uptime;
185 
186 #if defined(NO_SWAPPING)
187 static int vm_swap_enabled = 0;
188 static int vm_swap_idle_enabled = 0;
189 #else
190 static int vm_swap_enabled = 1;
191 static int vm_swap_idle_enabled = 0;
192 #endif
193 
194 static int vm_panic_on_oom = 0;
195 
196 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom,
197 	CTLFLAG_RWTUN, &vm_panic_on_oom, 0,
198 	"panic on out of memory instead of killing the largest process");
199 
200 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh,
201 	CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0,
202 	"free page threshold for waking up the pageout daemon");
203 
204 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period,
205 	CTLFLAG_RW, &vm_pageout_update_period, 0,
206 	"Maximum active LRU update period");
207 
208 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0,
209 	"Low memory callback period");
210 
211 #if defined(NO_SWAPPING)
212 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
213 	CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout");
214 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
215 	CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
216 #else
217 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
218 	CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
219 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
220 	CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
221 #endif
222 
223 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
224 	CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
225 
226 static int pageout_lock_miss;
227 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
228 	CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
229 
230 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq,
231 	CTLFLAG_RW, &vm_pageout_oom_seq, 0,
232 	"back-to-back calls to oom detector to start OOM");
233 
234 static int act_scan_laundry_weight = 3;
235 SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RW,
236     &act_scan_laundry_weight, 0,
237     "weight given to clean vs. dirty pages in active queue scans");
238 
239 static u_int vm_background_launder_target;
240 SYSCTL_UINT(_vm, OID_AUTO, background_launder_target, CTLFLAG_RW,
241     &vm_background_launder_target, 0,
242     "background laundering target, in pages");
243 
244 static u_int vm_background_launder_rate = 4096;
245 SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RW,
246     &vm_background_launder_rate, 0,
247     "background laundering rate, in kilobytes per second");
248 
249 static u_int vm_background_launder_max = 20 * 1024;
250 SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RW,
251     &vm_background_launder_max, 0, "background laundering cap, in kilobytes");
252 
253 #define VM_PAGEOUT_PAGE_COUNT 16
254 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
255 
256 int vm_page_max_wired;		/* XXX max # of wired pages system-wide */
257 SYSCTL_INT(_vm, OID_AUTO, max_wired,
258 	CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count");
259 
260 static u_int isqrt(u_int num);
261 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *);
262 static int vm_pageout_launder(struct vm_domain *vmd, int launder,
263     bool in_shortfall);
264 static void vm_pageout_laundry_worker(void *arg);
265 #if !defined(NO_SWAPPING)
266 static void vm_pageout_map_deactivate_pages(vm_map_t, long);
267 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long);
268 static void vm_req_vmdaemon(int req);
269 #endif
270 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *);
271 
272 /*
273  * Initialize a dummy page for marking the caller's place in the specified
274  * paging queue.  In principle, this function only needs to set the flag
275  * PG_MARKER.  Nonetheless, it write busies and initializes the hold count
276  * to one as safety precautions.
277  */
278 static void
279 vm_pageout_init_marker(vm_page_t marker, u_short queue)
280 {
281 
282 	bzero(marker, sizeof(*marker));
283 	marker->flags = PG_MARKER;
284 	marker->busy_lock = VPB_SINGLE_EXCLUSIVER;
285 	marker->queue = queue;
286 	marker->hold_count = 1;
287 }
288 
289 /*
290  * vm_pageout_fallback_object_lock:
291  *
292  * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is
293  * known to have failed and page queue must be either PQ_ACTIVE or
294  * PQ_INACTIVE.  To avoid lock order violation, unlock the page queue
295  * while locking the vm object.  Use marker page to detect page queue
296  * changes and maintain notion of next page on page queue.  Return
297  * TRUE if no changes were detected, FALSE otherwise.  vm object is
298  * locked on return.
299  *
300  * This function depends on both the lock portion of struct vm_object
301  * and normal struct vm_page being type stable.
302  */
303 static boolean_t
304 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next)
305 {
306 	struct vm_page marker;
307 	struct vm_pagequeue *pq;
308 	boolean_t unchanged;
309 	u_short queue;
310 	vm_object_t object;
311 
312 	queue = m->queue;
313 	vm_pageout_init_marker(&marker, queue);
314 	pq = vm_page_pagequeue(m);
315 	object = m->object;
316 
317 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
318 	vm_pagequeue_unlock(pq);
319 	vm_page_unlock(m);
320 	VM_OBJECT_WLOCK(object);
321 	vm_page_lock(m);
322 	vm_pagequeue_lock(pq);
323 
324 	/*
325 	 * The page's object might have changed, and/or the page might
326 	 * have moved from its original position in the queue.  If the
327 	 * page's object has changed, then the caller should abandon
328 	 * processing the page because the wrong object lock was
329 	 * acquired.  Use the marker's plinks.q, not the page's, to
330 	 * determine if the page has been moved.  The state of the
331 	 * page's plinks.q can be indeterminate; whereas, the marker's
332 	 * plinks.q must be valid.
333 	 */
334 	*next = TAILQ_NEXT(&marker, plinks.q);
335 	unchanged = m->object == object &&
336 	    m == TAILQ_PREV(&marker, pglist, plinks.q);
337 	KASSERT(!unchanged || m->queue == queue,
338 	    ("page %p queue %d %d", m, queue, m->queue));
339 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
340 	return (unchanged);
341 }
342 
343 /*
344  * Lock the page while holding the page queue lock.  Use marker page
345  * to detect page queue changes and maintain notion of next page on
346  * page queue.  Return TRUE if no changes were detected, FALSE
347  * otherwise.  The page is locked on return. The page queue lock might
348  * be dropped and reacquired.
349  *
350  * This function depends on normal struct vm_page being type stable.
351  */
352 static boolean_t
353 vm_pageout_page_lock(vm_page_t m, vm_page_t *next)
354 {
355 	struct vm_page marker;
356 	struct vm_pagequeue *pq;
357 	boolean_t unchanged;
358 	u_short queue;
359 
360 	vm_page_lock_assert(m, MA_NOTOWNED);
361 	if (vm_page_trylock(m))
362 		return (TRUE);
363 
364 	queue = m->queue;
365 	vm_pageout_init_marker(&marker, queue);
366 	pq = vm_page_pagequeue(m);
367 
368 	TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q);
369 	vm_pagequeue_unlock(pq);
370 	vm_page_lock(m);
371 	vm_pagequeue_lock(pq);
372 
373 	/* Page queue might have changed. */
374 	*next = TAILQ_NEXT(&marker, plinks.q);
375 	unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q);
376 	KASSERT(!unchanged || m->queue == queue,
377 	    ("page %p queue %d %d", m, queue, m->queue));
378 	TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q);
379 	return (unchanged);
380 }
381 
382 /*
383  * Scan for pages at adjacent offsets within the given page's object that are
384  * eligible for laundering, form a cluster of these pages and the given page,
385  * and launder that cluster.
386  */
387 static int
388 vm_pageout_cluster(vm_page_t m)
389 {
390 	vm_object_t object;
391 	vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps;
392 	vm_pindex_t pindex;
393 	int ib, is, page_base, pageout_count;
394 
395 	vm_page_assert_locked(m);
396 	object = m->object;
397 	VM_OBJECT_ASSERT_WLOCKED(object);
398 	pindex = m->pindex;
399 
400 	/*
401 	 * We can't clean the page if it is busy or held.
402 	 */
403 	vm_page_assert_unbusied(m);
404 	KASSERT(m->hold_count == 0, ("page %p is held", m));
405 	vm_page_unlock(m);
406 
407 	mc[vm_pageout_page_count] = pb = ps = m;
408 	pageout_count = 1;
409 	page_base = vm_pageout_page_count;
410 	ib = 1;
411 	is = 1;
412 
413 	/*
414 	 * We can cluster only if the page is not clean, busy, or held, and
415 	 * the page is in the laundry queue.
416 	 *
417 	 * During heavy mmap/modification loads the pageout
418 	 * daemon can really fragment the underlying file
419 	 * due to flushing pages out of order and not trying to
420 	 * align the clusters (which leaves sporadic out-of-order
421 	 * holes).  To solve this problem we do the reverse scan
422 	 * first and attempt to align our cluster, then do a
423 	 * forward scan if room remains.
424 	 */
425 more:
426 	while (ib != 0 && pageout_count < vm_pageout_page_count) {
427 		if (ib > pindex) {
428 			ib = 0;
429 			break;
430 		}
431 		if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) {
432 			ib = 0;
433 			break;
434 		}
435 		vm_page_test_dirty(p);
436 		if (p->dirty == 0) {
437 			ib = 0;
438 			break;
439 		}
440 		vm_page_lock(p);
441 		if (!vm_page_in_laundry(p) ||
442 		    p->hold_count != 0) {	/* may be undergoing I/O */
443 			vm_page_unlock(p);
444 			ib = 0;
445 			break;
446 		}
447 		vm_page_unlock(p);
448 		mc[--page_base] = pb = p;
449 		++pageout_count;
450 		++ib;
451 
452 		/*
453 		 * We are at an alignment boundary.  Stop here, and switch
454 		 * directions.  Do not clear ib.
455 		 */
456 		if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
457 			break;
458 	}
459 	while (pageout_count < vm_pageout_page_count &&
460 	    pindex + is < object->size) {
461 		if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p))
462 			break;
463 		vm_page_test_dirty(p);
464 		if (p->dirty == 0)
465 			break;
466 		vm_page_lock(p);
467 		if (!vm_page_in_laundry(p) ||
468 		    p->hold_count != 0) {	/* may be undergoing I/O */
469 			vm_page_unlock(p);
470 			break;
471 		}
472 		vm_page_unlock(p);
473 		mc[page_base + pageout_count] = ps = p;
474 		++pageout_count;
475 		++is;
476 	}
477 
478 	/*
479 	 * If we exhausted our forward scan, continue with the reverse scan
480 	 * when possible, even past an alignment boundary.  This catches
481 	 * boundary conditions.
482 	 */
483 	if (ib != 0 && pageout_count < vm_pageout_page_count)
484 		goto more;
485 
486 	return (vm_pageout_flush(&mc[page_base], pageout_count,
487 	    VM_PAGER_PUT_NOREUSE, 0, NULL, NULL));
488 }
489 
490 /*
491  * vm_pageout_flush() - launder the given pages
492  *
493  *	The given pages are laundered.  Note that we setup for the start of
494  *	I/O ( i.e. busy the page ), mark it read-only, and bump the object
495  *	reference count all in here rather then in the parent.  If we want
496  *	the parent to do more sophisticated things we may have to change
497  *	the ordering.
498  *
499  *	Returned runlen is the count of pages between mreq and first
500  *	page after mreq with status VM_PAGER_AGAIN.
501  *	*eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL
502  *	for any page in runlen set.
503  */
504 int
505 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen,
506     boolean_t *eio)
507 {
508 	vm_object_t object = mc[0]->object;
509 	int pageout_status[count];
510 	int numpagedout = 0;
511 	int i, runlen;
512 
513 	VM_OBJECT_ASSERT_WLOCKED(object);
514 
515 	/*
516 	 * Initiate I/O.  Bump the vm_page_t->busy counter and
517 	 * mark the pages read-only.
518 	 *
519 	 * We do not have to fixup the clean/dirty bits here... we can
520 	 * allow the pager to do it after the I/O completes.
521 	 *
522 	 * NOTE! mc[i]->dirty may be partial or fragmented due to an
523 	 * edge case with file fragments.
524 	 */
525 	for (i = 0; i < count; i++) {
526 		KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
527 		    ("vm_pageout_flush: partially invalid page %p index %d/%d",
528 			mc[i], i, count));
529 		vm_page_sbusy(mc[i]);
530 		pmap_remove_write(mc[i]);
531 	}
532 	vm_object_pip_add(object, count);
533 
534 	vm_pager_put_pages(object, mc, count, flags, pageout_status);
535 
536 	runlen = count - mreq;
537 	if (eio != NULL)
538 		*eio = FALSE;
539 	for (i = 0; i < count; i++) {
540 		vm_page_t mt = mc[i];
541 
542 		KASSERT(pageout_status[i] == VM_PAGER_PEND ||
543 		    !pmap_page_is_write_mapped(mt),
544 		    ("vm_pageout_flush: page %p is not write protected", mt));
545 		switch (pageout_status[i]) {
546 		case VM_PAGER_OK:
547 			vm_page_lock(mt);
548 			if (vm_page_in_laundry(mt))
549 				vm_page_deactivate_noreuse(mt);
550 			vm_page_unlock(mt);
551 			/* FALLTHROUGH */
552 		case VM_PAGER_PEND:
553 			numpagedout++;
554 			break;
555 		case VM_PAGER_BAD:
556 			/*
557 			 * The page is outside the object's range.  We pretend
558 			 * that the page out worked and clean the page, so the
559 			 * changes will be lost if the page is reclaimed by
560 			 * the page daemon.
561 			 */
562 			vm_page_undirty(mt);
563 			vm_page_lock(mt);
564 			if (vm_page_in_laundry(mt))
565 				vm_page_deactivate_noreuse(mt);
566 			vm_page_unlock(mt);
567 			break;
568 		case VM_PAGER_ERROR:
569 		case VM_PAGER_FAIL:
570 			/*
571 			 * If the page couldn't be paged out, then reactivate
572 			 * it so that it doesn't clog the laundry and inactive
573 			 * queues.  (We will try paging it out again later).
574 			 */
575 			vm_page_lock(mt);
576 			vm_page_activate(mt);
577 			vm_page_unlock(mt);
578 			if (eio != NULL && i >= mreq && i - mreq < runlen)
579 				*eio = TRUE;
580 			break;
581 		case VM_PAGER_AGAIN:
582 			if (i >= mreq && i - mreq < runlen)
583 				runlen = i - mreq;
584 			break;
585 		}
586 
587 		/*
588 		 * If the operation is still going, leave the page busy to
589 		 * block all other accesses. Also, leave the paging in
590 		 * progress indicator set so that we don't attempt an object
591 		 * collapse.
592 		 */
593 		if (pageout_status[i] != VM_PAGER_PEND) {
594 			vm_object_pip_wakeup(object);
595 			vm_page_sunbusy(mt);
596 		}
597 	}
598 	if (prunlen != NULL)
599 		*prunlen = runlen;
600 	return (numpagedout);
601 }
602 
603 #if !defined(NO_SWAPPING)
604 /*
605  *	vm_pageout_object_deactivate_pages
606  *
607  *	Deactivate enough pages to satisfy the inactive target
608  *	requirements.
609  *
610  *	The object and map must be locked.
611  */
612 static void
613 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
614     long desired)
615 {
616 	vm_object_t backing_object, object;
617 	vm_page_t p;
618 	int act_delta, remove_mode;
619 
620 	VM_OBJECT_ASSERT_LOCKED(first_object);
621 	if ((first_object->flags & OBJ_FICTITIOUS) != 0)
622 		return;
623 	for (object = first_object;; object = backing_object) {
624 		if (pmap_resident_count(pmap) <= desired)
625 			goto unlock_return;
626 		VM_OBJECT_ASSERT_LOCKED(object);
627 		if ((object->flags & OBJ_UNMANAGED) != 0 ||
628 		    object->paging_in_progress != 0)
629 			goto unlock_return;
630 
631 		remove_mode = 0;
632 		if (object->shadow_count > 1)
633 			remove_mode = 1;
634 		/*
635 		 * Scan the object's entire memory queue.
636 		 */
637 		TAILQ_FOREACH(p, &object->memq, listq) {
638 			if (pmap_resident_count(pmap) <= desired)
639 				goto unlock_return;
640 			if (vm_page_busied(p))
641 				continue;
642 			PCPU_INC(cnt.v_pdpages);
643 			vm_page_lock(p);
644 			if (p->wire_count != 0 || p->hold_count != 0 ||
645 			    !pmap_page_exists_quick(pmap, p)) {
646 				vm_page_unlock(p);
647 				continue;
648 			}
649 			act_delta = pmap_ts_referenced(p);
650 			if ((p->aflags & PGA_REFERENCED) != 0) {
651 				if (act_delta == 0)
652 					act_delta = 1;
653 				vm_page_aflag_clear(p, PGA_REFERENCED);
654 			}
655 			if (!vm_page_active(p) && act_delta != 0) {
656 				vm_page_activate(p);
657 				p->act_count += act_delta;
658 			} else if (vm_page_active(p)) {
659 				if (act_delta == 0) {
660 					p->act_count -= min(p->act_count,
661 					    ACT_DECLINE);
662 					if (!remove_mode && p->act_count == 0) {
663 						pmap_remove_all(p);
664 						vm_page_deactivate(p);
665 					} else
666 						vm_page_requeue(p);
667 				} else {
668 					vm_page_activate(p);
669 					if (p->act_count < ACT_MAX -
670 					    ACT_ADVANCE)
671 						p->act_count += ACT_ADVANCE;
672 					vm_page_requeue(p);
673 				}
674 			} else if (vm_page_inactive(p))
675 				pmap_remove_all(p);
676 			vm_page_unlock(p);
677 		}
678 		if ((backing_object = object->backing_object) == NULL)
679 			goto unlock_return;
680 		VM_OBJECT_RLOCK(backing_object);
681 		if (object != first_object)
682 			VM_OBJECT_RUNLOCK(object);
683 	}
684 unlock_return:
685 	if (object != first_object)
686 		VM_OBJECT_RUNLOCK(object);
687 }
688 
689 /*
690  * deactivate some number of pages in a map, try to do it fairly, but
691  * that is really hard to do.
692  */
693 static void
694 vm_pageout_map_deactivate_pages(map, desired)
695 	vm_map_t map;
696 	long desired;
697 {
698 	vm_map_entry_t tmpe;
699 	vm_object_t obj, bigobj;
700 	int nothingwired;
701 
702 	if (!vm_map_trylock(map))
703 		return;
704 
705 	bigobj = NULL;
706 	nothingwired = TRUE;
707 
708 	/*
709 	 * first, search out the biggest object, and try to free pages from
710 	 * that.
711 	 */
712 	tmpe = map->header.next;
713 	while (tmpe != &map->header) {
714 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
715 			obj = tmpe->object.vm_object;
716 			if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
717 				if (obj->shadow_count <= 1 &&
718 				    (bigobj == NULL ||
719 				     bigobj->resident_page_count < obj->resident_page_count)) {
720 					if (bigobj != NULL)
721 						VM_OBJECT_RUNLOCK(bigobj);
722 					bigobj = obj;
723 				} else
724 					VM_OBJECT_RUNLOCK(obj);
725 			}
726 		}
727 		if (tmpe->wired_count > 0)
728 			nothingwired = FALSE;
729 		tmpe = tmpe->next;
730 	}
731 
732 	if (bigobj != NULL) {
733 		vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired);
734 		VM_OBJECT_RUNLOCK(bigobj);
735 	}
736 	/*
737 	 * Next, hunt around for other pages to deactivate.  We actually
738 	 * do this search sort of wrong -- .text first is not the best idea.
739 	 */
740 	tmpe = map->header.next;
741 	while (tmpe != &map->header) {
742 		if (pmap_resident_count(vm_map_pmap(map)) <= desired)
743 			break;
744 		if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
745 			obj = tmpe->object.vm_object;
746 			if (obj != NULL) {
747 				VM_OBJECT_RLOCK(obj);
748 				vm_pageout_object_deactivate_pages(map->pmap, obj, desired);
749 				VM_OBJECT_RUNLOCK(obj);
750 			}
751 		}
752 		tmpe = tmpe->next;
753 	}
754 
755 	/*
756 	 * Remove all mappings if a process is swapped out, this will free page
757 	 * table pages.
758 	 */
759 	if (desired == 0 && nothingwired) {
760 		pmap_remove(vm_map_pmap(map), vm_map_min(map),
761 		    vm_map_max(map));
762 	}
763 
764 	vm_map_unlock(map);
765 }
766 #endif		/* !defined(NO_SWAPPING) */
767 
768 /*
769  * Attempt to acquire all of the necessary locks to launder a page and
770  * then call through the clustering layer to PUTPAGES.  Wait a short
771  * time for a vnode lock.
772  *
773  * Requires the page and object lock on entry, releases both before return.
774  * Returns 0 on success and an errno otherwise.
775  */
776 static int
777 vm_pageout_clean(vm_page_t m, int *numpagedout)
778 {
779 	struct vnode *vp;
780 	struct mount *mp;
781 	vm_object_t object;
782 	vm_pindex_t pindex;
783 	int error, lockmode;
784 
785 	vm_page_assert_locked(m);
786 	object = m->object;
787 	VM_OBJECT_ASSERT_WLOCKED(object);
788 	error = 0;
789 	vp = NULL;
790 	mp = NULL;
791 
792 	/*
793 	 * The object is already known NOT to be dead.   It
794 	 * is possible for the vget() to block the whole
795 	 * pageout daemon, but the new low-memory handling
796 	 * code should prevent it.
797 	 *
798 	 * We can't wait forever for the vnode lock, we might
799 	 * deadlock due to a vn_read() getting stuck in
800 	 * vm_wait while holding this vnode.  We skip the
801 	 * vnode if we can't get it in a reasonable amount
802 	 * of time.
803 	 */
804 	if (object->type == OBJT_VNODE) {
805 		vm_page_unlock(m);
806 		vp = object->handle;
807 		if (vp->v_type == VREG &&
808 		    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
809 			mp = NULL;
810 			error = EDEADLK;
811 			goto unlock_all;
812 		}
813 		KASSERT(mp != NULL,
814 		    ("vp %p with NULL v_mount", vp));
815 		vm_object_reference_locked(object);
816 		pindex = m->pindex;
817 		VM_OBJECT_WUNLOCK(object);
818 		lockmode = MNT_SHARED_WRITES(vp->v_mount) ?
819 		    LK_SHARED : LK_EXCLUSIVE;
820 		if (vget(vp, lockmode | LK_TIMELOCK, curthread)) {
821 			vp = NULL;
822 			error = EDEADLK;
823 			goto unlock_mp;
824 		}
825 		VM_OBJECT_WLOCK(object);
826 		vm_page_lock(m);
827 		/*
828 		 * While the object and page were unlocked, the page
829 		 * may have been:
830 		 * (1) moved to a different queue,
831 		 * (2) reallocated to a different object,
832 		 * (3) reallocated to a different offset, or
833 		 * (4) cleaned.
834 		 */
835 		if (!vm_page_in_laundry(m) || m->object != object ||
836 		    m->pindex != pindex || m->dirty == 0) {
837 			vm_page_unlock(m);
838 			error = ENXIO;
839 			goto unlock_all;
840 		}
841 
842 		/*
843 		 * The page may have been busied or held while the object
844 		 * and page locks were released.
845 		 */
846 		if (vm_page_busied(m) || m->hold_count != 0) {
847 			vm_page_unlock(m);
848 			error = EBUSY;
849 			goto unlock_all;
850 		}
851 	}
852 
853 	/*
854 	 * If a page is dirty, then it is either being washed
855 	 * (but not yet cleaned) or it is still in the
856 	 * laundry.  If it is still in the laundry, then we
857 	 * start the cleaning operation.
858 	 */
859 	if ((*numpagedout = vm_pageout_cluster(m)) == 0)
860 		error = EIO;
861 
862 unlock_all:
863 	VM_OBJECT_WUNLOCK(object);
864 
865 unlock_mp:
866 	vm_page_lock_assert(m, MA_NOTOWNED);
867 	if (mp != NULL) {
868 		if (vp != NULL)
869 			vput(vp);
870 		vm_object_deallocate(object);
871 		vn_finished_write(mp);
872 	}
873 
874 	return (error);
875 }
876 
877 /*
878  * Attempt to launder the specified number of pages.
879  *
880  * Returns the number of pages successfully laundered.
881  */
882 static int
883 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall)
884 {
885 	struct vm_pagequeue *pq;
886 	vm_object_t object;
887 	vm_page_t m, next;
888 	int act_delta, error, maxscan, numpagedout, starting_target;
889 	int vnodes_skipped;
890 	bool pageout_ok, queue_locked;
891 
892 	starting_target = launder;
893 	vnodes_skipped = 0;
894 
895 	/*
896 	 * Scan the laundry queue for pages eligible to be laundered.  We stop
897 	 * once the target number of dirty pages have been laundered, or once
898 	 * we've reached the end of the queue.  A single iteration of this loop
899 	 * may cause more than one page to be laundered because of clustering.
900 	 *
901 	 * maxscan ensures that we don't re-examine requeued pages.  Any
902 	 * additional pages written as part of a cluster are subtracted from
903 	 * maxscan since they must be taken from the laundry queue.
904 	 */
905 	pq = &vmd->vmd_pagequeues[PQ_LAUNDRY];
906 	maxscan = pq->pq_cnt;
907 
908 	vm_pagequeue_lock(pq);
909 	queue_locked = true;
910 	for (m = TAILQ_FIRST(&pq->pq_pl);
911 	    m != NULL && maxscan-- > 0 && launder > 0;
912 	    m = next) {
913 		vm_pagequeue_assert_locked(pq);
914 		KASSERT(queue_locked, ("unlocked laundry queue"));
915 		KASSERT(vm_page_in_laundry(m),
916 		    ("page %p has an inconsistent queue", m));
917 		next = TAILQ_NEXT(m, plinks.q);
918 		if ((m->flags & PG_MARKER) != 0)
919 			continue;
920 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
921 		    ("PG_FICTITIOUS page %p cannot be in laundry queue", m));
922 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
923 		    ("VPO_UNMANAGED page %p cannot be in laundry queue", m));
924 		if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) {
925 			vm_page_unlock(m);
926 			continue;
927 		}
928 		object = m->object;
929 		if ((!VM_OBJECT_TRYWLOCK(object) &&
930 		    (!vm_pageout_fallback_object_lock(m, &next) ||
931 		    m->hold_count != 0)) || vm_page_busied(m)) {
932 			VM_OBJECT_WUNLOCK(object);
933 			vm_page_unlock(m);
934 			continue;
935 		}
936 
937 		/*
938 		 * Unlock the laundry queue, invalidating the 'next' pointer.
939 		 * Use a marker to remember our place in the laundry queue.
940 		 */
941 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker,
942 		    plinks.q);
943 		vm_pagequeue_unlock(pq);
944 		queue_locked = false;
945 
946 		/*
947 		 * Invalid pages can be easily freed.  They cannot be
948 		 * mapped; vm_page_free() asserts this.
949 		 */
950 		if (m->valid == 0)
951 			goto free_page;
952 
953 		/*
954 		 * If the page has been referenced and the object is not dead,
955 		 * reactivate or requeue the page depending on whether the
956 		 * object is mapped.
957 		 */
958 		if ((m->aflags & PGA_REFERENCED) != 0) {
959 			vm_page_aflag_clear(m, PGA_REFERENCED);
960 			act_delta = 1;
961 		} else
962 			act_delta = 0;
963 		if (object->ref_count != 0)
964 			act_delta += pmap_ts_referenced(m);
965 		else {
966 			KASSERT(!pmap_page_is_mapped(m),
967 			    ("page %p is mapped", m));
968 		}
969 		if (act_delta != 0) {
970 			if (object->ref_count != 0) {
971 				PCPU_INC(cnt.v_reactivated);
972 				vm_page_activate(m);
973 
974 				/*
975 				 * Increase the activation count if the page
976 				 * was referenced while in the laundry queue.
977 				 * This makes it less likely that the page will
978 				 * be returned prematurely to the inactive
979 				 * queue.
980  				 */
981 				m->act_count += act_delta + ACT_ADVANCE;
982 
983 				/*
984 				 * If this was a background laundering, count
985 				 * activated pages towards our target.  The
986 				 * purpose of background laundering is to ensure
987 				 * that pages are eventually cycled through the
988 				 * laundry queue, and an activation is a valid
989 				 * way out.
990 				 */
991 				if (!in_shortfall)
992 					launder--;
993 				goto drop_page;
994 			} else if ((object->flags & OBJ_DEAD) == 0)
995 				goto requeue_page;
996 		}
997 
998 		/*
999 		 * If the page appears to be clean at the machine-independent
1000 		 * layer, then remove all of its mappings from the pmap in
1001 		 * anticipation of freeing it.  If, however, any of the page's
1002 		 * mappings allow write access, then the page may still be
1003 		 * modified until the last of those mappings are removed.
1004 		 */
1005 		if (object->ref_count != 0) {
1006 			vm_page_test_dirty(m);
1007 			if (m->dirty == 0)
1008 				pmap_remove_all(m);
1009 		}
1010 
1011 		/*
1012 		 * Clean pages are freed, and dirty pages are paged out unless
1013 		 * they belong to a dead object.  Requeueing dirty pages from
1014 		 * dead objects is pointless, as they are being paged out and
1015 		 * freed by the thread that destroyed the object.
1016 		 */
1017 		if (m->dirty == 0) {
1018 free_page:
1019 			vm_page_free(m);
1020 			PCPU_INC(cnt.v_dfree);
1021 		} else if ((object->flags & OBJ_DEAD) == 0) {
1022 			if (object->type != OBJT_SWAP &&
1023 			    object->type != OBJT_DEFAULT)
1024 				pageout_ok = true;
1025 			else if (disable_swap_pageouts)
1026 				pageout_ok = false;
1027 			else
1028 				pageout_ok = true;
1029 			if (!pageout_ok) {
1030 requeue_page:
1031 				vm_pagequeue_lock(pq);
1032 				queue_locked = true;
1033 				vm_page_requeue_locked(m);
1034 				goto drop_page;
1035 			}
1036 
1037 			/*
1038 			 * Form a cluster with adjacent, dirty pages from the
1039 			 * same object, and page out that entire cluster.
1040 			 *
1041 			 * The adjacent, dirty pages must also be in the
1042 			 * laundry.  However, their mappings are not checked
1043 			 * for new references.  Consequently, a recently
1044 			 * referenced page may be paged out.  However, that
1045 			 * page will not be prematurely reclaimed.  After page
1046 			 * out, the page will be placed in the inactive queue,
1047 			 * where any new references will be detected and the
1048 			 * page reactivated.
1049 			 */
1050 			error = vm_pageout_clean(m, &numpagedout);
1051 			if (error == 0) {
1052 				launder -= numpagedout;
1053 				maxscan -= numpagedout - 1;
1054 			} else if (error == EDEADLK) {
1055 				pageout_lock_miss++;
1056 				vnodes_skipped++;
1057 			}
1058 			goto relock_queue;
1059 		}
1060 drop_page:
1061 		vm_page_unlock(m);
1062 		VM_OBJECT_WUNLOCK(object);
1063 relock_queue:
1064 		if (!queue_locked) {
1065 			vm_pagequeue_lock(pq);
1066 			queue_locked = true;
1067 		}
1068 		next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q);
1069 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q);
1070 	}
1071 	vm_pagequeue_unlock(pq);
1072 
1073 	/*
1074 	 * Wakeup the sync daemon if we skipped a vnode in a writeable object
1075 	 * and we didn't launder enough pages.
1076 	 */
1077 	if (vnodes_skipped > 0 && launder > 0)
1078 		(void)speedup_syncer();
1079 
1080 	return (starting_target - launder);
1081 }
1082 
1083 /*
1084  * Compute the integer square root.
1085  */
1086 static u_int
1087 isqrt(u_int num)
1088 {
1089 	u_int bit, root, tmp;
1090 
1091 	bit = 1u << ((NBBY * sizeof(u_int)) - 2);
1092 	while (bit > num)
1093 		bit >>= 2;
1094 	root = 0;
1095 	while (bit != 0) {
1096 		tmp = root + bit;
1097 		root >>= 1;
1098 		if (num >= tmp) {
1099 			num -= tmp;
1100 			root += bit;
1101 		}
1102 		bit >>= 2;
1103 	}
1104 	return (root);
1105 }
1106 
1107 /*
1108  * Perform the work of the laundry thread: periodically wake up and determine
1109  * whether any pages need to be laundered.  If so, determine the number of pages
1110  * that need to be laundered, and launder them.
1111  */
1112 static void
1113 vm_pageout_laundry_worker(void *arg)
1114 {
1115 	struct vm_domain *domain;
1116 	struct vm_pagequeue *pq;
1117 	uint64_t nclean, ndirty;
1118 	u_int last_launder, wakeups;
1119 	int domidx, last_target, launder, shortfall, shortfall_cycle, target;
1120 	bool in_shortfall;
1121 
1122 	domidx = (uintptr_t)arg;
1123 	domain = &vm_dom[domidx];
1124 	pq = &domain->vmd_pagequeues[PQ_LAUNDRY];
1125 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1126 	vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY);
1127 
1128 	shortfall = 0;
1129 	in_shortfall = false;
1130 	shortfall_cycle = 0;
1131 	target = 0;
1132 	last_launder = 0;
1133 
1134 	/*
1135 	 * The pageout laundry worker is never done, so loop forever.
1136 	 */
1137 	for (;;) {
1138 		KASSERT(target >= 0, ("negative target %d", target));
1139 		KASSERT(shortfall_cycle >= 0,
1140 		    ("negative cycle %d", shortfall_cycle));
1141 		launder = 0;
1142 		wakeups = VM_METER_PCPU_CNT(v_pdwakeups);
1143 
1144 		/*
1145 		 * First determine whether we need to launder pages to meet a
1146 		 * shortage of free pages.
1147 		 */
1148 		if (shortfall > 0) {
1149 			in_shortfall = true;
1150 			shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE;
1151 			target = shortfall;
1152 		} else if (!in_shortfall)
1153 			goto trybackground;
1154 		else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) {
1155 			/*
1156 			 * We recently entered shortfall and began laundering
1157 			 * pages.  If we have completed that laundering run
1158 			 * (and we are no longer in shortfall) or we have met
1159 			 * our laundry target through other activity, then we
1160 			 * can stop laundering pages.
1161 			 */
1162 			in_shortfall = false;
1163 			target = 0;
1164 			goto trybackground;
1165 		}
1166 		last_launder = wakeups;
1167 		launder = target / shortfall_cycle--;
1168 		goto dolaundry;
1169 
1170 		/*
1171 		 * There's no immediate need to launder any pages; see if we
1172 		 * meet the conditions to perform background laundering:
1173 		 *
1174 		 * 1. The ratio of dirty to clean inactive pages exceeds the
1175 		 *    background laundering threshold and the pagedaemon has
1176 		 *    been woken up to reclaim pages since our last
1177 		 *    laundering, or
1178 		 * 2. we haven't yet reached the target of the current
1179 		 *    background laundering run.
1180 		 *
1181 		 * The background laundering threshold is not a constant.
1182 		 * Instead, it is a slowly growing function of the number of
1183 		 * page daemon wakeups since the last laundering.  Thus, as the
1184 		 * ratio of dirty to clean inactive pages grows, the amount of
1185 		 * memory pressure required to trigger laundering decreases.
1186 		 */
1187 trybackground:
1188 		nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count;
1189 		ndirty = vm_cnt.v_laundry_count;
1190 		if (target == 0 && wakeups != last_launder &&
1191 		    ndirty * isqrt(wakeups - last_launder) >= nclean) {
1192 			target = vm_background_launder_target;
1193 		}
1194 
1195 		/*
1196 		 * We have a non-zero background laundering target.  If we've
1197 		 * laundered up to our maximum without observing a page daemon
1198 		 * wakeup, just stop.  This is a safety belt that ensures we
1199 		 * don't launder an excessive amount if memory pressure is low
1200 		 * and the ratio of dirty to clean pages is large.  Otherwise,
1201 		 * proceed at the background laundering rate.
1202 		 */
1203 		if (target > 0) {
1204 			if (wakeups != last_launder) {
1205 				last_launder = wakeups;
1206 				last_target = target;
1207 			} else if (last_target - target >=
1208 			    vm_background_launder_max * PAGE_SIZE / 1024) {
1209 				target = 0;
1210 			}
1211 			launder = vm_background_launder_rate * PAGE_SIZE / 1024;
1212 			launder /= VM_LAUNDER_RATE;
1213 			if (launder > target)
1214 				launder = target;
1215 		}
1216 
1217 dolaundry:
1218 		if (launder > 0) {
1219 			/*
1220 			 * Because of I/O clustering, the number of laundered
1221 			 * pages could exceed "target" by the maximum size of
1222 			 * a cluster minus one.
1223 			 */
1224 			target -= min(vm_pageout_launder(domain, launder,
1225 			    in_shortfall), target);
1226 			pause("laundp", hz / VM_LAUNDER_RATE);
1227 		}
1228 
1229 		/*
1230 		 * If we're not currently laundering pages and the page daemon
1231 		 * hasn't posted a new request, sleep until the page daemon
1232 		 * kicks us.
1233 		 */
1234 		vm_pagequeue_lock(pq);
1235 		if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE)
1236 			(void)mtx_sleep(&vm_laundry_request,
1237 			    vm_pagequeue_lockptr(pq), PVM, "launds", 0);
1238 
1239 		/*
1240 		 * If the pagedaemon has indicated that it's in shortfall, start
1241 		 * a shortfall laundering unless we're already in the middle of
1242 		 * one.  This may preempt a background laundering.
1243 		 */
1244 		if (vm_laundry_request == VM_LAUNDRY_SHORTFALL &&
1245 		    (!in_shortfall || shortfall_cycle == 0)) {
1246 			shortfall = vm_laundry_target() + vm_pageout_deficit;
1247 			target = 0;
1248 		} else
1249 			shortfall = 0;
1250 
1251 		if (target == 0)
1252 			vm_laundry_request = VM_LAUNDRY_IDLE;
1253 		vm_pagequeue_unlock(pq);
1254 	}
1255 }
1256 
1257 /*
1258  *	vm_pageout_scan does the dirty work for the pageout daemon.
1259  *
1260  *	pass == 0: Update active LRU/deactivate pages
1261  *	pass >= 1: Free inactive pages
1262  *
1263  * Returns true if pass was zero or enough pages were freed by the inactive
1264  * queue scan to meet the target.
1265  */
1266 static bool
1267 vm_pageout_scan(struct vm_domain *vmd, int pass)
1268 {
1269 	vm_page_t m, next;
1270 	struct vm_pagequeue *pq;
1271 	vm_object_t object;
1272 	long min_scan;
1273 	int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan;
1274 	int page_shortage, scan_tick, scanned, starting_page_shortage;
1275 	boolean_t queue_locked;
1276 
1277 	/*
1278 	 * If we need to reclaim memory ask kernel caches to return
1279 	 * some.  We rate limit to avoid thrashing.
1280 	 */
1281 	if (vmd == &vm_dom[0] && pass > 0 &&
1282 	    (time_uptime - lowmem_uptime) >= lowmem_period) {
1283 		/*
1284 		 * Decrease registered cache sizes.
1285 		 */
1286 		SDT_PROBE0(vm, , , vm__lowmem_scan);
1287 		EVENTHANDLER_INVOKE(vm_lowmem, 0);
1288 		/*
1289 		 * We do this explicitly after the caches have been
1290 		 * drained above.
1291 		 */
1292 		uma_reclaim();
1293 		lowmem_uptime = time_uptime;
1294 	}
1295 
1296 	/*
1297 	 * The addl_page_shortage is the number of temporarily
1298 	 * stuck pages in the inactive queue.  In other words, the
1299 	 * number of pages from the inactive count that should be
1300 	 * discounted in setting the target for the active queue scan.
1301 	 */
1302 	addl_page_shortage = 0;
1303 
1304 	/*
1305 	 * Calculate the number of pages that we want to free.  This number
1306 	 * can be negative if many pages are freed between the wakeup call to
1307 	 * the page daemon and this calculation.
1308 	 */
1309 	if (pass > 0) {
1310 		deficit = atomic_readandclear_int(&vm_pageout_deficit);
1311 		page_shortage = vm_paging_target() + deficit;
1312 	} else
1313 		page_shortage = deficit = 0;
1314 	starting_page_shortage = page_shortage;
1315 
1316 	/*
1317 	 * Start scanning the inactive queue for pages that we can free.  The
1318 	 * scan will stop when we reach the target or we have scanned the
1319 	 * entire queue.  (Note that m->act_count is not used to make
1320 	 * decisions for the inactive queue, only for the active queue.)
1321 	 */
1322 	pq = &vmd->vmd_pagequeues[PQ_INACTIVE];
1323 	maxscan = pq->pq_cnt;
1324 	vm_pagequeue_lock(pq);
1325 	queue_locked = TRUE;
1326 	for (m = TAILQ_FIRST(&pq->pq_pl);
1327 	     m != NULL && maxscan-- > 0 && page_shortage > 0;
1328 	     m = next) {
1329 		vm_pagequeue_assert_locked(pq);
1330 		KASSERT(queue_locked, ("unlocked inactive queue"));
1331 		KASSERT(vm_page_inactive(m), ("Inactive queue %p", m));
1332 
1333 		PCPU_INC(cnt.v_pdpages);
1334 		next = TAILQ_NEXT(m, plinks.q);
1335 
1336 		/*
1337 		 * skip marker pages
1338 		 */
1339 		if (m->flags & PG_MARKER)
1340 			continue;
1341 
1342 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
1343 		    ("Fictitious page %p cannot be in inactive queue", m));
1344 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1345 		    ("Unmanaged page %p cannot be in inactive queue", m));
1346 
1347 		/*
1348 		 * The page or object lock acquisitions fail if the
1349 		 * page was removed from the queue or moved to a
1350 		 * different position within the queue.  In either
1351 		 * case, addl_page_shortage should not be incremented.
1352 		 */
1353 		if (!vm_pageout_page_lock(m, &next))
1354 			goto unlock_page;
1355 		else if (m->hold_count != 0) {
1356 			/*
1357 			 * Held pages are essentially stuck in the
1358 			 * queue.  So, they ought to be discounted
1359 			 * from the inactive count.  See the
1360 			 * calculation of inactq_shortage before the
1361 			 * loop over the active queue below.
1362 			 */
1363 			addl_page_shortage++;
1364 			goto unlock_page;
1365 		}
1366 		object = m->object;
1367 		if (!VM_OBJECT_TRYWLOCK(object)) {
1368 			if (!vm_pageout_fallback_object_lock(m, &next))
1369 				goto unlock_object;
1370 			else if (m->hold_count != 0) {
1371 				addl_page_shortage++;
1372 				goto unlock_object;
1373 			}
1374 		}
1375 		if (vm_page_busied(m)) {
1376 			/*
1377 			 * Don't mess with busy pages.  Leave them at
1378 			 * the front of the queue.  Most likely, they
1379 			 * are being paged out and will leave the
1380 			 * queue shortly after the scan finishes.  So,
1381 			 * they ought to be discounted from the
1382 			 * inactive count.
1383 			 */
1384 			addl_page_shortage++;
1385 unlock_object:
1386 			VM_OBJECT_WUNLOCK(object);
1387 unlock_page:
1388 			vm_page_unlock(m);
1389 			continue;
1390 		}
1391 		KASSERT(m->hold_count == 0, ("Held page %p", m));
1392 
1393 		/*
1394 		 * Dequeue the inactive page and unlock the inactive page
1395 		 * queue, invalidating the 'next' pointer.  Dequeueing the
1396 		 * page here avoids a later reacquisition (and release) of
1397 		 * the inactive page queue lock when vm_page_activate(),
1398 		 * vm_page_free(), or vm_page_launder() is called.  Use a
1399 		 * marker to remember our place in the inactive queue.
1400 		 */
1401 		TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q);
1402 		vm_page_dequeue_locked(m);
1403 		vm_pagequeue_unlock(pq);
1404 		queue_locked = FALSE;
1405 
1406 		/*
1407 		 * Invalid pages can be easily freed. They cannot be
1408 		 * mapped, vm_page_free() asserts this.
1409 		 */
1410 		if (m->valid == 0)
1411 			goto free_page;
1412 
1413 		/*
1414 		 * If the page has been referenced and the object is not dead,
1415 		 * reactivate or requeue the page depending on whether the
1416 		 * object is mapped.
1417 		 */
1418 		if ((m->aflags & PGA_REFERENCED) != 0) {
1419 			vm_page_aflag_clear(m, PGA_REFERENCED);
1420 			act_delta = 1;
1421 		} else
1422 			act_delta = 0;
1423 		if (object->ref_count != 0) {
1424 			act_delta += pmap_ts_referenced(m);
1425 		} else {
1426 			KASSERT(!pmap_page_is_mapped(m),
1427 			    ("vm_pageout_scan: page %p is mapped", m));
1428 		}
1429 		if (act_delta != 0) {
1430 			if (object->ref_count != 0) {
1431 				PCPU_INC(cnt.v_reactivated);
1432 				vm_page_activate(m);
1433 
1434 				/*
1435 				 * Increase the activation count if the page
1436 				 * was referenced while in the inactive queue.
1437 				 * This makes it less likely that the page will
1438 				 * be returned prematurely to the inactive
1439 				 * queue.
1440  				 */
1441 				m->act_count += act_delta + ACT_ADVANCE;
1442 				goto drop_page;
1443 			} else if ((object->flags & OBJ_DEAD) == 0) {
1444 				vm_pagequeue_lock(pq);
1445 				queue_locked = TRUE;
1446 				m->queue = PQ_INACTIVE;
1447 				TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
1448 				vm_pagequeue_cnt_inc(pq);
1449 				goto drop_page;
1450 			}
1451 		}
1452 
1453 		/*
1454 		 * If the page appears to be clean at the machine-independent
1455 		 * layer, then remove all of its mappings from the pmap in
1456 		 * anticipation of freeing it.  If, however, any of the page's
1457 		 * mappings allow write access, then the page may still be
1458 		 * modified until the last of those mappings are removed.
1459 		 */
1460 		if (object->ref_count != 0) {
1461 			vm_page_test_dirty(m);
1462 			if (m->dirty == 0)
1463 				pmap_remove_all(m);
1464 		}
1465 
1466 		/*
1467 		 * Clean pages can be freed, but dirty pages must be sent back
1468 		 * to the laundry, unless they belong to a dead object.
1469 		 * Requeueing dirty pages from dead objects is pointless, as
1470 		 * they are being paged out and freed by the thread that
1471 		 * destroyed the object.
1472 		 */
1473 		if (m->dirty == 0) {
1474 free_page:
1475 			vm_page_free(m);
1476 			PCPU_INC(cnt.v_dfree);
1477 			--page_shortage;
1478 		} else if ((object->flags & OBJ_DEAD) == 0)
1479 			vm_page_launder(m);
1480 drop_page:
1481 		vm_page_unlock(m);
1482 		VM_OBJECT_WUNLOCK(object);
1483 		if (!queue_locked) {
1484 			vm_pagequeue_lock(pq);
1485 			queue_locked = TRUE;
1486 		}
1487 		next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q);
1488 		TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q);
1489 	}
1490 	vm_pagequeue_unlock(pq);
1491 
1492 	/*
1493 	 * Wake up the laundry thread so that it can perform any needed
1494 	 * laundering.  If we didn't meet our target, we're in shortfall and
1495 	 * need to launder more aggressively.
1496 	 */
1497 	if (vm_laundry_request == VM_LAUNDRY_IDLE &&
1498 	    starting_page_shortage > 0) {
1499 		pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY];
1500 		vm_pagequeue_lock(pq);
1501 		if (page_shortage > 0) {
1502 			vm_laundry_request = VM_LAUNDRY_SHORTFALL;
1503 			PCPU_INC(cnt.v_pdshortfalls);
1504 		} else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL)
1505 			vm_laundry_request = VM_LAUNDRY_BACKGROUND;
1506 		wakeup(&vm_laundry_request);
1507 		vm_pagequeue_unlock(pq);
1508 	}
1509 
1510 #if !defined(NO_SWAPPING)
1511 	/*
1512 	 * Wakeup the swapout daemon if we didn't free the targeted number of
1513 	 * pages.
1514 	 */
1515 	if (vm_swap_enabled && page_shortage > 0)
1516 		vm_req_vmdaemon(VM_SWAP_NORMAL);
1517 #endif
1518 
1519 	/*
1520 	 * If the inactive queue scan fails repeatedly to meet its
1521 	 * target, kill the largest process.
1522 	 */
1523 	vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage);
1524 
1525 	/*
1526 	 * Compute the number of pages we want to try to move from the
1527 	 * active queue to either the inactive or laundry queue.
1528 	 *
1529 	 * When scanning active pages, we make clean pages count more heavily
1530 	 * towards the page shortage than dirty pages.  This is because dirty
1531 	 * pages must be laundered before they can be reused and thus have less
1532 	 * utility when attempting to quickly alleviate a shortage.  However,
1533 	 * this weighting also causes the scan to deactivate dirty pages more
1534 	 * more aggressively, improving the effectiveness of clustering and
1535 	 * ensuring that they can eventually be reused.
1536 	 */
1537 	inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count +
1538 	    vm_cnt.v_laundry_count / act_scan_laundry_weight) +
1539 	    vm_paging_target() + deficit + addl_page_shortage;
1540 	page_shortage *= act_scan_laundry_weight;
1541 
1542 	pq = &vmd->vmd_pagequeues[PQ_ACTIVE];
1543 	vm_pagequeue_lock(pq);
1544 	maxscan = pq->pq_cnt;
1545 
1546 	/*
1547 	 * If we're just idle polling attempt to visit every
1548 	 * active page within 'update_period' seconds.
1549 	 */
1550 	scan_tick = ticks;
1551 	if (vm_pageout_update_period != 0) {
1552 		min_scan = pq->pq_cnt;
1553 		min_scan *= scan_tick - vmd->vmd_last_active_scan;
1554 		min_scan /= hz * vm_pageout_update_period;
1555 	} else
1556 		min_scan = 0;
1557 	if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0))
1558 		vmd->vmd_last_active_scan = scan_tick;
1559 
1560 	/*
1561 	 * Scan the active queue for pages that can be deactivated.  Update
1562 	 * the per-page activity counter and use it to identify deactivation
1563 	 * candidates.  Held pages may be deactivated.
1564 	 */
1565 	for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned <
1566 	    min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next,
1567 	    scanned++) {
1568 		KASSERT(m->queue == PQ_ACTIVE,
1569 		    ("vm_pageout_scan: page %p isn't active", m));
1570 		next = TAILQ_NEXT(m, plinks.q);
1571 		if ((m->flags & PG_MARKER) != 0)
1572 			continue;
1573 		KASSERT((m->flags & PG_FICTITIOUS) == 0,
1574 		    ("Fictitious page %p cannot be in active queue", m));
1575 		KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1576 		    ("Unmanaged page %p cannot be in active queue", m));
1577 		if (!vm_pageout_page_lock(m, &next)) {
1578 			vm_page_unlock(m);
1579 			continue;
1580 		}
1581 
1582 		/*
1583 		 * The count for page daemon pages is updated after checking
1584 		 * the page for eligibility.
1585 		 */
1586 		PCPU_INC(cnt.v_pdpages);
1587 
1588 		/*
1589 		 * Check to see "how much" the page has been used.
1590 		 */
1591 		if ((m->aflags & PGA_REFERENCED) != 0) {
1592 			vm_page_aflag_clear(m, PGA_REFERENCED);
1593 			act_delta = 1;
1594 		} else
1595 			act_delta = 0;
1596 
1597 		/*
1598 		 * Perform an unsynchronized object ref count check.  While
1599 		 * the page lock ensures that the page is not reallocated to
1600 		 * another object, in particular, one with unmanaged mappings
1601 		 * that cannot support pmap_ts_referenced(), two races are,
1602 		 * nonetheless, possible:
1603 		 * 1) The count was transitioning to zero, but we saw a non-
1604 		 *    zero value.  pmap_ts_referenced() will return zero
1605 		 *    because the page is not mapped.
1606 		 * 2) The count was transitioning to one, but we saw zero.
1607 		 *    This race delays the detection of a new reference.  At
1608 		 *    worst, we will deactivate and reactivate the page.
1609 		 */
1610 		if (m->object->ref_count != 0)
1611 			act_delta += pmap_ts_referenced(m);
1612 
1613 		/*
1614 		 * Advance or decay the act_count based on recent usage.
1615 		 */
1616 		if (act_delta != 0) {
1617 			m->act_count += ACT_ADVANCE + act_delta;
1618 			if (m->act_count > ACT_MAX)
1619 				m->act_count = ACT_MAX;
1620 		} else
1621 			m->act_count -= min(m->act_count, ACT_DECLINE);
1622 
1623 		/*
1624 		 * Move this page to the tail of the active, inactive or laundry
1625 		 * queue depending on usage.
1626 		 */
1627 		if (m->act_count == 0) {
1628 			/* Dequeue to avoid later lock recursion. */
1629 			vm_page_dequeue_locked(m);
1630 
1631 			/*
1632 			 * When not short for inactive pages, let dirty pages go
1633 			 * through the inactive queue before moving to the
1634 			 * laundry queues.  This gives them some extra time to
1635 			 * be reactivated, potentially avoiding an expensive
1636 			 * pageout.  During a page shortage, the inactive queue
1637 			 * is necessarily small, so we may move dirty pages
1638 			 * directly to the laundry queue.
1639 			 */
1640 			if (inactq_shortage <= 0)
1641 				vm_page_deactivate(m);
1642 			else {
1643 				/*
1644 				 * Calling vm_page_test_dirty() here would
1645 				 * require acquisition of the object's write
1646 				 * lock.  However, during a page shortage,
1647 				 * directing dirty pages into the laundry
1648 				 * queue is only an optimization and not a
1649 				 * requirement.  Therefore, we simply rely on
1650 				 * the opportunistic updates to the page's
1651 				 * dirty field by the pmap.
1652 				 */
1653 				if (m->dirty == 0) {
1654 					vm_page_deactivate(m);
1655 					inactq_shortage -=
1656 					    act_scan_laundry_weight;
1657 				} else {
1658 					vm_page_launder(m);
1659 					inactq_shortage--;
1660 				}
1661 			}
1662 		} else
1663 			vm_page_requeue_locked(m);
1664 		vm_page_unlock(m);
1665 	}
1666 	vm_pagequeue_unlock(pq);
1667 #if !defined(NO_SWAPPING)
1668 	/*
1669 	 * Idle process swapout -- run once per second when we are reclaiming
1670 	 * pages.
1671 	 */
1672 	if (vm_swap_idle_enabled && pass > 0) {
1673 		static long lsec;
1674 		if (time_second != lsec) {
1675 			vm_req_vmdaemon(VM_SWAP_IDLE);
1676 			lsec = time_second;
1677 		}
1678 	}
1679 #endif
1680 	return (page_shortage <= 0);
1681 }
1682 
1683 static int vm_pageout_oom_vote;
1684 
1685 /*
1686  * The pagedaemon threads randlomly select one to perform the
1687  * OOM.  Trying to kill processes before all pagedaemons
1688  * failed to reach free target is premature.
1689  */
1690 static void
1691 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage,
1692     int starting_page_shortage)
1693 {
1694 	int old_vote;
1695 
1696 	if (starting_page_shortage <= 0 || starting_page_shortage !=
1697 	    page_shortage)
1698 		vmd->vmd_oom_seq = 0;
1699 	else
1700 		vmd->vmd_oom_seq++;
1701 	if (vmd->vmd_oom_seq < vm_pageout_oom_seq) {
1702 		if (vmd->vmd_oom) {
1703 			vmd->vmd_oom = FALSE;
1704 			atomic_subtract_int(&vm_pageout_oom_vote, 1);
1705 		}
1706 		return;
1707 	}
1708 
1709 	/*
1710 	 * Do not follow the call sequence until OOM condition is
1711 	 * cleared.
1712 	 */
1713 	vmd->vmd_oom_seq = 0;
1714 
1715 	if (vmd->vmd_oom)
1716 		return;
1717 
1718 	vmd->vmd_oom = TRUE;
1719 	old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1);
1720 	if (old_vote != vm_ndomains - 1)
1721 		return;
1722 
1723 	/*
1724 	 * The current pagedaemon thread is the last in the quorum to
1725 	 * start OOM.  Initiate the selection and signaling of the
1726 	 * victim.
1727 	 */
1728 	vm_pageout_oom(VM_OOM_MEM);
1729 
1730 	/*
1731 	 * After one round of OOM terror, recall our vote.  On the
1732 	 * next pass, current pagedaemon would vote again if the low
1733 	 * memory condition is still there, due to vmd_oom being
1734 	 * false.
1735 	 */
1736 	vmd->vmd_oom = FALSE;
1737 	atomic_subtract_int(&vm_pageout_oom_vote, 1);
1738 }
1739 
1740 /*
1741  * The OOM killer is the page daemon's action of last resort when
1742  * memory allocation requests have been stalled for a prolonged period
1743  * of time because it cannot reclaim memory.  This function computes
1744  * the approximate number of physical pages that could be reclaimed if
1745  * the specified address space is destroyed.
1746  *
1747  * Private, anonymous memory owned by the address space is the
1748  * principal resource that we expect to recover after an OOM kill.
1749  * Since the physical pages mapped by the address space's COW entries
1750  * are typically shared pages, they are unlikely to be released and so
1751  * they are not counted.
1752  *
1753  * To get to the point where the page daemon runs the OOM killer, its
1754  * efforts to write-back vnode-backed pages may have stalled.  This
1755  * could be caused by a memory allocation deadlock in the write path
1756  * that might be resolved by an OOM kill.  Therefore, physical pages
1757  * belonging to vnode-backed objects are counted, because they might
1758  * be freed without being written out first if the address space holds
1759  * the last reference to an unlinked vnode.
1760  *
1761  * Similarly, physical pages belonging to OBJT_PHYS objects are
1762  * counted because the address space might hold the last reference to
1763  * the object.
1764  */
1765 static long
1766 vm_pageout_oom_pagecount(struct vmspace *vmspace)
1767 {
1768 	vm_map_t map;
1769 	vm_map_entry_t entry;
1770 	vm_object_t obj;
1771 	long res;
1772 
1773 	map = &vmspace->vm_map;
1774 	KASSERT(!map->system_map, ("system map"));
1775 	sx_assert(&map->lock, SA_LOCKED);
1776 	res = 0;
1777 	for (entry = map->header.next; entry != &map->header;
1778 	    entry = entry->next) {
1779 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
1780 			continue;
1781 		obj = entry->object.vm_object;
1782 		if (obj == NULL)
1783 			continue;
1784 		if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 &&
1785 		    obj->ref_count != 1)
1786 			continue;
1787 		switch (obj->type) {
1788 		case OBJT_DEFAULT:
1789 		case OBJT_SWAP:
1790 		case OBJT_PHYS:
1791 		case OBJT_VNODE:
1792 			res += obj->resident_page_count;
1793 			break;
1794 		}
1795 	}
1796 	return (res);
1797 }
1798 
1799 void
1800 vm_pageout_oom(int shortage)
1801 {
1802 	struct proc *p, *bigproc;
1803 	vm_offset_t size, bigsize;
1804 	struct thread *td;
1805 	struct vmspace *vm;
1806 
1807 	/*
1808 	 * We keep the process bigproc locked once we find it to keep anyone
1809 	 * from messing with it; however, there is a possibility of
1810 	 * deadlock if process B is bigproc and one of its child processes
1811 	 * attempts to propagate a signal to B while we are waiting for A's
1812 	 * lock while walking this list.  To avoid this, we don't block on
1813 	 * the process lock but just skip a process if it is already locked.
1814 	 */
1815 	bigproc = NULL;
1816 	bigsize = 0;
1817 	sx_slock(&allproc_lock);
1818 	FOREACH_PROC_IN_SYSTEM(p) {
1819 		int breakout;
1820 
1821 		PROC_LOCK(p);
1822 
1823 		/*
1824 		 * If this is a system, protected or killed process, skip it.
1825 		 */
1826 		if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC |
1827 		    P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 ||
1828 		    p->p_pid == 1 || P_KILLED(p) ||
1829 		    (p->p_pid < 48 && swap_pager_avail != 0)) {
1830 			PROC_UNLOCK(p);
1831 			continue;
1832 		}
1833 		/*
1834 		 * If the process is in a non-running type state,
1835 		 * don't touch it.  Check all the threads individually.
1836 		 */
1837 		breakout = 0;
1838 		FOREACH_THREAD_IN_PROC(p, td) {
1839 			thread_lock(td);
1840 			if (!TD_ON_RUNQ(td) &&
1841 			    !TD_IS_RUNNING(td) &&
1842 			    !TD_IS_SLEEPING(td) &&
1843 			    !TD_IS_SUSPENDED(td) &&
1844 			    !TD_IS_SWAPPED(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 the process size
1857 		 */
1858 		vm = vmspace_acquire_ref(p);
1859 		if (vm == NULL) {
1860 			PROC_UNLOCK(p);
1861 			continue;
1862 		}
1863 		_PHOLD_LITE(p);
1864 		PROC_UNLOCK(p);
1865 		sx_sunlock(&allproc_lock);
1866 		if (!vm_map_trylock_read(&vm->vm_map)) {
1867 			vmspace_free(vm);
1868 			sx_slock(&allproc_lock);
1869 			PRELE(p);
1870 			continue;
1871 		}
1872 		size = vmspace_swap_count(vm);
1873 		if (shortage == VM_OOM_MEM)
1874 			size += vm_pageout_oom_pagecount(vm);
1875 		vm_map_unlock_read(&vm->vm_map);
1876 		vmspace_free(vm);
1877 		sx_slock(&allproc_lock);
1878 
1879 		/*
1880 		 * If this process is bigger than the biggest one,
1881 		 * remember it.
1882 		 */
1883 		if (size > bigsize) {
1884 			if (bigproc != NULL)
1885 				PRELE(bigproc);
1886 			bigproc = p;
1887 			bigsize = size;
1888 		} else {
1889 			PRELE(p);
1890 		}
1891 	}
1892 	sx_sunlock(&allproc_lock);
1893 	if (bigproc != NULL) {
1894 		if (vm_panic_on_oom != 0)
1895 			panic("out of swap space");
1896 		PROC_LOCK(bigproc);
1897 		killproc(bigproc, "out of swap space");
1898 		sched_nice(bigproc, PRIO_MIN);
1899 		_PRELE(bigproc);
1900 		PROC_UNLOCK(bigproc);
1901 		wakeup(&vm_cnt.v_free_count);
1902 	}
1903 }
1904 
1905 static void
1906 vm_pageout_worker(void *arg)
1907 {
1908 	struct vm_domain *domain;
1909 	int domidx, pass;
1910 	bool target_met;
1911 
1912 	domidx = (uintptr_t)arg;
1913 	domain = &vm_dom[domidx];
1914 	pass = 0;
1915 	target_met = true;
1916 
1917 	/*
1918 	 * XXXKIB It could be useful to bind pageout daemon threads to
1919 	 * the cores belonging to the domain, from which vm_page_array
1920 	 * is allocated.
1921 	 */
1922 
1923 	KASSERT(domain->vmd_segs != 0, ("domain without segments"));
1924 	domain->vmd_last_active_scan = ticks;
1925 	vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE);
1926 	vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE);
1927 	TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl,
1928 	    &domain->vmd_inacthead, plinks.q);
1929 
1930 	/*
1931 	 * The pageout daemon worker is never done, so loop forever.
1932 	 */
1933 	while (TRUE) {
1934 		mtx_lock(&vm_page_queue_free_mtx);
1935 
1936 		/*
1937 		 * Generally, after a level >= 1 scan, if there are enough
1938 		 * free pages to wakeup the waiters, then they are already
1939 		 * awake.  A call to vm_page_free() during the scan awakened
1940 		 * them.  However, in the following case, this wakeup serves
1941 		 * to bound the amount of time that a thread might wait.
1942 		 * Suppose a thread's call to vm_page_alloc() fails, but
1943 		 * before that thread calls VM_WAIT, enough pages are freed by
1944 		 * other threads to alleviate the free page shortage.  The
1945 		 * thread will, nonetheless, wait until another page is freed
1946 		 * or this wakeup is performed.
1947 		 */
1948 		if (vm_pages_needed && !vm_page_count_min()) {
1949 			vm_pages_needed = false;
1950 			wakeup(&vm_cnt.v_free_count);
1951 		}
1952 
1953 		/*
1954 		 * Do not clear vm_pageout_wanted until we reach our free page
1955 		 * target.  Otherwise, we may be awakened over and over again,
1956 		 * wasting CPU time.
1957 		 */
1958 		if (vm_pageout_wanted && target_met)
1959 			vm_pageout_wanted = false;
1960 
1961 		/*
1962 		 * Might the page daemon receive a wakeup call?
1963 		 */
1964 		if (vm_pageout_wanted) {
1965 			/*
1966 			 * No.  Either vm_pageout_wanted was set by another
1967 			 * thread during the previous scan, which must have
1968 			 * been a level 0 scan, or vm_pageout_wanted was
1969 			 * already set and the scan failed to free enough
1970 			 * pages.  If we haven't yet performed a level >= 1
1971 			 * (page reclamation) scan, then increase the level
1972 			 * and scan again now.  Otherwise, sleep a bit and
1973 			 * try again later.
1974 			 */
1975 			mtx_unlock(&vm_page_queue_free_mtx);
1976 			if (pass >= 1)
1977 				pause("psleep", hz / VM_INACT_SCAN_RATE);
1978 			pass++;
1979 		} else {
1980 			/*
1981 			 * Yes.  Sleep until pages need to be reclaimed or
1982 			 * have their reference stats updated.
1983 			 */
1984 			if (mtx_sleep(&vm_pageout_wanted,
1985 			    &vm_page_queue_free_mtx, PDROP | PVM, "psleep",
1986 			    hz) == 0) {
1987 				PCPU_INC(cnt.v_pdwakeups);
1988 				pass = 1;
1989 			} else
1990 				pass = 0;
1991 		}
1992 
1993 		target_met = vm_pageout_scan(domain, pass);
1994 	}
1995 }
1996 
1997 /*
1998  *	vm_pageout_init initialises basic pageout daemon settings.
1999  */
2000 static void
2001 vm_pageout_init(void)
2002 {
2003 	/*
2004 	 * Initialize some paging parameters.
2005 	 */
2006 	vm_cnt.v_interrupt_free_min = 2;
2007 	if (vm_cnt.v_page_count < 2000)
2008 		vm_pageout_page_count = 8;
2009 
2010 	/*
2011 	 * v_free_reserved needs to include enough for the largest
2012 	 * swap pager structures plus enough for any pv_entry structs
2013 	 * when paging.
2014 	 */
2015 	if (vm_cnt.v_page_count > 1024)
2016 		vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200;
2017 	else
2018 		vm_cnt.v_free_min = 4;
2019 	vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
2020 	    vm_cnt.v_interrupt_free_min;
2021 	vm_cnt.v_free_reserved = vm_pageout_page_count +
2022 	    vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768);
2023 	vm_cnt.v_free_severe = vm_cnt.v_free_min / 2;
2024 	vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved;
2025 	vm_cnt.v_free_min += vm_cnt.v_free_reserved;
2026 	vm_cnt.v_free_severe += vm_cnt.v_free_reserved;
2027 	vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2;
2028 	if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3)
2029 		vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3;
2030 
2031 	/*
2032 	 * Set the default wakeup threshold to be 10% above the minimum
2033 	 * page limit.  This keeps the steady state out of shortfall.
2034 	 */
2035 	vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11;
2036 
2037 	/*
2038 	 * Set interval in seconds for active scan.  We want to visit each
2039 	 * page at least once every ten minutes.  This is to prevent worst
2040 	 * case paging behaviors with stale active LRU.
2041 	 */
2042 	if (vm_pageout_update_period == 0)
2043 		vm_pageout_update_period = 600;
2044 
2045 	/* XXX does not really belong here */
2046 	if (vm_page_max_wired == 0)
2047 		vm_page_max_wired = vm_cnt.v_free_count / 3;
2048 
2049 	/*
2050 	 * Target amount of memory to move out of the laundry queue during a
2051 	 * background laundering.  This is proportional to the amount of system
2052 	 * memory.
2053 	 */
2054 	vm_background_launder_target = (vm_cnt.v_free_target -
2055 	    vm_cnt.v_free_min) / 10;
2056 }
2057 
2058 /*
2059  *     vm_pageout is the high level pageout daemon.
2060  */
2061 static void
2062 vm_pageout(void)
2063 {
2064 	int error;
2065 #ifdef VM_NUMA_ALLOC
2066 	int i;
2067 #endif
2068 
2069 	swap_pager_swap_init();
2070 	error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL,
2071 	    0, 0, "laundry: dom0");
2072 	if (error != 0)
2073 		panic("starting laundry for domain 0, error %d", error);
2074 #ifdef VM_NUMA_ALLOC
2075 	for (i = 1; i < vm_ndomains; i++) {
2076 		error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i,
2077 		    curproc, NULL, 0, 0, "dom%d", i);
2078 		if (error != 0) {
2079 			panic("starting pageout for domain %d, error %d\n",
2080 			    i, error);
2081 		}
2082 	}
2083 #endif
2084 	error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL,
2085 	    0, 0, "uma");
2086 	if (error != 0)
2087 		panic("starting uma_reclaim helper, error %d\n", error);
2088 	vm_pageout_worker((void *)(uintptr_t)0);
2089 }
2090 
2091 /*
2092  * Unless the free page queue lock is held by the caller, this function
2093  * should be regarded as advisory.  Specifically, the caller should
2094  * not msleep() on &vm_cnt.v_free_count following this function unless
2095  * the free page queue lock is held until the msleep() is performed.
2096  */
2097 void
2098 pagedaemon_wakeup(void)
2099 {
2100 
2101 	if (!vm_pageout_wanted && curthread->td_proc != pageproc) {
2102 		vm_pageout_wanted = true;
2103 		wakeup(&vm_pageout_wanted);
2104 	}
2105 }
2106 
2107 #if !defined(NO_SWAPPING)
2108 static void
2109 vm_req_vmdaemon(int req)
2110 {
2111 	static int lastrun = 0;
2112 
2113 	mtx_lock(&vm_daemon_mtx);
2114 	vm_pageout_req_swapout |= req;
2115 	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
2116 		wakeup(&vm_daemon_needed);
2117 		lastrun = ticks;
2118 	}
2119 	mtx_unlock(&vm_daemon_mtx);
2120 }
2121 
2122 static void
2123 vm_daemon(void)
2124 {
2125 	struct rlimit rsslim;
2126 	struct proc *p;
2127 	struct thread *td;
2128 	struct vmspace *vm;
2129 	int breakout, swapout_flags, tryagain, attempts;
2130 #ifdef RACCT
2131 	uint64_t rsize, ravailable;
2132 #endif
2133 
2134 	while (TRUE) {
2135 		mtx_lock(&vm_daemon_mtx);
2136 		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
2137 #ifdef RACCT
2138 		    racct_enable ? hz : 0
2139 #else
2140 		    0
2141 #endif
2142 		);
2143 		swapout_flags = vm_pageout_req_swapout;
2144 		vm_pageout_req_swapout = 0;
2145 		mtx_unlock(&vm_daemon_mtx);
2146 		if (swapout_flags)
2147 			swapout_procs(swapout_flags);
2148 
2149 		/*
2150 		 * scan the processes for exceeding their rlimits or if
2151 		 * process is swapped out -- deactivate pages
2152 		 */
2153 		tryagain = 0;
2154 		attempts = 0;
2155 again:
2156 		attempts++;
2157 		sx_slock(&allproc_lock);
2158 		FOREACH_PROC_IN_SYSTEM(p) {
2159 			vm_pindex_t limit, size;
2160 
2161 			/*
2162 			 * if this is a system process or if we have already
2163 			 * looked at this process, skip it.
2164 			 */
2165 			PROC_LOCK(p);
2166 			if (p->p_state != PRS_NORMAL ||
2167 			    p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
2168 				PROC_UNLOCK(p);
2169 				continue;
2170 			}
2171 			/*
2172 			 * if the process is in a non-running type state,
2173 			 * don't touch it.
2174 			 */
2175 			breakout = 0;
2176 			FOREACH_THREAD_IN_PROC(p, td) {
2177 				thread_lock(td);
2178 				if (!TD_ON_RUNQ(td) &&
2179 				    !TD_IS_RUNNING(td) &&
2180 				    !TD_IS_SLEEPING(td) &&
2181 				    !TD_IS_SUSPENDED(td)) {
2182 					thread_unlock(td);
2183 					breakout = 1;
2184 					break;
2185 				}
2186 				thread_unlock(td);
2187 			}
2188 			if (breakout) {
2189 				PROC_UNLOCK(p);
2190 				continue;
2191 			}
2192 			/*
2193 			 * get a limit
2194 			 */
2195 			lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
2196 			limit = OFF_TO_IDX(
2197 			    qmin(rsslim.rlim_cur, rsslim.rlim_max));
2198 
2199 			/*
2200 			 * let processes that are swapped out really be
2201 			 * swapped out set the limit to nothing (will force a
2202 			 * swap-out.)
2203 			 */
2204 			if ((p->p_flag & P_INMEM) == 0)
2205 				limit = 0;	/* XXX */
2206 			vm = vmspace_acquire_ref(p);
2207 			_PHOLD_LITE(p);
2208 			PROC_UNLOCK(p);
2209 			if (vm == NULL) {
2210 				PRELE(p);
2211 				continue;
2212 			}
2213 			sx_sunlock(&allproc_lock);
2214 
2215 			size = vmspace_resident_count(vm);
2216 			if (size >= limit) {
2217 				vm_pageout_map_deactivate_pages(
2218 				    &vm->vm_map, limit);
2219 			}
2220 #ifdef RACCT
2221 			if (racct_enable) {
2222 				rsize = IDX_TO_OFF(size);
2223 				PROC_LOCK(p);
2224 				racct_set(p, RACCT_RSS, rsize);
2225 				ravailable = racct_get_available(p, RACCT_RSS);
2226 				PROC_UNLOCK(p);
2227 				if (rsize > ravailable) {
2228 					/*
2229 					 * Don't be overly aggressive; this
2230 					 * might be an innocent process,
2231 					 * and the limit could've been exceeded
2232 					 * by some memory hog.  Don't try
2233 					 * to deactivate more than 1/4th
2234 					 * of process' resident set size.
2235 					 */
2236 					if (attempts <= 8) {
2237 						if (ravailable < rsize -
2238 						    (rsize / 4)) {
2239 							ravailable = rsize -
2240 							    (rsize / 4);
2241 						}
2242 					}
2243 					vm_pageout_map_deactivate_pages(
2244 					    &vm->vm_map,
2245 					    OFF_TO_IDX(ravailable));
2246 					/* Update RSS usage after paging out. */
2247 					size = vmspace_resident_count(vm);
2248 					rsize = IDX_TO_OFF(size);
2249 					PROC_LOCK(p);
2250 					racct_set(p, RACCT_RSS, rsize);
2251 					PROC_UNLOCK(p);
2252 					if (rsize > ravailable)
2253 						tryagain = 1;
2254 				}
2255 			}
2256 #endif
2257 			vmspace_free(vm);
2258 			sx_slock(&allproc_lock);
2259 			PRELE(p);
2260 		}
2261 		sx_sunlock(&allproc_lock);
2262 		if (tryagain != 0 && attempts <= 10)
2263 			goto again;
2264 	}
2265 }
2266 #endif			/* !defined(NO_SWAPPING) */
2267