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