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