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