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