vm_pageout.c revision 207759
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: head/sys/vm/vm_pageout.c 207759 2010-05-07 21:06:52Z jkim $");
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/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	vm_pageout_init_marker(&marker, PQ_INACTIVE);
769
770	/*
771	 * Start scanning the inactive queue for pages we can move to the
772	 * cache or free.  The scan will stop when the target is reached or
773	 * we have scanned the entire inactive queue.  Note that m->act_count
774	 * is not used to form decisions for the inactive queue, only for the
775	 * active queue.
776	 *
777	 * maxlaunder limits the number of dirty pages we flush per scan.
778	 * For most systems a smaller value (16 or 32) is more robust under
779	 * extreme memory and disk pressure because any unnecessary writes
780	 * to disk can result in extreme performance degredation.  However,
781	 * systems with excessive dirty pages (especially when MAP_NOSYNC is
782	 * used) will die horribly with limited laundering.  If the pageout
783	 * daemon cannot clean enough pages in the first pass, we let it go
784	 * all out in succeeding passes.
785	 */
786	if ((maxlaunder = vm_max_launder) <= 1)
787		maxlaunder = 1;
788	if (pass)
789		maxlaunder = 10000;
790	vm_page_lock_queues();
791rescan0:
792	addl_page_shortage = addl_page_shortage_init;
793	maxscan = cnt.v_inactive_count;
794
795	for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
796	     m != NULL && maxscan-- > 0 && page_shortage > 0;
797	     m = next) {
798
799		cnt.v_pdpages++;
800
801		if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE) {
802			goto rescan0;
803		}
804
805		next = TAILQ_NEXT(m, pageq);
806
807		/*
808		 * skip marker pages
809		 */
810		if (m->flags & PG_MARKER)
811			continue;
812
813		/*
814		 * Lock the page.
815		 */
816		if (!vm_pageout_page_lock(m, &next)) {
817			vm_page_unlock(m);
818			addl_page_shortage++;
819			continue;
820		}
821
822		/*
823		 * A held page may be undergoing I/O, so skip it.
824		 */
825		if (m->hold_count || (object = m->object) == NULL) {
826			vm_page_unlock(m);
827			vm_page_requeue(m);
828			addl_page_shortage++;
829			continue;
830		}
831
832		/*
833		 * Don't mess with busy pages, keep in the front of the
834		 * queue, most likely are being paged out.
835		 */
836		if (!VM_OBJECT_TRYLOCK(object) &&
837		    (!vm_pageout_fallback_object_lock(m, &next) ||
838			m->hold_count != 0)) {
839			VM_OBJECT_UNLOCK(object);
840			vm_page_unlock(m);
841			addl_page_shortage++;
842			continue;
843		}
844		if (m->busy || (m->oflags & VPO_BUSY)) {
845			vm_page_unlock(m);
846			VM_OBJECT_UNLOCK(object);
847			addl_page_shortage++;
848			continue;
849		}
850
851		/*
852		 * If the object is not being used, we ignore previous
853		 * references.
854		 */
855		if (object->ref_count == 0) {
856			vm_page_flag_clear(m, PG_REFERENCED);
857			KASSERT(!pmap_page_is_mapped(m),
858			    ("vm_pageout_scan: page %p is mapped", m));
859
860		/*
861		 * Otherwise, if the page has been referenced while in the
862		 * inactive queue, we bump the "activation count" upwards,
863		 * making it less likely that the page will be added back to
864		 * the inactive queue prematurely again.  Here we check the
865		 * page tables (or emulated bits, if any), given the upper
866		 * level VM system not knowing anything about existing
867		 * references.
868		 */
869		} else if (((m->flags & PG_REFERENCED) == 0) &&
870			(actcount = pmap_ts_referenced(m))) {
871			vm_page_activate(m);
872			VM_OBJECT_UNLOCK(object);
873			m->act_count += (actcount + ACT_ADVANCE);
874			vm_page_unlock(m);
875			continue;
876		}
877
878		/*
879		 * If the upper level VM system knows about any page
880		 * references, we activate the page.  We also set the
881		 * "activation count" higher than normal so that we will less
882		 * likely place pages back onto the inactive queue again.
883		 */
884		if ((m->flags & PG_REFERENCED) != 0) {
885			vm_page_flag_clear(m, PG_REFERENCED);
886			actcount = pmap_ts_referenced(m);
887			vm_page_activate(m);
888			VM_OBJECT_UNLOCK(object);
889			m->act_count += (actcount + ACT_ADVANCE + 1);
890			vm_page_unlock(m);
891			continue;
892		}
893
894		/*
895		 * If the upper level VM system does not believe that the page
896		 * is fully dirty, but it is mapped for write access, then we
897		 * consult the pmap to see if the page's dirty status should
898		 * be updated.
899		 */
900		if (m->dirty != VM_PAGE_BITS_ALL &&
901		    (m->flags & PG_WRITEABLE) != 0) {
902			/*
903			 * Avoid a race condition: Unless write access is
904			 * removed from the page, another processor could
905			 * modify it before all access is removed by the call
906			 * to vm_page_cache() below.  If vm_page_cache() finds
907			 * that the page has been modified when it removes all
908			 * access, it panics because it cannot cache dirty
909			 * pages.  In principle, we could eliminate just write
910			 * access here rather than all access.  In the expected
911			 * case, when there are no last instant modifications
912			 * to the page, removing all access will be cheaper
913			 * overall.
914			 */
915			if (pmap_is_modified(m))
916				vm_page_dirty(m);
917			else if (m->dirty == 0)
918				pmap_remove_all(m);
919		}
920
921		if (m->valid == 0) {
922			/*
923			 * Invalid pages can be easily freed
924			 */
925			vm_page_free(m);
926			cnt.v_dfree++;
927			--page_shortage;
928		} else if (m->dirty == 0) {
929			/*
930			 * Clean pages can be placed onto the cache queue.
931			 * This effectively frees them.
932			 */
933			vm_page_cache(m);
934			--page_shortage;
935		} else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
936			/*
937			 * Dirty pages need to be paged out, but flushing
938			 * a page is extremely expensive verses freeing
939			 * a clean page.  Rather then artificially limiting
940			 * the number of pages we can flush, we instead give
941			 * dirty pages extra priority on the inactive queue
942			 * by forcing them to be cycled through the queue
943			 * twice before being flushed, after which the
944			 * (now clean) page will cycle through once more
945			 * before being freed.  This significantly extends
946			 * the thrash point for a heavily loaded machine.
947			 */
948			vm_page_flag_set(m, PG_WINATCFLS);
949			vm_page_requeue(m);
950		} else if (maxlaunder > 0) {
951			/*
952			 * We always want to try to flush some dirty pages if
953			 * we encounter them, to keep the system stable.
954			 * Normally this number is small, but under extreme
955			 * pressure where there are insufficient clean pages
956			 * on the inactive queue, we may have to go all out.
957			 */
958			int swap_pageouts_ok, vfslocked = 0;
959			struct vnode *vp = NULL;
960			struct mount *mp = NULL;
961
962			if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
963				swap_pageouts_ok = 1;
964			} else {
965				swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
966				swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
967				vm_page_count_min());
968
969			}
970
971			/*
972			 * We don't bother paging objects that are "dead".
973			 * Those objects are in a "rundown" state.
974			 */
975			if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
976				vm_page_unlock(m);
977				VM_OBJECT_UNLOCK(object);
978				vm_page_requeue(m);
979				continue;
980			}
981
982			/*
983			 * Following operations may unlock
984			 * vm_page_queue_mtx, invalidating the 'next'
985			 * pointer.  To prevent an inordinate number
986			 * of restarts we use our marker to remember
987			 * our place.
988			 *
989			 */
990			TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl,
991					   m, &marker, pageq);
992			/*
993			 * The object is already known NOT to be dead.   It
994			 * is possible for the vget() to block the whole
995			 * pageout daemon, but the new low-memory handling
996			 * code should prevent it.
997			 *
998			 * The previous code skipped locked vnodes and, worse,
999			 * reordered pages in the queue.  This results in
1000			 * completely non-deterministic operation and, on a
1001			 * busy system, can lead to extremely non-optimal
1002			 * pageouts.  For example, it can cause clean pages
1003			 * to be freed and dirty pages to be moved to the end
1004			 * of the queue.  Since dirty pages are also moved to
1005			 * the end of the queue once-cleaned, this gives
1006			 * way too large a weighting to defering the freeing
1007			 * of dirty pages.
1008			 *
1009			 * We can't wait forever for the vnode lock, we might
1010			 * deadlock due to a vn_read() getting stuck in
1011			 * vm_wait while holding this vnode.  We skip the
1012			 * vnode if we can't get it in a reasonable amount
1013			 * of time.
1014			 */
1015			if (object->type == OBJT_VNODE) {
1016				vm_page_unlock_queues();
1017				vm_page_unlock(m);
1018				vp = object->handle;
1019				if (vp->v_type == VREG &&
1020				    vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1021					mp = NULL;
1022					++pageout_lock_miss;
1023					if (object->flags & OBJ_MIGHTBEDIRTY)
1024						vnodes_skipped++;
1025					vm_page_lock_queues();
1026					goto unlock_and_continue;
1027				}
1028				KASSERT(mp != NULL,
1029				    ("vp %p with NULL v_mount", vp));
1030				vm_object_reference_locked(object);
1031				VM_OBJECT_UNLOCK(object);
1032				vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1033				if (vget(vp, LK_EXCLUSIVE | LK_TIMELOCK,
1034				    curthread)) {
1035					VM_OBJECT_LOCK(object);
1036					vm_page_lock_queues();
1037					++pageout_lock_miss;
1038					if (object->flags & OBJ_MIGHTBEDIRTY)
1039						vnodes_skipped++;
1040					vp = NULL;
1041					goto unlock_and_continue;
1042				}
1043				VM_OBJECT_LOCK(object);
1044				vm_page_lock(m);
1045				vm_page_lock_queues();
1046				/*
1047				 * The page might have been moved to another
1048				 * queue during potential blocking in vget()
1049				 * above.  The page might have been freed and
1050				 * reused for another vnode.
1051				 */
1052				if (VM_PAGE_GETQUEUE(m) != PQ_INACTIVE ||
1053				    m->object != object ||
1054				    TAILQ_NEXT(m, pageq) != &marker) {
1055					vm_page_unlock(m);
1056					if (object->flags & OBJ_MIGHTBEDIRTY)
1057						vnodes_skipped++;
1058					goto unlock_and_continue;
1059				}
1060
1061				/*
1062				 * The page may have been busied during the
1063				 * blocking in vget().  We don't move the
1064				 * page back onto the end of the queue so that
1065				 * statistics are more correct if we don't.
1066				 */
1067				if (m->busy || (m->oflags & VPO_BUSY)) {
1068					vm_page_unlock(m);
1069					goto unlock_and_continue;
1070				}
1071
1072				/*
1073				 * If the page has become held it might
1074				 * be undergoing I/O, so skip it
1075				 */
1076				if (m->hold_count) {
1077					vm_page_unlock(m);
1078					vm_page_requeue(m);
1079					if (object->flags & OBJ_MIGHTBEDIRTY)
1080						vnodes_skipped++;
1081					goto unlock_and_continue;
1082				}
1083			}
1084			vm_page_unlock(m);
1085
1086			/*
1087			 * If a page is dirty, then it is either being washed
1088			 * (but not yet cleaned) or it is still in the
1089			 * laundry.  If it is still in the laundry, then we
1090			 * start the cleaning operation.
1091			 *
1092			 * decrement page_shortage on success to account for
1093			 * the (future) cleaned page.  Otherwise we could wind
1094			 * up laundering or cleaning too many pages.
1095			 */
1096			vm_page_unlock_queues();
1097			if (vm_pageout_clean(m) != 0) {
1098				--page_shortage;
1099				--maxlaunder;
1100			}
1101			vm_page_lock_queues();
1102unlock_and_continue:
1103			vm_page_lock_assert(m, MA_NOTOWNED);
1104			VM_OBJECT_UNLOCK(object);
1105			if (mp != NULL) {
1106				vm_page_unlock_queues();
1107				if (vp != NULL)
1108					vput(vp);
1109				VFS_UNLOCK_GIANT(vfslocked);
1110				vm_object_deallocate(object);
1111				vn_finished_write(mp);
1112				vm_page_lock_queues();
1113			}
1114			next = TAILQ_NEXT(&marker, pageq);
1115			TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl,
1116				     &marker, pageq);
1117			vm_page_lock_assert(m, MA_NOTOWNED);
1118			continue;
1119		}
1120		vm_page_unlock(m);
1121		VM_OBJECT_UNLOCK(object);
1122	}
1123
1124	/*
1125	 * Compute the number of pages we want to try to move from the
1126	 * active queue to the inactive queue.
1127	 */
1128	page_shortage = vm_paging_target() +
1129		cnt.v_inactive_target - cnt.v_inactive_count;
1130	page_shortage += addl_page_shortage;
1131
1132	/*
1133	 * Scan the active queue for things we can deactivate. We nominally
1134	 * track the per-page activity counter and use it to locate
1135	 * deactivation candidates.
1136	 */
1137	pcount = cnt.v_active_count;
1138	m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1139	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1140
1141	while ((m != NULL) && (pcount-- > 0) && (page_shortage > 0)) {
1142
1143		KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1144		    ("vm_pageout_scan: page %p isn't active", m));
1145
1146		next = TAILQ_NEXT(m, pageq);
1147		object = m->object;
1148		if ((m->flags & PG_MARKER) != 0) {
1149			m = next;
1150			continue;
1151		}
1152		if (!vm_pageout_page_lock(m, &next) ||
1153		    (object = m->object) == NULL) {
1154			vm_page_unlock(m);
1155			m = next;
1156			continue;
1157		}
1158		if (!VM_OBJECT_TRYLOCK(object) &&
1159		    !vm_pageout_fallback_object_lock(m, &next)) {
1160			VM_OBJECT_UNLOCK(object);
1161			vm_page_unlock(m);
1162			m = next;
1163			continue;
1164		}
1165
1166		/*
1167		 * Don't deactivate pages that are busy.
1168		 */
1169		if ((m->busy != 0) ||
1170		    (m->oflags & VPO_BUSY) ||
1171		    (m->hold_count != 0)) {
1172			vm_page_unlock(m);
1173			VM_OBJECT_UNLOCK(object);
1174			vm_page_requeue(m);
1175			m = next;
1176			continue;
1177		}
1178
1179		/*
1180		 * The count for pagedaemon pages is done after checking the
1181		 * page for eligibility...
1182		 */
1183		cnt.v_pdpages++;
1184
1185		/*
1186		 * Check to see "how much" the page has been used.
1187		 */
1188		actcount = 0;
1189		if (object->ref_count != 0) {
1190			if (m->flags & PG_REFERENCED) {
1191				actcount += 1;
1192			}
1193			actcount += pmap_ts_referenced(m);
1194			if (actcount) {
1195				m->act_count += ACT_ADVANCE + actcount;
1196				if (m->act_count > ACT_MAX)
1197					m->act_count = ACT_MAX;
1198			}
1199		}
1200
1201		/*
1202		 * Since we have "tested" this bit, we need to clear it now.
1203		 */
1204		vm_page_flag_clear(m, PG_REFERENCED);
1205
1206		/*
1207		 * Only if an object is currently being used, do we use the
1208		 * page activation count stats.
1209		 */
1210		if (actcount && (object->ref_count != 0)) {
1211			vm_page_requeue(m);
1212		} else {
1213			m->act_count -= min(m->act_count, ACT_DECLINE);
1214			if (vm_pageout_algorithm ||
1215			    object->ref_count == 0 ||
1216			    m->act_count == 0) {
1217				page_shortage--;
1218				if (object->ref_count == 0) {
1219					KASSERT(!pmap_page_is_mapped(m),
1220				    ("vm_pageout_scan: page %p is mapped", m));
1221					if (m->dirty == 0)
1222						vm_page_cache(m);
1223					else
1224						vm_page_deactivate(m);
1225				} else {
1226					vm_page_deactivate(m);
1227				}
1228			} else {
1229				vm_page_requeue(m);
1230			}
1231		}
1232		vm_page_unlock(m);
1233		VM_OBJECT_UNLOCK(object);
1234		m = next;
1235	}
1236	vm_page_unlock_queues();
1237#if !defined(NO_SWAPPING)
1238	/*
1239	 * Idle process swapout -- run once per second.
1240	 */
1241	if (vm_swap_idle_enabled) {
1242		static long lsec;
1243		if (time_second != lsec) {
1244			vm_req_vmdaemon(VM_SWAP_IDLE);
1245			lsec = time_second;
1246		}
1247	}
1248#endif
1249
1250	/*
1251	 * If we didn't get enough free pages, and we have skipped a vnode
1252	 * in a writeable object, wakeup the sync daemon.  And kick swapout
1253	 * if we did not get enough free pages.
1254	 */
1255	if (vm_paging_target() > 0) {
1256		if (vnodes_skipped && vm_page_count_min())
1257			(void) speedup_syncer();
1258#if !defined(NO_SWAPPING)
1259		if (vm_swap_enabled && vm_page_count_target())
1260			vm_req_vmdaemon(VM_SWAP_NORMAL);
1261#endif
1262	}
1263
1264	/*
1265	 * If we are critically low on one of RAM or swap and low on
1266	 * the other, kill the largest process.  However, we avoid
1267	 * doing this on the first pass in order to give ourselves a
1268	 * chance to flush out dirty vnode-backed pages and to allow
1269	 * active pages to be moved to the inactive queue and reclaimed.
1270	 */
1271	if (pass != 0 &&
1272	    ((swap_pager_avail < 64 && vm_page_count_min()) ||
1273	     (swap_pager_full && vm_paging_target() > 0)))
1274		vm_pageout_oom(VM_OOM_MEM);
1275}
1276
1277
1278void
1279vm_pageout_oom(int shortage)
1280{
1281	struct proc *p, *bigproc;
1282	vm_offset_t size, bigsize;
1283	struct thread *td;
1284	struct vmspace *vm;
1285
1286	/*
1287	 * We keep the process bigproc locked once we find it to keep anyone
1288	 * from messing with it; however, there is a possibility of
1289	 * deadlock if process B is bigproc and one of it's child processes
1290	 * attempts to propagate a signal to B while we are waiting for A's
1291	 * lock while walking this list.  To avoid this, we don't block on
1292	 * the process lock but just skip a process if it is already locked.
1293	 */
1294	bigproc = NULL;
1295	bigsize = 0;
1296	sx_slock(&allproc_lock);
1297	FOREACH_PROC_IN_SYSTEM(p) {
1298		int breakout;
1299
1300		if (PROC_TRYLOCK(p) == 0)
1301			continue;
1302		/*
1303		 * If this is a system, protected or killed process, skip it.
1304		 */
1305		if ((p->p_flag & (P_INEXEC | P_PROTECTED | P_SYSTEM)) ||
1306		    (p->p_pid == 1) || P_KILLED(p) ||
1307		    ((p->p_pid < 48) && (swap_pager_avail != 0))) {
1308			PROC_UNLOCK(p);
1309			continue;
1310		}
1311		/*
1312		 * If the process is in a non-running type state,
1313		 * don't touch it.  Check all the threads individually.
1314		 */
1315		breakout = 0;
1316		FOREACH_THREAD_IN_PROC(p, td) {
1317			thread_lock(td);
1318			if (!TD_ON_RUNQ(td) &&
1319			    !TD_IS_RUNNING(td) &&
1320			    !TD_IS_SLEEPING(td)) {
1321				thread_unlock(td);
1322				breakout = 1;
1323				break;
1324			}
1325			thread_unlock(td);
1326		}
1327		if (breakout) {
1328			PROC_UNLOCK(p);
1329			continue;
1330		}
1331		/*
1332		 * get the process size
1333		 */
1334		vm = vmspace_acquire_ref(p);
1335		if (vm == NULL) {
1336			PROC_UNLOCK(p);
1337			continue;
1338		}
1339		if (!vm_map_trylock_read(&vm->vm_map)) {
1340			vmspace_free(vm);
1341			PROC_UNLOCK(p);
1342			continue;
1343		}
1344		size = vmspace_swap_count(vm);
1345		vm_map_unlock_read(&vm->vm_map);
1346		if (shortage == VM_OOM_MEM)
1347			size += vmspace_resident_count(vm);
1348		vmspace_free(vm);
1349		/*
1350		 * if the this process is bigger than the biggest one
1351		 * remember it.
1352		 */
1353		if (size > bigsize) {
1354			if (bigproc != NULL)
1355				PROC_UNLOCK(bigproc);
1356			bigproc = p;
1357			bigsize = size;
1358		} else
1359			PROC_UNLOCK(p);
1360	}
1361	sx_sunlock(&allproc_lock);
1362	if (bigproc != NULL) {
1363		killproc(bigproc, "out of swap space");
1364		sched_nice(bigproc, PRIO_MIN);
1365		PROC_UNLOCK(bigproc);
1366		wakeup(&cnt.v_free_count);
1367	}
1368}
1369
1370/*
1371 * This routine tries to maintain the pseudo LRU active queue,
1372 * so that during long periods of time where there is no paging,
1373 * that some statistic accumulation still occurs.  This code
1374 * helps the situation where paging just starts to occur.
1375 */
1376static void
1377vm_pageout_page_stats()
1378{
1379	vm_object_t object;
1380	vm_page_t m,next;
1381	int pcount,tpcount;		/* Number of pages to check */
1382	static int fullintervalcount = 0;
1383	int page_shortage;
1384
1385	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
1386	page_shortage =
1387	    (cnt.v_inactive_target + cnt.v_cache_max + cnt.v_free_min) -
1388	    (cnt.v_free_count + cnt.v_inactive_count + cnt.v_cache_count);
1389
1390	if (page_shortage <= 0)
1391		return;
1392
1393	pcount = cnt.v_active_count;
1394	fullintervalcount += vm_pageout_stats_interval;
1395	if (fullintervalcount < vm_pageout_full_stats_interval) {
1396		tpcount = (int64_t)vm_pageout_stats_max * cnt.v_active_count /
1397		    cnt.v_page_count;
1398		if (pcount > tpcount)
1399			pcount = tpcount;
1400	} else {
1401		fullintervalcount = 0;
1402	}
1403
1404	m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1405	while ((m != NULL) && (pcount-- > 0)) {
1406		int actcount;
1407
1408		KASSERT(VM_PAGE_INQUEUE2(m, PQ_ACTIVE),
1409		    ("vm_pageout_page_stats: page %p isn't active", m));
1410
1411		next = TAILQ_NEXT(m, pageq);
1412		if ((m->flags & PG_MARKER) != 0) {
1413			m = next;
1414			continue;
1415		}
1416		vm_page_lock_assert(m, MA_NOTOWNED);
1417		if (!vm_pageout_page_lock(m, &next) ||
1418		    (object = m->object) == NULL) {
1419			vm_page_unlock(m);
1420			m = next;
1421			continue;
1422		}
1423		if (!VM_OBJECT_TRYLOCK(object) &&
1424		    !vm_pageout_fallback_object_lock(m, &next)) {
1425			VM_OBJECT_UNLOCK(object);
1426			vm_page_unlock(m);
1427			m = next;
1428			continue;
1429		}
1430
1431		/*
1432		 * Don't deactivate pages that are busy.
1433		 */
1434		if ((m->busy != 0) ||
1435		    (m->oflags & VPO_BUSY) ||
1436		    (m->hold_count != 0)) {
1437			vm_page_unlock(m);
1438			VM_OBJECT_UNLOCK(object);
1439			vm_page_requeue(m);
1440			m = next;
1441			continue;
1442		}
1443
1444		actcount = 0;
1445		if (m->flags & PG_REFERENCED) {
1446			vm_page_flag_clear(m, PG_REFERENCED);
1447			actcount += 1;
1448		}
1449
1450		actcount += pmap_ts_referenced(m);
1451		if (actcount) {
1452			m->act_count += ACT_ADVANCE + actcount;
1453			if (m->act_count > ACT_MAX)
1454				m->act_count = ACT_MAX;
1455			vm_page_requeue(m);
1456		} else {
1457			if (m->act_count == 0) {
1458				/*
1459				 * We turn off page access, so that we have
1460				 * more accurate RSS stats.  We don't do this
1461				 * in the normal page deactivation when the
1462				 * system is loaded VM wise, because the
1463				 * cost of the large number of page protect
1464				 * operations would be higher than the value
1465				 * of doing the operation.
1466				 */
1467				pmap_remove_all(m);
1468				vm_page_deactivate(m);
1469			} else {
1470				m->act_count -= min(m->act_count, ACT_DECLINE);
1471				vm_page_requeue(m);
1472			}
1473		}
1474		vm_page_unlock(m);
1475		VM_OBJECT_UNLOCK(object);
1476		m = next;
1477	}
1478}
1479
1480/*
1481 *	vm_pageout is the high level pageout daemon.
1482 */
1483static void
1484vm_pageout()
1485{
1486	int error, pass;
1487
1488	/*
1489	 * Initialize some paging parameters.
1490	 */
1491	cnt.v_interrupt_free_min = 2;
1492	if (cnt.v_page_count < 2000)
1493		vm_pageout_page_count = 8;
1494
1495	/*
1496	 * v_free_reserved needs to include enough for the largest
1497	 * swap pager structures plus enough for any pv_entry structs
1498	 * when paging.
1499	 */
1500	if (cnt.v_page_count > 1024)
1501		cnt.v_free_min = 4 + (cnt.v_page_count - 1024) / 200;
1502	else
1503		cnt.v_free_min = 4;
1504	cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1505	    cnt.v_interrupt_free_min;
1506	cnt.v_free_reserved = vm_pageout_page_count +
1507	    cnt.v_pageout_free_min + (cnt.v_page_count / 768);
1508	cnt.v_free_severe = cnt.v_free_min / 2;
1509	cnt.v_free_min += cnt.v_free_reserved;
1510	cnt.v_free_severe += cnt.v_free_reserved;
1511
1512	/*
1513	 * v_free_target and v_cache_min control pageout hysteresis.  Note
1514	 * that these are more a measure of the VM cache queue hysteresis
1515	 * then the VM free queue.  Specifically, v_free_target is the
1516	 * high water mark (free+cache pages).
1517	 *
1518	 * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1519	 * low water mark, while v_free_min is the stop.  v_cache_min must
1520	 * be big enough to handle memory needs while the pageout daemon
1521	 * is signalled and run to free more pages.
1522	 */
1523	if (cnt.v_free_count > 6144)
1524		cnt.v_free_target = 4 * cnt.v_free_min + cnt.v_free_reserved;
1525	else
1526		cnt.v_free_target = 2 * cnt.v_free_min + cnt.v_free_reserved;
1527
1528	if (cnt.v_free_count > 2048) {
1529		cnt.v_cache_min = cnt.v_free_target;
1530		cnt.v_cache_max = 2 * cnt.v_cache_min;
1531		cnt.v_inactive_target = (3 * cnt.v_free_target) / 2;
1532	} else {
1533		cnt.v_cache_min = 0;
1534		cnt.v_cache_max = 0;
1535		cnt.v_inactive_target = cnt.v_free_count / 4;
1536	}
1537	if (cnt.v_inactive_target > cnt.v_free_count / 3)
1538		cnt.v_inactive_target = cnt.v_free_count / 3;
1539
1540	/* XXX does not really belong here */
1541	if (vm_page_max_wired == 0)
1542		vm_page_max_wired = cnt.v_free_count / 3;
1543
1544	if (vm_pageout_stats_max == 0)
1545		vm_pageout_stats_max = cnt.v_free_target;
1546
1547	/*
1548	 * Set interval in seconds for stats scan.
1549	 */
1550	if (vm_pageout_stats_interval == 0)
1551		vm_pageout_stats_interval = 5;
1552	if (vm_pageout_full_stats_interval == 0)
1553		vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1554
1555	swap_pager_swap_init();
1556	pass = 0;
1557	/*
1558	 * The pageout daemon is never done, so loop forever.
1559	 */
1560	while (TRUE) {
1561		/*
1562		 * If we have enough free memory, wakeup waiters.  Do
1563		 * not clear vm_pages_needed until we reach our target,
1564		 * otherwise we may be woken up over and over again and
1565		 * waste a lot of cpu.
1566		 */
1567		mtx_lock(&vm_page_queue_free_mtx);
1568		if (vm_pages_needed && !vm_page_count_min()) {
1569			if (!vm_paging_needed())
1570				vm_pages_needed = 0;
1571			wakeup(&cnt.v_free_count);
1572		}
1573		if (vm_pages_needed) {
1574			/*
1575			 * Still not done, take a second pass without waiting
1576			 * (unlimited dirty cleaning), otherwise sleep a bit
1577			 * and try again.
1578			 */
1579			++pass;
1580			if (pass > 1)
1581				msleep(&vm_pages_needed,
1582				    &vm_page_queue_free_mtx, PVM, "psleep",
1583				    hz / 2);
1584		} else {
1585			/*
1586			 * Good enough, sleep & handle stats.  Prime the pass
1587			 * for the next run.
1588			 */
1589			if (pass > 1)
1590				pass = 1;
1591			else
1592				pass = 0;
1593			error = msleep(&vm_pages_needed,
1594			    &vm_page_queue_free_mtx, PVM, "psleep",
1595			    vm_pageout_stats_interval * hz);
1596			if (error && !vm_pages_needed) {
1597				mtx_unlock(&vm_page_queue_free_mtx);
1598				pass = 0;
1599				vm_page_lock_queues();
1600				vm_pageout_page_stats();
1601				vm_page_unlock_queues();
1602				continue;
1603			}
1604		}
1605		if (vm_pages_needed)
1606			cnt.v_pdwakeups++;
1607		mtx_unlock(&vm_page_queue_free_mtx);
1608		vm_pageout_scan(pass);
1609	}
1610}
1611
1612/*
1613 * Unless the free page queue lock is held by the caller, this function
1614 * should be regarded as advisory.  Specifically, the caller should
1615 * not msleep() on &cnt.v_free_count following this function unless
1616 * the free page queue lock is held until the msleep() is performed.
1617 */
1618void
1619pagedaemon_wakeup()
1620{
1621
1622	if (!vm_pages_needed && curthread->td_proc != pageproc) {
1623		vm_pages_needed = 1;
1624		wakeup(&vm_pages_needed);
1625	}
1626}
1627
1628#if !defined(NO_SWAPPING)
1629static void
1630vm_req_vmdaemon(int req)
1631{
1632	static int lastrun = 0;
1633
1634	mtx_lock(&vm_daemon_mtx);
1635	vm_pageout_req_swapout |= req;
1636	if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1637		wakeup(&vm_daemon_needed);
1638		lastrun = ticks;
1639	}
1640	mtx_unlock(&vm_daemon_mtx);
1641}
1642
1643static void
1644vm_daemon()
1645{
1646	struct rlimit rsslim;
1647	struct proc *p;
1648	struct thread *td;
1649	struct vmspace *vm;
1650	int breakout, swapout_flags;
1651
1652	while (TRUE) {
1653		mtx_lock(&vm_daemon_mtx);
1654		msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", 0);
1655		swapout_flags = vm_pageout_req_swapout;
1656		vm_pageout_req_swapout = 0;
1657		mtx_unlock(&vm_daemon_mtx);
1658		if (swapout_flags)
1659			swapout_procs(swapout_flags);
1660
1661		/*
1662		 * scan the processes for exceeding their rlimits or if
1663		 * process is swapped out -- deactivate pages
1664		 */
1665		sx_slock(&allproc_lock);
1666		FOREACH_PROC_IN_SYSTEM(p) {
1667			vm_pindex_t limit, size;
1668
1669			/*
1670			 * if this is a system process or if we have already
1671			 * looked at this process, skip it.
1672			 */
1673			PROC_LOCK(p);
1674			if (p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
1675				PROC_UNLOCK(p);
1676				continue;
1677			}
1678			/*
1679			 * if the process is in a non-running type state,
1680			 * don't touch it.
1681			 */
1682			breakout = 0;
1683			FOREACH_THREAD_IN_PROC(p, td) {
1684				thread_lock(td);
1685				if (!TD_ON_RUNQ(td) &&
1686				    !TD_IS_RUNNING(td) &&
1687				    !TD_IS_SLEEPING(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			vmspace_free(vm);
1723		}
1724		sx_sunlock(&allproc_lock);
1725	}
1726}
1727#endif			/* !defined(NO_SWAPPING) */
1728