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