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