]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_swapout.c
Swap in WKILLED processes.
[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/_kstack_cache.h>
89 #include <sys/kthread.h>
90 #include <sys/ktr.h>
91 #include <sys/mount.h>
92 #include <sys/racct.h>
93 #include <sys/resourcevar.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
163 static void swapclear(struct proc *);
164 static int swapout(struct proc *);
165 static void vm_swapout_map_deactivate_pages(vm_map_t, long);
166 static void vm_swapout_object_deactivate_pages(pmap_t, vm_object_t, long);
167 static void swapout_procs(int action);
168 static void vm_req_vmdaemon(int req);
169 static void vm_thread_swapout(struct thread *td);
170
171 /*
172  *      vm_swapout_object_deactivate_pages
173  *
174  *      Deactivate enough pages to satisfy the inactive target
175  *      requirements.
176  *
177  *      The object and map must be locked.
178  */
179 static void
180 vm_swapout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object,
181     long desired)
182 {
183         vm_object_t backing_object, object;
184         vm_page_t p;
185         int act_delta, remove_mode;
186
187         VM_OBJECT_ASSERT_LOCKED(first_object);
188         if ((first_object->flags & OBJ_FICTITIOUS) != 0)
189                 return;
190         for (object = first_object;; object = backing_object) {
191                 if (pmap_resident_count(pmap) <= desired)
192                         goto unlock_return;
193                 VM_OBJECT_ASSERT_LOCKED(object);
194                 if ((object->flags & OBJ_UNMANAGED) != 0 ||
195                     object->paging_in_progress != 0)
196                         goto unlock_return;
197
198                 remove_mode = 0;
199                 if (object->shadow_count > 1)
200                         remove_mode = 1;
201                 /*
202                  * Scan the object's entire memory queue.
203                  */
204                 TAILQ_FOREACH(p, &object->memq, listq) {
205                         if (pmap_resident_count(pmap) <= desired)
206                                 goto unlock_return;
207                         if (should_yield())
208                                 goto unlock_return;
209                         if (vm_page_busied(p))
210                                 continue;
211                         VM_CNT_INC(v_pdpages);
212                         vm_page_lock(p);
213                         if (vm_page_held(p) ||
214                             !pmap_page_exists_quick(pmap, p)) {
215                                 vm_page_unlock(p);
216                                 continue;
217                         }
218                         act_delta = pmap_ts_referenced(p);
219                         if ((p->aflags & PGA_REFERENCED) != 0) {
220                                 if (act_delta == 0)
221                                         act_delta = 1;
222                                 vm_page_aflag_clear(p, PGA_REFERENCED);
223                         }
224                         if (!vm_page_active(p) && act_delta != 0) {
225                                 vm_page_activate(p);
226                                 p->act_count += act_delta;
227                         } else if (vm_page_active(p)) {
228                                 if (act_delta == 0) {
229                                         p->act_count -= min(p->act_count,
230                                             ACT_DECLINE);
231                                         if (!remove_mode && p->act_count == 0) {
232                                                 pmap_remove_all(p);
233                                                 vm_page_deactivate(p);
234                                         } else
235                                                 vm_page_requeue(p);
236                                 } else {
237                                         vm_page_activate(p);
238                                         if (p->act_count < ACT_MAX -
239                                             ACT_ADVANCE)
240                                                 p->act_count += ACT_ADVANCE;
241                                         vm_page_requeue(p);
242                                 }
243                         } else if (vm_page_inactive(p))
244                                 pmap_remove_all(p);
245                         vm_page_unlock(p);
246                 }
247                 if ((backing_object = object->backing_object) == NULL)
248                         goto unlock_return;
249                 VM_OBJECT_RLOCK(backing_object);
250                 if (object != first_object)
251                         VM_OBJECT_RUNLOCK(object);
252         }
253 unlock_return:
254         if (object != first_object)
255                 VM_OBJECT_RUNLOCK(object);
256 }
257
258 /*
259  * deactivate some number of pages in a map, try to do it fairly, but
260  * that is really hard to do.
261  */
262 static void
263 vm_swapout_map_deactivate_pages(vm_map_t map, long desired)
264 {
265         vm_map_entry_t tmpe;
266         vm_object_t obj, bigobj;
267         int nothingwired;
268
269         if (!vm_map_trylock_read(map))
270                 return;
271
272         bigobj = NULL;
273         nothingwired = TRUE;
274
275         /*
276          * first, search out the biggest object, and try to free pages from
277          * that.
278          */
279         tmpe = map->header.next;
280         while (tmpe != &map->header) {
281                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
282                         obj = tmpe->object.vm_object;
283                         if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) {
284                                 if (obj->shadow_count <= 1 &&
285                                     (bigobj == NULL ||
286                                      bigobj->resident_page_count <
287                                      obj->resident_page_count)) {
288                                         if (bigobj != NULL)
289                                                 VM_OBJECT_RUNLOCK(bigobj);
290                                         bigobj = obj;
291                                 } else
292                                         VM_OBJECT_RUNLOCK(obj);
293                         }
294                 }
295                 if (tmpe->wired_count > 0)
296                         nothingwired = FALSE;
297                 tmpe = tmpe->next;
298         }
299
300         if (bigobj != NULL) {
301                 vm_swapout_object_deactivate_pages(map->pmap, bigobj, desired);
302                 VM_OBJECT_RUNLOCK(bigobj);
303         }
304         /*
305          * Next, hunt around for other pages to deactivate.  We actually
306          * do this search sort of wrong -- .text first is not the best idea.
307          */
308         tmpe = map->header.next;
309         while (tmpe != &map->header) {
310                 if (pmap_resident_count(vm_map_pmap(map)) <= desired)
311                         break;
312                 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
313                         obj = tmpe->object.vm_object;
314                         if (obj != NULL) {
315                                 VM_OBJECT_RLOCK(obj);
316                                 vm_swapout_object_deactivate_pages(map->pmap,
317                                     obj, desired);
318                                 VM_OBJECT_RUNLOCK(obj);
319                         }
320                 }
321                 tmpe = tmpe->next;
322         }
323
324         /*
325          * Remove all mappings if a process is swapped out, this will free page
326          * table pages.
327          */
328         if (desired == 0 && nothingwired) {
329                 pmap_remove(vm_map_pmap(map), vm_map_min(map),
330                     vm_map_max(map));
331         }
332
333         vm_map_unlock_read(map);
334 }
335
336 /*
337  * Swap out requests
338  */
339 #define VM_SWAP_NORMAL 1
340 #define VM_SWAP_IDLE 2
341
342 void
343 vm_swapout_run(void)
344 {
345
346         if (vm_swap_enabled)
347                 vm_req_vmdaemon(VM_SWAP_NORMAL);
348 }
349
350 /*
351  * Idle process swapout -- run once per second when pagedaemons are
352  * reclaiming pages.
353  */
354 void
355 vm_swapout_run_idle(void)
356 {
357         static long lsec;
358
359         if (!vm_swap_idle_enabled || time_second == lsec)
360                 return;
361         vm_req_vmdaemon(VM_SWAP_IDLE);
362         lsec = time_second;
363 }
364
365 static void
366 vm_req_vmdaemon(int req)
367 {
368         static int lastrun = 0;
369
370         mtx_lock(&vm_daemon_mtx);
371         vm_pageout_req_swapout |= req;
372         if ((ticks > (lastrun + hz)) || (ticks < lastrun)) {
373                 wakeup(&vm_daemon_needed);
374                 lastrun = ticks;
375         }
376         mtx_unlock(&vm_daemon_mtx);
377 }
378
379 static void
380 vm_daemon(void)
381 {
382         struct rlimit rsslim;
383         struct proc *p;
384         struct thread *td;
385         struct vmspace *vm;
386         int breakout, swapout_flags, tryagain, attempts;
387 #ifdef RACCT
388         uint64_t rsize, ravailable;
389 #endif
390
391         while (TRUE) {
392                 mtx_lock(&vm_daemon_mtx);
393                 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep",
394 #ifdef RACCT
395                     racct_enable ? hz : 0
396 #else
397                     0
398 #endif
399                 );
400                 swapout_flags = vm_pageout_req_swapout;
401                 vm_pageout_req_swapout = 0;
402                 mtx_unlock(&vm_daemon_mtx);
403                 if (swapout_flags != 0) {
404                         /*
405                          * Drain the per-CPU page queue batches as a deadlock
406                          * avoidance measure.
407                          */
408                         if ((swapout_flags & VM_SWAP_NORMAL) != 0)
409                                 vm_page_drain_pqbatch();
410                         swapout_procs(swapout_flags);
411                 }
412
413                 /*
414                  * scan the processes for exceeding their rlimits or if
415                  * process is swapped out -- deactivate pages
416                  */
417                 tryagain = 0;
418                 attempts = 0;
419 again:
420                 attempts++;
421                 sx_slock(&allproc_lock);
422                 FOREACH_PROC_IN_SYSTEM(p) {
423                         vm_pindex_t limit, size;
424
425                         /*
426                          * if this is a system process or if we have already
427                          * looked at this process, skip it.
428                          */
429                         PROC_LOCK(p);
430                         if (p->p_state != PRS_NORMAL ||
431                             p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) {
432                                 PROC_UNLOCK(p);
433                                 continue;
434                         }
435                         /*
436                          * if the process is in a non-running type state,
437                          * don't touch it.
438                          */
439                         breakout = 0;
440                         FOREACH_THREAD_IN_PROC(p, td) {
441                                 thread_lock(td);
442                                 if (!TD_ON_RUNQ(td) &&
443                                     !TD_IS_RUNNING(td) &&
444                                     !TD_IS_SLEEPING(td) &&
445                                     !TD_IS_SUSPENDED(td)) {
446                                         thread_unlock(td);
447                                         breakout = 1;
448                                         break;
449                                 }
450                                 thread_unlock(td);
451                         }
452                         if (breakout) {
453                                 PROC_UNLOCK(p);
454                                 continue;
455                         }
456                         /*
457                          * get a limit
458                          */
459                         lim_rlimit_proc(p, RLIMIT_RSS, &rsslim);
460                         limit = OFF_TO_IDX(
461                             qmin(rsslim.rlim_cur, rsslim.rlim_max));
462
463                         /*
464                          * let processes that are swapped out really be
465                          * swapped out set the limit to nothing (will force a
466                          * swap-out.)
467                          */
468                         if ((p->p_flag & P_INMEM) == 0)
469                                 limit = 0;      /* XXX */
470                         vm = vmspace_acquire_ref(p);
471                         _PHOLD_LITE(p);
472                         PROC_UNLOCK(p);
473                         if (vm == NULL) {
474                                 PRELE(p);
475                                 continue;
476                         }
477                         sx_sunlock(&allproc_lock);
478
479                         size = vmspace_resident_count(vm);
480                         if (size >= limit) {
481                                 vm_swapout_map_deactivate_pages(
482                                     &vm->vm_map, limit);
483                                 size = vmspace_resident_count(vm);
484                         }
485 #ifdef RACCT
486                         if (racct_enable) {
487                                 rsize = IDX_TO_OFF(size);
488                                 PROC_LOCK(p);
489                                 if (p->p_state == PRS_NORMAL)
490                                         racct_set(p, RACCT_RSS, rsize);
491                                 ravailable = racct_get_available(p, RACCT_RSS);
492                                 PROC_UNLOCK(p);
493                                 if (rsize > ravailable) {
494                                         /*
495                                          * Don't be overly aggressive; this
496                                          * might be an innocent process,
497                                          * and the limit could've been exceeded
498                                          * by some memory hog.  Don't try
499                                          * to deactivate more than 1/4th
500                                          * of process' resident set size.
501                                          */
502                                         if (attempts <= 8) {
503                                                 if (ravailable < rsize -
504                                                     (rsize / 4)) {
505                                                         ravailable = rsize -
506                                                             (rsize / 4);
507                                                 }
508                                         }
509                                         vm_swapout_map_deactivate_pages(
510                                             &vm->vm_map,
511                                             OFF_TO_IDX(ravailable));
512                                         /* Update RSS usage after paging out. */
513                                         size = vmspace_resident_count(vm);
514                                         rsize = IDX_TO_OFF(size);
515                                         PROC_LOCK(p);
516                                         if (p->p_state == PRS_NORMAL)
517                                                 racct_set(p, RACCT_RSS, rsize);
518                                         PROC_UNLOCK(p);
519                                         if (rsize > ravailable)
520                                                 tryagain = 1;
521                                 }
522                         }
523 #endif
524                         vmspace_free(vm);
525                         sx_slock(&allproc_lock);
526                         PRELE(p);
527                 }
528                 sx_sunlock(&allproc_lock);
529                 if (tryagain != 0 && attempts <= 10) {
530                         maybe_yield();
531                         goto again;
532                 }
533         }
534 }
535
536 /*
537  * Allow a thread's kernel stack to be paged out.
538  */
539 static void
540 vm_thread_swapout(struct thread *td)
541 {
542         vm_object_t ksobj;
543         vm_page_t m;
544         int i, pages;
545
546         cpu_thread_swapout(td);
547         pages = td->td_kstack_pages;
548         ksobj = td->td_kstack_obj;
549         pmap_qremove(td->td_kstack, pages);
550         VM_OBJECT_WLOCK(ksobj);
551         for (i = 0; i < pages; i++) {
552                 m = vm_page_lookup(ksobj, i);
553                 if (m == NULL)
554                         panic("vm_thread_swapout: kstack already missing?");
555                 vm_page_dirty(m);
556                 vm_page_lock(m);
557                 vm_page_unwire(m, PQ_LAUNDRY);
558                 vm_page_unlock(m);
559         }
560         VM_OBJECT_WUNLOCK(ksobj);
561 }
562
563 /*
564  * Bring the kernel stack for a specified thread back in.
565  */
566 static void
567 vm_thread_swapin(struct thread *td, int oom_alloc)
568 {
569         vm_object_t ksobj;
570         vm_page_t ma[KSTACK_MAX_PAGES];
571         int a, count, i, j, pages, rv;
572
573         pages = td->td_kstack_pages;
574         ksobj = td->td_kstack_obj;
575         VM_OBJECT_WLOCK(ksobj);
576         (void)vm_page_grab_pages(ksobj, 0, oom_alloc | VM_ALLOC_WIRED, ma,
577             pages);
578         for (i = 0; i < pages;) {
579                 vm_page_assert_xbusied(ma[i]);
580                 if (ma[i]->valid == VM_PAGE_BITS_ALL) {
581                         vm_page_xunbusy(ma[i]);
582                         i++;
583                         continue;
584                 }
585                 vm_object_pip_add(ksobj, 1);
586                 for (j = i + 1; j < pages; j++)
587                         if (ma[j]->valid == VM_PAGE_BITS_ALL)
588                                 break;
589                 rv = vm_pager_has_page(ksobj, ma[i]->pindex, NULL, &a);
590                 KASSERT(rv == 1, ("%s: missing page %p", __func__, ma[i]));
591                 count = min(a + 1, j - i);
592                 rv = vm_pager_get_pages(ksobj, ma + i, count, NULL, NULL);
593                 KASSERT(rv == VM_PAGER_OK, ("%s: cannot get kstack for proc %d",
594                     __func__, td->td_proc->p_pid));
595                 vm_object_pip_wakeup(ksobj);
596                 for (j = i; j < i + count; j++)
597                         vm_page_xunbusy(ma[j]);
598                 i += count;
599         }
600         VM_OBJECT_WUNLOCK(ksobj);
601         pmap_qenter(td->td_kstack, ma, pages);
602         cpu_thread_swapin(td);
603 }
604
605 void
606 faultin(struct proc *p)
607 {
608         struct thread *td;
609         int oom_alloc;
610
611         PROC_LOCK_ASSERT(p, MA_OWNED);
612
613         /*
614          * If another process is swapping in this process,
615          * just wait until it finishes.
616          */
617         if (p->p_flag & P_SWAPPINGIN) {
618                 while (p->p_flag & P_SWAPPINGIN)
619                         msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
620                 return;
621         }
622
623         if ((p->p_flag & P_INMEM) == 0) {
624                 oom_alloc = (p->p_flag & P_WKILLED) != 0 ? VM_ALLOC_SYSTEM :
625                     VM_ALLOC_NORMAL;
626
627                 /*
628                  * Don't let another thread swap process p out while we are
629                  * busy swapping it in.
630                  */
631                 ++p->p_lock;
632                 p->p_flag |= P_SWAPPINGIN;
633                 PROC_UNLOCK(p);
634                 sx_xlock(&allproc_lock);
635                 MPASS(swapped_cnt > 0);
636                 swapped_cnt--;
637                 sx_xunlock(&allproc_lock);
638
639                 /*
640                  * We hold no lock here because the list of threads
641                  * can not change while all threads in the process are
642                  * swapped out.
643                  */
644                 FOREACH_THREAD_IN_PROC(p, td)
645                         vm_thread_swapin(td, oom_alloc);
646
647                 PROC_LOCK(p);
648                 swapclear(p);
649                 p->p_swtick = ticks;
650
651                 /* Allow other threads to swap p out now. */
652                 wakeup(&p->p_flag);
653                 --p->p_lock;
654         }
655 }
656
657 /*
658  * This swapin algorithm attempts to swap-in processes only if there
659  * is enough space for them.  Of course, if a process waits for a long
660  * time, it will be swapped in anyway.
661  */
662
663 static struct proc *
664 swapper_selector(void)
665 {
666         struct proc *p, *res;
667         struct thread *td;
668         int min_flag, ppri, pri, slptime, swtime;
669
670         sx_assert(&allproc_lock, SA_SLOCKED);
671         if (swapped_cnt == 0)
672                 return (NULL);
673         res = NULL;
674         ppri = INT_MIN;
675         min_flag = vm_page_count_min();
676         FOREACH_PROC_IN_SYSTEM(p) {
677                 PROC_LOCK(p);
678                 if (p->p_state == PRS_NEW || (p->p_flag & (P_SWAPPINGOUT |
679                     P_SWAPPINGIN | P_INMEM)) != 0) {
680                         PROC_UNLOCK(p);
681                         continue;
682                 }
683                 if (p->p_state == PRS_NORMAL && (p->p_flag & P_WKILLED) != 0) {
684                         /*
685                          * A swapped-out process might have mapped a
686                          * large portion of the system's pages as
687                          * anonymous memory.  There is no other way to
688                          * release the memory other than to kill the
689                          * process, for which we need to swap it in.
690                          */
691                         return (p);
692                 }
693                 if (min_flag) {
694                         PROC_UNLOCK(p);
695                         continue;
696                 }
697                 swtime = (ticks - p->p_swtick) / hz;
698                 FOREACH_THREAD_IN_PROC(p, td) {
699                         /*
700                          * An otherwise runnable thread of a process
701                          * swapped out has only the TDI_SWAPPED bit set.
702                          */
703                         thread_lock(td);
704                         if (td->td_inhibitors == TDI_SWAPPED) {
705                                 slptime = (ticks - td->td_slptick) / hz;
706                                 pri = swtime + slptime;
707                                 if ((td->td_flags & TDF_SWAPINREQ) == 0)
708                                         pri -= p->p_nice * 8;
709                                 /*
710                                  * if this thread is higher priority
711                                  * and there is enough space, then select
712                                  * this process instead of the previous
713                                  * selection.
714                                  */
715                                 if (pri > ppri) {
716                                         res = p;
717                                         ppri = pri;
718                                 }
719                         }
720                         thread_unlock(td);
721                 }
722                 PROC_UNLOCK(p);
723         }
724         if (res != NULL)
725                 PROC_LOCK(res);
726         return (res);
727 }
728
729 void
730 swapper(void)
731 {
732         struct proc *p;
733
734         for (;;) {
735                 sx_slock(&allproc_lock);
736                 p = swapper_selector();
737                 sx_sunlock(&allproc_lock);
738
739                 if (p == NULL) {
740                         tsleep(&proc0, PVM, "swapin", MAXSLP * hz / 2);
741                 } else {
742                         PROC_LOCK_ASSERT(p, MA_OWNED);
743
744                         /*
745                          * Another process may be bringing or may have
746                          * already brought this process in while we
747                          * traverse all threads.  Or, this process may
748                          * have exited or even being swapped out
749                          * again.
750                          */
751                         if (p->p_state == PRS_NORMAL && (p->p_flag & (P_INMEM |
752                             P_SWAPPINGOUT | P_SWAPPINGIN)) == 0) {
753                                 faultin(p);
754                         }
755                         PROC_UNLOCK(p);
756                 }
757         }
758 }
759
760 /*
761  * First, if any processes have been sleeping or stopped for at least
762  * "swap_idle_threshold1" seconds, they are swapped out.  If, however,
763  * no such processes exist, then the longest-sleeping or stopped
764  * process is swapped out.  Finally, and only as a last resort, if
765  * there are no sleeping or stopped processes, the longest-resident
766  * process is swapped out.
767  */
768 static void
769 swapout_procs(int action)
770 {
771         struct proc *p;
772         struct thread *td;
773         int slptime;
774         bool didswap, doswap;
775
776         MPASS((action & (VM_SWAP_NORMAL | VM_SWAP_IDLE)) != 0);
777
778         didswap = false;
779         sx_slock(&allproc_lock);
780         FOREACH_PROC_IN_SYSTEM(p) {
781                 /*
782                  * Filter out not yet fully constructed processes.  Do
783                  * not swap out held processes.  Avoid processes which
784                  * are system, exiting, execing, traced, already swapped
785                  * out or are in the process of being swapped in or out.
786                  */
787                 PROC_LOCK(p);
788                 if (p->p_state != PRS_NORMAL || p->p_lock != 0 || (p->p_flag &
789                     (P_SYSTEM | P_WEXIT | P_INEXEC | P_STOPPED_SINGLE |
790                     P_TRACED | P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) !=
791                     P_INMEM) {
792                         PROC_UNLOCK(p);
793                         continue;
794                 }
795
796                 /*
797                  * Further consideration of this process for swap out
798                  * requires iterating over its threads.  We release
799                  * allproc_lock here so that process creation and
800                  * destruction are not blocked while we iterate.
801                  *
802                  * To later reacquire allproc_lock and resume
803                  * iteration over the allproc list, we will first have
804                  * to release the lock on the process.  We place a
805                  * hold on the process so that it remains in the
806                  * allproc list while it is unlocked.
807                  */
808                 _PHOLD_LITE(p);
809                 sx_sunlock(&allproc_lock);
810
811                 /*
812                  * Do not swapout a realtime process.
813                  * Guarantee swap_idle_threshold1 time in memory.
814                  * If the system is under memory stress, or if we are
815                  * swapping idle processes >= swap_idle_threshold2,
816                  * then swap the process out.
817                  */
818                 doswap = true;
819                 FOREACH_THREAD_IN_PROC(p, td) {
820                         thread_lock(td);
821                         slptime = (ticks - td->td_slptick) / hz;
822                         if (PRI_IS_REALTIME(td->td_pri_class) ||
823                             slptime < swap_idle_threshold1 ||
824                             !thread_safetoswapout(td) ||
825                             ((action & VM_SWAP_NORMAL) == 0 &&
826                             slptime < swap_idle_threshold2))
827                                 doswap = false;
828                         thread_unlock(td);
829                         if (!doswap)
830                                 break;
831                 }
832                 if (doswap && swapout(p) == 0)
833                         didswap = true;
834
835                 PROC_UNLOCK(p);
836                 if (didswap) {
837                         sx_xlock(&allproc_lock);
838                         swapped_cnt++;
839                         sx_downgrade(&allproc_lock);
840                 } else
841                         sx_slock(&allproc_lock);
842                 PRELE(p);
843         }
844         sx_sunlock(&allproc_lock);
845
846         /*
847          * If we swapped something out, and another process needed memory,
848          * then wakeup the sched process.
849          */
850         if (didswap)
851                 wakeup(&proc0);
852 }
853
854 static void
855 swapclear(struct proc *p)
856 {
857         struct thread *td;
858
859         PROC_LOCK_ASSERT(p, MA_OWNED);
860
861         FOREACH_THREAD_IN_PROC(p, td) {
862                 thread_lock(td);
863                 td->td_flags |= TDF_INMEM;
864                 td->td_flags &= ~TDF_SWAPINREQ;
865                 TD_CLR_SWAPPED(td);
866                 if (TD_CAN_RUN(td))
867                         if (setrunnable(td)) {
868 #ifdef INVARIANTS
869                                 /*
870                                  * XXX: We just cleared TDI_SWAPPED
871                                  * above and set TDF_INMEM, so this
872                                  * should never happen.
873                                  */
874                                 panic("not waking up swapper");
875 #endif
876                         }
877                 thread_unlock(td);
878         }
879         p->p_flag &= ~(P_SWAPPINGIN | P_SWAPPINGOUT);
880         p->p_flag |= P_INMEM;
881 }
882
883 static int
884 swapout(struct proc *p)
885 {
886         struct thread *td;
887
888         PROC_LOCK_ASSERT(p, MA_OWNED);
889
890         /*
891          * The states of this process and its threads may have changed
892          * by now.  Assuming that there is only one pageout daemon thread,
893          * this process should still be in memory.
894          */
895         KASSERT((p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) ==
896             P_INMEM, ("swapout: lost a swapout race?"));
897
898         /*
899          * Remember the resident count.
900          */
901         p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
902
903         /*
904          * Check and mark all threads before we proceed.
905          */
906         p->p_flag &= ~P_INMEM;
907         p->p_flag |= P_SWAPPINGOUT;
908         FOREACH_THREAD_IN_PROC(p, td) {
909                 thread_lock(td);
910                 if (!thread_safetoswapout(td)) {
911                         thread_unlock(td);
912                         swapclear(p);
913                         return (EBUSY);
914                 }
915                 td->td_flags &= ~TDF_INMEM;
916                 TD_SET_SWAPPED(td);
917                 thread_unlock(td);
918         }
919         td = FIRST_THREAD_IN_PROC(p);
920         ++td->td_ru.ru_nswap;
921         PROC_UNLOCK(p);
922
923         /*
924          * This list is stable because all threads are now prevented from
925          * running.  The list is only modified in the context of a running
926          * thread in this process.
927          */
928         FOREACH_THREAD_IN_PROC(p, td)
929                 vm_thread_swapout(td);
930
931         PROC_LOCK(p);
932         p->p_flag &= ~P_SWAPPINGOUT;
933         p->p_swtick = ticks;
934         return (0);
935 }