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