kernel - Improve pageout daemon pipelining.
[dragonfly.git] / sys / vm / vm_pageout.c
1 /*
2  * Copyright (c) 2003-2020 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Matthew Dillon <dillon@backplane.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * Copyright (c) 1991 Regents of the University of California.
35  * All rights reserved.
36  * Copyright (c) 1994 John S. Dyson
37  * All rights reserved.
38  * Copyright (c) 1994 David Greenman
39  * All rights reserved.
40  *
41  * This code is derived from software contributed to Berkeley by
42  * The Mach Operating System project at Carnegie-Mellon University.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. Neither the name of the University nor the names of its contributors
53  *    may be used to endorse or promote products derived from this software
54  *    without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  *
68  *      from: @(#)vm_pageout.c  7.4 (Berkeley) 5/7/91
69  *
70  *
71  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
72  * All rights reserved.
73  *
74  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
75  *
76  * Permission to use, copy, modify and distribute this software and
77  * its documentation is hereby granted, provided that both the copyright
78  * notice and this permission notice appear in all copies of the
79  * software, derivative works or modified versions, and any portions
80  * thereof, and that both notices appear in supporting documentation.
81  *
82  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
83  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
84  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
85  *
86  * Carnegie Mellon requests users of this software to return to
87  *
88  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
89  *  School of Computer Science
90  *  Carnegie Mellon University
91  *  Pittsburgh PA 15213-3890
92  *
93  * any improvements or extensions that they make and grant Carnegie the
94  * rights to redistribute these changes.
95  */
96
97 /*
98  * The proverbial page-out daemon, rewritten many times over the decades.
99  */
100
101 #include "opt_vm.h"
102 #include <sys/param.h>
103 #include <sys/systm.h>
104 #include <sys/kernel.h>
105 #include <sys/proc.h>
106 #include <sys/kthread.h>
107 #include <sys/resourcevar.h>
108 #include <sys/signalvar.h>
109 #include <sys/vnode.h>
110 #include <sys/vmmeter.h>
111 #include <sys/conf.h>
112 #include <sys/sysctl.h>
113
114 #include <vm/vm.h>
115 #include <vm/vm_param.h>
116 #include <sys/lock.h>
117 #include <vm/vm_object.h>
118 #include <vm/vm_page.h>
119 #include <vm/vm_map.h>
120 #include <vm/vm_pageout.h>
121 #include <vm/vm_pager.h>
122 #include <vm/swap_pager.h>
123 #include <vm/vm_extern.h>
124
125 #include <sys/spinlock2.h>
126 #include <vm/vm_page2.h>
127
128 /*
129  * System initialization
130  */
131
132 /* the kernel process "vm_pageout"*/
133 static int vm_pageout_page(vm_page_t m, long *max_launderp,
134                            long *vnodes_skippedp, struct vnode **vpfailedp,
135                            int pass, int vmflush_flags);
136 static int vm_pageout_clean_helper (vm_page_t, int);
137 static void vm_pageout_free_page_calc (vm_size_t count);
138 static void vm_pageout_page_free(vm_page_t m) ;
139 struct thread *emergpager;
140 struct thread *pagethread;
141 static int sequence_emerg_pager;
142
143 #if !defined(NO_SWAPPING)
144 /* the kernel process "vm_daemon"*/
145 static void vm_daemon (void);
146 static struct   thread *vmthread;
147
148 static struct kproc_desc vm_kp = {
149         "vmdaemon",
150         vm_daemon,
151         &vmthread
152 };
153 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
154 #endif
155
156 int vm_pages_needed = 0;        /* Event on which pageout daemon sleeps */
157 int vm_pageout_deficit = 0;     /* Estimated number of pages deficit */
158 int vm_pageout_pages_needed = 0;/* pageout daemon needs pages */
159 int vm_page_free_hysteresis = 16;
160 static int vm_pagedaemon_time;
161
162 #if !defined(NO_SWAPPING)
163 static int vm_pageout_req_swapout;
164 static int vm_daemon_needed;
165 #endif
166 __read_mostly static int vm_max_launder = 4096;
167 __read_mostly static int vm_emerg_launder = 100;
168 __read_mostly static int vm_pageout_stats_max=0, vm_pageout_stats_interval = 0;
169 __read_mostly static int vm_pageout_full_stats_interval = 0;
170 __read_mostly static int vm_pageout_stats_free_max=0, vm_pageout_algorithm=0;
171 __read_mostly static int defer_swap_pageouts=0;
172 __read_mostly static int disable_swap_pageouts=0;
173 __read_mostly static u_int vm_anonmem_decline = ACT_DECLINE;
174 __read_mostly static u_int vm_filemem_decline = ACT_DECLINE * 2;
175 __read_mostly static int vm_pageout_debug;
176
177 #if defined(NO_SWAPPING)
178 __read_mostly static int vm_swap_enabled=0;
179 __read_mostly static int vm_swap_idle_enabled=0;
180 #else
181 __read_mostly static int vm_swap_enabled=1;
182 __read_mostly static int vm_swap_idle_enabled=0;
183 #endif
184
185 /* 0-disable, 1-passive, 2-active swp*/
186 __read_mostly int vm_pageout_memuse_mode=1;
187
188 SYSCTL_UINT(_vm, VM_PAGEOUT_ALGORITHM, anonmem_decline,
189         CTLFLAG_RW, &vm_anonmem_decline, 0, "active->inactive anon memory");
190
191 SYSCTL_INT(_vm, VM_PAGEOUT_ALGORITHM, filemem_decline,
192         CTLFLAG_RW, &vm_filemem_decline, 0, "active->inactive file cache");
193
194 SYSCTL_INT(_vm, OID_AUTO, page_free_hysteresis,
195         CTLFLAG_RW, &vm_page_free_hysteresis, 0,
196         "Free more pages than the minimum required");
197
198 SYSCTL_INT(_vm, OID_AUTO, max_launder,
199         CTLFLAG_RW, &vm_max_launder, 0, "Limit dirty flushes in pageout");
200 SYSCTL_INT(_vm, OID_AUTO, emerg_launder,
201         CTLFLAG_RW, &vm_emerg_launder, 0, "Emergency pager minimum");
202
203 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_max,
204         CTLFLAG_RW, &vm_pageout_stats_max, 0, "Max pageout stats scan length");
205
206 SYSCTL_INT(_vm, OID_AUTO, pageout_full_stats_interval,
207         CTLFLAG_RW, &vm_pageout_full_stats_interval, 0, "Interval for full stats scan");
208
209 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_interval,
210         CTLFLAG_RW, &vm_pageout_stats_interval, 0, "Interval for partial stats scan");
211
212 SYSCTL_INT(_vm, OID_AUTO, pageout_stats_free_max,
213         CTLFLAG_RW, &vm_pageout_stats_free_max, 0, "Not implemented");
214 SYSCTL_INT(_vm, OID_AUTO, pageout_memuse_mode,
215         CTLFLAG_RW, &vm_pageout_memuse_mode, 0, "memoryuse resource mode");
216 SYSCTL_INT(_vm, OID_AUTO, pageout_debug,
217         CTLFLAG_RW, &vm_pageout_debug, 0, "debug pageout pages (count)");
218
219
220 #if defined(NO_SWAPPING)
221 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
222         CTLFLAG_RD, &vm_swap_enabled, 0, "");
223 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
224         CTLFLAG_RD, &vm_swap_idle_enabled, 0, "");
225 #else
226 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled,
227         CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout");
228 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled,
229         CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria");
230 #endif
231
232 SYSCTL_INT(_vm, OID_AUTO, defer_swapspace_pageouts,
233         CTLFLAG_RW, &defer_swap_pageouts, 0, "Give preference to dirty pages in mem");
234
235 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts,
236         CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages");
237
238 static int pageout_lock_miss;
239 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss,
240         CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout");
241
242 int vm_page_max_wired;          /* XXX max # of wired pages system-wide */
243
244 #if !defined(NO_SWAPPING)
245 static void vm_req_vmdaemon (void);
246 #endif
247 static void vm_pageout_page_stats(int q);
248
249 /*
250  * Calculate approximately how many pages on each queue to try to
251  * clean.  An exact calculation creates an edge condition when the
252  * queues are unbalanced so add significant slop.  The queue scans
253  * will stop early when targets are reached and will start where they
254  * left off on the next pass.
255  *
256  * We need to be generous here because there are all sorts of loading
257  * conditions that can cause edge cases if try to average over all queues.
258  * In particular, storage subsystems have become so fast that paging
259  * activity can become quite frantic.  Eventually we will probably need
260  * two paging threads, one for dirty pages and one for clean, to deal
261  * with the bandwidth requirements.
262
263  * So what we do is calculate a value that can be satisfied nominally by
264  * only having to scan half the queues.
265  */
266 static __inline long
267 PQAVERAGE(long n)
268 {
269         long avg;
270
271         if (n >= 0) {
272                 avg = ((n + (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) + 1);
273         } else {
274                 avg = ((n - (PQ_L2_SIZE - 1)) / (PQ_L2_SIZE / 2) - 1);
275         }
276         return avg;
277 }
278
279 /*
280  * vm_pageout_clean_helper:
281  *
282  * Clean the page and remove it from the laundry.  The page must be busied
283  * by the caller and will be disposed of (put away, flushed) by this routine.
284  */
285 static int
286 vm_pageout_clean_helper(vm_page_t m, int vmflush_flags)
287 {
288         vm_object_t object;
289         vm_page_t mc[BLIST_MAX_ALLOC];
290         int error;
291         int ib, is, page_base;
292         vm_pindex_t pindex = m->pindex;
293
294         object = m->object;
295
296         /*
297          * Don't mess with the page if it's held or special.  Theoretically
298          * we can pageout held pages but there is no real need to press our
299          * luck, so don't.
300          */
301         if (m->hold_count != 0 || (m->flags & PG_UNQUEUED)) {
302                 vm_page_wakeup(m);
303                 return 0;
304         }
305
306         /*
307          * Place page in cluster.  Align cluster for optimal swap space
308          * allocation (whether it is swap or not).  This is typically ~16-32
309          * pages, which also tends to align the cluster to multiples of the
310          * filesystem block size if backed by a filesystem.
311          */
312         page_base = pindex % BLIST_MAX_ALLOC;
313         mc[page_base] = m;
314         ib = page_base - 1;
315         is = page_base + 1;
316
317         /*
318          * Scan object for clusterable pages.
319          *
320          * We can cluster ONLY if: ->> the page is NOT
321          * clean, wired, busy, held, or mapped into a
322          * buffer, and one of the following:
323          * 1) The page is inactive, or a seldom used
324          *    active page.
325          * -or-
326          * 2) we force the issue.
327          *
328          * During heavy mmap/modification loads the pageout
329          * daemon can really fragment the underlying file
330          * due to flushing pages out of order and not trying
331          * align the clusters (which leave sporatic out-of-order
332          * holes).  To solve this problem we do the reverse scan
333          * first and attempt to align our cluster, then do a 
334          * forward scan if room remains.
335          */
336         vm_object_hold(object);
337
338         while (ib >= 0) {
339                 vm_page_t p;
340
341                 p = vm_page_lookup_busy_try(object, pindex - page_base + ib,
342                                             TRUE, &error);
343                 if (error || p == NULL)
344                         break;
345                 if ((p->queue - p->pc) == PQ_CACHE ||
346                     (p->flags & PG_UNQUEUED)) {
347                         vm_page_wakeup(p);
348                         break;
349                 }
350                 vm_page_test_dirty(p);
351                 if (((p->dirty & p->valid) == 0 &&
352                      (p->flags & PG_NEED_COMMIT) == 0) ||
353                     p->wire_count != 0 ||       /* may be held by buf cache */
354                     p->hold_count != 0) {       /* may be undergoing I/O */
355                         vm_page_wakeup(p);
356                         break;
357                 }
358                 if (p->queue - p->pc != PQ_INACTIVE) {
359                         if (p->queue - p->pc != PQ_ACTIVE ||
360                             (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
361                                 vm_page_wakeup(p);
362                                 break;
363                         }
364                 }
365
366                 /*
367                  * Try to maintain page groupings in the cluster.
368                  */
369                 if (m->flags & PG_WINATCFLS)
370                         vm_page_flag_set(p, PG_WINATCFLS);
371                 else
372                         vm_page_flag_clear(p, PG_WINATCFLS);
373                 p->act_count = m->act_count;
374
375                 mc[ib] = p;
376                 --ib;
377         }
378         ++ib;   /* fixup */
379
380         while (is < BLIST_MAX_ALLOC &&
381                pindex - page_base + is < object->size) {
382                 vm_page_t p;
383
384                 p = vm_page_lookup_busy_try(object, pindex - page_base + is,
385                                             TRUE, &error);
386                 if (error || p == NULL)
387                         break;
388                 if (((p->queue - p->pc) == PQ_CACHE) ||
389                     (p->flags & PG_UNQUEUED)) {
390                         vm_page_wakeup(p);
391                         break;
392                 }
393                 vm_page_test_dirty(p);
394                 if (((p->dirty & p->valid) == 0 &&
395                      (p->flags & PG_NEED_COMMIT) == 0) ||
396                     p->wire_count != 0 ||       /* may be held by buf cache */
397                     p->hold_count != 0) {       /* may be undergoing I/O */
398                         vm_page_wakeup(p);
399                         break;
400                 }
401                 if (p->queue - p->pc != PQ_INACTIVE) {
402                         if (p->queue - p->pc != PQ_ACTIVE ||
403                             (vmflush_flags & VM_PAGER_ALLOW_ACTIVE) == 0) {
404                                 vm_page_wakeup(p);
405                                 break;
406                         }
407                 }
408
409                 /*
410                  * Try to maintain page groupings in the cluster.
411                  */
412                 if (m->flags & PG_WINATCFLS)
413                         vm_page_flag_set(p, PG_WINATCFLS);
414                 else
415                         vm_page_flag_clear(p, PG_WINATCFLS);
416                 p->act_count = m->act_count;
417
418                 mc[is] = p;
419                 ++is;
420         }
421
422         vm_object_drop(object);
423
424         /*
425          * we allow reads during pageouts...
426          */
427         return vm_pageout_flush(&mc[ib], is - ib, vmflush_flags);
428 }
429
430 /*
431  * vm_pageout_flush() - launder the given pages
432  *
433  *      The given pages are laundered.  Note that we setup for the start of
434  *      I/O ( i.e. busy the page ), mark it read-only, and bump the object
435  *      reference count all in here rather then in the parent.  If we want
436  *      the parent to do more sophisticated things we may have to change
437  *      the ordering.
438  *
439  *      The pages in the array must be busied by the caller and will be
440  *      unbusied by this function.
441  */
442 int
443 vm_pageout_flush(vm_page_t *mc, int count, int vmflush_flags)
444 {
445         vm_object_t object;
446         int pageout_status[count];
447         int numpagedout = 0;
448         int i;
449         int dodebug;
450
451         if (vm_pageout_debug > 0) {
452                 --vm_pageout_debug;
453                 dodebug = 1;
454         } else {
455                 dodebug = 0;
456         }
457
458         /*
459          * Initiate I/O.  Bump the vm_page_t->busy counter.
460          */
461         for (i = 0; i < count; i++) {
462                 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL,
463                         ("vm_pageout_flush page %p index %d/%d: partially "
464                          "invalid page", mc[i], i, count));
465                 vm_page_io_start(mc[i]);
466         }
467
468         /*
469          * We must make the pages read-only.  This will also force the
470          * modified bit in the related pmaps to be cleared.  The pager
471          * cannot clear the bit for us since the I/O completion code
472          * typically runs from an interrupt.  The act of making the page
473          * read-only handles the case for us.
474          *
475          * Then we can unbusy the pages, we still hold a reference by virtue
476          * of our soft-busy.
477          */
478         if (dodebug)
479                 kprintf("pageout: ");
480         for (i = 0; i < count; i++) {
481                 if (vmflush_flags & VM_PAGER_TRY_TO_CACHE)
482                         vm_page_protect(mc[i], VM_PROT_NONE);
483                 else
484                         vm_page_protect(mc[i], VM_PROT_READ);
485                 vm_page_wakeup(mc[i]);
486                 if (dodebug)
487                         kprintf(" %p", mc[i]);
488         }
489         if (dodebug)
490                 kprintf("\n");
491
492         object = mc[0]->object;
493         vm_object_pip_add(object, count);
494
495         vm_pager_put_pages(object, mc, count,
496                            (vmflush_flags |
497                             ((object == &kernel_object) ?
498                                 VM_PAGER_PUT_SYNC : 0)),
499                            pageout_status);
500
501         if (dodebug)
502                 kprintf("result: ");
503         for (i = 0; i < count; i++) {
504                 vm_page_t mt = mc[i];
505
506                 if (dodebug)
507                         kprintf("  S%d", pageout_status[i]);
508
509                 switch (pageout_status[i]) {
510                 case VM_PAGER_OK:
511                         numpagedout++;
512                         break;
513                 case VM_PAGER_PEND:
514                         numpagedout++;
515                         break;
516                 case VM_PAGER_BAD:
517                         /*
518                          * Page outside of range of object. Right now we
519                          * essentially lose the changes by pretending it
520                          * worked.
521                          */
522                         vm_page_busy_wait(mt, FALSE, "pgbad");
523                         pmap_clear_modify(mt);
524                         vm_page_undirty(mt);
525                         vm_page_wakeup(mt);
526                         break;
527                 case VM_PAGER_ERROR:
528                 case VM_PAGER_FAIL:
529                         /*
530                          * A page typically cannot be paged out when we
531                          * have run out of swap.  We leave the page
532                          * marked inactive and will try to page it out
533                          * again later.
534                          *
535                          * Starvation of the active page list is used to
536                          * determine when the system is massively memory
537                          * starved.
538                          */
539                         break;
540                 case VM_PAGER_AGAIN:
541                         break;
542                 }
543
544                 /*
545                  * If not PENDing this was a synchronous operation and we
546                  * clean up after the I/O.  If it is PENDing the mess is
547                  * cleaned up asynchronously.
548                  *
549                  * Also nominally act on the caller's wishes if the caller
550                  * wants to try to really clean (cache or free) the page.
551                  *
552                  * Also nominally deactivate the page if the system is
553                  * memory-stressed.
554                  */
555                 if (pageout_status[i] != VM_PAGER_PEND) {
556                         vm_page_busy_wait(mt, FALSE, "pgouw");
557                         vm_page_io_finish(mt);
558                         if (vmflush_flags & VM_PAGER_TRY_TO_CACHE) {
559                                 vm_page_try_to_cache(mt);
560                                 if (dodebug)
561                                 kprintf("A[pq_cache=%d]",
562                                          ((mt->queue - mt->pc) == PQ_CACHE));
563                         } else if (vm_page_count_severe()) {
564                                 vm_page_deactivate(mt);
565                                 vm_page_wakeup(mt);
566                                 if (dodebug)
567                                 kprintf("B");
568                         } else {
569                                 vm_page_wakeup(mt);
570                                 if (dodebug)
571                                 kprintf("C");
572                         }
573                         vm_object_pip_wakeup(object);
574                 }
575         }
576         if (dodebug)
577                 kprintf("\n");
578         return numpagedout;
579 }
580
581 #if !defined(NO_SWAPPING)
582
583 /*
584  * Callback function, page busied for us.  We must dispose of the busy
585  * condition.  Any related pmap pages may be held but will not be locked.
586  */
587 static
588 int
589 vm_pageout_mdp_callback(struct pmap_pgscan_info *info, vm_offset_t va,
590                         vm_page_t p)
591 {
592         int actcount;
593         int cleanit = 0;
594
595         /*
596          * Basic tests - There should never be a marker, and we can stop
597          *               once the RSS is below the required level.
598          */
599         KKASSERT((p->flags & PG_MARKER) == 0);
600         if (pmap_resident_tlnw_count(info->pmap) <= info->limit) {
601                 vm_page_wakeup(p);
602                 return(-1);
603         }
604
605         mycpu->gd_cnt.v_pdpages++;
606
607         if (p->wire_count || p->hold_count || (p->flags & PG_UNQUEUED)) {
608                 vm_page_wakeup(p);
609                 goto done;
610         }
611
612         ++info->actioncount;
613
614         /*
615          * Check if the page has been referened recently.  If it has,
616          * activate it and skip.
617          */
618         actcount = pmap_ts_referenced(p);
619         if (actcount) {
620                 vm_page_flag_set(p, PG_REFERENCED);
621         } else if (p->flags & PG_REFERENCED) {
622                 actcount = 1;
623         }
624
625         if (actcount) {
626                 if (p->queue - p->pc != PQ_ACTIVE) {
627                         vm_page_and_queue_spin_lock(p);
628                         if (p->queue - p->pc != PQ_ACTIVE) {
629                                 vm_page_and_queue_spin_unlock(p);
630                                 vm_page_activate(p);
631                         } else {
632                                 vm_page_and_queue_spin_unlock(p);
633                         }
634                 } else {
635                         p->act_count += actcount;
636                         if (p->act_count > ACT_MAX)
637                                 p->act_count = ACT_MAX;
638                 }
639                 vm_page_flag_clear(p, PG_REFERENCED);
640                 vm_page_wakeup(p);
641                 goto done;
642         }
643
644         /*
645          * Remove the page from this particular pmap.  Once we do this, our
646          * pmap scans will not see it again (unless it gets faulted in), so
647          * we must actively dispose of or deal with the page.
648          */
649         pmap_remove_specific(info->pmap, p);
650
651         /*
652          * If the page is not mapped to another process (i.e. as would be
653          * typical if this were a shared page from a library) then deactivate
654          * the page and clean it in two passes only.
655          *
656          * If the page hasn't been referenced since the last check, remove it
657          * from the pmap.  If it is no longer mapped, deactivate it
658          * immediately, accelerating the normal decline.
659          *
660          * Once the page has been removed from the pmap the RSS code no
661          * longer tracks it so we have to make sure that it is staged for
662          * potential flush action.
663          */
664         if ((p->flags & PG_MAPPED) == 0 ||
665             (pmap_mapped_sync(p) & PG_MAPPED) == 0) {
666                 if (p->queue - p->pc == PQ_ACTIVE) {
667                         vm_page_deactivate(p);
668                 }
669                 if (p->queue - p->pc == PQ_INACTIVE) {
670                         cleanit = 1;
671                 }
672         }
673
674         /*
675          * Ok, try to fully clean the page and any nearby pages such that at
676          * least the requested page is freed or moved to the cache queue.
677          *
678          * We usually do this synchronously to allow us to get the page into
679          * the CACHE queue quickly, which will prevent memory exhaustion if
680          * a process with a memoryuse limit is running away.  However, the
681          * sysadmin may desire to set vm.swap_user_async which relaxes this
682          * and improves write performance.
683          */
684         if (cleanit) {
685                 long max_launder = 0x7FFF;
686                 long vnodes_skipped = 0;
687                 int vmflush_flags;
688                 struct vnode *vpfailed = NULL;
689
690                 info->offset = va;
691
692                 if (vm_pageout_memuse_mode >= 2) {
693                         vmflush_flags = VM_PAGER_TRY_TO_CACHE |
694                                         VM_PAGER_ALLOW_ACTIVE;
695                         if (swap_user_async == 0)
696                                 vmflush_flags |= VM_PAGER_PUT_SYNC;
697                         vm_page_flag_set(p, PG_WINATCFLS);
698                         info->cleancount +=
699                                 vm_pageout_page(p, &max_launder,
700                                                 &vnodes_skipped,
701                                                 &vpfailed, 1, vmflush_flags);
702                 } else {
703                         vm_page_wakeup(p);
704                         ++info->cleancount;
705                 }
706         } else {
707                 vm_page_wakeup(p);
708         }
709
710         /*
711          * Must be at end to avoid SMP races.
712          */
713 done:
714         lwkt_user_yield();
715         return 0;
716 }
717
718 /*
719  * Deactivate some number of pages in a map due to set RLIMIT_RSS limits.
720  * that is relatively difficult to do.  We try to keep track of where we
721  * left off last time to reduce scan overhead.
722  *
723  * Called when vm_pageout_memuse_mode is >= 1.
724  */
725 void
726 vm_pageout_map_deactivate_pages(vm_map_t map, vm_pindex_t limit)
727 {
728         vm_offset_t pgout_offset;
729         struct pmap_pgscan_info info;
730         int retries = 3;
731
732         pgout_offset = map->pgout_offset;
733 again:
734 #if 0
735         kprintf("%016jx ", pgout_offset);
736 #endif
737         if (pgout_offset < VM_MIN_USER_ADDRESS)
738                 pgout_offset = VM_MIN_USER_ADDRESS;
739         if (pgout_offset >= VM_MAX_USER_ADDRESS)
740                 pgout_offset = 0;
741         info.pmap = vm_map_pmap(map);
742         info.limit = limit;
743         info.beg_addr = pgout_offset;
744         info.end_addr = VM_MAX_USER_ADDRESS;
745         info.callback = vm_pageout_mdp_callback;
746         info.cleancount = 0;
747         info.actioncount = 0;
748         info.busycount = 0;
749
750         pmap_pgscan(&info);
751         pgout_offset = info.offset;
752 #if 0
753         kprintf("%016jx %08lx %08lx\n", pgout_offset,
754                 info.cleancount, info.actioncount);
755 #endif
756
757         if (pgout_offset != VM_MAX_USER_ADDRESS &&
758             pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
759                 goto again;
760         } else if (retries &&
761                    pmap_resident_tlnw_count(vm_map_pmap(map)) > limit) {
762                 --retries;
763                 goto again;
764         }
765         map->pgout_offset = pgout_offset;
766 }
767 #endif
768
769 /*
770  * Called when the pageout scan wants to free a page.  We no longer
771  * try to cycle the vm_object here with a reference & dealloc, which can
772  * cause a non-trivial object collapse in a critical path.
773  *
774  * It is unclear why we cycled the ref_count in the past, perhaps to try
775  * to optimize shadow chain collapses but I don't quite see why it would
776  * be necessary.  An OBJ_DEAD object should terminate any and all vm_pages
777  * synchronously and not have to be kicked-start.
778  */
779 static void
780 vm_pageout_page_free(vm_page_t m) 
781 {
782         vm_page_protect(m, VM_PROT_NONE);
783         vm_page_free(m);
784 }
785
786 /*
787  * vm_pageout_scan does the dirty work for the pageout daemon.
788  */
789 struct vm_pageout_scan_info {
790         struct proc *bigproc;
791         vm_offset_t bigsize;
792 };
793
794 static int vm_pageout_scan_callback(struct proc *p, void *data);
795
796 /*
797  * Scan inactive queue
798  *
799  * WARNING! Can be called from two pagedaemon threads simultaneously.
800  */
801 static int
802 vm_pageout_scan_inactive(int pass, int q, long avail_shortage,
803                          long *vnodes_skipped)
804 {
805         vm_page_t m;
806         struct vm_page marker;
807         struct vnode *vpfailed;         /* warning, allowed to be stale */
808         long maxscan;
809         long delta = 0;
810         long max_launder;
811         int isep;
812         int vmflush_flags;
813
814         isep = (curthread == emergpager);
815
816         /*
817          * Start scanning the inactive queue for pages we can move to the
818          * cache or free.  The scan will stop when the target is reached or
819          * we have scanned the entire inactive queue.  Note that m->act_count
820          * is not used to form decisions for the inactive queue, only for the
821          * active queue.
822          *
823          * max_launder limits the number of dirty pages we flush per scan.
824          * For most systems a smaller value (16 or 32) is more robust under
825          * extreme memory and disk pressure because any unnecessary writes
826          * to disk can result in extreme performance degredation.  However,
827          * systems with excessive dirty pages (especially when MAP_NOSYNC is
828          * used) will die horribly with limited laundering.  If the pageout
829          * daemon cannot clean enough pages in the first pass, we let it go
830          * all out in succeeding passes.
831          *
832          * NOTE!  THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
833          *        PAGES.
834          */
835         if ((max_launder = vm_max_launder) <= 1)
836                 max_launder = 1;
837         if (pass)
838                 max_launder = 10000;
839
840         /*
841          * Initialize our marker
842          */
843         bzero(&marker, sizeof(marker));
844         marker.flags = PG_FICTITIOUS | PG_MARKER;
845         marker.busy_count = PBUSY_LOCKED;
846         marker.queue = PQ_INACTIVE + q;
847         marker.pc = q;
848         marker.wire_count = 1;
849
850         /*
851          * Inactive queue scan.
852          *
853          * NOTE: The vm_page must be spinlocked before the queue to avoid
854          *       deadlocks, so it is easiest to simply iterate the loop
855          *       with the queue unlocked at the top.
856          */
857         vpfailed = NULL;
858
859         vm_page_queues_spin_lock(PQ_INACTIVE + q);
860         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
861         maxscan = vm_page_queues[PQ_INACTIVE + q].lcnt;
862
863         /*
864          * Queue locked at top of loop to avoid stack marker issues.
865          */
866         while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
867                maxscan-- > 0 && avail_shortage - delta > 0)
868         {
869                 int count;
870
871                 KKASSERT(m->queue == PQ_INACTIVE + q);
872                 TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl,
873                              &marker, pageq);
874                 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_INACTIVE + q].pl, m,
875                                    &marker, pageq);
876                 mycpu->gd_cnt.v_pdpages++;
877
878                 /*
879                  * Skip marker pages (atomic against other markers to avoid
880                  * infinite hop-over scans).
881                  */
882                 if (m->flags & PG_MARKER)
883                         continue;
884
885                 /*
886                  * Try to busy the page.  Don't mess with pages which are
887                  * already busy or reorder them in the queue.
888                  */
889                 if (vm_page_busy_try(m, TRUE))
890                         continue;
891
892                 /*
893                  * Remaining operations run with the page busy and neither
894                  * the page or the queue will be spin-locked.
895                  */
896                 KKASSERT(m->queue == PQ_INACTIVE + q);
897                 vm_page_queues_spin_unlock(PQ_INACTIVE + q);
898
899                 /*
900                  * The emergency pager runs when the primary pager gets
901                  * stuck, which typically means the primary pager deadlocked
902                  * on a vnode-backed page.  Therefore, the emergency pager
903                  * must skip any complex objects.
904                  *
905                  * We disallow VNODEs unless they are VCHR whos device ops
906                  * does not flag D_NOEMERGPGR.
907                  */
908                 if (isep && m->object) {
909                         struct vnode *vp;
910
911                         switch(m->object->type) {
912                         case OBJT_DEFAULT:
913                         case OBJT_SWAP:
914                                 /*
915                                  * Allow anonymous memory and assume that
916                                  * swap devices are not complex, since its
917                                  * kinda worthless if we can't swap out dirty
918                                  * anonymous pages.
919                                  */
920                                 break;
921                         case OBJT_VNODE:
922                                 /*
923                                  * Allow VCHR device if the D_NOEMERGPGR
924                                  * flag is not set, deny other vnode types
925                                  * as being too complex.
926                                  */
927                                 vp = m->object->handle;
928                                 if (vp && vp->v_type == VCHR &&
929                                     vp->v_rdev && vp->v_rdev->si_ops &&
930                                     (vp->v_rdev->si_ops->head.flags &
931                                      D_NOEMERGPGR) == 0) {
932                                         break;
933                                 }
934                                 /* Deny - fall through */
935                         default:
936                                 /*
937                                  * Deny
938                                  */
939                                 vm_page_wakeup(m);
940                                 vm_page_queues_spin_lock(PQ_INACTIVE + q);
941                                 lwkt_yield();
942                                 continue;
943                         }
944                 }
945
946                 /*
947                  * Try to pageout the page and perhaps other nearby pages.
948                  * We want to get the pages into the cache on the second
949                  * pass.  Otherwise the pages can wind up just cycling in
950                  * the inactive queue, getting flushed over and over again.
951                  */
952                 if (m->flags & PG_WINATCFLS)
953                         vmflush_flags = VM_PAGER_TRY_TO_CACHE;
954                 else
955                         vmflush_flags = 0;
956                 count = vm_pageout_page(m, &max_launder, vnodes_skipped,
957                                         &vpfailed, pass, vmflush_flags);
958                 delta += count;
959
960                 /*
961                  * Systems with a ton of memory can wind up with huge
962                  * deactivation counts.  Because the inactive scan is
963                  * doing a lot of flushing, the combination can result
964                  * in excessive paging even in situations where other
965                  * unrelated threads free up sufficient VM.
966                  *
967                  * To deal with this we abort the nominal active->inactive
968                  * scan before we hit the inactive target when free+cache
969                  * levels have reached a reasonable target.
970                  *
971                  * When deciding to stop early we need to add some slop to
972                  * the test and we need to return full completion to the caller
973                  * to prevent the caller from thinking there is something
974                  * wrong and issuing a low-memory+swap warning or pkill.
975                  *
976                  * A deficit forces paging regardless of the state of the
977                  * VM page queues (used for RSS enforcement).
978                  */
979                 lwkt_yield();
980                 vm_page_queues_spin_lock(PQ_INACTIVE + q);
981                 if (vm_paging_target() < -vm_max_launder) {
982                         /*
983                          * Stopping early, return full completion to caller.
984                          */
985                         if (delta < avail_shortage)
986                                 delta = avail_shortage;
987                         break;
988                 }
989         }
990
991         /* page queue still spin-locked */
992         TAILQ_REMOVE(&vm_page_queues[PQ_INACTIVE + q].pl, &marker, pageq);
993         vm_page_queues_spin_unlock(PQ_INACTIVE + q);
994
995         return (delta);
996 }
997
998 /*
999  * Pageout the specified page, return the total number of pages paged out
1000  * (this routine may cluster).
1001  *
1002  * The page must be busied and soft-busied by the caller and will be disposed
1003  * of by this function.
1004  */
1005 static int
1006 vm_pageout_page(vm_page_t m, long *max_launderp, long *vnodes_skippedp,
1007                 struct vnode **vpfailedp, int pass, int vmflush_flags)
1008 {
1009         vm_object_t object;
1010         int actcount;
1011         int count = 0;
1012
1013         /*
1014          * Wiring no longer removes a page from its queue.  The last unwiring
1015          * will requeue the page.  Obviously wired pages cannot be paged out
1016          * so unqueue it and return.
1017          */
1018         if (m->wire_count) {
1019                 vm_page_unqueue_nowakeup(m);
1020                 vm_page_wakeup(m);
1021                 return 0;
1022         }
1023
1024         /*
1025          * A held page may be undergoing I/O, so skip it.
1026          */
1027         if (m->hold_count) {
1028                 vm_page_and_queue_spin_lock(m);
1029                 if (m->queue - m->pc == PQ_INACTIVE) {
1030                         TAILQ_REMOVE(
1031                                 &vm_page_queues[m->queue].pl, m, pageq);
1032                         TAILQ_INSERT_TAIL(
1033                                 &vm_page_queues[m->queue].pl, m, pageq);
1034                 }
1035                 vm_page_and_queue_spin_unlock(m);
1036                 vm_page_wakeup(m);
1037                 return 0;
1038         }
1039
1040         if (m->object == NULL || m->object->ref_count == 0) {
1041                 /*
1042                  * If the object is not being used, we ignore previous
1043                  * references.
1044                  */
1045                 vm_page_flag_clear(m, PG_REFERENCED);
1046                 pmap_clear_reference(m);
1047                 /* fall through to end */
1048         } else if (((m->flags & PG_REFERENCED) == 0) &&
1049                     (actcount = pmap_ts_referenced(m))) {
1050                 /*
1051                  * Otherwise, if the page has been referenced while
1052                  * in the inactive queue, we bump the "activation
1053                  * count" upwards, making it less likely that the
1054                  * page will be added back to the inactive queue
1055                  * prematurely again.  Here we check the page tables
1056                  * (or emulated bits, if any), given the upper level
1057                  * VM system not knowing anything about existing
1058                  * references.
1059                  */
1060                 vm_page_activate(m);
1061                 m->act_count += (actcount + ACT_ADVANCE);
1062                 vm_page_wakeup(m);
1063                 return 0;
1064         }
1065
1066         /*
1067          * (m) is still busied.
1068          *
1069          * If the upper level VM system knows about any page
1070          * references, we activate the page.  We also set the
1071          * "activation count" higher than normal so that we will less
1072          * likely place pages back onto the inactive queue again.
1073          */
1074         if ((m->flags & PG_REFERENCED) != 0) {
1075                 vm_page_flag_clear(m, PG_REFERENCED);
1076                 actcount = pmap_ts_referenced(m);
1077                 vm_page_activate(m);
1078                 m->act_count += (actcount + ACT_ADVANCE + 1);
1079                 vm_page_wakeup(m);
1080                 return 0;
1081         }
1082
1083         /*
1084          * If the upper level VM system doesn't know anything about
1085          * the page being dirty, we have to check for it again.  As
1086          * far as the VM code knows, any partially dirty pages are
1087          * fully dirty.
1088          *
1089          * Pages marked PG_WRITEABLE may be mapped into the user
1090          * address space of a process running on another cpu.  A
1091          * user process (without holding the MP lock) running on
1092          * another cpu may be able to touch the page while we are
1093          * trying to remove it.  vm_page_cache() will handle this
1094          * case for us.
1095          */
1096         if (m->dirty == 0) {
1097                 vm_page_test_dirty(m);
1098         } else {
1099                 vm_page_dirty(m);
1100         }
1101
1102         if (m->valid == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1103                 /*
1104                  * Invalid pages can be easily freed
1105                  */
1106                 vm_pageout_page_free(m);
1107                 mycpu->gd_cnt.v_dfree++;
1108                 ++count;
1109         } else if (m->dirty == 0 && (m->flags & PG_NEED_COMMIT) == 0) {
1110                 /*
1111                  * Clean pages can be placed onto the cache queue.
1112                  * This effectively frees them.
1113                  */
1114                 vm_page_cache(m);
1115                 ++count;
1116         } else if ((m->flags & PG_WINATCFLS) == 0 && pass == 0) {
1117                 /*
1118                  * Dirty pages need to be paged out, but flushing
1119                  * a page is extremely expensive verses freeing
1120                  * a clean page.  Rather then artificially limiting
1121                  * the number of pages we can flush, we instead give
1122                  * dirty pages extra priority on the inactive queue
1123                  * by forcing them to be cycled through the queue
1124                  * twice before being flushed, after which the
1125                  * (now clean) page will cycle through once more
1126                  * before being freed.  This significantly extends
1127                  * the thrash point for a heavily loaded machine.
1128                  */
1129                 vm_page_flag_set(m, PG_WINATCFLS);
1130                 vm_page_and_queue_spin_lock(m);
1131                 if (m->queue - m->pc == PQ_INACTIVE) {
1132                         TAILQ_REMOVE(
1133                                 &vm_page_queues[m->queue].pl, m, pageq);
1134                         TAILQ_INSERT_TAIL(
1135                                 &vm_page_queues[m->queue].pl, m, pageq);
1136                 }
1137                 vm_page_and_queue_spin_unlock(m);
1138                 vm_page_wakeup(m);
1139         } else if (*max_launderp > 0) {
1140                 /*
1141                  * We always want to try to flush some dirty pages if
1142                  * we encounter them, to keep the system stable.
1143                  * Normally this number is small, but under extreme
1144                  * pressure where there are insufficient clean pages
1145                  * on the inactive queue, we may have to go all out.
1146                  */
1147                 int swap_pageouts_ok;
1148                 struct vnode *vp = NULL;
1149
1150                 swap_pageouts_ok = 0;
1151                 object = m->object;
1152                 if (object &&
1153                     (object->type != OBJT_SWAP) &&
1154                     (object->type != OBJT_DEFAULT)) {
1155                         swap_pageouts_ok = 1;
1156                 } else {
1157                         swap_pageouts_ok = !(defer_swap_pageouts ||
1158                                              disable_swap_pageouts);
1159                         swap_pageouts_ok |= (!disable_swap_pageouts &&
1160                                              defer_swap_pageouts &&
1161                                              vm_page_count_min(0));
1162                 }
1163
1164                 /*
1165                  * We don't bother paging objects that are "dead".
1166                  * Those objects are in a "rundown" state.
1167                  */
1168                 if (!swap_pageouts_ok ||
1169                     (object == NULL) ||
1170                     (object->flags & OBJ_DEAD)) {
1171                         vm_page_and_queue_spin_lock(m);
1172                         if (m->queue - m->pc == PQ_INACTIVE) {
1173                                 TAILQ_REMOVE(
1174                                     &vm_page_queues[m->queue].pl,
1175                                     m, pageq);
1176                                 TAILQ_INSERT_TAIL(
1177                                     &vm_page_queues[m->queue].pl,
1178                                     m, pageq);
1179                         }
1180                         vm_page_and_queue_spin_unlock(m);
1181                         vm_page_wakeup(m);
1182                         return 0;
1183                 }
1184
1185                 /*
1186                  * (m) is still busied.
1187                  *
1188                  * The object is already known NOT to be dead.   It
1189                  * is possible for the vget() to block the whole
1190                  * pageout daemon, but the new low-memory handling
1191                  * code should prevent it.
1192                  *
1193                  * The previous code skipped locked vnodes and, worse,
1194                  * reordered pages in the queue.  This results in
1195                  * completely non-deterministic operation because,
1196                  * quite often, a vm_fault has initiated an I/O and
1197                  * is holding a locked vnode at just the point where
1198                  * the pageout daemon is woken up.
1199                  *
1200                  * We can't wait forever for the vnode lock, we might
1201                  * deadlock due to a vn_read() getting stuck in
1202                  * vm_wait while holding this vnode.  We skip the
1203                  * vnode if we can't get it in a reasonable amount
1204                  * of time.
1205                  *
1206                  * vpfailed is used to (try to) avoid the case where
1207                  * a large number of pages are associated with a
1208                  * locked vnode, which could cause the pageout daemon
1209                  * to stall for an excessive amount of time.
1210                  */
1211                 if (object->type == OBJT_VNODE) {
1212                         int flags;
1213
1214                         vp = object->handle;
1215                         flags = LK_EXCLUSIVE;
1216                         if (vp == *vpfailedp)
1217                                 flags |= LK_NOWAIT;
1218                         else
1219                                 flags |= LK_TIMELOCK;
1220                         vm_page_hold(m);
1221                         vm_page_wakeup(m);
1222
1223                         /*
1224                          * We have unbusied (m) temporarily so we can
1225                          * acquire the vp lock without deadlocking.
1226                          * (m) is held to prevent destruction.
1227                          */
1228                         if (vget(vp, flags) != 0) {
1229                                 *vpfailedp = vp;
1230                                 ++pageout_lock_miss;
1231                                 if (object->flags & OBJ_MIGHTBEDIRTY)
1232                                             ++*vnodes_skippedp;
1233                                 vm_page_unhold(m);
1234                                 return 0;
1235                         }
1236
1237                         /*
1238                          * The page might have been moved to another
1239                          * queue during potential blocking in vget()
1240                          * above.  The page might have been freed and
1241                          * reused for another vnode.  The object might
1242                          * have been reused for another vnode.
1243                          */
1244                         if (m->queue - m->pc != PQ_INACTIVE ||
1245                             m->object != object ||
1246                             object->handle != vp) {
1247                                 if (object->flags & OBJ_MIGHTBEDIRTY)
1248                                         ++*vnodes_skippedp;
1249                                 vput(vp);
1250                                 vm_page_unhold(m);
1251                                 return 0;
1252                         }
1253
1254                         /*
1255                          * The page may have been busied during the
1256                          * blocking in vput();  We don't move the
1257                          * page back onto the end of the queue so that
1258                          * statistics are more correct if we don't.
1259                          */
1260                         if (vm_page_busy_try(m, TRUE)) {
1261                                 vput(vp);
1262                                 vm_page_unhold(m);
1263                                 return 0;
1264                         }
1265                         vm_page_unhold(m);
1266
1267                         /*
1268                          * If it was wired while we didn't own it.
1269                          */
1270                         if (m->wire_count) {
1271                                 vm_page_unqueue_nowakeup(m);
1272                                 vput(vp);
1273                                 vm_page_wakeup(m);
1274                                 return 0;
1275                         }
1276
1277                         /*
1278                          * (m) is busied again
1279                          *
1280                          * We own the busy bit and remove our hold
1281                          * bit.  If the page is still held it
1282                          * might be undergoing I/O, so skip it.
1283                          */
1284                         if (m->hold_count) {
1285                                 vm_page_and_queue_spin_lock(m);
1286                                 if (m->queue - m->pc == PQ_INACTIVE) {
1287                                         TAILQ_REMOVE(&vm_page_queues[m->queue].pl, m, pageq);
1288                                         TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m, pageq);
1289                                 }
1290                                 vm_page_and_queue_spin_unlock(m);
1291                                 if (object->flags & OBJ_MIGHTBEDIRTY)
1292                                         ++*vnodes_skippedp;
1293                                 vm_page_wakeup(m);
1294                                 vput(vp);
1295                                 return 0;
1296                         }
1297                         /* (m) is left busied as we fall through */
1298                 }
1299
1300                 /*
1301                  * page is busy and not held here.
1302                  *
1303                  * If a page is dirty, then it is either being washed
1304                  * (but not yet cleaned) or it is still in the
1305                  * laundry.  If it is still in the laundry, then we
1306                  * start the cleaning operation.
1307                  *
1308                  * decrement inactive_shortage on success to account
1309                  * for the (future) cleaned page.  Otherwise we
1310                  * could wind up laundering or cleaning too many
1311                  * pages.
1312                  *
1313                  * NOTE: Cleaning the page here does not cause
1314                  *       force_deficit to be adjusted, because the
1315                  *       page is not being freed or moved to the
1316                  *       cache.
1317                  */
1318                 count = vm_pageout_clean_helper(m, vmflush_flags);
1319                 *max_launderp -= count;
1320
1321                 /*
1322                  * Clean ate busy, page no longer accessible
1323                  */
1324                 if (vp != NULL)
1325                         vput(vp);
1326         } else {
1327                 vm_page_wakeup(m);
1328         }
1329         return count;
1330 }
1331
1332 /*
1333  * Scan active queue
1334  *
1335  * WARNING! Can be called from two pagedaemon threads simultaneously.
1336  */
1337 static int
1338 vm_pageout_scan_active(int pass, int q,
1339                        long avail_shortage, long inactive_shortage,
1340                        long *recycle_countp)
1341 {
1342         struct vm_page marker;
1343         vm_page_t m;
1344         int actcount;
1345         long delta = 0;
1346         long maxscan;
1347         int isep;
1348
1349         isep = (curthread == emergpager);
1350
1351         /*
1352          * We want to move pages from the active queue to the inactive
1353          * queue to get the inactive queue to the inactive target.  If
1354          * we still have a page shortage from above we try to directly free
1355          * clean pages instead of moving them.
1356          *
1357          * If we do still have a shortage we keep track of the number of
1358          * pages we free or cache (recycle_count) as a measure of thrashing
1359          * between the active and inactive queues.
1360          *
1361          * If we were able to completely satisfy the free+cache targets
1362          * from the inactive pool we limit the number of pages we move
1363          * from the active pool to the inactive pool to 2x the pages we
1364          * had removed from the inactive pool (with a minimum of 1/5 the
1365          * inactive target).  If we were not able to completely satisfy
1366          * the free+cache targets we go for the whole target aggressively.
1367          *
1368          * NOTE: Both variables can end up negative.
1369          * NOTE: We are still in a critical section.
1370          *
1371          * NOTE!  THE EMERGENCY PAGER (isep) DOES NOT LAUNDER VNODE-BACKED
1372          *        PAGES.
1373          */
1374
1375         bzero(&marker, sizeof(marker));
1376         marker.flags = PG_FICTITIOUS | PG_MARKER;
1377         marker.busy_count = PBUSY_LOCKED;
1378         marker.queue = PQ_ACTIVE + q;
1379         marker.pc = q;
1380         marker.wire_count = 1;
1381
1382         vm_page_queues_spin_lock(PQ_ACTIVE + q);
1383         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1384         maxscan = vm_page_queues[PQ_ACTIVE + q].lcnt;
1385
1386         /*
1387          * Queue locked at top of loop to avoid stack marker issues.
1388          */
1389         while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1390                maxscan-- > 0 && (avail_shortage - delta > 0 ||
1391                                 inactive_shortage > 0))
1392         {
1393                 KKASSERT(m->queue == PQ_ACTIVE + q);
1394                 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl,
1395                              &marker, pageq);
1396                 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1397                                    &marker, pageq);
1398
1399                 /*
1400                  * Skip marker pages (atomic against other markers to avoid
1401                  * infinite hop-over scans).
1402                  */
1403                 if (m->flags & PG_MARKER)
1404                         continue;
1405
1406                 /*
1407                  * Try to busy the page.  Don't mess with pages which are
1408                  * already busy or reorder them in the queue.
1409                  */
1410                 if (vm_page_busy_try(m, TRUE))
1411                         continue;
1412
1413                 /*
1414                  * Remaining operations run with the page busy and neither
1415                  * the page or the queue will be spin-locked.
1416                  */
1417                 KKASSERT(m->queue == PQ_ACTIVE + q);
1418                 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1419
1420 #if 0
1421                 /*
1422                  * Don't deactivate pages that are held, even if we can
1423                  * busy them.  (XXX why not?)
1424                  */
1425                 if (m->hold_count) {
1426                         vm_page_and_queue_spin_lock(m);
1427                         if (m->queue - m->pc == PQ_ACTIVE) {
1428                                 TAILQ_REMOVE(
1429                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1430                                         m, pageq);
1431                                 TAILQ_INSERT_TAIL(
1432                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1433                                         m, pageq);
1434                         }
1435                         vm_page_and_queue_spin_unlock(m);
1436                         vm_page_wakeup(m);
1437                         goto next;
1438                 }
1439 #endif
1440                 /*
1441                  * We can just remove wired pages from the queue
1442                  */
1443                 if (m->wire_count) {
1444                         vm_page_unqueue_nowakeup(m);
1445                         vm_page_wakeup(m);
1446                         goto next;
1447                 }
1448
1449                 /*
1450                  * The emergency pager ignores vnode-backed pages as these
1451                  * are the pages that probably bricked the main pager.
1452                  */
1453                 if (isep && m->object && m->object->type == OBJT_VNODE) {
1454                         vm_page_and_queue_spin_lock(m);
1455                         if (m->queue - m->pc == PQ_ACTIVE) {
1456                                 TAILQ_REMOVE(
1457                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1458                                         m, pageq);
1459                                 TAILQ_INSERT_TAIL(
1460                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1461                                         m, pageq);
1462                         }
1463                         vm_page_and_queue_spin_unlock(m);
1464                         vm_page_wakeup(m);
1465                         goto next;
1466                 }
1467
1468                 /*
1469                  * The count for pagedaemon pages is done after checking the
1470                  * page for eligibility...
1471                  */
1472                 mycpu->gd_cnt.v_pdpages++;
1473
1474                 /*
1475                  * Check to see "how much" the page has been used and clear
1476                  * the tracking access bits.  If the object has no references
1477                  * don't bother paying the expense.
1478                  */
1479                 actcount = 0;
1480                 if (m->object && m->object->ref_count != 0) {
1481                         if (m->flags & PG_REFERENCED)
1482                                 ++actcount;
1483                         actcount += pmap_ts_referenced(m);
1484                         if (actcount) {
1485                                 m->act_count += ACT_ADVANCE + actcount;
1486                                 if (m->act_count > ACT_MAX)
1487                                         m->act_count = ACT_MAX;
1488                         }
1489                 }
1490                 vm_page_flag_clear(m, PG_REFERENCED);
1491
1492                 /*
1493                  * actcount is only valid if the object ref_count is non-zero.
1494                  * If the page does not have an object, actcount will be zero.
1495                  */
1496                 if (actcount && m->object->ref_count != 0) {
1497                         vm_page_and_queue_spin_lock(m);
1498                         if (m->queue - m->pc == PQ_ACTIVE) {
1499                                 TAILQ_REMOVE(
1500                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1501                                         m, pageq);
1502                                 TAILQ_INSERT_TAIL(
1503                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1504                                         m, pageq);
1505                         }
1506                         vm_page_and_queue_spin_unlock(m);
1507                         vm_page_wakeup(m);
1508                 } else {
1509                         switch(m->object->type) {
1510                         case OBJT_DEFAULT:
1511                         case OBJT_SWAP:
1512                                 m->act_count -= min(m->act_count,
1513                                                     vm_anonmem_decline);
1514                                 break;
1515                         default:
1516                                 m->act_count -= min(m->act_count,
1517                                                     vm_filemem_decline);
1518                                 break;
1519                         }
1520                         if (vm_pageout_algorithm ||
1521                             (m->object == NULL) ||
1522                             (m->object && (m->object->ref_count == 0)) ||
1523                             m->act_count < pass + 1
1524                         ) {
1525                                 /*
1526                                  * Deactivate the page.  If we had a
1527                                  * shortage from our inactive scan try to
1528                                  * free (cache) the page instead.
1529                                  *
1530                                  * Don't just blindly cache the page if
1531                                  * we do not have a shortage from the
1532                                  * inactive scan, that could lead to
1533                                  * gigabytes being moved.
1534                                  */
1535                                 --inactive_shortage;
1536                                 if (avail_shortage - delta > 0 ||
1537                                     (m->object && (m->object->ref_count == 0)))
1538                                 {
1539                                         if (avail_shortage - delta > 0)
1540                                                 ++*recycle_countp;
1541                                         vm_page_protect(m, VM_PROT_NONE);
1542                                         if (m->dirty == 0 &&
1543                                             (m->flags & PG_NEED_COMMIT) == 0 &&
1544                                             avail_shortage - delta > 0) {
1545                                                 vm_page_cache(m);
1546                                         } else {
1547                                                 vm_page_deactivate(m);
1548                                                 vm_page_wakeup(m);
1549                                         }
1550                                 } else {
1551                                         vm_page_deactivate(m);
1552                                         vm_page_wakeup(m);
1553                                 }
1554                                 ++delta;
1555                         } else {
1556                                 vm_page_and_queue_spin_lock(m);
1557                                 if (m->queue - m->pc == PQ_ACTIVE) {
1558                                         TAILQ_REMOVE(
1559                                             &vm_page_queues[PQ_ACTIVE + q].pl,
1560                                             m, pageq);
1561                                         TAILQ_INSERT_TAIL(
1562                                             &vm_page_queues[PQ_ACTIVE + q].pl,
1563                                             m, pageq);
1564                                 }
1565                                 vm_page_and_queue_spin_unlock(m);
1566                                 vm_page_wakeup(m);
1567                         }
1568                 }
1569 next:
1570                 lwkt_yield();
1571                 vm_page_queues_spin_lock(PQ_ACTIVE + q);
1572         }
1573
1574         /*
1575          * Clean out our local marker.
1576          *
1577          * Page queue still spin-locked.
1578          */
1579         TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1580         vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1581
1582         return (delta);
1583 }
1584
1585 /*
1586  * The number of actually free pages can drop down to v_free_reserved,
1587  * we try to build the free count back above v_free_min.  Note that
1588  * vm_paging_needed() also returns TRUE if v_free_count is not at
1589  * least v_free_min so that is the minimum we must build the free
1590  * count to.
1591  *
1592  * We use a slightly higher target to improve hysteresis,
1593  * ((v_free_target + v_free_min) / 2).  Since v_free_target
1594  * is usually the same as v_cache_min this maintains about
1595  * half the pages in the free queue as are in the cache queue,
1596  * providing pretty good pipelining for pageout operation.
1597  *
1598  * The system operator can manipulate vm.v_cache_min and
1599  * vm.v_free_target to tune the pageout demon.  Be sure
1600  * to keep vm.v_free_min < vm.v_free_target.
1601  *
1602  * Note that the original paging target is to get at least
1603  * (free_min + cache_min) into (free + cache).  The slightly
1604  * higher target will shift additional pages from cache to free
1605  * without effecting the original paging target in order to
1606  * maintain better hysteresis and not have the free count always
1607  * be dead-on v_free_min.
1608  *
1609  * NOTE: we are still in a critical section.
1610  *
1611  * Pages moved from PQ_CACHE to totally free are not counted in the
1612  * pages_freed counter.
1613  *
1614  * WARNING! Can be called from two pagedaemon threads simultaneously.
1615  */
1616 static void
1617 vm_pageout_scan_cache(long avail_shortage, int pass,
1618                       long vnodes_skipped, long recycle_count)
1619 {
1620         static int lastkillticks;
1621         struct vm_pageout_scan_info info;
1622         vm_page_t m;
1623         int isep;
1624
1625         isep = (curthread == emergpager);
1626
1627         while (vmstats.v_free_count <
1628                (vmstats.v_free_min + vmstats.v_free_target) / 2) {
1629                 /*
1630                  * This steals some code from vm/vm_page.c
1631                  *
1632                  * Create two rovers and adjust the code to reduce
1633                  * chances of them winding up at the same index (which
1634                  * can cause a lot of contention).
1635                  */
1636                 static int cache_rover[2] = { 0, PQ_L2_MASK / 2 };
1637
1638                 if (((cache_rover[0] ^ cache_rover[1]) & PQ_L2_MASK) == 0)
1639                         goto next_rover;
1640
1641                 m = vm_page_list_find(PQ_CACHE, cache_rover[isep] & PQ_L2_MASK);
1642                 if (m == NULL)
1643                         break;
1644
1645                 /*
1646                  * If the busy attempt fails we can still deactivate the page.
1647                  */
1648                 /* page is returned removed from its queue and spinlocked */
1649                 if (vm_page_busy_try(m, TRUE)) {
1650                         vm_page_deactivate_locked(m);
1651                         vm_page_spin_unlock(m);
1652                         continue;
1653                 }
1654                 vm_page_spin_unlock(m);
1655                 pagedaemon_wakeup();
1656                 lwkt_yield();
1657
1658                 /*
1659                  * Remaining operations run with the page busy and neither
1660                  * the page or the queue will be spin-locked.
1661                  */
1662                 if ((m->flags & (PG_UNQUEUED | PG_NEED_COMMIT)) ||
1663                     m->hold_count ||
1664                     m->wire_count) {
1665                         vm_page_deactivate(m);
1666                         vm_page_wakeup(m);
1667                         continue;
1668                 }
1669                 pmap_mapped_sync(m);
1670                 KKASSERT((m->flags & PG_MAPPED) == 0);
1671                 KKASSERT(m->dirty == 0);
1672                 vm_pageout_page_free(m);
1673                 mycpu->gd_cnt.v_dfree++;
1674 next_rover:
1675                 if (isep)
1676                         cache_rover[1] -= PQ_PRIME2;
1677                 else
1678                         cache_rover[0] += PQ_PRIME2;
1679         }
1680
1681 #if !defined(NO_SWAPPING)
1682         /*
1683          * Idle process swapout -- run once per second.
1684          */
1685         if (vm_swap_idle_enabled) {
1686                 static time_t lsec;
1687                 if (time_uptime != lsec) {
1688                         atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_IDLE);
1689                         vm_req_vmdaemon();
1690                         lsec = time_uptime;
1691                 }
1692         }
1693 #endif
1694                 
1695         /*
1696          * If we didn't get enough free pages, and we have skipped a vnode
1697          * in a writeable object, wakeup the sync daemon.  And kick swapout
1698          * if we did not get enough free pages.
1699          */
1700         if (vm_paging_target() > 0) {
1701                 if (vnodes_skipped && vm_page_count_min(0))
1702                         speedup_syncer(NULL);
1703 #if !defined(NO_SWAPPING)
1704                 if (vm_swap_enabled && vm_page_count_target()) {
1705                         atomic_set_int(&vm_pageout_req_swapout, VM_SWAP_NORMAL);
1706                         vm_req_vmdaemon();
1707                 }
1708 #endif
1709         }
1710
1711         /*
1712          * Handle catastrophic conditions.  Under good conditions we should
1713          * be at the target, well beyond our minimum.  If we could not even
1714          * reach our minimum the system is under heavy stress.  But just being
1715          * under heavy stress does not trigger process killing.
1716          *
1717          * We consider ourselves to have run out of memory if the swap pager
1718          * is full and avail_shortage is still positive.  The secondary check
1719          * ensures that we do not kill processes if the instantanious
1720          * availability is good, even if the pageout demon pass says it
1721          * couldn't get to the target.
1722          *
1723          * NOTE!  THE EMERGENCY PAGER (isep) DOES NOT HANDLE SWAP FULL
1724          *        SITUATIONS.
1725          */
1726         if (swap_pager_almost_full &&
1727             pass > 0 &&
1728             isep == 0 &&
1729             (vm_page_count_min(recycle_count) || avail_shortage > 0)) {
1730                 kprintf("Warning: system low on memory+swap "
1731                         "shortage %ld for %d ticks!\n",
1732                         avail_shortage, ticks - swap_fail_ticks);
1733                 if (bootverbose)
1734                 kprintf("Metrics: spaf=%d spf=%d pass=%d "
1735                         "avail=%ld target=%ld last=%u\n",
1736                         swap_pager_almost_full,
1737                         swap_pager_full,
1738                         pass,
1739                         avail_shortage,
1740                         vm_paging_target(),
1741                         (unsigned int)(ticks - lastkillticks));
1742         }
1743         if (swap_pager_full &&
1744             pass > 1 &&
1745             isep == 0 &&
1746             avail_shortage > 0 &&
1747             vm_paging_target() > 0 &&
1748             (unsigned int)(ticks - lastkillticks) >= hz) {
1749                 /*
1750                  * Kill something, maximum rate once per second to give
1751                  * the process time to free up sufficient memory.
1752                  */
1753                 lastkillticks = ticks;
1754                 info.bigproc = NULL;
1755                 info.bigsize = 0;
1756                 allproc_scan(vm_pageout_scan_callback, &info, 0);
1757                 if (info.bigproc != NULL) {
1758                         kprintf("Try to kill process %d %s\n",
1759                                 info.bigproc->p_pid, info.bigproc->p_comm);
1760                         info.bigproc->p_nice = PRIO_MIN;
1761                         info.bigproc->p_usched->resetpriority(
1762                                 FIRST_LWP_IN_PROC(info.bigproc));
1763                         atomic_set_int(&info.bigproc->p_flags, P_LOWMEMKILL);
1764                         killproc(info.bigproc, "out of swap space");
1765                         wakeup(&vmstats.v_free_count);
1766                         PRELE(info.bigproc);
1767                 }
1768         }
1769 }
1770
1771 static int
1772 vm_pageout_scan_callback(struct proc *p, void *data)
1773 {
1774         struct vm_pageout_scan_info *info = data;
1775         vm_offset_t size;
1776
1777         /*
1778          * Never kill system processes or init.  If we have configured swap
1779          * then try to avoid killing low-numbered pids.
1780          */
1781         if ((p->p_flags & P_SYSTEM) || (p->p_pid == 1) ||
1782             ((p->p_pid < 48) && (vm_swap_size != 0))) {
1783                 return (0);
1784         }
1785
1786         lwkt_gettoken(&p->p_token);
1787
1788         /*
1789          * if the process is in a non-running type state,
1790          * don't touch it.
1791          */
1792         if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
1793                 lwkt_reltoken(&p->p_token);
1794                 return (0);
1795         }
1796
1797         /*
1798          * Get the approximate process size.  Note that anonymous pages
1799          * with backing swap will be counted twice, but there should not
1800          * be too many such pages due to the stress the VM system is
1801          * under at this point.
1802          */
1803         size = vmspace_anonymous_count(p->p_vmspace) +
1804                 vmspace_swap_count(p->p_vmspace);
1805
1806         /*
1807          * If the this process is bigger than the biggest one
1808          * remember it.
1809          */
1810         if (info->bigsize < size) {
1811                 if (info->bigproc)
1812                         PRELE(info->bigproc);
1813                 PHOLD(p);
1814                 info->bigproc = p;
1815                 info->bigsize = size;
1816         }
1817         lwkt_reltoken(&p->p_token);
1818         lwkt_yield();
1819
1820         return(0);
1821 }
1822
1823 /*
1824  * This old guy slowly walks PQ_HOLD looking for pages which need to be
1825  * moved back to PQ_FREE.  It is possible for pages to accumulate here
1826  * when vm_page_free() races against vm_page_unhold(), resulting in a
1827  * page being left on a PQ_HOLD queue with hold_count == 0.
1828  *
1829  * It is easier to handle this edge condition here, in non-critical code,
1830  * rather than enforce a spin-lock for every 1->0 transition in
1831  * vm_page_unhold().
1832  *
1833  * NOTE: TAILQ_FOREACH becomes invalid the instant we unlock the queue.
1834  */
1835 static void
1836 vm_pageout_scan_hold(int q)
1837 {
1838         vm_page_t m;
1839
1840         vm_page_queues_spin_lock(PQ_HOLD + q);
1841         TAILQ_FOREACH(m, &vm_page_queues[PQ_HOLD + q].pl, pageq) {
1842                 if (m->flags & PG_MARKER)
1843                         continue;
1844
1845                 /*
1846                  * Process one page and return
1847                  */
1848                 if (m->hold_count)
1849                         break;
1850                 kprintf("DEBUG: pageout HOLD->FREE %p\n", m);
1851                 vm_page_hold(m);
1852                 vm_page_queues_spin_unlock(PQ_HOLD + q);
1853                 vm_page_unhold(m);      /* reprocess */
1854                 return;
1855         }
1856         vm_page_queues_spin_unlock(PQ_HOLD + q);
1857 }
1858
1859 /*
1860  * This routine tries to maintain the pseudo LRU active queue,
1861  * so that during long periods of time where there is no paging,
1862  * that some statistic accumulation still occurs.  This code
1863  * helps the situation where paging just starts to occur.
1864  */
1865 static void
1866 vm_pageout_page_stats(int q)
1867 {
1868         static int fullintervalcount = 0;
1869         struct vm_page marker;
1870         vm_page_t m;
1871         long pcount, tpcount;           /* Number of pages to check */
1872         long page_shortage;
1873
1874         page_shortage = (vmstats.v_inactive_target + vmstats.v_cache_max +
1875                          vmstats.v_free_min) -
1876                         (vmstats.v_free_count + vmstats.v_inactive_count +
1877                          vmstats.v_cache_count);
1878
1879         if (page_shortage <= 0)
1880                 return;
1881
1882         pcount = vm_page_queues[PQ_ACTIVE + q].lcnt;
1883         fullintervalcount += vm_pageout_stats_interval;
1884         if (fullintervalcount < vm_pageout_full_stats_interval) {
1885                 tpcount = (vm_pageout_stats_max * pcount) /
1886                           vmstats.v_page_count + 1;
1887                 if (pcount > tpcount)
1888                         pcount = tpcount;
1889         } else {
1890                 fullintervalcount = 0;
1891         }
1892
1893         bzero(&marker, sizeof(marker));
1894         marker.flags = PG_FICTITIOUS | PG_MARKER;
1895         marker.busy_count = PBUSY_LOCKED;
1896         marker.queue = PQ_ACTIVE + q;
1897         marker.pc = q;
1898         marker.wire_count = 1;
1899
1900         vm_page_queues_spin_lock(PQ_ACTIVE + q);
1901         TAILQ_INSERT_HEAD(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1902
1903         /*
1904          * Queue locked at top of loop to avoid stack marker issues.
1905          */
1906         while ((m = TAILQ_NEXT(&marker, pageq)) != NULL &&
1907                pcount-- > 0)
1908         {
1909                 int actcount;
1910
1911                 KKASSERT(m->queue == PQ_ACTIVE + q);
1912                 TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
1913                 TAILQ_INSERT_AFTER(&vm_page_queues[PQ_ACTIVE + q].pl, m,
1914                                    &marker, pageq);
1915
1916                 /*
1917                  * Skip marker pages (atomic against other markers to avoid
1918                  * infinite hop-over scans).
1919                  */
1920                 if (m->flags & PG_MARKER)
1921                         continue;
1922
1923                 /*
1924                  * Ignore pages we can't busy
1925                  */
1926                 if (vm_page_busy_try(m, TRUE))
1927                         continue;
1928
1929                 /*
1930                  * Remaining operations run with the page busy and neither
1931                  * the page or the queue will be spin-locked.
1932                  */
1933                 KKASSERT(m->queue == PQ_ACTIVE + q);
1934                 vm_page_queues_spin_unlock(PQ_ACTIVE + q);
1935
1936                 /*
1937                  * We can just remove wired pages from the queue
1938                  */
1939                 if (m->wire_count) {
1940                         vm_page_unqueue_nowakeup(m);
1941                         vm_page_wakeup(m);
1942                         goto next;
1943                 }
1944
1945
1946                 /*
1947                  * We now have a safely busied page, the page and queue
1948                  * spinlocks have been released.
1949                  *
1950                  * Ignore held and wired pages
1951                  */
1952                 if (m->hold_count || m->wire_count) {
1953                         vm_page_wakeup(m);
1954                         goto next;
1955                 }
1956
1957                 /*
1958                  * Calculate activity
1959                  */
1960                 actcount = 0;
1961                 if (m->flags & PG_REFERENCED) {
1962                         vm_page_flag_clear(m, PG_REFERENCED);
1963                         actcount += 1;
1964                 }
1965                 actcount += pmap_ts_referenced(m);
1966
1967                 /*
1968                  * Update act_count and move page to end of queue.
1969                  */
1970                 if (actcount) {
1971                         m->act_count += ACT_ADVANCE + actcount;
1972                         if (m->act_count > ACT_MAX)
1973                                 m->act_count = ACT_MAX;
1974                         vm_page_and_queue_spin_lock(m);
1975                         if (m->queue - m->pc == PQ_ACTIVE) {
1976                                 TAILQ_REMOVE(
1977                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1978                                         m, pageq);
1979                                 TAILQ_INSERT_TAIL(
1980                                         &vm_page_queues[PQ_ACTIVE + q].pl,
1981                                         m, pageq);
1982                         }
1983                         vm_page_and_queue_spin_unlock(m);
1984                         vm_page_wakeup(m);
1985                         goto next;
1986                 }
1987
1988                 if (m->act_count == 0) {
1989                         /*
1990                          * We turn off page access, so that we have
1991                          * more accurate RSS stats.  We don't do this
1992                          * in the normal page deactivation when the
1993                          * system is loaded VM wise, because the
1994                          * cost of the large number of page protect
1995                          * operations would be higher than the value
1996                          * of doing the operation.
1997                          *
1998                          * We use the marker to save our place so
1999                          * we can release the spin lock.  both (m)
2000                          * and (next) will be invalid.
2001                          */
2002                         vm_page_protect(m, VM_PROT_NONE);
2003                         vm_page_deactivate(m);
2004                 } else {
2005                         m->act_count -= min(m->act_count, ACT_DECLINE);
2006                         vm_page_and_queue_spin_lock(m);
2007                         if (m->queue - m->pc == PQ_ACTIVE) {
2008                                 TAILQ_REMOVE(
2009                                         &vm_page_queues[PQ_ACTIVE + q].pl,
2010                                         m, pageq);
2011                                 TAILQ_INSERT_TAIL(
2012                                         &vm_page_queues[PQ_ACTIVE + q].pl,
2013                                         m, pageq);
2014                         }
2015                         vm_page_and_queue_spin_unlock(m);
2016                 }
2017                 vm_page_wakeup(m);
2018 next:
2019                 vm_page_queues_spin_lock(PQ_ACTIVE + q);
2020         }
2021
2022         /*
2023          * Remove our local marker
2024          *
2025          * Page queue still spin-locked.
2026          */
2027         TAILQ_REMOVE(&vm_page_queues[PQ_ACTIVE + q].pl, &marker, pageq);
2028         vm_page_queues_spin_unlock(PQ_ACTIVE + q);
2029 }
2030
2031 static void
2032 vm_pageout_free_page_calc(vm_size_t count)
2033 {
2034         /*
2035          * v_free_min           normal allocations
2036          * v_free_reserved      system allocations
2037          * v_pageout_free_min   allocations by pageout daemon
2038          * v_interrupt_free_min low level allocations (e.g swap structures)
2039          *
2040          * v_free_min is used to generate several other baselines, and they
2041          * can get pretty silly on systems with a lot of memory.
2042          */
2043         vmstats.v_free_min = 64 + vmstats.v_page_count / 200;
2044         vmstats.v_free_reserved = vmstats.v_free_min * 4 / 8 + 7;
2045         vmstats.v_free_severe = vmstats.v_free_min * 4 / 8 + 0;
2046         vmstats.v_pageout_free_min = vmstats.v_free_min * 2 / 8 + 7;
2047         vmstats.v_interrupt_free_min = vmstats.v_free_min * 1 / 8 + 7;
2048 }
2049
2050
2051 /*
2052  * vm_pageout is the high level pageout daemon.  TWO kernel threads run
2053  * this daemon, the primary pageout daemon and the emergency pageout daemon.
2054  *
2055  * The emergency pageout daemon takes over when the primary pageout daemon
2056  * deadlocks.  The emergency pageout daemon ONLY pages out to swap, thus
2057  * avoiding the many low-memory deadlocks which can occur when paging out
2058  * to VFS's.
2059  */
2060 static void
2061 vm_pageout_thread(void)
2062 {
2063         int pass;
2064         int q;
2065         int q1iterator = 0;
2066         int q2iterator = 0;
2067         int q3iterator = 0;
2068         int isep;
2069
2070         curthread->td_flags |= TDF_SYSTHREAD;
2071
2072         /*
2073          * We only need to setup once.
2074          */
2075         isep = 0;
2076         if (curthread == emergpager) {
2077                 isep = 1;
2078                 goto skip_setup;
2079         }
2080
2081         /*
2082          * Initialize some paging parameters.
2083          */
2084         vm_pageout_free_page_calc(vmstats.v_page_count);
2085
2086         /*
2087          * v_free_target and v_cache_min control pageout hysteresis.  Note
2088          * that these are more a measure of the VM cache queue hysteresis
2089          * then the VM free queue.  Specifically, v_free_target is the
2090          * high water mark (free+cache pages).
2091          *
2092          * v_free_reserved + v_cache_min (mostly means v_cache_min) is the
2093          * low water mark, while v_free_min is the stop.  v_cache_min must
2094          * be big enough to handle memory needs while the pageout daemon
2095          * is signalled and run to free more pages.
2096          */
2097         vmstats.v_free_target = 4 * vmstats.v_free_min +
2098                                 vmstats.v_free_reserved;
2099
2100         /*
2101          * NOTE: With the new buffer cache b_act_count we want the default
2102          *       inactive target to be a percentage of available memory.
2103          *
2104          *       The inactive target essentially determines the minimum
2105          *       number of 'temporary' pages capable of caching one-time-use
2106          *       files when the VM system is otherwise full of pages
2107          *       belonging to multi-time-use files or active program data.
2108          *
2109          * NOTE: The inactive target is aggressively persued only if the
2110          *       inactive queue becomes too small.  If the inactive queue
2111          *       is large enough to satisfy page movement to free+cache
2112          *       then it is repopulated more slowly from the active queue.
2113          *       This allows a general inactive_target default to be set.
2114          *
2115          *       There is an issue here for processes which sit mostly idle
2116          *       'overnight', such as sshd, tcsh, and X.  Any movement from
2117          *       the active queue will eventually cause such pages to
2118          *       recycle eventually causing a lot of paging in the morning.
2119          *       To reduce the incidence of this pages cycled out of the
2120          *       buffer cache are moved directly to the inactive queue if
2121          *       they were only used once or twice.
2122          *
2123          *       The vfs.vm_cycle_point sysctl can be used to adjust this.
2124          *       Increasing the value (up to 64) increases the number of
2125          *       buffer recyclements which go directly to the inactive queue.
2126          */
2127         if (vmstats.v_free_count > 2048) {
2128                 vmstats.v_cache_min = vmstats.v_free_target;
2129                 vmstats.v_cache_max = 2 * vmstats.v_cache_min;
2130         } else {
2131                 vmstats.v_cache_min = 0;
2132                 vmstats.v_cache_max = 0;
2133         }
2134         vmstats.v_inactive_target = vmstats.v_free_count / 4;
2135
2136         /* XXX does not really belong here */
2137         if (vm_page_max_wired == 0)
2138                 vm_page_max_wired = vmstats.v_free_count / 3;
2139
2140         if (vm_pageout_stats_max == 0)
2141                 vm_pageout_stats_max = vmstats.v_free_target;
2142
2143         /*
2144          * Set interval in seconds for stats scan.
2145          */
2146         if (vm_pageout_stats_interval == 0)
2147                 vm_pageout_stats_interval = 5;
2148         if (vm_pageout_full_stats_interval == 0)
2149                 vm_pageout_full_stats_interval = vm_pageout_stats_interval * 4;
2150         
2151
2152         /*
2153          * Set maximum free per pass
2154          */
2155         if (vm_pageout_stats_free_max == 0)
2156                 vm_pageout_stats_free_max = 5;
2157
2158         swap_pager_swap_init();
2159         pass = 0;
2160
2161         atomic_swap_int(&sequence_emerg_pager, 1);
2162         wakeup(&sequence_emerg_pager);
2163
2164 skip_setup:
2165         /*
2166          * Sequence emergency pager startup
2167          */
2168         if (isep) {
2169                 while (sequence_emerg_pager == 0)
2170                         tsleep(&sequence_emerg_pager, 0, "pstartup", hz);
2171         }
2172
2173         /*
2174          * The pageout daemon is never done, so loop forever.
2175          *
2176          * WARNING!  This code is being executed by two kernel threads
2177          *           potentially simultaneously.
2178          */
2179         while (TRUE) {
2180                 int error;
2181                 long avail_shortage;
2182                 long inactive_shortage;
2183                 long vnodes_skipped = 0;
2184                 long recycle_count = 0;
2185                 long tmp;
2186
2187                 /*
2188                  * Wait for an action request.  If we timeout check to
2189                  * see if paging is needed (in case the normal wakeup
2190                  * code raced us).
2191                  */
2192                 if (isep) {
2193                         /*
2194                          * Emergency pagedaemon monitors the primary
2195                          * pagedaemon while vm_pages_needed != 0.
2196                          *
2197                          * The emergency pagedaemon only runs if VM paging
2198                          * is needed and the primary pagedaemon has not
2199                          * updated vm_pagedaemon_time for more than 2 seconds.
2200                          */
2201                         if (vm_pages_needed)
2202                                 tsleep(&vm_pagedaemon_time, 0, "psleep", hz);
2203                         else
2204                                 tsleep(&vm_pagedaemon_time, 0, "psleep", hz*10);
2205                         if (vm_pages_needed == 0) {
2206                                 pass = 0;
2207                                 continue;
2208                         }
2209                         if ((int)(ticks - vm_pagedaemon_time) < hz * 2) {
2210                                 pass = 0;
2211                                 continue;
2212                         }
2213                 } else {
2214                         /*
2215                          * Primary pagedaemon
2216                          *
2217                          * NOTE: We unconditionally cleanup PQ_HOLD even
2218                          *       when there is no work to do.
2219                          */
2220                         vm_pageout_scan_hold(q3iterator & PQ_L2_MASK);
2221                         ++q3iterator;
2222
2223                         if (vm_pages_needed == 0) {
2224                                 error = tsleep(&vm_pages_needed,
2225                                                0, "psleep",
2226                                                vm_pageout_stats_interval * hz);
2227                                 if (error &&
2228                                     vm_paging_needed(0) == 0 &&
2229                                     vm_pages_needed == 0) {
2230                                         for (q = 0; q < PQ_L2_SIZE; ++q)
2231                                                 vm_pageout_page_stats(q);
2232                                         continue;
2233                                 }
2234                                 vm_pagedaemon_time = ticks;
2235                                 vm_pages_needed = 1;
2236
2237                                 /*
2238                                  * Wake the emergency pagedaemon up so it
2239                                  * can monitor us.  It will automatically
2240                                  * go back into a long sleep when
2241                                  * vm_pages_needed returns to 0.
2242                                  */
2243                                 wakeup(&vm_pagedaemon_time);
2244                         }
2245                 }
2246
2247                 mycpu->gd_cnt.v_pdwakeups++;
2248
2249                 /*
2250                  * Scan for INACTIVE->CLEAN/PAGEOUT
2251                  *
2252                  * This routine tries to avoid thrashing the system with
2253                  * unnecessary activity.
2254                  *
2255                  * Calculate our target for the number of free+cache pages we
2256                  * want to get to.  This is higher then the number that causes
2257                  * allocations to stall (severe) in order to provide hysteresis,
2258                  * and if we don't make it all the way but get to the minimum
2259                  * we're happy.  Goose it a bit if there are multiple requests
2260                  * for memory.
2261                  *
2262                  * Don't reduce avail_shortage inside the loop or the
2263                  * PQAVERAGE() calculation will break.
2264                  *
2265                  * NOTE! deficit is differentiated from avail_shortage as
2266                  *       REQUIRING at least (deficit) pages to be cleaned,
2267                  *       even if the page queues are in good shape.  This
2268                  *       is used primarily for handling per-process
2269                  *       RLIMIT_RSS and may also see small values when
2270                  *       processes block due to low memory.
2271                  */
2272                 vmstats_rollup();
2273                 if (isep == 0)
2274                         vm_pagedaemon_time = ticks;
2275                 avail_shortage = vm_paging_target() + vm_pageout_deficit;
2276                 vm_pageout_deficit = 0;
2277
2278                 if (avail_shortage > 0) {
2279                         long delta = 0;
2280                         int qq;
2281
2282                         qq = q1iterator;
2283                         for (q = 0; q < PQ_L2_SIZE; ++q) {
2284                                 delta += vm_pageout_scan_inactive(
2285                                             pass,
2286                                             qq & PQ_L2_MASK,
2287                                             PQAVERAGE(avail_shortage),
2288                                             &vnodes_skipped);
2289                                 if (isep)
2290                                         --qq;
2291                                 else
2292                                         ++qq;
2293                                 if (avail_shortage - delta <= 0)
2294                                         break;
2295
2296                                 /*
2297                                  * It is possible for avail_shortage to be
2298                                  * very large.  If a large program exits or
2299                                  * frees a ton of memory all at once, we do
2300                                  * not have to continue deactivations.
2301                                  *
2302                                  * (We will still run the active->inactive
2303                                  * target, however).
2304                                  */
2305                                 if (!vm_page_count_target() &&
2306                                     !vm_page_count_min(
2307                                                 vm_page_free_hysteresis)) {
2308                                         avail_shortage = 0;
2309                                         break;
2310                                 }
2311                         }
2312                         avail_shortage -= delta;
2313                         q1iterator = qq;
2314                 }
2315
2316                 /*
2317                  * Figure out how many active pages we must deactivate.  If
2318                  * we were able to reach our target with just the inactive
2319                  * scan above we limit the number of active pages we
2320                  * deactivate to reduce unnecessary work.
2321                  */
2322                 vmstats_rollup();
2323                 if (isep == 0)
2324                         vm_pagedaemon_time = ticks;
2325                 inactive_shortage = vmstats.v_inactive_target -
2326                                     vmstats.v_inactive_count;
2327
2328                 /*
2329                  * If we were unable to free sufficient inactive pages to
2330                  * satisfy the free/cache queue requirements then simply
2331                  * reaching the inactive target may not be good enough.
2332                  * Try to deactivate pages in excess of the target based
2333                  * on the shortfall.
2334                  *
2335                  * However to prevent thrashing the VM system do not
2336                  * deactivate more than an additional 1/10 the inactive
2337                  * target's worth of active pages.
2338                  */
2339                 if (avail_shortage > 0) {
2340                         tmp = avail_shortage * 2;
2341                         if (tmp > vmstats.v_inactive_target / 10)
2342                                 tmp = vmstats.v_inactive_target / 10;
2343                         inactive_shortage += tmp;
2344                 }
2345
2346                 /*
2347                  * Only trigger a pmap cleanup on inactive shortage.
2348                  */
2349                 if (isep == 0 && inactive_shortage > 0) {
2350                         pmap_collect();
2351                 }
2352
2353                 /*
2354                  * Scan for ACTIVE->INACTIVE
2355                  *
2356                  * Only trigger on inactive shortage.  Triggering on
2357                  * avail_shortage can starve the active queue with
2358                  * unnecessary active->inactive transitions and destroy
2359                  * performance.
2360                  *
2361                  * If this is the emergency pager, always try to move
2362                  * a few pages from active to inactive because the inactive
2363                  * queue might have enough pages, but not enough anonymous
2364                  * pages.
2365                  */
2366                 if (isep && inactive_shortage < vm_emerg_launder)
2367                         inactive_shortage = vm_emerg_launder;
2368
2369                 if (/*avail_shortage > 0 ||*/ inactive_shortage > 0) {
2370                         long delta = 0;
2371                         int qq;
2372
2373                         qq = q2iterator;
2374                         for (q = 0; q < PQ_L2_SIZE; ++q) {
2375                                 delta += vm_pageout_scan_active(
2376                                                 pass,
2377                                                 qq & PQ_L2_MASK,
2378                                                 PQAVERAGE(avail_shortage),
2379                                                 PQAVERAGE(inactive_shortage),
2380                                                 &recycle_count);
2381                                 if (isep)
2382                                         --qq;
2383                                 else
2384                                         ++qq;
2385                                 if (inactive_shortage - delta <= 0 &&
2386                                     avail_shortage - delta <= 0) {
2387                                         break;
2388                                 }
2389
2390                                 /*
2391                                  * inactive_shortage can be a very large
2392                                  * number.  This is intended to break out
2393                                  * early if our inactive_target has been
2394                                  * reached due to other system activity.
2395                                  */
2396                                 if (vmstats.v_inactive_count >
2397                                     vmstats.v_inactive_target) {
2398                                         inactive_shortage = 0;
2399                                         break;
2400                                 }
2401                         }
2402                         inactive_shortage -= delta;
2403                         avail_shortage -= delta;
2404                         q2iterator = qq;
2405                 }
2406
2407                 /*
2408                  * Scan for CACHE->FREE
2409                  *
2410                  * Finally free enough cache pages to meet our free page
2411                  * requirement and take more drastic measures if we are
2412                  * still in trouble.
2413                  */
2414                 vmstats_rollup();
2415                 if (isep == 0)
2416                         vm_pagedaemon_time = ticks;
2417                 vm_pageout_scan_cache(avail_shortage, pass,
2418                                       vnodes_skipped, recycle_count);
2419
2420                 /*
2421                  * This is a bit sophisticated because we do not necessarily
2422                  * want to force paging until our targets are reached if we
2423                  * were able to successfully retire the shortage we calculated.
2424                  */
2425                 if (avail_shortage > 0) {
2426                         /*
2427                          * If we did not retire enough pages continue the
2428                          * pageout operation until we are able to.
2429                          */
2430                         ++pass;
2431
2432                         if (pass < 10 && vm_pages_needed > 1) {
2433                                 /*
2434                                  * Normal operation, additional processes
2435                                  * have already kicked us.  Retry immediately
2436                                  * unless swap space is completely full in
2437                                  * which case delay a bit.
2438                                  */
2439                                 if (swap_pager_full) {
2440                                         tsleep(&vm_pages_needed, 0, "pdelay",
2441                                                 hz / 5);
2442                                 } /* else immediate retry */
2443                         } else if (pass < 10) {
2444                                 /*
2445                                  * Do a short sleep for the first 10 passes,
2446                                  * allow the sleep to be woken up by resetting
2447                                  * vm_pages_needed to 1 (NOTE: we are still
2448                                  * active paging!).
2449                                  */
2450                                 if (isep == 0)
2451                                         vm_pages_needed = 1;
2452                                 tsleep(&vm_pages_needed, 0, "pdelay", 2);
2453                         } else if (swap_pager_full == 0) {
2454                                 /*
2455                                  * We've taken too many passes, force a
2456                                  * longer delay.
2457                                  */
2458                                 tsleep(&vm_pages_needed, 0, "pdelay", hz / 10);
2459                         } else {
2460                                 /*
2461                                  * Running out of memory, catastrophic
2462                                  * back-off to one-second intervals.
2463                                  */
2464                                 tsleep(&vm_pages_needed, 0, "pdelay", hz);
2465                         }
2466                 } else if (vm_pages_needed) {
2467                         /*
2468                          * We retired our calculated shortage but we may have
2469                          * to continue paging if threads drain memory too far
2470                          * below our target.
2471                          *
2472                          * Similar to vm_page_free_wakeup() in vm_page.c.
2473                          */
2474                         pass = 0;
2475                         if (!vm_paging_needed(0)) {
2476                                 /* still more than half-way to our target */
2477                                 vm_pages_needed = 0;
2478                                 wakeup(&vmstats.v_free_count);
2479                         } else
2480                         if (!vm_page_count_min(vm_page_free_hysteresis)) {
2481                                 /*
2482                                  * Continue operations with wakeup
2483                                  * (set variable to avoid overflow)
2484                                  */
2485                                 vm_pages_needed = 2;
2486                                 wakeup(&vmstats.v_free_count);
2487                         } else {
2488                                 /*
2489                                  * No wakeup() needed, continue operations.
2490                                  * (set variable to avoid overflow)
2491                                  */
2492                                 vm_pages_needed = 2;
2493                         }
2494                 } else {
2495                         /*
2496                          * Turn paging back on immediately if we are under
2497                          * minimum.
2498                          */
2499                         pass = 0;
2500                 }
2501         }
2502 }
2503
2504 static struct kproc_desc pg1_kp = {
2505         "pagedaemon",
2506         vm_pageout_thread,
2507         &pagethread
2508 };
2509 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, kproc_start, &pg1_kp);
2510
2511 static struct kproc_desc pg2_kp = {
2512         "emergpager",
2513         vm_pageout_thread,
2514         &emergpager
2515 };
2516 SYSINIT(emergpager, SI_SUB_KTHREAD_PAGE, SI_ORDER_ANY, kproc_start, &pg2_kp);
2517
2518
2519 /*
2520  * Called after allocating a page out of the cache or free queue
2521  * to possibly wake the pagedaemon up to replentish our supply.
2522  *
2523  * We try to generate some hysteresis by waking the pagedaemon up
2524  * when our free+cache pages go below the free_min+cache_min level.
2525  * The pagedaemon tries to get the count back up to at least the
2526  * minimum, and through to the target level if possible.
2527  *
2528  * If the pagedaemon is already active bump vm_pages_needed as a hint
2529  * that there are even more requests pending.
2530  *
2531  * SMP races ok?
2532  * No requirements.
2533  */
2534 void
2535 pagedaemon_wakeup(void)
2536 {
2537         if (vm_paging_needed(0) && curthread != pagethread) {
2538                 if (vm_pages_needed <= 1) {
2539                         vm_pages_needed = 1;            /* SMP race ok */
2540                         wakeup(&vm_pages_needed);       /* tickle pageout */
2541                 } else if (vm_page_count_min(0)) {
2542                         ++vm_pages_needed;              /* SMP race ok */
2543                         /* a wakeup() would be wasted here */
2544                 }
2545         }
2546 }
2547
2548 #if !defined(NO_SWAPPING)
2549
2550 /*
2551  * SMP races ok?
2552  * No requirements.
2553  */
2554 static void
2555 vm_req_vmdaemon(void)
2556 {
2557         static int lastrun = 0;
2558
2559         if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
2560                 wakeup(&vm_daemon_needed);
2561                 lastrun = ticks;
2562         }
2563 }
2564
2565 static int vm_daemon_callback(struct proc *p, void *data __unused);
2566
2567 /*
2568  * No requirements.
2569  */
2570 static void
2571 vm_daemon(void)
2572 {
2573         int req_swapout;
2574
2575         while (TRUE) {
2576                 tsleep(&vm_daemon_needed, 0, "psleep", 0);
2577                 req_swapout = atomic_swap_int(&vm_pageout_req_swapout, 0);
2578
2579                 /*
2580                  * forced swapouts
2581                  */
2582                 if (req_swapout)
2583                         swapout_procs(vm_pageout_req_swapout);
2584
2585                 /*
2586                  * scan the processes for exceeding their rlimits or if
2587                  * process is swapped out -- deactivate pages
2588                  */
2589                 allproc_scan(vm_daemon_callback, NULL, 0);
2590         }
2591 }
2592
2593 static int
2594 vm_daemon_callback(struct proc *p, void *data __unused)
2595 {
2596         struct vmspace *vm;
2597         vm_pindex_t limit, size;
2598
2599         /*
2600          * if this is a system process or if we have already
2601          * looked at this process, skip it.
2602          */
2603         lwkt_gettoken(&p->p_token);
2604
2605         if (p->p_flags & (P_SYSTEM | P_WEXIT)) {
2606                 lwkt_reltoken(&p->p_token);
2607                 return (0);
2608         }
2609
2610         /*
2611          * if the process is in a non-running type state,
2612          * don't touch it.
2613          */
2614         if (p->p_stat != SACTIVE && p->p_stat != SSTOP && p->p_stat != SCORE) {
2615                 lwkt_reltoken(&p->p_token);
2616                 return (0);
2617         }
2618
2619         /*
2620          * get a limit
2621          */
2622         limit = OFF_TO_IDX(qmin(p->p_rlimit[RLIMIT_RSS].rlim_cur,
2623                                 p->p_rlimit[RLIMIT_RSS].rlim_max));
2624
2625         /*
2626          * let processes that are swapped out really be
2627          * swapped out.  Set the limit to nothing to get as
2628          * many pages out to swap as possible.
2629          */
2630         if (p->p_flags & P_SWAPPEDOUT)
2631                 limit = 0;
2632
2633         vm = p->p_vmspace;
2634         vmspace_hold(vm);
2635         size = pmap_resident_tlnw_count(&vm->vm_pmap);
2636         if (limit >= 0 && size > 4096 &&
2637             size - 4096 >= limit && vm_pageout_memuse_mode >= 1) {
2638                 vm_pageout_map_deactivate_pages(&vm->vm_map, limit);
2639         }
2640         vmspace_drop(vm);
2641
2642         lwkt_reltoken(&p->p_token);
2643
2644         return (0);
2645 }
2646
2647 #endif