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