]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_swapout.c
Introduce vm_page_astate.
[FreeBSD/FreeBSD.git] / sys / vm / vm_swapout.c
1 /*-
2  * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991 Regents of the University of California.
5  * All rights reserved.
6  * Copyright (c) 1994 John S. Dyson
7  * All rights reserved.
8  * Copyright (c) 1994 David Greenman
9  * All rights reserved.
10  * Copyright (c) 2005 Yahoo! Technologies Norway AS
11  * All rights reserved.
12  *
13  * This code is derived from software contributed to Berkeley by
14  * The Mach Operating System project at Carnegie-Mellon University.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. All advertising materials mentioning features or use of this software
25  *    must display the following acknowledgement:
26  *      This product includes software developed by the University of
27  *      California, Berkeley and its contributors.
28  * 4. Neither the name of the University nor the names of its contributors
29  *    may be used to endorse or promote products derived from this software
30  *    without specific prior written permission.
31  *
32  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42  * SUCH DAMAGE.
43  *
44  *      from: @(#)vm_pageout.c  7.4 (Berkeley) 5/7/91
45  *
46  *
47  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
48  * All rights reserved.
49  *
50  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
51  *
52  * Permission to use, copy, modify and distribute this software and
53  * its documentation is hereby granted, provided that both the copyright
54  * notice and this permission notice appear in all copies of the
55  * software, derivative works or modified versions, and any portions
56  * thereof, and that both notices appear in supporting documentation.
57  *
58  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
59  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
60  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
61  *
62  * Carnegie Mellon requests users of this software to return to
63  *
64  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
65  *  School of Computer Science
66  *  Carnegie Mellon University
67  *  Pittsburgh PA 15213-3890
68  *
69  * any improvements or extensions that they make and grant Carnegie the
70  * rights to redistribute these changes.
71  */
72
73 #include <sys/cdefs.h>
74 __FBSDID("$FreeBSD$");
75
76 #include "opt_kstack_pages.h"
77 #include "opt_kstack_max_pages.h"
78 #include "opt_vm.h"
79
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/limits.h>
83 #include <sys/kernel.h>
84 #include <sys/eventhandler.h>
85 #include <sys/lock.h>
86 #include <sys/mutex.h>
87 #include <sys/proc.h>
88 #include <sys/kthread.h>
89 #include <sys/ktr.h>
90 #include <sys/mount.h>
91 #include <sys/racct.h>
92 #include <sys/resourcevar.h>
93 #include <sys/refcount.h>
94 #include <sys/sched.h>
95 #include <sys/sdt.h>
96 #include <sys/signalvar.h>
97 #include <sys/smp.h>
98 #include <sys/time.h>
99 #include <sys/vnode.h>
100 #include <sys/vmmeter.h>
101 #include <sys/rwlock.h>
102 #include <sys/sx.h>
103 #include <sys/sysctl.h>
104
105 #include <vm/vm.h>
106 #include <vm/vm_param.h>
107 #include <vm/vm_object.h>
108 #include <vm/vm_page.h>
109 #include <vm/vm_map.h>
110 #include <vm/vm_pageout.h>
111 #include <vm/vm_pager.h>
112 #include <vm/vm_phys.h>
113 #include <vm/swap_pager.h>
114 #include <vm/vm_extern.h>
115 #include <vm/uma.h>
116
117 /* the kernel process "vm_daemon" */
118 static void vm_daemon(void);
119 static struct proc *vmproc;
120
121 static struct kproc_desc vm_kp = {
122         "vmdaemon",
123         vm_daemon,
124         &vmproc
125 };
126 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp);
127
128 static int vm_swap_enabled = 1;
129 static int vm_swap_idle_enabled = 0;
130
131 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled, CTLFLAG_RW,
132     &vm_swap_enabled, 0,
133     "Enable entire process swapout");
134 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled, CTLFLAG_RW,
135     &vm_swap_idle_enabled, 0,
136     "Allow swapout on idle criteria");
137
138 /*
139  * Swap_idle_threshold1 is the guaranteed swapped in time for a process
140  */
141 static int swap_idle_threshold1 = 2;
142 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1, CTLFLAG_RW,
143     &swap_idle_threshold1, 0,
144     "Guaranteed swapped in time for a process");
145
146 /*
147  * Swap_idle_threshold2 is the time that a process can be idle before
148  * it will be swapped out, if idle swapping is enabled.
149  */
150 static int swap_idle_threshold2 = 10;
151 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2, CTLFLAG_RW,
152     &swap_idle_threshold2, 0,
153     "Time before a process will be swapped out");
154
155 static int vm_pageout_req_swapout;      /* XXX */
156 static int vm_daemon_needed;
157 static struct mtx vm_daemon_mtx;
158 /* Allow for use by vm_pageout before vm_daemon is initialized. */
159 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF);
160
161 static int swapped_cnt;
162 static int swap_inprogress;     /* Pending swap-ins done outside swapper. */
163 static int last_swapin;
164
165 static void swapclear(struct proc *);
166 static int swapout(struct proc *);
167 static void vm_swapout_map_deactivate_pages(vm_map_t, long);
168 static void vm_swapout_object_deactivate_pages(pmap_t, vm_object_t, long);
169 static void swapout_procs(int action);
170 static void vm_req_vmdaemon(int req);
171 static void vm_thread_swapout(struct thread *td);
172
173 /*
174  *      vm_swapout_object_deactivate_pages
175  *
176  *      Deactivate enough pages to satisfy the inactive target
177  *      requirements.
178  *
179  *      The object and map must be locked.
180  */
181 static void
182 vm_swapout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
183     long desired)
184 {
185         vm_object_t backing_object, object;
186         vm_page_t p;
187         int act_delta, remove_mode;
188
189         VM_OBJECT_ASSERT_LOCKED(first_object);
190         if ((first_object->flags & OBJ_FICTITIOUS) != 0)
191                 return;
192         for (object = first_object;; object = backing_object) {
193                 if (pmap_resident_count(pmap) <= desired)
194                         goto unlock_return;
195                 VM_OBJECT_ASSERT_LOCKED(object);
196                 if ((object->flags & OBJ_UNMANAGED) != 0 ||
197                     REFCOUNT_COUNT(object->paging_in_progress) > 0)
198                         goto unlock_return;
199
200                 remove_mode = 0;
201                 if (object->shadow_count > 1)
202                         remove_mode = 1;
203                 /*
204                  * Scan the object's entire memory queue.
205                  */
206                 TAILQ_FOREACH(p, &object->memq, listq) {
207                         if (pmap_resident_count(pmap) <= desired)
208                                 goto unlock_return;
209                         if (should_yield())
210                                 goto unlock_return;
211                         if (vm_page_tryxbusy(p) == 0)
212                                 continue;
213                         VM_CNT_INC(v_pdpages);
214
215                         /*
216                          * The page may acquire a wiring after this check.
217                          * The page daemon handles wired pages, so there is
218                          * no harm done if a wiring appears while we are
219                          * attempting to deactivate the page.
220                          */
221                         if (vm_page_wired(p) || !pmap_page_exists_quick(pmap, p)) {
222                                 vm_page_xunbusy(p);
223                                 continue;
224                         }
225                         act_delta = pmap_ts_referenced(p);
226                         vm_page_lock(p);
227                         if ((p->a.flags & PGA_REFERENCED) != 0) {
228                                 if (act_delta == 0)
229                                         act_delta = 1;
230                                 vm_page_aflag_clear(p, PGA_REFERENCED);
231                         }
232                         if (!vm_page_active(p) && act_delta != 0) {
233                                 vm_page_activate(p);
234                                 p->a.act_count += act_delta;
235                         } else if (vm_page_active(p)) {
236                                 /*
237                                  * The page daemon does not requeue pages
238                                  * after modifying their activation count.
239                                  */
240                                 if (act_delta == 0) {
241                                         p->a.act_count -= min(p->a.act_count,
242                                             ACT_DECLINE);
243                                         if (!remove_mode && p->a.act_count == 0) {
244                                                 (void)vm_page_try_remove_all(p);
245                                                 vm_page_deactivate(p);
246                                         }
247                                 } else {
248                                         vm_page_activate(p);
249                                         if (p->a.act_count < ACT_MAX -
250                                             ACT_ADVANCE)
251                                                 p->a.act_count += ACT_ADVANCE;
252                                 }
253                         } else if (vm_page_inactive(p))
254                                 (void)vm_page_try_remove_all(p);
255                         vm_page_unlock(p);
256                         vm_page_xunbusy(p);
257                 }
258                 if ((backing_object = object->backing_object) == NULL)
259                         goto unlock_return;
260                 VM_OBJECT_RLOCK(backing_object);
261                 if (object != first_object)
262                         VM_OBJECT_RUNLOCK(object);
263         }
264 unlock_return:
265         if (object != first_object)
266                 VM_OBJECT_RUNLOCK(object);
267 }
268
269 /*
270  * deactivate some number of pages in a map, try to do it fairly, but
271  * that is really hard to do.
272  */
273 static void
274 vm_swapout_map_deactivate_pages(vm_map_t map, long desired)
275 {
276         vm_map_entry_t tmpe;
277         vm_object_t obj, bigobj;
278         int nothingwired;
279
280         if (!vm_map_trylock_read(map))
281                 return;
282
283         bigobj = NULL;
284         nothingwired = TRUE;
285
286         /*
287          * first, search out the biggest object, and try to free pages from
288          * that.
289          */
290         VM_MAP_ENTRY_FOREACH(tmpe, map) {
291                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
292                         obj = tmpe->object.vm_object;
293                         if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
294                                 if (obj->shadow_count <= 1 &&
295                                     (bigobj == NULL ||
296                                      bigobj->resident_page_count <
297                                      obj->resident_page_count)) {
298                                         if (bigobj != NULL)
299                                                 VM_OBJECT_RUNLOCK(bigobj);
300                                         bigobj = obj;
301                                 } else
302                                         VM_OBJECT_RUNLOCK(obj);
303                         }
304                 }
305                 if (tmpe->wired_count > 0)
306                         nothingwired = FALSE;
307         }
308
309         if (bigobj != NULL) {
310                 vm_swapout_object_deactivate_pages(map->pmap, bigobj, desired);
311                 VM_OBJECT_RUNLOCK(bigobj);
312         }
313         /*
314          * Next, hunt around for other pages to deactivate.  We actually
315          * do this search sort of wrong -- .text first is not the best idea.
316          */
317         VM_MAP_ENTRY_FOREACH(tmpe, map) {
318                 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
319                         break;
320                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
321                         obj = tmpe->object.vm_object;
322                         if (obj != NULL) {
323                                 VM_OBJECT_RLOCK(obj);
324                                 vm_swapout_object_deactivate_pages(map->pmap,
325                                     obj, desired);
326                                 VM_OBJECT_RUNLOCK(obj);
327                         }
328                 }
329         }
330
331         /*
332          * Remove all mappings if a process is swapped out, this will free page
333          * table pages.
334          */
335         if (desired == 0 && nothingwired) {
336                 pmap_remove(vm_map_pmap(map), vm_map_min(map),
337                     vm_map_max(map));
338         }
339
340         vm_map_unlock_read(map);
341 }
342
343 /*
344  * Swap out requests
345  */
346 #define VM_SWAP_NORMAL 1
347 #define VM_SWAP_IDLE 2
348
349 void
350 vm_swapout_run(void)
351 {
352
353         if (vm_swap_enabled)
354                 vm_req_vmdaemon(VM_SWAP_NORMAL);
355 }
356
357 /*
358  * Idle process swapout -- run once per second when pagedaemons are
359  * reclaiming pages.
360  */
361 void
362 vm_swapout_run_idle(void)
363 {
364         static long lsec;
365
366         if (!vm_swap_idle_enabled || time_second == lsec)
367                 return;
368         vm_req_vmdaemon(VM_SWAP_IDLE);
369         lsec = time_second;
370 }
371
372 static void
373 vm_req_vmdaemon(int req)
374 {
375         static int lastrun = 0;
376
377         mtx_lock(&vm_daemon_mtx);
378         vm_pageout_req_swapout |= req;
379         if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
380                 wakeup(&vm_daemon_needed);
381                 lastrun = ticks;
382         }
383         mtx_unlock(&vm_daemon_mtx);
384 }
385
386 static void
387 vm_daemon(void)
388 {
389         struct rlimit rsslim;
390         struct proc *p;
391         struct thread *td;
392         struct vmspace *vm;
393         int breakout, swapout_flags, tryagain, attempts;
394 #ifdef RACCT
395         uint64_t rsize, ravailable;
396 #endif
397
398         while (TRUE) {
399                 mtx_lock(&vm_daemon_mtx);
400                 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
401 #ifdef RACCT
402                     racct_enable ? hz : 0
403 #else
404                     0
405 #endif
406                 );
407                 swapout_flags = vm_pageout_req_swapout;
408                 vm_pageout_req_swapout = 0;
409                 mtx_unlock(&vm_daemon_mtx);
410                 if (swapout_flags != 0) {
411                         /*
412                          * Drain the per-CPU page queue batches as a deadlock
413                          * avoidance measure.
414                          */
415                         if ((swapout_flags & VM_SWAP_NORMAL) != 0)
416                                 vm_page_pqbatch_drain();
417                         swapout_procs(swapout_flags);
418                 }
419
420                 /*
421                  * scan the processes for exceeding their rlimits or if
422                  * process is swapped out -- deactivate pages
423                  */
424                 tryagain = 0;
425                 attempts = 0;
426 again:
427                 attempts++;
428                 sx_slock(&allproc_lock);
429                 FOREACH_PROC_IN_SYSTEM(p) {
430                         vm_pindex_t limit, size;
431
432                         /*
433                          * if this is a system process or if we have already
434                          * looked at this process, skip it.
435                          */
436                         PROC_LOCK(p);
437                         if (p->p_state != PRS_NORMAL ||
438                             p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
439                                 PROC_UNLOCK(p);
440                                 continue;
441                         }
442                         /*
443                          * if the process is in a non-running type state,
444                          * don't touch it.
445                          */
446                         breakout = 0;
447                         FOREACH_THREAD_IN_PROC(p, td) {
448                                 thread_lock(td);
449                                 if (!TD_ON_RUNQ(td) &&
450                                     !TD_IS_RUNNING(td) &&
451                                     !TD_IS_SLEEPING(td) &&
452                                     !TD_IS_SUSPENDED(td)) {
453                                         thread_unlock(td);
454                                         breakout = 1;
455                                         break;
456                                 }
457                                 thread_unlock(td);
458                         }
459                         if (breakout) {
460                                 PROC_UNLOCK(p);
461                                 continue;
462                         }
463                         /*
464                          * get a limit
465                          */
466                         lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
467                         limit = OFF_TO_IDX(
468                             qmin(rsslim.rlim_cur, rsslim.rlim_max));
469
470                         /*
471                          * let processes that are swapped out really be
472                          * swapped out set the limit to nothing (will force a
473                          * swap-out.)
474                          */
475                         if ((p->p_flag & P_INMEM) == 0)
476                                 limit = 0;      /* XXX */
477                         vm = vmspace_acquire_ref(p);
478                         _PHOLD_LITE(p);
479                         PROC_UNLOCK(p);
480                         if (vm == NULL) {
481                                 PRELE(p);
482                                 continue;
483                         }
484                         sx_sunlock(&allproc_lock);
485
486                         size = vmspace_resident_count(vm);
487                         if (size >= limit) {
488                                 vm_swapout_map_deactivate_pages(
489                                     &vm->vm_map, limit);
490                                 size = vmspace_resident_count(vm);
491                         }
492 #ifdef RACCT
493                         if (racct_enable) {
494                                 rsize = IDX_TO_OFF(size);
495                                 PROC_LOCK(p);
496                                 if (p->p_state == PRS_NORMAL)
497                                         racct_set(p, RACCT_RSS, rsize);
498                                 ravailable = racct_get_available(p, RACCT_RSS);
499                                 PROC_UNLOCK(p);
500                                 if (rsize > ravailable) {
501                                         /*
502                                          * Don't be overly aggressive; this
503                                          * might be an innocent process,
504                                          * and the limit could've been exceeded
505                                          * by some memory hog.  Don't try
506                                          * to deactivate more than 1/4th
507                                          * of process' resident set size.
508                                          */
509                                         if (attempts <= 8) {
510                                                 if (ravailable < rsize -
511                                                     (rsize / 4)) {
512                                                         ravailable = rsize -
513                                                             (rsize / 4);
514                                                 }
515                                         }
516                                         vm_swapout_map_deactivate_pages(
517                                             &vm->vm_map,
518                                             OFF_TO_IDX(ravailable));
519                                         /* Update RSS usage after paging out. */
520                                         size = vmspace_resident_count(vm);
521                                         rsize = IDX_TO_OFF(size);
522                                         PROC_LOCK(p);
523                                         if (p->p_state == PRS_NORMAL)
524                                                 racct_set(p, RACCT_RSS, rsize);
525                                         PROC_UNLOCK(p);
526                                         if (rsize > ravailable)
527                                                 tryagain = 1;
528                                 }
529                         }
530 #endif
531                         vmspace_free(vm);
532                         sx_slock(&allproc_lock);
533                         PRELE(p);
534                 }
535                 sx_sunlock(&allproc_lock);
536                 if (tryagain != 0 && attempts <= 10) {
537                         maybe_yield();
538                         goto again;
539                 }
540         }
541 }
542
543 /*
544  * Allow a thread's kernel stack to be paged out.
545  */
546 static void
547 vm_thread_swapout(struct thread *td)
548 {
549         vm_object_t ksobj;
550         vm_page_t m;
551         int i, pages;
552
553         cpu_thread_swapout(td);
554         pages = td->td_kstack_pages;
555         ksobj = td->td_kstack_obj;
556         pmap_qremove(td->td_kstack, pages);
557         VM_OBJECT_WLOCK(ksobj);
558         for (i = 0; i < pages; i++) {
559                 m = vm_page_lookup(ksobj, i);
560                 if (m == NULL)
561                         panic("vm_thread_swapout: kstack already missing?");
562                 vm_page_dirty(m);
563                 vm_page_unwire(m, PQ_LAUNDRY);
564         }
565         VM_OBJECT_WUNLOCK(ksobj);
566 }
567
568 /*
569  * Bring the kernel stack for a specified thread back in.
570  */
571 static void
572 vm_thread_swapin(struct thread *td, int oom_alloc)
573 {
574         vm_object_t ksobj;
575         vm_page_t ma[KSTACK_MAX_PAGES];
576         int a, count, i, j, pages, rv;
577
578         pages = td->td_kstack_pages;
579         ksobj = td->td_kstack_obj;
580         VM_OBJECT_WLOCK(ksobj);
581         (void)vm_page_grab_pages(ksobj, 0, oom_alloc | VM_ALLOC_WIRED, ma,
582             pages);
583         for (i = 0; i < pages;) {
584                 vm_page_assert_xbusied(ma[i]);
585                 if (vm_page_all_valid(ma[i])) {
586                         vm_page_xunbusy(ma[i]);
587                         i++;
588                         continue;
589                 }
590                 vm_object_pip_add(ksobj, 1);
591                 for (j = i + 1; j < pages; j++)
592                         if (vm_page_all_valid(ma[j]))
593                                 break;
594                 rv = vm_pager_has_page(ksobj, ma[i]->pindex, NULL, &a);
595                 KASSERT(rv == 1, ("%s: missing page %p", __func__, ma[i]));
596                 count = min(a + 1, j - i);
597                 rv = vm_pager_get_pages(ksobj, ma + i, count, NULL, NULL);
598                 KASSERT(rv == VM_PAGER_OK, ("%s: cannot get kstack for proc %d",
599                     __func__, td->td_proc->p_pid));
600                 vm_object_pip_wakeup(ksobj);
601                 for (j = i; j < i + count; j++)
602                         vm_page_xunbusy(ma[j]);
603                 i += count;
604         }
605         VM_OBJECT_WUNLOCK(ksobj);
606         pmap_qenter(td->td_kstack, ma, pages);
607         cpu_thread_swapin(td);
608 }
609
610 void
611 faultin(struct proc *p)
612 {
613         struct thread *td;
614         int oom_alloc;
615
616         PROC_LOCK_ASSERT(p, MA_OWNED);
617
618         /*
619          * If another process is swapping in this process,
620          * just wait until it finishes.
621          */
622         if (p->p_flag & P_SWAPPINGIN) {
623                 while (p->p_flag & P_SWAPPINGIN)
624                         msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
625                 return;
626         }
627
628         if ((p->p_flag & P_INMEM) == 0) {
629                 oom_alloc = (p->p_flag & P_WKILLED) != 0 ? VM_ALLOC_SYSTEM :
630                     VM_ALLOC_NORMAL;
631
632                 /*
633                  * Don't let another thread swap process p out while we are
634                  * busy swapping it in.
635                  */
636                 ++p->p_lock;
637                 p->p_flag |= P_SWAPPINGIN;
638                 PROC_UNLOCK(p);
639                 sx_xlock(&allproc_lock);
640                 MPASS(swapped_cnt > 0);
641                 swapped_cnt--;
642                 if (curthread != &thread0)
643                         swap_inprogress++;
644                 sx_xunlock(&allproc_lock);
645
646                 /*
647                  * We hold no lock here because the list of threads
648                  * can not change while all threads in the process are
649                  * swapped out.
650                  */
651                 FOREACH_THREAD_IN_PROC(p, td)
652                         vm_thread_swapin(td, oom_alloc);
653
654                 if (curthread != &thread0) {
655                         sx_xlock(&allproc_lock);
656                         MPASS(swap_inprogress > 0);
657                         swap_inprogress--;
658                         last_swapin = ticks;
659                         sx_xunlock(&allproc_lock);
660                 }
661                 PROC_LOCK(p);
662                 swapclear(p);
663                 p->p_swtick = ticks;
664
665                 /* Allow other threads to swap p out now. */
666                 wakeup(&p->p_flag);
667                 --p->p_lock;
668         }
669 }
670
671 /*
672  * This swapin algorithm attempts to swap-in processes only if there
673  * is enough space for them.  Of course, if a process waits for a long
674  * time, it will be swapped in anyway.
675  */
676
677 static struct proc *
678 swapper_selector(bool wkilled_only)
679 {
680         struct proc *p, *res;
681         struct thread *td;
682         int ppri, pri, slptime, swtime;
683
684         sx_assert(&allproc_lock, SA_SLOCKED);
685         if (swapped_cnt == 0)
686                 return (NULL);
687         res = NULL;
688         ppri = INT_MIN;
689         FOREACH_PROC_IN_SYSTEM(p) {
690                 PROC_LOCK(p);
691                 if (p->p_state == PRS_NEW || (p->p_flag & (P_SWAPPINGOUT |
692                     P_SWAPPINGIN | P_INMEM)) != 0) {
693                         PROC_UNLOCK(p);
694                         continue;
695                 }
696                 if (p->p_state == PRS_NORMAL && (p->p_flag & P_WKILLED) != 0) {
697                         /*
698                          * A swapped-out process might have mapped a
699                          * large portion of the system's pages as
700                          * anonymous memory.  There is no other way to
701                          * release the memory other than to kill the
702                          * process, for which we need to swap it in.
703                          */
704                         return (p);
705                 }
706                 if (wkilled_only) {
707                         PROC_UNLOCK(p);
708                         continue;
709                 }
710                 swtime = (ticks - p->p_swtick) / hz;
711                 FOREACH_THREAD_IN_PROC(p, td) {
712                         /*
713                          * An otherwise runnable thread of a process
714                          * swapped out has only the TDI_SWAPPED bit set.
715                          */
716                         thread_lock(td);
717                         if (td->td_inhibitors == TDI_SWAPPED) {
718                                 slptime = (ticks - td->td_slptick) / hz;
719                                 pri = swtime + slptime;
720                                 if ((td->td_flags & TDF_SWAPINREQ) == 0)
721                                         pri -= p->p_nice * 8;
722                                 /*
723                                  * if this thread is higher priority
724                                  * and there is enough space, then select
725                                  * this process instead of the previous
726                                  * selection.
727                                  */
728                                 if (pri > ppri) {
729                                         res = p;
730                                         ppri = pri;
731                                 }
732                         }
733                         thread_unlock(td);
734                 }
735                 PROC_UNLOCK(p);
736         }
737
738         if (res != NULL)
739                 PROC_LOCK(res);
740         return (res);
741 }
742
743 #define SWAPIN_INTERVAL (MAXSLP * hz / 2)
744
745 /*
746  * Limit swapper to swap in one non-WKILLED process in MAXSLP/2
747  * interval, assuming that there is:
748  * - at least one domain that is not suffering from a shortage of free memory;
749  * - no parallel swap-ins;
750  * - no other swap-ins in the current SWAPIN_INTERVAL.
751  */
752 static bool
753 swapper_wkilled_only(void)
754 {
755
756         return (vm_page_count_min_set(&all_domains) || swap_inprogress > 0 ||
757             (u_int)(ticks - last_swapin) < SWAPIN_INTERVAL);
758 }
759
760 void
761 swapper(void)
762 {
763         struct proc *p;
764
765         for (;;) {
766                 sx_slock(&allproc_lock);
767                 p = swapper_selector(swapper_wkilled_only());
768                 sx_sunlock(&allproc_lock);
769
770                 if (p == NULL) {
771                         tsleep(&proc0, PVM, "swapin", SWAPIN_INTERVAL);
772                 } else {
773                         PROC_LOCK_ASSERT(p, MA_OWNED);
774
775                         /*
776                          * Another process may be bringing or may have
777                          * already brought this process in while we
778                          * traverse all threads.  Or, this process may
779                          * have exited or even being swapped out
780                          * again.
781                          */
782                         if (p->p_state == PRS_NORMAL && (p->p_flag & (P_INMEM |
783                             P_SWAPPINGOUT | P_SWAPPINGIN)) == 0) {
784                                 faultin(p);
785                         }
786                         PROC_UNLOCK(p);
787                 }
788         }
789 }
790
791 /*
792  * First, if any processes have been sleeping or stopped for at least
793  * "swap_idle_threshold1" seconds, they are swapped out.  If, however,
794  * no such processes exist, then the longest-sleeping or stopped
795  * process is swapped out.  Finally, and only as a last resort, if
796  * there are no sleeping or stopped processes, the longest-resident
797  * process is swapped out.
798  */
799 static void
800 swapout_procs(int action)
801 {
802         struct proc *p;
803         struct thread *td;
804         int slptime;
805         bool didswap, doswap;
806
807         MPASS((action & (VM_SWAP_NORMAL | VM_SWAP_IDLE)) != 0);
808
809         didswap = false;
810         sx_slock(&allproc_lock);
811         FOREACH_PROC_IN_SYSTEM(p) {
812                 /*
813                  * Filter out not yet fully constructed processes.  Do
814                  * not swap out held processes.  Avoid processes which
815                  * are system, exiting, execing, traced, already swapped
816                  * out or are in the process of being swapped in or out.
817                  */
818                 PROC_LOCK(p);
819                 if (p->p_state != PRS_NORMAL || p->p_lock != 0 || (p->p_flag &
820                     (P_SYSTEM | P_WEXIT | P_INEXEC | P_STOPPED_SINGLE |
821                     P_TRACED | P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) !=
822                     P_INMEM) {
823                         PROC_UNLOCK(p);
824                         continue;
825                 }
826
827                 /*
828                  * Further consideration of this process for swap out
829                  * requires iterating over its threads.  We release
830                  * allproc_lock here so that process creation and
831                  * destruction are not blocked while we iterate.
832                  *
833                  * To later reacquire allproc_lock and resume
834                  * iteration over the allproc list, we will first have
835                  * to release the lock on the process.  We place a
836                  * hold on the process so that it remains in the
837                  * allproc list while it is unlocked.
838                  */
839                 _PHOLD_LITE(p);
840                 sx_sunlock(&allproc_lock);
841
842                 /*
843                  * Do not swapout a realtime process.
844                  * Guarantee swap_idle_threshold1 time in memory.
845                  * If the system is under memory stress, or if we are
846                  * swapping idle processes >= swap_idle_threshold2,
847                  * then swap the process out.
848                  */
849                 doswap = true;
850                 FOREACH_THREAD_IN_PROC(p, td) {
851                         thread_lock(td);
852                         slptime = (ticks - td->td_slptick) / hz;
853                         if (PRI_IS_REALTIME(td->td_pri_class) ||
854                             slptime < swap_idle_threshold1 ||
855                             !thread_safetoswapout(td) ||
856                             ((action & VM_SWAP_NORMAL) == 0 &&
857                             slptime < swap_idle_threshold2))
858                                 doswap = false;
859                         thread_unlock(td);
860                         if (!doswap)
861                                 break;
862                 }
863                 if (doswap && swapout(p) == 0)
864                         didswap = true;
865
866                 PROC_UNLOCK(p);
867                 if (didswap) {
868                         sx_xlock(&allproc_lock);
869                         swapped_cnt++;
870                         sx_downgrade(&allproc_lock);
871                 } else
872                         sx_slock(&allproc_lock);
873                 PRELE(p);
874         }
875         sx_sunlock(&allproc_lock);
876
877         /*
878          * If we swapped something out, and another process needed memory,
879          * then wakeup the sched process.
880          */
881         if (didswap)
882                 wakeup(&proc0);
883 }
884
885 static void
886 swapclear(struct proc *p)
887 {
888         struct thread *td;
889
890         PROC_LOCK_ASSERT(p, MA_OWNED);
891
892         FOREACH_THREAD_IN_PROC(p, td) {
893                 thread_lock(td);
894                 td->td_flags |= TDF_INMEM;
895                 td->td_flags &= ~TDF_SWAPINREQ;
896                 TD_CLR_SWAPPED(td);
897                 if (TD_CAN_RUN(td))
898                         if (setrunnable(td)) {
899 #ifdef INVARIANTS
900                                 /*
901                                  * XXX: We just cleared TDI_SWAPPED
902                                  * above and set TDF_INMEM, so this
903                                  * should never happen.
904                                  */
905                                 panic("not waking up swapper");
906 #endif
907                         }
908                 thread_unlock(td);
909         }
910         p->p_flag &= ~(P_SWAPPINGIN | P_SWAPPINGOUT);
911         p->p_flag |= P_INMEM;
912 }
913
914 static int
915 swapout(struct proc *p)
916 {
917         struct thread *td;
918
919         PROC_LOCK_ASSERT(p, MA_OWNED);
920
921         /*
922          * The states of this process and its threads may have changed
923          * by now.  Assuming that there is only one pageout daemon thread,
924          * this process should still be in memory.
925          */
926         KASSERT((p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) ==
927             P_INMEM, ("swapout: lost a swapout race?"));
928
929         /*
930          * Remember the resident count.
931          */
932         p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
933
934         /*
935          * Check and mark all threads before we proceed.
936          */
937         p->p_flag &= ~P_INMEM;
938         p->p_flag |= P_SWAPPINGOUT;
939         FOREACH_THREAD_IN_PROC(p, td) {
940                 thread_lock(td);
941                 if (!thread_safetoswapout(td)) {
942                         thread_unlock(td);
943                         swapclear(p);
944                         return (EBUSY);
945                 }
946                 td->td_flags &= ~TDF_INMEM;
947                 TD_SET_SWAPPED(td);
948                 thread_unlock(td);
949         }
950         td = FIRST_THREAD_IN_PROC(p);
951         ++td->td_ru.ru_nswap;
952         PROC_UNLOCK(p);
953
954         /*
955          * This list is stable because all threads are now prevented from
956          * running.  The list is only modified in the context of a running
957          * thread in this process.
958          */
959         FOREACH_THREAD_IN_PROC(p, td)
960                 vm_thread_swapout(td);
961
962         PROC_LOCK(p);
963         p->p_flag &= ~P_SWAPPINGOUT;
964         p->p_swtick = ticks;
965         return (0);
966 }