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