589aad8ce0c616d78634f52ed1c4e35db3a4ec11
[dragonfly.git] / sys / vm / vm_pageout.c
1 /*
2  * (MPSAFE)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
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  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)vm_pageout.c  7.4 (Berkeley) 5/7/91
39  *
40  *
41  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42  * All rights reserved.
43  *
44  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
45  *
46  * Permission to use, copy, modify and distribute this software and
47  * its documentation is hereby granted, provided that both the copyright
48  * notice and this permission notice appear in all copies of the
49  * software, derivative works or modified versions, and any portions
50  * thereof, and that both notices appear in supporting documentation.
51  *
52  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
53  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
54  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
55  *
56  * Carnegie Mellon requests users of this software to return to
57  *
58  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
59  *  School of Computer Science
60  *  Carnegie Mellon University
61  *  Pittsburgh PA 15213-3890
62  *
63  * any improvements or extensions that they make and grant Carnegie the
64  * rights to redistribute these changes.
65  *
66  * $FreeBSD: src/sys/vm/vm_pageout.c,v 1.151.2.15 2002/12/29 18:21:04 dillon Exp $
67  */
68
69 /*
70  *      The proverbial page-out daemon.
71  */
72
73 #include "opt_vm.h"
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/kernel.h>
77 #include <sys/proc.h>
78 #include <sys/kthread.h>
79 #include <sys/resourcevar.h>
80 #include <sys/signalvar.h>
81 #include <sys/vnode.h>
82 #include <sys/vmmeter.h>
83 #include <sys/sysctl.h>
84
85 #include <vm/vm.h>
86 #include <vm/vm_param.h>
87 #include <sys/lock.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_pageout.h>
92 #include <vm/vm_pager.h>
93 #include <vm/swap_pager.h>
94 #include <vm/vm_extern.h>
95
96 #include <sys/thread2.h>
97 #include <vm/vm_page2.h>
98
99 /*
100  * System initialization
101  */
102
103 /* the kernel process "vm_pageout"*/
104 static int vm_pageout_clean (vm_page_t);
105 static int vm_pageout_scan (int pass);
106 static int vm_pageout_free_page_calc (vm_size_t count);
107 struct thread *pagethread;
108
109 #if !defined(NO_SWAPPING)
110 /* the kernel process "vm_daemon"*/
111 static void vm_daemon (void);
112 static struct   thread *vmthread;
113
114 static struct kproc_desc vm_kp = {
115         "vmdaemon",
116         vm_daemon,
117         &vmthread
118 };
119 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp)
120 #endif
121
122
123 int vm_pages_needed=0;          /* Event on which pageout daemon sleeps */
124 int vm_pageout_deficit=0;       /* Estimated number of pages deficit */
125 int vm_pageout_pages_needed=0;  /* flag saying that the pageout daemon needs pages */
126
127 #if !defined(NO_SWAPPING)
128 static int vm_pageout_req_swapout;      /* XXX */
129 static int vm_daemon_needed;
130 #endif
131 static int vm_max_launder = 32;
132 static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
133 static int vm_pageout_full_stats_interval = 0;
134 static int vm_pageout_stats_free_max=0, vm_pageout_algorithm=0;
135 static int defer_swap_pageouts=0;
136 static int disable_swap_pageouts=0;
137
138 #if defined(NO_SWAPPING)
139 static int vm_swap_enabled=0;
140 static int vm_swap_idle_enabled=0;
141 #else
142 static int vm_swap_enabled=1;
143 static int vm_swap_idle_enabled=0;
144 #endif
145
146 SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, pageout_algorithm,
147         CTLFLAG_RW, &vm_pageout_algorithm, 0, "LRU page mgmt");
148
149 SYSCTL_INT(_vm, OID_AUTO, max_launder,
150         CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
151
152 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
153         CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length");
154
155 SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
156         CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan");
157
158 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
159         CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan");
160
161 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_free_max,
162         CTLFLAG_RW, &vm_pageout_stats_free_max, 0, "Not implemented");
163
164 #if defined(NO_SWAPPING)
165 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
166         CTLFLAG_RD, &vm_swap_enabled, 0, "");
167 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
168         CTLFLAG_RD, &vm_swap_idle_enabled, 0, "");
169 #else
170 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
171         CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
172 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
173         CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
174 #endif
175
176 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
177         CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
178
179 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
180         CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
181
182 static int pageout_lock_miss;
183 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
184         CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
185
186 int vm_load;
187 SYSCTL_INT(_vm, OID_AUTO, vm_load,
188         CTLFLAG_RD, &vm_load, 0, "load on the VM system");
189 int vm_load_enable = 1;
190 SYSCTL_INT(_vm, OID_AUTO, vm_load_enable,
191         CTLFLAG_RW, &vm_load_enable, 0, "enable vm_load rate limiting");
192 #ifdef INVARIANTS
193 int vm_load_debug;
194 SYSCTL_INT(_vm, OID_AUTO, vm_load_debug,
195         CTLFLAG_RW, &vm_load_debug, 0, "debug vm_load");
196 #endif
197
198 #define VM_PAGEOUT_PAGE_COUNT 16
199 int vm_pageout_page_count = VM_PAGEOUT_PAGE_COUNT;
200
201 int vm_page_max_wired;          /* XXX max # of wired pages system-wide */
202
203 #if !defined(NO_SWAPPING)
204 typedef void freeer_fcn_t (vm_map_t, vm_object_t, vm_pindex_t, int);
205 static void vm_pageout_map_deactivate_pages (vm_map_t, vm_pindex_t);
206 static freeer_fcn_t vm_pageout_object_deactivate_pages;
207 static void vm_req_vmdaemon (void);
208 #endif
209 static void vm_pageout_page_stats(void);
210
211 /*
212  * Update vm_load to slow down faulting processes.
213  *
214  * SMP races ok.
215  * No requirements.
216  */
217 void
218 vm_fault_ratecheck(void)
219 {
220         if (vm_pages_needed) {
221                 if (vm_load < 1000)
222                         ++vm_load;
223         } else {
224                 if (vm_load > 0)
225                         --vm_load;
226         }
227 }
228
229 /*
230  * vm_pageout_clean:
231  *
232  * Clean the page and remove it from the laundry.  The page must not be
233  * busy on-call.
234  * 
235  * We set the busy bit to cause potential page faults on this page to
236  * block.  Note the careful timing, however, the busy bit isn't set till
237  * late and we cannot do anything that will mess with the page.
238  *
239  * The caller must hold vm_token.
240  */
241 static int
242 vm_pageout_clean(vm_page_t m)
243 {
244         vm_object_t object;
245         vm_page_t mc[2*vm_pageout_page_count];
246         int pageout_count;
247         int ib, is, page_base;
248         vm_pindex_t pindex = m->pindex;
249
250         object = m->object;
251
252         /*
253          * It doesn't cost us anything to pageout OBJT_DEFAULT or OBJT_SWAP
254          * with the new swapper, but we could have serious problems paging
255          * out other object types if there is insufficient memory.  
256          *
257          * Unfortunately, checking free memory here is far too late, so the
258          * check has been moved up a procedural level.
259          */
260
261         /*
262          * Don't mess with the page if it's busy, held, or special
263          */
264         if ((m->hold_count != 0) ||
265             ((m->busy != 0) || (m->flags & (PG_BUSY|PG_UNMANAGED)))) {
266                 return 0;
267         }
268
269         mc[vm_pageout_page_count] = m;
270         pageout_count = 1;
271         page_base = vm_pageout_page_count;
272         ib = 1;
273         is = 1;
274
275         /*
276          * Scan object for clusterable pages.
277          *
278          * We can cluster ONLY if: ->> the page is NOT
279          * clean, wired, busy, held, or mapped into a
280          * buffer, and one of the following:
281          * 1) The page is inactive, or a seldom used
282          *    active page.
283          * -or-
284          * 2) we force the issue.
285          *
286          * During heavy mmap/modification loads the pageout
287          * daemon can really fragment the underlying file
288          * due to flushing pages out of order and not trying
289          * align the clusters (which leave sporatic out-of-order
290          * holes).  To solve this problem we do the reverse scan
291          * first and attempt to align our cluster, then do a 
292          * forward scan if room remains.
293          */
294
295         vm_object_hold(object);
296 more:
297         while (ib && pageout_count < vm_pageout_page_count) {
298                 vm_page_t p;
299
300                 if (ib > pindex) {
301                         ib = 0;
302                         break;
303                 }
304
305                 if ((p = vm_page_lookup(object, pindex - ib)) == NULL) {
306                         ib = 0;
307                         break;
308                 }
309                 if (((p->queue - p->pc) == PQ_CACHE) ||
310                     (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) {
311                         ib = 0;
312                         break;
313                 }
314                 vm_page_test_dirty(p);
315                 if ((p->dirty & p->valid) == 0 ||
316                     p->queue != PQ_INACTIVE ||
317                     p->wire_count != 0 ||       /* may be held by buf cache */
318                     p->hold_count != 0) {       /* may be undergoing I/O */
319                         ib = 0;
320                         break;
321                 }
322                 mc[--page_base] = p;
323                 ++pageout_count;
324                 ++ib;
325                 /*
326                  * alignment boundry, stop here and switch directions.  Do
327                  * not clear ib.
328                  */
329                 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0)
330                         break;
331         }
332
333         while (pageout_count < vm_pageout_page_count && 
334             pindex + is < object->size) {
335                 vm_page_t p;
336
337                 if ((p = vm_page_lookup(object, pindex + is)) == NULL)
338                         break;
339                 if (((p->queue - p->pc) == PQ_CACHE) ||
340                     (p->flags & (PG_BUSY|PG_UNMANAGED)) || p->busy) {
341                         break;
342                 }
343                 vm_page_test_dirty(p);
344                 if ((p->dirty & p->valid) == 0 ||
345                     p->queue != PQ_INACTIVE ||
346                     p->wire_count != 0 ||       /* may be held by buf cache */
347                     p->hold_count != 0) {       /* may be undergoing I/O */
348                         break;
349                 }
350                 mc[page_base + pageout_count] = p;
351                 ++pageout_count;
352                 ++is;
353         }
354
355         /*
356          * If we exhausted our forward scan, continue with the reverse scan
357          * when possible, even past a page boundry.  This catches boundry
358          * conditions.
359          */
360         if (ib && pageout_count < vm_pageout_page_count)
361                 goto more;
362
363         vm_object_drop(object);
364
365         /*
366          * we allow reads during pageouts...
367          */
368         return vm_pageout_flush(&mc[page_base], pageout_count, 0);
369 }
370
371 /*
372  * vm_pageout_flush() - launder the given pages
373  *
374  *      The given pages are laundered.  Note that we setup for the start of
375  *      I/O ( i.e. busy the page ), mark it read-only, and bump the object
376  *      reference count all in here rather then in the parent.  If we want
377  *      the parent to do more sophisticated things we may have to change
378  *      the ordering.
379  *
380  * The caller must hold vm_token.
381  */
382 int
383 vm_pageout_flush(vm_page_t *mc, int count, int flags)
384 {
385         vm_object_t object;
386         int pageout_status[count];
387         int numpagedout = 0;
388         int i;
389
390         ASSERT_LWKT_TOKEN_HELD(&vm_token);
391
392         /*
393          * Initiate I/O.  Bump the vm_page_t->busy counter.
394          */
395         for (i = 0; i < count; i++) {
396                 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL, ("vm_pageout_flush page %p index %d/%d: partially invalid page", mc[i], i, count));
397                 vm_page_io_start(mc[i]);
398         }
399
400         /*
401          * We must make the pages read-only.  This will also force the
402          * modified bit in the related pmaps to be cleared.  The pager
403          * cannot clear the bit for us since the I/O completion code
404          * typically runs from an interrupt.  The act of making the page
405          * read-only handles the case for us.
406          */
407         for (i = 0; i < count; i++) {
408                 vm_page_protect(mc[i], VM_PROT_READ);
409         }
410
411         object = mc[0]->object;
412         vm_object_pip_add(object, count);
413
414         vm_pager_put_pages(object, mc, count,
415             (flags | ((object == &kernel_object) ? VM_PAGER_PUT_SYNC : 0)),
416             pageout_status);
417
418         for (i = 0; i < count; i++) {
419                 vm_page_t mt = mc[i];
420
421                 switch (pageout_status[i]) {
422                 case VM_PAGER_OK:
423                         numpagedout++;
424                         break;
425                 case VM_PAGER_PEND:
426                         numpagedout++;
427                         break;
428                 case VM_PAGER_BAD:
429                         /*
430                          * Page outside of range of object. Right now we
431                          * essentially lose the changes by pretending it
432                          * worked.
433                          */
434                         pmap_clear_modify(mt);
435                         vm_page_undirty(mt);
436                         break;
437                 case VM_PAGER_ERROR:
438                 case VM_PAGER_FAIL:
439                         /*
440                          * A page typically cannot be paged out when we
441                          * have run out of swap.  We leave the page
442                          * marked inactive and will try to page it out
443                          * again later.
444                          *
445                          * Starvation of the active page list is used to
446                          * determine when the system is massively memory
447                          * starved.
448                          */
449                         break;
450                 case VM_PAGER_AGAIN:
451                         break;
452                 }
453
454                 /*
455                  * If the operation is still going, leave the page busy to
456                  * block all other accesses. Also, leave the paging in
457                  * progress indicator set so that we don't attempt an object
458                  * collapse.
459                  *
460                  * For any pages which have completed synchronously, 
461                  * deactivate the page if we are under a severe deficit.
462                  * Do not try to enter them into the cache, though, they
463                  * might still be read-heavy.
464                  */
465                 if (pageout_status[i] != VM_PAGER_PEND) {
466                         if (vm_page_count_severe())
467                                 vm_page_deactivate(mt);
468 #if 0
469                         if (!vm_page_count_severe() || !vm_page_try_to_cache(mt))
470                                 vm_page_protect(mt, VM_PROT_READ);
471 #endif
472                         vm_page_io_finish(mt);
473                         vm_object_pip_wakeup(object);
474                 }
475         }
476         return numpagedout;
477 }
478
479 #if !defined(NO_SWAPPING)
480 /*
481  *      vm_pageout_object_deactivate_pages
482  *
483  *      deactivate enough pages to satisfy the inactive target
484  *      requirements or if vm_page_proc_limit is set, then
485  *      deactivate all of the pages in the object and its
486  *      backing_objects.
487  *
488  * The map must be locked.
489  * The caller must hold vm_token.
490  * The caller must hold the vm_object.
491  */
492 static int vm_pageout_object_deactivate_pages_callback(vm_page_t, void *);
493
494 static void
495 vm_pageout_object_deactivate_pages(vm_map_t map, vm_object_t object,
496                                    vm_pindex_t desired, int map_remove_only)
497 {
498         struct rb_vm_page_scan_info info;
499         vm_object_t tmp;
500         int remove_mode;
501
502         while (object) {
503                 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
504                         return;
505
506                 vm_object_hold(object);
507
508                 if (object->type == OBJT_DEVICE || object->type == OBJT_PHYS) {
509                         vm_object_drop(object);
510                         return;
511                 }
512                 if (object->paging_in_progress) {
513                         vm_object_drop(object);
514                         return;
515                 }
516
517                 remove_mode = map_remove_only;
518                 if (object->shadow_count > 1)
519                         remove_mode = 1;
520
521                 /*
522                  * scan the objects entire memory queue.  spl protection is
523                  * required to avoid an interrupt unbusy/free race against
524                  * our busy check.
525                  */
526                 crit_enter();
527                 info.limit = remove_mode;
528                 info.map = map;
529                 info.desired = desired;
530                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
531                                 vm_pageout_object_deactivate_pages_callback,
532                                 &info
533                 );
534                 crit_exit();
535                 tmp = object->backing_object;
536                 vm_object_drop(object);
537                 object = tmp;
538         }
539 }
540
541 /*
542  * The caller must hold vm_token.
543  * The caller must hold the vm_object.
544  */
545 static int
546 vm_pageout_object_deactivate_pages_callback(vm_page_t p, void *data)
547 {
548         struct rb_vm_page_scan_info *info = data;
549         int actcount;
550
551         if (pmap_resident_count(vm_map_pmap(info->map)) <= info->desired) {
552                 return(-1);
553         }
554         mycpu->gd_cnt.v_pdpages++;
555         if (p->wire_count != 0 || p->hold_count != 0 || p->busy != 0 ||
556             (p->flags & (PG_BUSY|PG_UNMANAGED)) ||
557             !pmap_page_exists_quick(vm_map_pmap(info->map), p)) {
558                 return(0);
559         }
560
561         actcount = pmap_ts_referenced(p);
562         if (actcount) {
563                 vm_page_flag_set(p, PG_REFERENCED);
564         } else if (p->flags & PG_REFERENCED) {
565                 actcount = 1;
566         }
567
568         if ((p->queue != PQ_ACTIVE) &&
569                 (p->flags & PG_REFERENCED)) {
570                 vm_page_activate(p);
571                 p->act_count += actcount;
572                 vm_page_flag_clear(p, PG_REFERENCED);
573         } else if (p->queue == PQ_ACTIVE) {
574                 if ((p->flags & PG_REFERENCED) == 0) {
575                         p->act_count -= min(p->act_count, ACT_DECLINE);
576                         if (!info->limit && (vm_pageout_algorithm || (p->act_count == 0))) {
577                                 vm_page_busy(p);
578                                 vm_page_protect(p, VM_PROT_NONE);
579                                 vm_page_deactivate(p);
580                                 vm_page_wakeup(p);
581                         } else {
582                                 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, p, pageq);
583                                 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, p, pageq);
584                         }
585                 } else {
586                         vm_page_activate(p);
587                         vm_page_flag_clear(p, PG_REFERENCED);
588                         if (p->act_count < (ACT_MAX - ACT_ADVANCE))
589                                 p->act_count += ACT_ADVANCE;
590                         TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, p, pageq);
591                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, p, pageq);
592                 }
593         } else if (p->queue == PQ_INACTIVE) {
594                 vm_page_busy(p);
595                 vm_page_protect(p, VM_PROT_NONE);
596                 vm_page_wakeup(p);
597         }
598         return(0);
599 }
600
601 /*
602  * Deactivate some number of pages in a map, try to do it fairly, but
603  * that is really hard to do.
604  *
605  * The caller must hold vm_token.
606  */
607 static void
608 vm_pageout_map_deactivate_pages(vm_map_t map, vm_pindex_t desired)
609 {
610         vm_map_entry_t tmpe;
611         vm_object_t obj, bigobj;
612         int nothingwired;
613
614         if (lockmgr(&map->lock, LK_EXCLUSIVE | LK_NOWAIT)) {
615                 return;
616         }
617
618         bigobj = NULL;
619         nothingwired = TRUE;
620
621         /*
622          * first, search out the biggest object, and try to free pages from
623          * that.
624          */
625         tmpe = map->header.next;
626         while (tmpe != &map->header) {
627                 switch(tmpe->maptype) {
628                 case VM_MAPTYPE_NORMAL:
629                 case VM_MAPTYPE_VPAGETABLE:
630                         obj = tmpe->object.vm_object;
631                         if ((obj != NULL) && (obj->shadow_count <= 1) &&
632                                 ((bigobj == NULL) ||
633                                  (bigobj->resident_page_count < obj->resident_page_count))) {
634                                 bigobj = obj;
635                         }
636                         break;
637                 default:
638                         break;
639                 }
640                 if (tmpe->wired_count > 0)
641                         nothingwired = FALSE;
642                 tmpe = tmpe->next;
643         }
644
645         if (bigobj) 
646                 vm_pageout_object_deactivate_pages(map, bigobj, desired, 0);
647
648         /*
649          * Next, hunt around for other pages to deactivate.  We actually
650          * do this search sort of wrong -- .text first is not the best idea.
651          */
652         tmpe = map->header.next;
653         while (tmpe != &map->header) {
654                 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
655                         break;
656                 switch(tmpe->maptype) {
657                 case VM_MAPTYPE_NORMAL:
658                 case VM_MAPTYPE_VPAGETABLE:
659                         obj = tmpe->object.vm_object;
660                         if (obj) 
661                                 vm_pageout_object_deactivate_pages(map, obj, desired, 0);
662                         break;
663                 default:
664                         break;
665                 }
666                 tmpe = tmpe->next;
667         };
668
669         /*
670          * Remove all mappings if a process is swapped out, this will free page
671          * table pages.
672          */
673         if (desired == 0 && nothingwired)
674                 pmap_remove(vm_map_pmap(map),
675                             VM_MIN_USER_ADDRESS, VM_MAX_USER_ADDRESS);
676         vm_map_unlock(map);
677 }
678 #endif
679
680 /*
681  * Don't try to be fancy - being fancy can lead to vnode deadlocks.   We
682  * only do it for OBJT_DEFAULT and OBJT_SWAP objects which we know can
683  * be trivially freed.
684  *
685  * The caller must hold vm_token.
686  *
687  * WARNING: vm_object_reference() can block.
688  */
689 static void
690 vm_pageout_page_free(vm_page_t m) 
691 {
692         vm_object_t object = m->object;
693         int type = object->type;
694
695         vm_page_busy(m);
696         if (type == OBJT_SWAP || type == OBJT_DEFAULT)
697                 vm_object_reference(object);
698         vm_page_protect(m, VM_PROT_NONE);
699         vm_page_free(m);
700         if (type == OBJT_SWAP || type == OBJT_DEFAULT)
701                 vm_object_deallocate(object);
702 }
703
704 /*
705  * vm_pageout_scan does the dirty work for the pageout daemon.
706  */
707 struct vm_pageout_scan_info {
708         struct proc *bigproc;
709         vm_offset_t bigsize;
710 };
711
712 static int vm_pageout_scan_callback(struct proc *p, void *data);
713
714 /*
715  * The caller must hold vm_token.
716  */
717 static int
718 vm_pageout_scan(int pass)
719 {
720         struct vm_pageout_scan_info info;
721         vm_page_t m, next;
722         struct vm_page marker;
723         struct vnode *vpfailed;         /* warning, allowed to be stale */
724         int maxscan, pcount;
725         int recycle_count;
726         int inactive_shortage, active_shortage;
727         int inactive_original_shortage;
728         vm_object_t object;
729         int actcount;
730         int vnodes_skipped = 0;
731         int maxlaunder;
732
733         /*
734          * Do whatever cleanup that the pmap code can.
735          */
736         pmap_collect();
737
738         /*
739          * Calculate our target for the number of free+cache pages we
740          * want to get to.  This is higher then the number that causes
741          * allocations to stall (severe) in order to provide hysteresis,
742          * and if we don't make it all the way but get to the minimum
743          * we're happy.
744          */
745         inactive_shortage = vm_paging_target() + vm_pageout_deficit;
746         inactive_original_shortage = inactive_shortage;
747         vm_pageout_deficit = 0;
748
749         /*
750          * Initialize our marker
751          */
752         bzero(&marker, sizeof(marker));
753         marker.flags = PG_BUSY | PG_FICTITIOUS | PG_MARKER;
754         marker.queue = PQ_INACTIVE;
755         marker.wire_count = 1;
756
757         /*
758          * Start scanning the inactive queue for pages we can move to the
759          * cache or free.  The scan will stop when the target is reached or
760          * we have scanned the entire inactive queue.  Note that m->act_count
761          * is not used to form decisions for the inactive queue, only for the
762          * active queue.
763          *
764          * maxlaunder limits the number of dirty pages we flush per scan.
765          * For most systems a smaller value (16 or 32) is more robust under
766          * extreme memory and disk pressure because any unnecessary writes
767          * to disk can result in extreme performance degredation.  However,
768          * systems with excessive dirty pages (especially when MAP_NOSYNC is
769          * used) will die horribly with limited laundering.  If the pageout
770          * daemon cannot clean enough pages in the first pass, we let it go
771          * all out in succeeding passes.
772          */
773         if ((maxlaunder = vm_max_launder) <= 1)
774                 maxlaunder = 1;
775         if (pass)
776                 maxlaunder = 10000;
777
778         /*
779          * We will generally be in a critical section throughout the 
780          * scan, but we can release it temporarily when we are sitting on a
781          * non-busy page without fear.  this is required to prevent an
782          * interrupt from unbusying or freeing a page prior to our busy
783          * check, leaving us on the wrong queue or checking the wrong
784          * page.
785          */
786         crit_enter();
787 rescan0:
788         vpfailed = NULL;
789         maxscan = vmstats.v_inactive_count;
790         for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
791              m != NULL && maxscan-- > 0 && inactive_shortage > 0;
792              m = next
793          ) {
794                 mycpu->gd_cnt.v_pdpages++;
795
796                 /*
797                  * Give interrupts a chance
798                  */
799                 crit_exit();
800                 crit_enter();
801
802                 /*
803                  * It's easier for some of the conditions below to just loop
804                  * and catch queue changes here rather then check everywhere
805                  * else.
806                  */
807                 if (m->queue != PQ_INACTIVE)
808                         goto rescan0;
809                 next = TAILQ_NEXT(m, pageq);
810
811                 /*
812                  * skip marker pages
813                  */
814                 if (m->flags & PG_MARKER)
815                         continue;
816
817                 /*
818                  * A held page may be undergoing I/O, so skip it.
819                  */
820                 if (m->hold_count) {
821                         TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
822                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
823                         ++vm_swapcache_inactive_heuristic;
824                         continue;
825                 }
826
827                 /*
828                  * Dont mess with busy pages, keep in the front of the
829                  * queue, most likely are being paged out.
830                  */
831                 if (m->busy || (m->flags & PG_BUSY)) {
832                         continue;
833                 }
834
835                 if (m->object->ref_count == 0) {
836                         /*
837                          * If the object is not being used, we ignore previous 
838                          * references.
839                          */
840                         vm_page_flag_clear(m, PG_REFERENCED);
841                         pmap_clear_reference(m);
842
843                 } else if (((m->flags & PG_REFERENCED) == 0) &&
844                             (actcount = pmap_ts_referenced(m))) {
845                         /*
846                          * Otherwise, if the page has been referenced while 
847                          * in the inactive queue, we bump the "activation
848                          * count" upwards, making it less likely that the
849                          * page will be added back to the inactive queue
850                          * prematurely again.  Here we check the page tables
851                          * (or emulated bits, if any), given the upper level
852                          * VM system not knowing anything about existing 
853                          * references.
854                          */
855                         vm_page_activate(m);
856                         m->act_count += (actcount + ACT_ADVANCE);
857                         continue;
858                 }
859
860                 /*
861                  * If the upper level VM system knows about any page 
862                  * references, we activate the page.  We also set the 
863                  * "activation count" higher than normal so that we will less 
864                  * likely place pages back onto the inactive queue again.
865                  */
866                 if ((m->flags & PG_REFERENCED) != 0) {
867                         vm_page_flag_clear(m, PG_REFERENCED);
868                         actcount = pmap_ts_referenced(m);
869                         vm_page_activate(m);
870                         m->act_count += (actcount + ACT_ADVANCE + 1);
871                         continue;
872                 }
873
874                 /*
875                  * If the upper level VM system doesn't know anything about 
876                  * the page being dirty, we have to check for it again.  As 
877                  * far as the VM code knows, any partially dirty pages are 
878                  * fully dirty.
879                  *
880                  * Pages marked PG_WRITEABLE may be mapped into the user
881                  * address space of a process running on another cpu.  A
882                  * user process (without holding the MP lock) running on
883                  * another cpu may be able to touch the page while we are
884                  * trying to remove it.  vm_page_cache() will handle this
885                  * case for us.
886                  */
887                 if (m->dirty == 0) {
888                         vm_page_test_dirty(m);
889                 } else {
890                         vm_page_dirty(m);
891                 }
892
893                 if (m->valid == 0) {
894                         /*
895                          * Invalid pages can be easily freed
896                          */
897                         vm_pageout_page_free(m);
898                         mycpu->gd_cnt.v_dfree++;
899                         --inactive_shortage;
900                 } else if (m->dirty == 0) {
901                         /*
902                          * Clean pages can be placed onto the cache queue.
903                          * This effectively frees them.
904                          */
905                         vm_page_busy(m);
906                         vm_page_cache(m);
907                         --inactive_shortage;
908                 } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
909                         /*
910                          * Dirty pages need to be paged out, but flushing
911                          * a page is extremely expensive verses freeing
912                          * a clean page.  Rather then artificially limiting
913                          * the number of pages we can flush, we instead give
914                          * dirty pages extra priority on the inactive queue
915                          * by forcing them to be cycled through the queue
916                          * twice before being flushed, after which the 
917                          * (now clean) page will cycle through once more
918                          * before being freed.  This significantly extends
919                          * the thrash point for a heavily loaded machine.
920                          */
921                         vm_page_flag_set(m, PG_WINATCFLS);
922                         TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
923                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
924                         ++vm_swapcache_inactive_heuristic;
925                 } else if (maxlaunder > 0) {
926                         /*
927                          * We always want to try to flush some dirty pages if
928                          * we encounter them, to keep the system stable.
929                          * Normally this number is small, but under extreme
930                          * pressure where there are insufficient clean pages
931                          * on the inactive queue, we may have to go all out.
932                          */
933                         int swap_pageouts_ok;
934                         struct vnode *vp = NULL;
935
936                         object = m->object;
937
938                         if ((object->type != OBJT_SWAP) && (object->type != OBJT_DEFAULT)) {
939                                 swap_pageouts_ok = 1;
940                         } else {
941                                 swap_pageouts_ok = !(defer_swap_pageouts || disable_swap_pageouts);
942                                 swap_pageouts_ok |= (!disable_swap_pageouts && defer_swap_pageouts &&
943                                 vm_page_count_min(0));
944                                                                                 
945                         }
946
947                         /*
948                          * We don't bother paging objects that are "dead".  
949                          * Those objects are in a "rundown" state.
950                          */
951                         if (!swap_pageouts_ok || (object->flags & OBJ_DEAD)) {
952                                 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
953                                 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
954                                 ++vm_swapcache_inactive_heuristic;
955                                 continue;
956                         }
957
958                         /*
959                          * The object is already known NOT to be dead.   It
960                          * is possible for the vget() to block the whole
961                          * pageout daemon, but the new low-memory handling
962                          * code should prevent it.
963                          *
964                          * The previous code skipped locked vnodes and, worse,
965                          * reordered pages in the queue.  This results in
966                          * completely non-deterministic operation because,
967                          * quite often, a vm_fault has initiated an I/O and
968                          * is holding a locked vnode at just the point where
969                          * the pageout daemon is woken up.
970                          *
971                          * We can't wait forever for the vnode lock, we might
972                          * deadlock due to a vn_read() getting stuck in
973                          * vm_wait while holding this vnode.  We skip the 
974                          * vnode if we can't get it in a reasonable amount
975                          * of time.
976                          *
977                          * vpfailed is used to (try to) avoid the case where
978                          * a large number of pages are associated with a
979                          * locked vnode, which could cause the pageout daemon
980                          * to stall for an excessive amount of time.
981                          */
982                         if (object->type == OBJT_VNODE) {
983                                 int flags;
984
985                                 vp = object->handle;
986                                 flags = LK_EXCLUSIVE | LK_NOOBJ;
987                                 if (vp == vpfailed)
988                                         flags |= LK_NOWAIT;
989                                 else
990                                         flags |= LK_TIMELOCK;
991                                 if (vget(vp, flags) != 0) {
992                                         vpfailed = vp;
993                                         ++pageout_lock_miss;
994                                         if (object->flags & OBJ_MIGHTBEDIRTY)
995                                                     vnodes_skipped++;
996                                         continue;
997                                 }
998
999                                 /*
1000                                  * The page might have been moved to another
1001                                  * queue during potential blocking in vget()
1002                                  * above.  The page might have been freed and
1003                                  * reused for another vnode.  The object might
1004                                  * have been reused for another vnode.
1005                                  */
1006                                 if (m->queue != PQ_INACTIVE ||
1007                                     m->object != object ||
1008                                     object->handle != vp) {
1009                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1010                                                 vnodes_skipped++;
1011                                         vput(vp);
1012                                         continue;
1013                                 }
1014         
1015                                 /*
1016                                  * The page may have been busied during the
1017                                  * blocking in vput();  We don't move the
1018                                  * page back onto the end of the queue so that
1019                                  * statistics are more correct if we don't.
1020                                  */
1021                                 if (m->busy || (m->flags & PG_BUSY)) {
1022                                         vput(vp);
1023                                         continue;
1024                                 }
1025
1026                                 /*
1027                                  * If the page has become held it might
1028                                  * be undergoing I/O, so skip it
1029                                  */
1030                                 if (m->hold_count) {
1031                                         TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1032                                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1033                                         ++vm_swapcache_inactive_heuristic;
1034                                         if (object->flags & OBJ_MIGHTBEDIRTY)
1035                                                 vnodes_skipped++;
1036                                         vput(vp);
1037                                         continue;
1038                                 }
1039                         }
1040
1041                         /*
1042                          * If a page is dirty, then it is either being washed
1043                          * (but not yet cleaned) or it is still in the
1044                          * laundry.  If it is still in the laundry, then we
1045                          * start the cleaning operation. 
1046                          *
1047                          * This operation may cluster, invalidating the 'next'
1048                          * pointer.  To prevent an inordinate number of
1049                          * restarts we use our marker to remember our place.
1050                          *
1051                          * decrement inactive_shortage on success to account
1052                          * for the (future) cleaned page.  Otherwise we
1053                          * could wind up laundering or cleaning too many
1054                          * pages.
1055                          */
1056                         TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE].pl, m, &marker, pageq);
1057                         if (vm_pageout_clean(m) != 0) {
1058                                 --inactive_shortage;
1059                                 --maxlaunder;
1060                         }
1061                         next = TAILQ_NEXT(&marker, pageq);
1062                         TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE].pl, &marker, pageq);
1063                         if (vp != NULL)
1064                                 vput(vp);
1065                 }
1066         }
1067
1068         /*
1069          * We want to move pages from the active queue to the inactive
1070          * queue to get the inactive queue to the inactive target.  If
1071          * we still have a page shortage from above we try to directly free
1072          * clean pages instead of moving them.
1073          *
1074          * If we do still have a shortage we keep track of the number of
1075          * pages we free or cache (recycle_count) as a measure of thrashing
1076          * between the active and inactive queues.
1077          *
1078          * If we were able to completely satisfy the free+cache targets
1079          * from the inactive pool we limit the number of pages we move
1080          * from the active pool to the inactive pool to 2x the pages we
1081          * had removed from the inactive pool (with a minimum of 1/5 the
1082          * inactive target).  If we were not able to completely satisfy
1083          * the free+cache targets we go for the whole target aggressively.
1084          *
1085          * NOTE: Both variables can end up negative.
1086          * NOTE: We are still in a critical section.
1087          */
1088         active_shortage = vmstats.v_inactive_target - vmstats.v_inactive_count;
1089         if (inactive_original_shortage < vmstats.v_inactive_target / 10)
1090                 inactive_original_shortage = vmstats.v_inactive_target / 10;
1091         if (inactive_shortage <= 0 &&
1092             active_shortage > inactive_original_shortage * 2) {
1093                 active_shortage = inactive_original_shortage * 2;
1094         }
1095
1096         pcount = vmstats.v_active_count;
1097         recycle_count = 0;
1098         m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1099
1100         while ((m != NULL) && (pcount-- > 0) &&
1101                (inactive_shortage > 0 || active_shortage > 0)
1102         ) {
1103                 /*
1104                  * Give interrupts a chance.
1105                  */
1106                 crit_exit();
1107                 crit_enter();
1108
1109                 /*
1110                  * If the page was ripped out from under us, just stop.
1111                  */
1112                 if (m->queue != PQ_ACTIVE)
1113                         break;
1114                 next = TAILQ_NEXT(m, pageq);
1115
1116                 /*
1117                  * Don't deactivate pages that are busy.
1118                  */
1119                 if ((m->busy != 0) ||
1120                     (m->flags & PG_BUSY) ||
1121                     (m->hold_count != 0)) {
1122                         TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1123                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1124                         m = next;
1125                         continue;
1126                 }
1127
1128                 /*
1129                  * The count for pagedaemon pages is done after checking the
1130                  * page for eligibility...
1131                  */
1132                 mycpu->gd_cnt.v_pdpages++;
1133
1134                 /*
1135                  * Check to see "how much" the page has been used and clear
1136                  * the tracking access bits.  If the object has no references
1137                  * don't bother paying the expense.
1138                  */
1139                 actcount = 0;
1140                 if (m->object->ref_count != 0) {
1141                         if (m->flags & PG_REFERENCED)
1142                                 ++actcount;
1143                         actcount += pmap_ts_referenced(m);
1144                         if (actcount) {
1145                                 m->act_count += ACT_ADVANCE + actcount;
1146                                 if (m->act_count > ACT_MAX)
1147                                         m->act_count = ACT_MAX;
1148                         }
1149                 }
1150                 vm_page_flag_clear(m, PG_REFERENCED);
1151
1152                 /*
1153                  * actcount is only valid if the object ref_count is non-zero.
1154                  */
1155                 if (actcount && m->object->ref_count != 0) {
1156                         TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1157                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1158                 } else {
1159                         m->act_count -= min(m->act_count, ACT_DECLINE);
1160                         if (vm_pageout_algorithm ||
1161                             m->object->ref_count == 0 ||
1162                             m->act_count < pass + 1
1163                         ) {
1164                                 /*
1165                                  * Deactivate the page.  If we had a
1166                                  * shortage from our inactive scan try to
1167                                  * free (cache) the page instead.
1168                                  *
1169                                  * Don't just blindly cache the page if
1170                                  * we do not have a shortage from the
1171                                  * inactive scan, that could lead to
1172                                  * gigabytes being moved.
1173                                  */
1174                                 --active_shortage;
1175                                 if (inactive_shortage > 0 ||
1176                                     m->object->ref_count == 0) {
1177                                         if (inactive_shortage > 0)
1178                                                 ++recycle_count;
1179                                         vm_page_busy(m);
1180                                         vm_page_protect(m, VM_PROT_NONE);
1181                                         if (m->dirty == 0 &&
1182                                             inactive_shortage > 0) {
1183                                                 --inactive_shortage;
1184                                                 vm_page_cache(m);
1185                                         } else {
1186                                                 vm_page_deactivate(m);
1187                                                 vm_page_wakeup(m);
1188                                         }
1189                                 } else {
1190                                         vm_page_deactivate(m);
1191                                 }
1192                         } else {
1193                                 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1194                                 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1195                         }
1196                 }
1197                 m = next;
1198         }
1199
1200         /*
1201          * The number of actually free pages can drop down to v_free_reserved,
1202          * we try to build the free count back above v_free_min.  Note that
1203          * vm_paging_needed() also returns TRUE if v_free_count is not at
1204          * least v_free_min so that is the minimum we must build the free
1205          * count to.
1206          *
1207          * We use a slightly higher target to improve hysteresis,
1208          * ((v_free_target + v_free_min) / 2).  Since v_free_target
1209          * is usually the same as v_cache_min this maintains about
1210          * half the pages in the free queue as are in the cache queue,
1211          * providing pretty good pipelining for pageout operation.
1212          *
1213          * The system operator can manipulate vm.v_cache_min and
1214          * vm.v_free_target to tune the pageout demon.  Be sure
1215          * to keep vm.v_free_min < vm.v_free_target.
1216          *
1217          * Note that the original paging target is to get at least
1218          * (free_min + cache_min) into (free + cache).  The slightly
1219          * higher target will shift additional pages from cache to free
1220          * without effecting the original paging target in order to
1221          * maintain better hysteresis and not have the free count always
1222          * be dead-on v_free_min.
1223          *
1224          * NOTE: we are still in a critical section.
1225          *
1226          * Pages moved from PQ_CACHE to totally free are not counted in the
1227          * pages_freed counter.
1228          */
1229         while (vmstats.v_free_count <
1230                (vmstats.v_free_min + vmstats.v_free_target) / 2) {
1231                 /*
1232                  *
1233                  */
1234                 static int cache_rover = 0;
1235                 m = vm_page_list_find(PQ_CACHE, cache_rover, FALSE);
1236                 if (m == NULL)
1237                         break;
1238                 if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || 
1239                     m->busy || 
1240                     m->hold_count || 
1241                     m->wire_count) {
1242 #ifdef INVARIANTS
1243                         kprintf("Warning: busy page %p found in cache\n", m);
1244 #endif
1245                         vm_page_deactivate(m);
1246                         continue;
1247                 }
1248                 KKASSERT((m->flags & PG_MAPPED) == 0);
1249                 KKASSERT(m->dirty == 0);
1250                 cache_rover = (cache_rover + PQ_PRIME2) & PQ_L2_MASK;
1251                 vm_pageout_page_free(m);
1252                 mycpu->gd_cnt.v_dfree++;
1253         }
1254
1255         crit_exit();
1256
1257 #if !defined(NO_SWAPPING)
1258         /*
1259          * Idle process swapout -- run once per second.
1260          */
1261         if (vm_swap_idle_enabled) {
1262                 static long lsec;
1263                 if (time_second != lsec) {
1264                         vm_pageout_req_swapout |= VM_SWAP_IDLE;
1265                         vm_req_vmdaemon();
1266                         lsec = time_second;
1267                 }
1268         }
1269 #endif
1270                 
1271         /*
1272          * If we didn't get enough free pages, and we have skipped a vnode
1273          * in a writeable object, wakeup the sync daemon.  And kick swapout
1274          * if we did not get enough free pages.
1275          */
1276         if (vm_paging_target() > 0) {
1277                 if (vnodes_skipped && vm_page_count_min(0))
1278                         speedup_syncer();
1279 #if !defined(NO_SWAPPING)
1280                 if (vm_swap_enabled && vm_page_count_target()) {
1281                         vm_req_vmdaemon();
1282                         vm_pageout_req_swapout |= VM_SWAP_NORMAL;
1283                 }
1284 #endif
1285         }
1286
1287         /*
1288          * Handle catastrophic conditions.  Under good conditions we should
1289          * be at the target, well beyond our minimum.  If we could not even
1290          * reach our minimum the system is under heavy stress.
1291          *
1292          * Determine whether we have run out of memory.  This occurs when
1293          * swap_pager_full is TRUE and the only pages left in the page
1294          * queues are dirty.  We will still likely have page shortages.
1295          *
1296          * - swap_pager_full is set if insufficient swap was
1297          *   available to satisfy a requested pageout.
1298          *
1299          * - the inactive queue is bloated (4 x size of active queue),
1300          *   meaning it is unable to get rid of dirty pages and.
1301          *
1302          * - vm_page_count_min() without counting pages recycled from the
1303          *   active queue (recycle_count) means we could not recover
1304          *   enough pages to meet bare minimum needs.  This test only
1305          *   works if the inactive queue is bloated.
1306          *
1307          * - due to a positive inactive_shortage we shifted the remaining
1308          *   dirty pages from the active queue to the inactive queue
1309          *   trying to find clean ones to free.
1310          */
1311         if (swap_pager_full && vm_page_count_min(recycle_count))
1312                 kprintf("Warning: system low on memory+swap!\n");
1313         if (swap_pager_full && vm_page_count_min(recycle_count) &&
1314             vmstats.v_inactive_count > vmstats.v_active_count * 4 &&
1315             inactive_shortage > 0) {
1316                 /*
1317                  * Kill something.
1318                  */
1319                 info.bigproc = NULL;
1320                 info.bigsize = 0;
1321                 allproc_scan(vm_pageout_scan_callback, &info);
1322                 if (info.bigproc != NULL) {
1323                         killproc(info.bigproc, "out of swap space");
1324                         info.bigproc->p_nice = PRIO_MIN;
1325                         info.bigproc->p_usched->resetpriority(
1326                                 FIRST_LWP_IN_PROC(info.bigproc));
1327                         wakeup(&vmstats.v_free_count);
1328                         PRELE(info.bigproc);
1329                 }
1330         }
1331         return(inactive_shortage);
1332 }
1333
1334 /*
1335  * The caller must hold vm_token and proc_token.
1336  */
1337 static int
1338 vm_pageout_scan_callback(struct proc *p, void *data)
1339 {
1340         struct vm_pageout_scan_info *info = data;
1341         vm_offset_t size;
1342
1343         /*
1344          * Never kill system processes or init.  If we have configured swap
1345          * then try to avoid killing low-numbered pids.
1346          */
1347         if ((p->p_flag & P_SYSTEM) || (p->p_pid == 1) ||
1348             ((p->p_pid < 48) && (vm_swap_size != 0))) {
1349                 return (0);
1350         }
1351
1352         /*
1353          * if the process is in a non-running type state,
1354          * don't touch it.
1355          */
1356         if (p->p_stat != SACTIVE && p->p_stat != SSTOP)
1357                 return (0);
1358
1359         /*
1360          * Get the approximate process size.  Note that anonymous pages
1361          * with backing swap will be counted twice, but there should not
1362          * be too many such pages due to the stress the VM system is
1363          * under at this point.
1364          */
1365         size = vmspace_anonymous_count(p->p_vmspace) +
1366                 vmspace_swap_count(p->p_vmspace);
1367
1368         /*
1369          * If the this process is bigger than the biggest one
1370          * remember it.
1371          */
1372         if (info->bigsize < size) {
1373                 if (info->bigproc)
1374                         PRELE(info->bigproc);
1375                 PHOLD(p);
1376                 info->bigproc = p;
1377                 info->bigsize = size;
1378         }
1379         return(0);
1380 }
1381
1382 /*
1383  * This routine tries to maintain the pseudo LRU active queue,
1384  * so that during long periods of time where there is no paging,
1385  * that some statistic accumulation still occurs.  This code
1386  * helps the situation where paging just starts to occur.
1387  *
1388  * The caller must hold vm_token.
1389  */
1390 static void
1391 vm_pageout_page_stats(void)
1392 {
1393         vm_page_t m,next;
1394         int pcount,tpcount;             /* Number of pages to check */
1395         static int fullintervalcount = 0;
1396         int page_shortage;
1397
1398         page_shortage = 
1399             (vmstats.v_inactive_target + vmstats.v_cache_max + vmstats.v_free_min) -
1400             (vmstats.v_free_count + vmstats.v_inactive_count + vmstats.v_cache_count);
1401
1402         if (page_shortage <= 0)
1403                 return;
1404
1405         crit_enter();
1406
1407         pcount = vmstats.v_active_count;
1408         fullintervalcount += vm_pageout_stats_interval;
1409         if (fullintervalcount < vm_pageout_full_stats_interval) {
1410                 tpcount = (vm_pageout_stats_max * vmstats.v_active_count) / vmstats.v_page_count;
1411                 if (pcount > tpcount)
1412                         pcount = tpcount;
1413         } else {
1414                 fullintervalcount = 0;
1415         }
1416
1417         m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1418         while ((m != NULL) && (pcount-- > 0)) {
1419                 int actcount;
1420
1421                 if (m->queue != PQ_ACTIVE) {
1422                         break;
1423                 }
1424
1425                 next = TAILQ_NEXT(m, pageq);
1426                 /*
1427                  * Don't deactivate pages that are busy.
1428                  */
1429                 if ((m->busy != 0) ||
1430                     (m->flags & PG_BUSY) ||
1431                     (m->hold_count != 0)) {
1432                         TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1433                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1434                         m = next;
1435                         continue;
1436                 }
1437
1438                 actcount = 0;
1439                 if (m->flags & PG_REFERENCED) {
1440                         vm_page_flag_clear(m, PG_REFERENCED);
1441                         actcount += 1;
1442                 }
1443
1444                 actcount += pmap_ts_referenced(m);
1445                 if (actcount) {
1446                         m->act_count += ACT_ADVANCE + actcount;
1447                         if (m->act_count > ACT_MAX)
1448                                 m->act_count = ACT_MAX;
1449                         TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1450                         TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1451                 } else {
1452                         if (m->act_count == 0) {
1453                                 /*
1454                                  * We turn off page access, so that we have
1455                                  * more accurate RSS stats.  We don't do this
1456                                  * in the normal page deactivation when the
1457                                  * system is loaded VM wise, because the
1458                                  * cost of the large number of page protect
1459                                  * operations would be higher than the value
1460                                  * of doing the operation.
1461                                  */
1462                                 vm_page_busy(m);
1463                                 vm_page_protect(m, VM_PROT_NONE);
1464                                 vm_page_deactivate(m);
1465                                 vm_page_wakeup(m);
1466                         } else {
1467                                 m->act_count -= min(m->act_count, ACT_DECLINE);
1468                                 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1469                                 TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1470                         }
1471                 }
1472
1473                 m = next;
1474         }
1475         crit_exit();
1476 }
1477
1478 /*
1479  * The caller must hold vm_token.
1480  */
1481 static int
1482 vm_pageout_free_page_calc(vm_size_t count)
1483 {
1484         if (count < vmstats.v_page_count)
1485                  return 0;
1486         /*
1487          * free_reserved needs to include enough for the largest swap pager
1488          * structures plus enough for any pv_entry structs when paging.
1489          */
1490         if (vmstats.v_page_count > 1024)
1491                 vmstats.v_free_min = 4 + (vmstats.v_page_count - 1024) / 200;
1492         else
1493                 vmstats.v_free_min = 4;
1494         vmstats.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE +
1495                 vmstats.v_interrupt_free_min;
1496         vmstats.v_free_reserved = vm_pageout_page_count +
1497                 vmstats.v_pageout_free_min + (count / 768) + PQ_L2_SIZE;
1498         vmstats.v_free_severe = vmstats.v_free_min / 2;
1499         vmstats.v_free_min += vmstats.v_free_reserved;
1500         vmstats.v_free_severe += vmstats.v_free_reserved;
1501         return 1;
1502 }
1503
1504
1505 /*
1506  * vm_pageout is the high level pageout daemon.
1507  *
1508  * No requirements.
1509  */
1510 static void
1511 vm_pageout_thread(void)
1512 {
1513         int pass;
1514         int inactive_shortage;
1515
1516         /*
1517          * Permanently hold vm_token.
1518          */
1519         lwkt_gettoken(&vm_token);
1520
1521         /*
1522          * Initialize some paging parameters.
1523          */
1524         curthread->td_flags |= TDF_SYSTHREAD;
1525
1526         vmstats.v_interrupt_free_min = 2;
1527         if (vmstats.v_page_count < 2000)
1528                 vm_pageout_page_count = 8;
1529
1530         vm_pageout_free_page_calc(vmstats.v_page_count);
1531
1532         /*
1533          * v_free_target and v_cache_min control pageout hysteresis.  Note
1534          * that these are more a measure of the VM cache queue hysteresis
1535          * then the VM free queue.  Specifically, v_free_target is the
1536          * high water mark (free+cache pages).
1537          *
1538          * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
1539          * low water mark, while v_free_min is the stop.  v_cache_min must
1540          * be big enough to handle memory needs while the pageout daemon
1541          * is signalled and run to free more pages.
1542          */
1543         if (vmstats.v_free_count > 6144)
1544                 vmstats.v_free_target = 4 * vmstats.v_free_min + vmstats.v_free_reserved;
1545         else
1546                 vmstats.v_free_target = 2 * vmstats.v_free_min + vmstats.v_free_reserved;
1547
1548         /*
1549          * NOTE: With the new buffer cache b_act_count we want the default
1550          *       inactive target to be a percentage of available memory.
1551          *
1552          *       The inactive target essentially determines the minimum
1553          *       number of 'temporary' pages capable of caching one-time-use
1554          *       files when the VM system is otherwise full of pages
1555          *       belonging to multi-time-use files or active program data.
1556          *
1557          * NOTE: The inactive target is aggressively persued only if the
1558          *       inactive queue becomes too small.  If the inactive queue
1559          *       is large enough to satisfy page movement to free+cache
1560          *       then it is repopulated more slowly from the active queue.
1561          *       This allows a general inactive_target default to be set.
1562          *
1563          *       There is an issue here for processes which sit mostly idle
1564          *       'overnight', such as sshd, tcsh, and X.  Any movement from
1565          *       the active queue will eventually cause such pages to
1566          *       recycle eventually causing a lot of paging in the morning.
1567          *       To reduce the incidence of this pages cycled out of the
1568          *       buffer cache are moved directly to the inactive queue if
1569          *       they were only used once or twice.
1570          *
1571          *       The vfs.vm_cycle_point sysctl can be used to adjust this.
1572          *       Increasing the value (up to 64) increases the number of
1573          *       buffer recyclements which go directly to the inactive queue.
1574          */
1575         if (vmstats.v_free_count > 2048) {
1576                 vmstats.v_cache_min = vmstats.v_free_target;
1577                 vmstats.v_cache_max = 2 * vmstats.v_cache_min;
1578         } else {
1579                 vmstats.v_cache_min = 0;
1580                 vmstats.v_cache_max = 0;
1581         }
1582         vmstats.v_inactive_target = vmstats.v_free_count / 4;
1583
1584         /* XXX does not really belong here */
1585         if (vm_page_max_wired == 0)
1586                 vm_page_max_wired = vmstats.v_free_count / 3;
1587
1588         if (vm_pageout_stats_max == 0)
1589                 vm_pageout_stats_max = vmstats.v_free_target;
1590
1591         /*
1592          * Set interval in seconds for stats scan.
1593          */
1594         if (vm_pageout_stats_interval == 0)
1595                 vm_pageout_stats_interval = 5;
1596         if (vm_pageout_full_stats_interval == 0)
1597                 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
1598         
1599
1600         /*
1601          * Set maximum free per pass
1602          */
1603         if (vm_pageout_stats_free_max == 0)
1604                 vm_pageout_stats_free_max = 5;
1605
1606         swap_pager_swap_init();
1607         pass = 0;
1608
1609         /*
1610          * The pageout daemon is never done, so loop forever.
1611          */
1612         while (TRUE) {
1613                 int error;
1614
1615                 /*
1616                  * Wait for an action request.  If we timeout check to
1617                  * see if paging is needed (in case the normal wakeup
1618                  * code raced us).
1619                  */
1620                 if (vm_pages_needed == 0) {
1621                         error = tsleep(&vm_pages_needed,
1622                                        0, "psleep",
1623                                        vm_pageout_stats_interval * hz);
1624                         if (error &&
1625                             vm_paging_needed() == 0 &&
1626                             vm_pages_needed == 0) {
1627                                 vm_pageout_page_stats();
1628                                 continue;
1629                         }
1630                         vm_pages_needed = 1;
1631                 }
1632
1633                 mycpu->gd_cnt.v_pdwakeups++;
1634
1635                 /*
1636                  * Scan for pageout.  Try to avoid thrashing the system
1637                  * with activity.
1638                  */
1639                 inactive_shortage = vm_pageout_scan(pass);
1640                 if (inactive_shortage > 0) {
1641                         ++pass;
1642                         if (swap_pager_full) {
1643                                 /*
1644                                  * Running out of memory, catastrophic back-off
1645                                  * to one-second intervals.
1646                                  */
1647                                 tsleep(&vm_pages_needed, 0, "pdelay", hz);
1648                         } else if (pass < 10 && vm_pages_needed > 1) {
1649                                 /*
1650                                  * Normal operation, additional processes
1651                                  * have already kicked us.  Retry immediately.
1652                                  */
1653                         } else if (pass < 10) {
1654                                 /*
1655                                  * Normal operation, fewer processes.  Delay
1656                                  * a bit but allow wakeups.
1657                                  */
1658                                 vm_pages_needed = 0;
1659                                 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
1660                                 vm_pages_needed = 1;
1661                         } else {
1662                                 /*
1663                                  * We've taken too many passes, forced delay.
1664                                  */
1665                                 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
1666                         }
1667                 } else {
1668                         /*
1669                          * Interlocked wakeup of waiters (non-optional)
1670                          */
1671                         pass = 0;
1672                         if (vm_pages_needed && !vm_page_count_min(0)) {
1673                                 wakeup(&vmstats.v_free_count);
1674                                 vm_pages_needed = 0;
1675                         }
1676                 }
1677         }
1678 }
1679
1680 static struct kproc_desc page_kp = {
1681         "pagedaemon",
1682         vm_pageout_thread,
1683         &pagethread
1684 };
1685 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &page_kp)
1686
1687
1688 /*
1689  * Called after allocating a page out of the cache or free queue
1690  * to possibly wake the pagedaemon up to replentish our supply.
1691  *
1692  * We try to generate some hysteresis by waking the pagedaemon up
1693  * when our free+cache pages go below the free_min+cache_min level.
1694  * The pagedaemon tries to get the count back up to at least the
1695  * minimum, and through to the target level if possible.
1696  *
1697  * If the pagedaemon is already active bump vm_pages_needed as a hint
1698  * that there are even more requests pending.
1699  *
1700  * SMP races ok?
1701  * No requirements.
1702  */
1703 void
1704 pagedaemon_wakeup(void)
1705 {
1706         if (vm_paging_needed() && curthread != pagethread) {
1707                 if (vm_pages_needed == 0) {
1708                         vm_pages_needed = 1;    /* SMP race ok */
1709                         wakeup(&vm_pages_needed);
1710                 } else if (vm_page_count_min(0)) {
1711                         ++vm_pages_needed;      /* SMP race ok */
1712                 }
1713         }
1714 }
1715
1716 #if !defined(NO_SWAPPING)
1717
1718 /*
1719  * SMP races ok?
1720  * No requirements.
1721  */
1722 static void
1723 vm_req_vmdaemon(void)
1724 {
1725         static int lastrun = 0;
1726
1727         if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
1728                 wakeup(&vm_daemon_needed);
1729                 lastrun = ticks;
1730         }
1731 }
1732
1733 static int vm_daemon_callback(struct proc *p, void *data __unused);
1734
1735 /*
1736  * No requirements.
1737  */
1738 static void
1739 vm_daemon(void)
1740 {
1741         /*
1742          * Permanently hold vm_token.
1743          */
1744         lwkt_gettoken(&vm_token);
1745
1746         while (TRUE) {
1747                 tsleep(&vm_daemon_needed, 0, "psleep", 0);
1748                 if (vm_pageout_req_swapout) {
1749                         swapout_procs(vm_pageout_req_swapout);
1750                         vm_pageout_req_swapout = 0;
1751                 }
1752                 /*
1753                  * scan the processes for exceeding their rlimits or if
1754                  * process is swapped out -- deactivate pages
1755                  */
1756                 allproc_scan(vm_daemon_callback, NULL);
1757         }
1758 }
1759
1760 /*
1761  * Caller must hold vm_token and proc_token.
1762  */
1763 static int
1764 vm_daemon_callback(struct proc *p, void *data __unused)
1765 {
1766         vm_pindex_t limit, size;
1767
1768         /*
1769          * if this is a system process or if we have already
1770          * looked at this process, skip it.
1771          */
1772         if (p->p_flag & (P_SYSTEM | P_WEXIT))
1773                 return (0);
1774
1775         /*
1776          * if the process is in a non-running type state,
1777          * don't touch it.
1778          */
1779         if (p->p_stat != SACTIVE && p->p_stat != SSTOP)
1780                 return (0);
1781
1782         /*
1783          * get a limit
1784          */
1785         limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
1786                                 p->p_rlimit[RLIMIT_RSS].rlim_max));
1787
1788         /*
1789          * let processes that are swapped out really be
1790          * swapped out.  Set the limit to nothing to get as
1791          * many pages out to swap as possible.
1792          */
1793         if (p->p_flag & P_SWAPPEDOUT)
1794                 limit = 0;
1795
1796         size = vmspace_resident_count(p->p_vmspace);
1797         if (limit >= 0 && size >= limit) {
1798                 vm_pageout_map_deactivate_pages(
1799                     &p->p_vmspace->vm_map, limit);
1800         }
1801         return (0);
1802 }
1803
1804 #endif