xref: /freebsd/sys/vm/vm_glue.c (revision 4b2eaea43fec8e8792be611dea204071a10b655a)
1 /*
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	from: @(#)vm_glue.c	8.6 (Berkeley) 1/5/94
37  *
38  *
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  *
62  * $FreeBSD$
63  */
64 
65 #include "opt_vm.h"
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/lock.h>
70 #include <sys/mutex.h>
71 #include <sys/proc.h>
72 #include <sys/resourcevar.h>
73 #include <sys/shm.h>
74 #include <sys/vmmeter.h>
75 #include <sys/sx.h>
76 #include <sys/sysctl.h>
77 
78 #include <sys/kernel.h>
79 #include <sys/ktr.h>
80 #include <sys/unistd.h>
81 
82 #include <machine/limits.h>
83 
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_object.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
93 #include <vm/vm_pager.h>
94 #include <vm/swap_pager.h>
95 
96 #include <sys/user.h>
97 
98 extern int maxslp;
99 
100 /*
101  * System initialization
102  *
103  * Note: proc0 from proc.h
104  */
105 static void vm_init_limits(void *);
106 SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
107 
108 /*
109  * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
110  *
111  * Note: run scheduling should be divorced from the vm system.
112  */
113 static void scheduler(void *);
114 SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, scheduler, NULL)
115 
116 #ifndef NO_SWAPPING
117 static void swapout(struct proc *);
118 static void vm_proc_swapin(struct proc *p);
119 static void vm_proc_swapout(struct proc *p);
120 #endif
121 
122 /*
123  * MPSAFE
124  *
125  * WARNING!  This code calls vm_map_check_protection() which only checks
126  * the associated vm_map_entry range.  It does not determine whether the
127  * contents of the memory is actually readable or writable.  In most cases
128  * just checking the vm_map_entry is sufficient within the kernel's address
129  * space.
130  */
131 int
132 kernacc(addr, len, rw)
133 	void *addr;
134 	int len, rw;
135 {
136 	boolean_t rv;
137 	vm_offset_t saddr, eaddr;
138 	vm_prot_t prot;
139 
140 	KASSERT((rw & ~VM_PROT_ALL) == 0,
141 	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
142 	prot = rw;
143 	saddr = trunc_page((vm_offset_t)addr);
144 	eaddr = round_page((vm_offset_t)addr + len);
145 	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
146 	return (rv == TRUE);
147 }
148 
149 /*
150  * MPSAFE
151  *
152  * WARNING!  This code calls vm_map_check_protection() which only checks
153  * the associated vm_map_entry range.  It does not determine whether the
154  * contents of the memory is actually readable or writable.  vmapbuf(),
155  * vm_fault_quick(), or copyin()/copout()/su*()/fu*() functions should be
156  * used in conjuction with this call.
157  */
158 int
159 useracc(addr, len, rw)
160 	void *addr;
161 	int len, rw;
162 {
163 	boolean_t rv;
164 	vm_prot_t prot;
165 	vm_map_t map;
166 
167 	KASSERT((rw & ~VM_PROT_ALL) == 0,
168 	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
169 	prot = rw;
170 	map = &curproc->p_vmspace->vm_map;
171 	if ((vm_offset_t)addr + len > vm_map_max(map) ||
172 	    (vm_offset_t)addr + len < (vm_offset_t)addr) {
173 		return (FALSE);
174 	}
175 	rv = vm_map_check_protection(map, trunc_page((vm_offset_t)addr),
176 	    round_page((vm_offset_t)addr + len), prot);
177 	return (rv == TRUE);
178 }
179 
180 /*
181  * MPSAFE
182  */
183 void
184 vslock(addr, len)
185 	void *addr;
186 	u_int len;
187 {
188 
189 	vm_map_wire(&curproc->p_vmspace->vm_map, trunc_page((vm_offset_t)addr),
190 	    round_page((vm_offset_t)addr + len), FALSE);
191 }
192 
193 /*
194  * MPSAFE
195  */
196 void
197 vsunlock(addr, len)
198 	void *addr;
199 	u_int len;
200 {
201 
202 	vm_map_unwire(&curproc->p_vmspace->vm_map,
203 	    trunc_page((vm_offset_t)addr),
204 	    round_page((vm_offset_t)addr + len), FALSE);
205 }
206 
207 /*
208  * Create the U area for a new process.
209  * This routine directly affects the fork perf for a process.
210  */
211 void
212 vm_proc_new(struct proc *p)
213 {
214 	vm_page_t ma[UAREA_PAGES];
215 	vm_object_t upobj;
216 	vm_offset_t up;
217 	vm_page_t m;
218 	u_int i;
219 
220 	/*
221 	 * Allocate object for the upage.
222 	 */
223 	upobj = vm_object_allocate(OBJT_DEFAULT, UAREA_PAGES);
224 	p->p_upages_obj = upobj;
225 
226 	/*
227 	 * Get a kernel virtual address for the U area for this process.
228 	 */
229 	up = kmem_alloc_nofault(kernel_map, UAREA_PAGES * PAGE_SIZE);
230 	if (up == 0)
231 		panic("vm_proc_new: upage allocation failed");
232 	p->p_uarea = (struct user *)up;
233 
234 	for (i = 0; i < UAREA_PAGES; i++) {
235 		/*
236 		 * Get a uarea page.
237 		 */
238 		m = vm_page_grab(upobj, i,
239 		    VM_ALLOC_NORMAL | VM_ALLOC_RETRY | VM_ALLOC_WIRED);
240 		ma[i] = m;
241 
242 		vm_page_lock_queues();
243 		vm_page_wakeup(m);
244 		vm_page_flag_clear(m, PG_ZERO);
245 		m->valid = VM_PAGE_BITS_ALL;
246 		vm_page_unlock_queues();
247 	}
248 
249 	/*
250 	 * Enter the pages into the kernel address space.
251 	 */
252 	pmap_qenter(up, ma, UAREA_PAGES);
253 }
254 
255 /*
256  * Dispose the U area for a process that has exited.
257  * This routine directly impacts the exit perf of a process.
258  * XXX proc_zone is marked UMA_ZONE_NOFREE, so this should never be called.
259  */
260 void
261 vm_proc_dispose(struct proc *p)
262 {
263 	vm_object_t upobj;
264 	vm_offset_t up;
265 	vm_page_t m;
266 
267 	upobj = p->p_upages_obj;
268 	if (upobj->resident_page_count != UAREA_PAGES)
269 		panic("vm_proc_dispose: incorrect number of pages in upobj");
270 	vm_page_lock_queues();
271 	while ((m = TAILQ_FIRST(&upobj->memq)) != NULL) {
272 		vm_page_busy(m);
273 		vm_page_unwire(m, 0);
274 		vm_page_free(m);
275 	}
276 	vm_page_unlock_queues();
277 	up = (vm_offset_t)p->p_uarea;
278 	pmap_qremove(up, UAREA_PAGES);
279 	kmem_free(kernel_map, up, UAREA_PAGES * PAGE_SIZE);
280 	vm_object_deallocate(upobj);
281 }
282 
283 #ifndef NO_SWAPPING
284 /*
285  * Allow the U area for a process to be prejudicially paged out.
286  */
287 static void
288 vm_proc_swapout(struct proc *p)
289 {
290 	vm_object_t upobj;
291 	vm_offset_t up;
292 	vm_page_t m;
293 
294 	upobj = p->p_upages_obj;
295 	if (upobj->resident_page_count != UAREA_PAGES)
296 		panic("vm_proc_dispose: incorrect number of pages in upobj");
297 	vm_page_lock_queues();
298 	TAILQ_FOREACH(m, &upobj->memq, listq) {
299 		vm_page_dirty(m);
300 		vm_page_unwire(m, 0);
301 	}
302 	vm_page_unlock_queues();
303 	up = (vm_offset_t)p->p_uarea;
304 	pmap_qremove(up, UAREA_PAGES);
305 }
306 
307 /*
308  * Bring the U area for a specified process back in.
309  */
310 static void
311 vm_proc_swapin(struct proc *p)
312 {
313 	vm_page_t ma[UAREA_PAGES];
314 	vm_object_t upobj;
315 	vm_offset_t up;
316 	vm_page_t m;
317 	int rv;
318 	int i;
319 
320 	upobj = p->p_upages_obj;
321 	for (i = 0; i < UAREA_PAGES; i++) {
322 		m = vm_page_grab(upobj, i, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
323 		if (m->valid != VM_PAGE_BITS_ALL) {
324 			rv = vm_pager_get_pages(upobj, &m, 1, 0);
325 			if (rv != VM_PAGER_OK)
326 				panic("vm_proc_swapin: cannot get upage");
327 		}
328 		ma[i] = m;
329 	}
330 	if (upobj->resident_page_count != UAREA_PAGES)
331 		panic("vm_proc_swapin: lost pages from upobj");
332 	vm_page_lock_queues();
333 	TAILQ_FOREACH(m, &upobj->memq, listq) {
334 		m->valid = VM_PAGE_BITS_ALL;
335 		vm_page_wire(m);
336 		vm_page_wakeup(m);
337 	}
338 	vm_page_unlock_queues();
339 	up = (vm_offset_t)p->p_uarea;
340 	pmap_qenter(up, ma, UAREA_PAGES);
341 }
342 
343 /*
344  * Swap in the UAREAs of all processes swapped out to the given device.
345  * The pages in the UAREA are marked dirty and their swap metadata is freed.
346  */
347 void
348 vm_proc_swapin_all(int devidx)
349 {
350 	struct proc *p;
351 	vm_object_t object;
352 	vm_page_t m;
353 
354 retry:
355 	sx_slock(&allproc_lock);
356 	FOREACH_PROC_IN_SYSTEM(p) {
357 		PROC_LOCK(p);
358 		mtx_lock_spin(&sched_lock);
359 
360 		object = p->p_upages_obj;
361 		if (object != NULL &&
362 		    swap_pager_isswapped(p->p_upages_obj, devidx)) {
363 			sx_sunlock(&allproc_lock);
364 			faultin(p);
365 			mtx_unlock_spin(&sched_lock);
366 			PROC_UNLOCK(p);
367 			vm_page_lock_queues();
368 			TAILQ_FOREACH(m, &object->memq, listq)
369 				vm_page_dirty(m);
370 			vm_page_unlock_queues();
371 			swap_pager_freespace(object, 0,
372 			    object->un_pager.swp.swp_bcount);
373 			goto retry;
374 		}
375 
376 		mtx_unlock_spin(&sched_lock);
377 		PROC_UNLOCK(p);
378 	}
379 	sx_sunlock(&allproc_lock);
380 }
381 #endif
382 
383 /*
384  * Implement fork's actions on an address space.
385  * Here we arrange for the address space to be copied or referenced,
386  * allocate a user struct (pcb and kernel stack), then call the
387  * machine-dependent layer to fill those in and make the new process
388  * ready to run.  The new process is set up so that it returns directly
389  * to user mode to avoid stack copying and relocation problems.
390  */
391 void
392 vm_forkproc(td, p2, td2, flags)
393 	struct thread *td;
394 	struct proc *p2;
395 	struct thread *td2;
396 	int flags;
397 {
398 	struct proc *p1 = td->td_proc;
399 	struct user *up;
400 
401 	GIANT_REQUIRED;
402 
403 	if ((flags & RFPROC) == 0) {
404 		/*
405 		 * Divorce the memory, if it is shared, essentially
406 		 * this changes shared memory amongst threads, into
407 		 * COW locally.
408 		 */
409 		if ((flags & RFMEM) == 0) {
410 			if (p1->p_vmspace->vm_refcnt > 1) {
411 				vmspace_unshare(p1);
412 			}
413 		}
414 		cpu_fork(td, p2, td2, flags);
415 		return;
416 	}
417 
418 	if (flags & RFMEM) {
419 		p2->p_vmspace = p1->p_vmspace;
420 		p1->p_vmspace->vm_refcnt++;
421 	}
422 
423 	while (vm_page_count_severe()) {
424 		VM_WAIT;
425 	}
426 
427 	if ((flags & RFMEM) == 0) {
428 		p2->p_vmspace = vmspace_fork(p1->p_vmspace);
429 
430 		pmap_pinit2(vmspace_pmap(p2->p_vmspace));
431 
432 		if (p1->p_vmspace->vm_shm)
433 			shmfork(p1, p2);
434 	}
435 
436 	/* XXXKSE this is unsatisfactory but should be adequate */
437 	up = p2->p_uarea;
438 
439 	/*
440 	 * p_stats currently points at fields in the user struct
441 	 * but not at &u, instead at p_addr. Copy parts of
442 	 * p_stats; zero the rest of p_stats (statistics).
443 	 *
444 	 * If procsig->ps_refcnt is 1 and p2->p_sigacts is NULL we dont' need
445 	 * to share sigacts, so we use the up->u_sigacts.
446 	 */
447 	p2->p_stats = &up->u_stats;
448 	if (p2->p_sigacts == NULL) {
449 		if (p2->p_procsig->ps_refcnt != 1)
450 			printf ("PID:%d NULL sigacts with refcnt not 1!\n",p2->p_pid);
451 		p2->p_sigacts = &up->u_sigacts;
452 		up->u_sigacts = *p1->p_sigacts;
453 	}
454 
455 	bzero(&up->u_stats.pstat_startzero,
456 	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
457 		(caddr_t) &up->u_stats.pstat_startzero));
458 	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
459 	    ((caddr_t) &up->u_stats.pstat_endcopy -
460 		(caddr_t) &up->u_stats.pstat_startcopy));
461 
462 
463 	/*
464 	 * cpu_fork will copy and update the pcb, set up the kernel stack,
465 	 * and make the child ready to run.
466 	 */
467 	cpu_fork(td, p2, td2, flags);
468 }
469 
470 /*
471  * Called after process has been wait(2)'ed apon and is being reaped.
472  * The idea is to reclaim resources that we could not reclaim while
473  * the process was still executing.
474  */
475 void
476 vm_waitproc(p)
477 	struct proc *p;
478 {
479 
480 	GIANT_REQUIRED;
481 	cpu_wait(p);
482 	vmspace_exitfree(p);		/* and clean-out the vmspace */
483 }
484 
485 /*
486  * Set default limits for VM system.
487  * Called for proc 0, and then inherited by all others.
488  *
489  * XXX should probably act directly on proc0.
490  */
491 static void
492 vm_init_limits(udata)
493 	void *udata;
494 {
495 	struct proc *p = udata;
496 	int rss_limit;
497 
498 	/*
499 	 * Set up the initial limits on process VM. Set the maximum resident
500 	 * set size to be half of (reasonably) available memory.  Since this
501 	 * is a soft limit, it comes into effect only when the system is out
502 	 * of memory - half of main memory helps to favor smaller processes,
503 	 * and reduces thrashing of the object cache.
504 	 */
505 	p->p_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
506 	p->p_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
507 	p->p_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
508 	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
509 	/* limit the limit to no less than 2MB */
510 	rss_limit = max(cnt.v_free_count, 512);
511 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
512 	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
513 }
514 
515 void
516 faultin(p)
517 	struct proc *p;
518 {
519 
520 	GIANT_REQUIRED;
521 	PROC_LOCK_ASSERT(p, MA_OWNED);
522 	mtx_assert(&sched_lock, MA_OWNED);
523 #ifdef NO_SWAPPING
524 	if ((p->p_sflag & PS_INMEM) == 0)
525 		panic("faultin: proc swapped out with NO_SWAPPING!");
526 #else
527 	if ((p->p_sflag & PS_INMEM) == 0) {
528 		struct thread *td;
529 
530 		++p->p_lock;
531 		/*
532 		 * If another process is swapping in this process,
533 		 * just wait until it finishes.
534 		 */
535 		if (p->p_sflag & PS_SWAPPINGIN) {
536 			mtx_unlock_spin(&sched_lock);
537 			msleep(&p->p_sflag, &p->p_mtx, PVM, "faultin", 0);
538 			mtx_lock_spin(&sched_lock);
539 			--p->p_lock;
540 			return;
541 		}
542 
543 		p->p_sflag |= PS_SWAPPINGIN;
544 		mtx_unlock_spin(&sched_lock);
545 		PROC_UNLOCK(p);
546 
547 		vm_proc_swapin(p);
548 		FOREACH_THREAD_IN_PROC (p, td) {
549 			pmap_swapin_thread(td);
550 			TD_CLR_SWAPPED(td);
551 		}
552 
553 		PROC_LOCK(p);
554 		mtx_lock_spin(&sched_lock);
555 		p->p_sflag &= ~PS_SWAPPINGIN;
556 		p->p_sflag |= PS_INMEM;
557 		FOREACH_THREAD_IN_PROC (p, td)
558 			if (TD_CAN_RUN(td))
559 				setrunnable(td);
560 
561 		wakeup(&p->p_sflag);
562 
563 		/* undo the effect of setting SLOCK above */
564 		--p->p_lock;
565 	}
566 #endif
567 }
568 
569 /*
570  * This swapin algorithm attempts to swap-in processes only if there
571  * is enough space for them.  Of course, if a process waits for a long
572  * time, it will be swapped in anyway.
573  *
574  *  XXXKSE - process with the thread with highest priority counts..
575  *
576  * Giant is still held at this point, to be released in tsleep.
577  */
578 /* ARGSUSED*/
579 static void
580 scheduler(dummy)
581 	void *dummy;
582 {
583 	struct proc *p;
584 	struct thread *td;
585 	int pri;
586 	struct proc *pp;
587 	int ppri;
588 
589 	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
590 	/* GIANT_REQUIRED */
591 
592 loop:
593 	if (vm_page_count_min()) {
594 		VM_WAIT;
595 		goto loop;
596 	}
597 
598 	pp = NULL;
599 	ppri = INT_MIN;
600 	sx_slock(&allproc_lock);
601 	FOREACH_PROC_IN_SYSTEM(p) {
602 		struct ksegrp *kg;
603 		if (p->p_sflag & (PS_INMEM | PS_SWAPPING | PS_SWAPPINGIN)) {
604 			continue;
605 		}
606 		mtx_lock_spin(&sched_lock);
607 		FOREACH_THREAD_IN_PROC(p, td) {
608 			/*
609 			 * An otherwise runnable thread of a process
610 			 * swapped out has only the TDI_SWAPPED bit set.
611 			 *
612 			 */
613 			if (td->td_inhibitors == TDI_SWAPPED) {
614 				kg = td->td_ksegrp;
615 				pri = p->p_swtime + kg->kg_slptime;
616 				if ((p->p_sflag & PS_SWAPINREQ) == 0) {
617 					pri -= kg->kg_nice * 8;
618 				}
619 
620 				/*
621 				 * if this ksegrp is higher priority
622 				 * and there is enough space, then select
623 				 * this process instead of the previous
624 				 * selection.
625 				 */
626 				if (pri > ppri) {
627 					pp = p;
628 					ppri = pri;
629 				}
630 			}
631 		}
632 		mtx_unlock_spin(&sched_lock);
633 	}
634 	sx_sunlock(&allproc_lock);
635 
636 	/*
637 	 * Nothing to do, back to sleep.
638 	 */
639 	if ((p = pp) == NULL) {
640 		tsleep(&proc0, PVM, "sched", maxslp * hz / 2);
641 		goto loop;
642 	}
643 	PROC_LOCK(p);
644 	mtx_lock_spin(&sched_lock);
645 
646 	/*
647 	 * Another process may be bringing or may have already
648 	 * brought this process in while we traverse all threads.
649 	 * Or, this process may even be being swapped out again.
650 	 */
651 	if (p->p_sflag & (PS_INMEM|PS_SWAPPING|PS_SWAPPINGIN)) {
652 		mtx_unlock_spin(&sched_lock);
653 		PROC_UNLOCK(p);
654 		goto loop;
655 	}
656 
657 	p->p_sflag &= ~PS_SWAPINREQ;
658 
659 	/*
660 	 * We would like to bring someone in. (only if there is space).
661 	 * [What checks the space? ]
662 	 */
663 	faultin(p);
664 	PROC_UNLOCK(p);
665 	p->p_swtime = 0;
666 	mtx_unlock_spin(&sched_lock);
667 	goto loop;
668 }
669 
670 #ifndef NO_SWAPPING
671 
672 /*
673  * Swap_idle_threshold1 is the guaranteed swapped in time for a process
674  */
675 static int swap_idle_threshold1 = 2;
676 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1,
677 	CTLFLAG_RW, &swap_idle_threshold1, 0, "");
678 
679 /*
680  * Swap_idle_threshold2 is the time that a process can be idle before
681  * it will be swapped out, if idle swapping is enabled.
682  */
683 static int swap_idle_threshold2 = 10;
684 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2,
685 	CTLFLAG_RW, &swap_idle_threshold2, 0, "");
686 
687 /*
688  * Swapout is driven by the pageout daemon.  Very simple, we find eligible
689  * procs and unwire their u-areas.  We try to always "swap" at least one
690  * process in case we need the room for a swapin.
691  * If any procs have been sleeping/stopped for at least maxslp seconds,
692  * they are swapped.  Else, we swap the longest-sleeping or stopped process,
693  * if any, otherwise the longest-resident process.
694  */
695 void
696 swapout_procs(action)
697 int action;
698 {
699 	struct proc *p;
700 	struct thread *td;
701 	struct ksegrp *kg;
702 	struct proc *outp, *outp2;
703 	int outpri, outpri2;
704 	int didswap = 0;
705 
706 	GIANT_REQUIRED;
707 
708 	outp = outp2 = NULL;
709 	outpri = outpri2 = INT_MIN;
710 retry:
711 	sx_slock(&allproc_lock);
712 	FOREACH_PROC_IN_SYSTEM(p) {
713 		struct vmspace *vm;
714 		int minslptime = 100000;
715 
716 		/*
717 		 * Watch out for a process in
718 		 * creation.  It may have no
719 		 * address space or lock yet.
720 		 */
721 		mtx_lock_spin(&sched_lock);
722 		if (p->p_state == PRS_NEW) {
723 			mtx_unlock_spin(&sched_lock);
724 			continue;
725 		}
726 		mtx_unlock_spin(&sched_lock);
727 
728 		/*
729 		 * An aio daemon switches its
730 		 * address space while running.
731 		 * Perform a quick check whether
732 		 * a process has P_SYSTEM.
733 		 */
734 		PROC_LOCK(p);
735 		if ((p->p_flag & P_SYSTEM) != 0) {
736 			PROC_UNLOCK(p);
737 			continue;
738 		}
739 
740 		/*
741 		 * Do not swapout a process that
742 		 * is waiting for VM data
743 		 * structures as there is a possible
744 		 * deadlock.  Test this first as
745 		 * this may block.
746 		 *
747 		 * Lock the map until swapout
748 		 * finishes, or a thread of this
749 		 * process may attempt to alter
750 		 * the map.
751 		 */
752 		vm = p->p_vmspace;
753 		KASSERT(vm != NULL,
754 			("swapout_procs: a process has no address space"));
755 		++vm->vm_refcnt;
756 		PROC_UNLOCK(p);
757 		if (!vm_map_trylock(&vm->vm_map))
758 			goto nextproc1;
759 
760 		PROC_LOCK(p);
761 		if (p->p_lock != 0 ||
762 		    (p->p_flag & (P_STOPPED_SINGLE|P_TRACED|P_SYSTEM|P_WEXIT)
763 		    ) != 0) {
764 			goto nextproc2;
765 		}
766 		/*
767 		 * only aiod changes vmspace, however it will be
768 		 * skipped because of the if statement above checking
769 		 * for P_SYSTEM
770 		 */
771 		mtx_lock_spin(&sched_lock);
772 		if ((p->p_sflag & (PS_INMEM|PS_SWAPPING|PS_SWAPPINGIN)) != PS_INMEM)
773 			goto nextproc;
774 
775 		switch (p->p_state) {
776 		default:
777 			/* Don't swap out processes in any sort
778 			 * of 'special' state. */
779 			goto nextproc;
780 
781 		case PRS_NORMAL:
782 			/*
783 			 * do not swapout a realtime process
784 			 * Check all the thread groups..
785 			 */
786 			FOREACH_KSEGRP_IN_PROC(p, kg) {
787 				if (PRI_IS_REALTIME(kg->kg_pri_class))
788 					goto nextproc;
789 
790 				/*
791 				 * Guarantee swap_idle_threshold1
792 				 * time in memory.
793 				 */
794 				if (kg->kg_slptime < swap_idle_threshold1)
795 					goto nextproc;
796 
797 				/*
798 				 * Do not swapout a process if it is
799 				 * waiting on a critical event of some
800 				 * kind or there is a thread whose
801 				 * pageable memory may be accessed.
802 				 *
803 				 * This could be refined to support
804 				 * swapping out a thread.
805 				 */
806 				FOREACH_THREAD_IN_GROUP(kg, td) {
807 					if ((td->td_priority) < PSOCK ||
808 					    !thread_safetoswapout(td))
809 						goto nextproc;
810 				}
811 				/*
812 				 * If the system is under memory stress,
813 				 * or if we are swapping
814 				 * idle processes >= swap_idle_threshold2,
815 				 * then swap the process out.
816 				 */
817 				if (((action & VM_SWAP_NORMAL) == 0) &&
818 				    (((action & VM_SWAP_IDLE) == 0) ||
819 				    (kg->kg_slptime < swap_idle_threshold2)))
820 					goto nextproc;
821 
822 				if (minslptime > kg->kg_slptime)
823 					minslptime = kg->kg_slptime;
824 			}
825 
826 			/*
827 			 * If the process has been asleep for awhile and had
828 			 * most of its pages taken away already, swap it out.
829 			 */
830 			if ((action & VM_SWAP_NORMAL) ||
831 				((action & VM_SWAP_IDLE) &&
832 				 (minslptime > swap_idle_threshold2))) {
833 				swapout(p);
834 				didswap++;
835 
836 				/*
837 				 * swapout() unlocks a proc lock. This is
838 				 * ugly, but avoids superfluous lock.
839 				 */
840 				mtx_unlock_spin(&sched_lock);
841 				vm_map_unlock(&vm->vm_map);
842 				vmspace_free(vm);
843 				sx_sunlock(&allproc_lock);
844 				goto retry;
845 			}
846 		}
847 nextproc:
848 		mtx_unlock_spin(&sched_lock);
849 nextproc2:
850 		PROC_UNLOCK(p);
851 		vm_map_unlock(&vm->vm_map);
852 nextproc1:
853 		vmspace_free(vm);
854 		continue;
855 	}
856 	sx_sunlock(&allproc_lock);
857 	/*
858 	 * If we swapped something out, and another process needed memory,
859 	 * then wakeup the sched process.
860 	 */
861 	if (didswap)
862 		wakeup(&proc0);
863 }
864 
865 static void
866 swapout(p)
867 	struct proc *p;
868 {
869 	struct thread *td;
870 
871 	PROC_LOCK_ASSERT(p, MA_OWNED);
872 	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
873 #if defined(SWAP_DEBUG)
874 	printf("swapping out %d\n", p->p_pid);
875 #endif
876 
877 	/*
878 	 * The states of this process and its threads may have changed
879 	 * by now.  Assuming that there is only one pageout daemon thread,
880 	 * this process should still be in memory.
881 	 */
882 	KASSERT((p->p_sflag & (PS_INMEM|PS_SWAPPING|PS_SWAPPINGIN)) == PS_INMEM,
883 		("swapout: lost a swapout race?"));
884 
885 #if defined(INVARIANTS)
886 	/*
887 	 * Make sure that all threads are safe to be swapped out.
888 	 *
889 	 * Alternatively, we could swap out only safe threads.
890 	 */
891 	FOREACH_THREAD_IN_PROC(p, td) {
892 		KASSERT(thread_safetoswapout(td),
893 			("swapout: there is a thread not safe for swapout"));
894 	}
895 #endif /* INVARIANTS */
896 
897 	++p->p_stats->p_ru.ru_nswap;
898 	/*
899 	 * remember the process resident count
900 	 */
901 	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
902 
903 	PROC_UNLOCK(p);
904 	p->p_sflag &= ~PS_INMEM;
905 	p->p_sflag |= PS_SWAPPING;
906 	mtx_unlock_spin(&sched_lock);
907 
908 	vm_proc_swapout(p);
909 	FOREACH_THREAD_IN_PROC(p, td) {
910 		pmap_swapout_thread(td);
911 		TD_SET_SWAPPED(td);
912 	}
913 	mtx_lock_spin(&sched_lock);
914 	p->p_sflag &= ~PS_SWAPPING;
915 	p->p_swtime = 0;
916 }
917 #endif /* !NO_SWAPPING */
918