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