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