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