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