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