vm_glue.c revision 99559
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: head/sys/vm/vm_glue.c 99559 2002-07-07 23:05:27Z peter $
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
95#include <sys/user.h>
96
97extern int maxslp;
98
99/*
100 * System initialization
101 *
102 * Note: proc0 from proc.h
103 */
104static void vm_init_limits(void *);
105SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
106
107/*
108 * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
109 *
110 * Note: run scheduling should be divorced from the vm system.
111 */
112static void scheduler(void *);
113SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, scheduler, NULL)
114
115#ifndef NO_SWAPPING
116static void swapout(struct proc *);
117static void vm_proc_swapin(struct proc *p);
118static void vm_proc_swapout(struct proc *p);
119#endif
120
121/*
122 * MPSAFE
123 */
124int
125kernacc(addr, len, rw)
126	caddr_t addr;
127	int len, rw;
128{
129	boolean_t rv;
130	vm_offset_t saddr, eaddr;
131	vm_prot_t prot;
132
133	KASSERT((rw & ~VM_PROT_ALL) == 0,
134	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
135	prot = rw;
136	saddr = trunc_page((vm_offset_t)addr);
137	eaddr = round_page((vm_offset_t)addr + len);
138	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
139	return (rv == TRUE);
140}
141
142/*
143 * MPSAFE
144 */
145int
146useracc(addr, len, rw)
147	caddr_t addr;
148	int len, rw;
149{
150	boolean_t rv;
151	vm_prot_t prot;
152
153	KASSERT((rw & ~VM_PROT_ALL) == 0,
154	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
155	prot = rw;
156	/*
157	 * XXX - check separately to disallow access to user area and user
158	 * page tables - they are in the map.
159	 *
160	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  It was once
161	 * only used (as an end address) in trap.c.  Use it as an end address
162	 * here too.  This bogusness has spread.  I just fixed where it was
163	 * used as a max in vm_mmap.c.
164	 */
165	if ((vm_offset_t) addr + len > /* XXX */ VM_MAXUSER_ADDRESS
166	    || (vm_offset_t) addr + len < (vm_offset_t) addr) {
167		return (FALSE);
168	}
169	rv = vm_map_check_protection(&curproc->p_vmspace->vm_map,
170	    trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len),
171	    prot);
172	return (rv == TRUE);
173}
174
175/*
176 * MPSAFE
177 */
178void
179vslock(addr, len)
180	caddr_t addr;
181	u_int len;
182{
183
184	vm_map_wire(&curproc->p_vmspace->vm_map, trunc_page((vm_offset_t)addr),
185	    round_page((vm_offset_t)addr + len), FALSE);
186}
187
188/*
189 * MPSAFE
190 */
191void
192vsunlock(addr, len)
193	caddr_t addr;
194	u_int len;
195{
196
197	vm_map_unwire(&curproc->p_vmspace->vm_map,
198	    trunc_page((vm_offset_t)addr),
199	    round_page((vm_offset_t)addr + len), FALSE);
200}
201
202/*
203 * Create the U area for a new process.
204 * This routine directly affects the fork perf for a process.
205 */
206void
207vm_proc_new(struct proc *p)
208{
209	vm_page_t ma[UAREA_PAGES];
210	vm_object_t upobj;
211	vm_offset_t up;
212	vm_page_t m;
213	u_int i;
214
215	/*
216	 * Allocate object for the upage.
217	 */
218	upobj = vm_object_allocate(OBJT_DEFAULT, UAREA_PAGES);
219	p->p_upages_obj = upobj;
220
221	/*
222	 * Get a kernel virtual address for the U area for this process.
223	 */
224	up = kmem_alloc_nofault(kernel_map, UAREA_PAGES * PAGE_SIZE);
225	if (up == 0)
226		panic("vm_proc_new: upage allocation failed");
227	p->p_uarea = (struct user *)up;
228
229	for (i = 0; i < UAREA_PAGES; i++) {
230		/*
231		 * Get a uarea page.
232		 */
233		m = vm_page_grab(upobj, i, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
234		ma[i] = m;
235
236		/*
237		 * Wire the page.
238		 */
239		m->wire_count++;
240		cnt.v_wire_count++;
241
242		vm_page_wakeup(m);
243		vm_page_flag_clear(m, PG_ZERO);
244		vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
245		m->valid = VM_PAGE_BITS_ALL;
246	}
247
248	/*
249	 * Enter the pages into the kernel address space.
250	 */
251	pmap_qenter(up, ma, UAREA_PAGES);
252}
253
254/*
255 * Dispose the U area for a process that has exited.
256 * This routine directly impacts the exit perf of a process.
257 * XXX proc_zone is marked UMA_ZONE_NOFREE, so this should never be called.
258 */
259void
260vm_proc_dispose(struct proc *p)
261{
262	vm_object_t upobj;
263	vm_offset_t up;
264	vm_page_t m;
265	int i;
266
267	upobj = p->p_upages_obj;
268	up = (vm_offset_t)p->p_uarea;
269	for (i = 0; i < UAREA_PAGES; i++) {
270		m = vm_page_lookup(upobj, i);
271		if (m == NULL)
272			panic("vm_proc_dispose: upage already missing?");
273		vm_page_busy(m);
274		vm_page_unwire(m, 0);
275		vm_page_free(m);
276	}
277	pmap_qremove(up, UAREA_PAGES);
278	kmem_free(kernel_map, up, UAREA_PAGES * PAGE_SIZE);
279	p->p_upages_obj = NULL;
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 */
287void
288vm_proc_swapout(struct proc *p)
289{
290	vm_object_t upobj;
291	vm_offset_t up;
292	vm_page_t m;
293	int i;
294
295	upobj = p->p_upages_obj;
296	up = (vm_offset_t)p->p_uarea;
297	for (i = 0; i < UAREA_PAGES; i++) {
298		m = vm_page_lookup(upobj, i);
299		if (m == NULL)
300			panic("vm_proc_swapout: upage already missing?");
301		vm_page_dirty(m);
302		vm_page_unwire(m, 0);
303	}
304	pmap_qremove(up, UAREA_PAGES);
305}
306
307/*
308 * Bring the U area for a specified process back in.
309 */
310void
311vm_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	up = (vm_offset_t)p->p_uarea;
322	for (i = 0; i < UAREA_PAGES; i++) {
323		m = vm_page_grab(upobj, i, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
324		if (m->valid != VM_PAGE_BITS_ALL) {
325			rv = vm_pager_get_pages(upobj, &m, 1, 0);
326			if (rv != VM_PAGER_OK)
327				panic("vm_proc_swapin: cannot get upage");
328			m = vm_page_lookup(upobj, i);
329			m->valid = VM_PAGE_BITS_ALL;
330		}
331		ma[i] = m;
332		vm_page_wire(m);
333		vm_page_wakeup(m);
334		vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
335	}
336	pmap_qenter(up, ma, UAREA_PAGES);
337}
338#endif
339
340/*
341 * Implement fork's actions on an address space.
342 * Here we arrange for the address space to be copied or referenced,
343 * allocate a user struct (pcb and kernel stack), then call the
344 * machine-dependent layer to fill those in and make the new process
345 * ready to run.  The new process is set up so that it returns directly
346 * to user mode to avoid stack copying and relocation problems.
347 */
348void
349vm_forkproc(td, p2, td2, flags)
350	struct thread *td;
351	struct proc *p2;
352	struct thread *td2;
353	int flags;
354{
355	struct proc *p1 = td->td_proc;
356	struct user *up;
357
358	GIANT_REQUIRED;
359
360	if ((flags & RFPROC) == 0) {
361		/*
362		 * Divorce the memory, if it is shared, essentially
363		 * this changes shared memory amongst threads, into
364		 * COW locally.
365		 */
366		if ((flags & RFMEM) == 0) {
367			if (p1->p_vmspace->vm_refcnt > 1) {
368				vmspace_unshare(p1);
369			}
370		}
371		cpu_fork(td, p2, td2, flags);
372		return;
373	}
374
375	if (flags & RFMEM) {
376		p2->p_vmspace = p1->p_vmspace;
377		p1->p_vmspace->vm_refcnt++;
378	}
379
380	while (vm_page_count_severe()) {
381		VM_WAIT;
382	}
383
384	if ((flags & RFMEM) == 0) {
385		p2->p_vmspace = vmspace_fork(p1->p_vmspace);
386
387		pmap_pinit2(vmspace_pmap(p2->p_vmspace));
388
389		if (p1->p_vmspace->vm_shm)
390			shmfork(p1, p2);
391	}
392
393	/* XXXKSE this is unsatisfactory but should be adequate */
394	up = p2->p_uarea;
395
396	/*
397	 * p_stats currently points at fields in the user struct
398	 * but not at &u, instead at p_addr. Copy parts of
399	 * p_stats; zero the rest of p_stats (statistics).
400	 *
401	 * If procsig->ps_refcnt is 1 and p2->p_sigacts is NULL we dont' need
402	 * to share sigacts, so we use the up->u_sigacts.
403	 */
404	p2->p_stats = &up->u_stats;
405	if (p2->p_sigacts == NULL) {
406		if (p2->p_procsig->ps_refcnt != 1)
407			printf ("PID:%d NULL sigacts with refcnt not 1!\n",p2->p_pid);
408		p2->p_sigacts = &up->u_sigacts;
409		up->u_sigacts = *p1->p_sigacts;
410	}
411
412	bzero(&up->u_stats.pstat_startzero,
413	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
414		(caddr_t) &up->u_stats.pstat_startzero));
415	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
416	    ((caddr_t) &up->u_stats.pstat_endcopy -
417		(caddr_t) &up->u_stats.pstat_startcopy));
418
419
420	/*
421	 * cpu_fork will copy and update the pcb, set up the kernel stack,
422	 * and make the child ready to run.
423	 */
424	cpu_fork(td, p2, td2, flags);
425}
426
427/*
428 * Called after process has been wait(2)'ed apon and is being reaped.
429 * The idea is to reclaim resources that we could not reclaim while
430 * the process was still executing.
431 */
432void
433vm_waitproc(p)
434	struct proc *p;
435{
436	struct thread *td;
437
438	GIANT_REQUIRED;
439	cpu_wait(p);
440/* XXXKSE by here there should not be any threads left! */
441	FOREACH_THREAD_IN_PROC(p, td) {
442		panic("vm_waitproc: Survivor thread!");
443	}
444	vmspace_exitfree(p);		/* and clean-out the vmspace */
445}
446
447/*
448 * Set default limits for VM system.
449 * Called for proc 0, and then inherited by all others.
450 *
451 * XXX should probably act directly on proc0.
452 */
453static void
454vm_init_limits(udata)
455	void *udata;
456{
457	struct proc *p = udata;
458	int rss_limit;
459
460	/*
461	 * Set up the initial limits on process VM. Set the maximum resident
462	 * set size to be half of (reasonably) available memory.  Since this
463	 * is a soft limit, it comes into effect only when the system is out
464	 * of memory - half of main memory helps to favor smaller processes,
465	 * and reduces thrashing of the object cache.
466	 */
467	p->p_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
468	p->p_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
469	p->p_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
470	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
471	/* limit the limit to no less than 2MB */
472	rss_limit = max(cnt.v_free_count, 512);
473	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
474	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
475}
476
477void
478faultin(p)
479	struct proc *p;
480{
481
482	GIANT_REQUIRED;
483	PROC_LOCK_ASSERT(p, MA_OWNED);
484	mtx_lock_spin(&sched_lock);
485#ifdef NO_SWAPPING
486	if ((p->p_sflag & PS_INMEM) == 0)
487		panic("faultin: proc swapped out with NO_SWAPPING!");
488#else
489	if ((p->p_sflag & PS_INMEM) == 0) {
490		struct thread *td;
491
492		++p->p_lock;
493		mtx_unlock_spin(&sched_lock);
494		PROC_UNLOCK(p);
495
496		vm_proc_swapin(p);
497		FOREACH_THREAD_IN_PROC (p, td)
498			pmap_swapin_thread(td);
499
500		PROC_LOCK(p);
501		mtx_lock_spin(&sched_lock);
502		FOREACH_THREAD_IN_PROC (p, td)
503			if (td->td_state == TDS_RUNQ)	/* XXXKSE */
504				setrunqueue(td);
505
506		p->p_sflag |= PS_INMEM;
507
508		/* undo the effect of setting SLOCK above */
509		--p->p_lock;
510	}
511#endif
512	mtx_unlock_spin(&sched_lock);
513}
514
515/*
516 * This swapin algorithm attempts to swap-in processes only if there
517 * is enough space for them.  Of course, if a process waits for a long
518 * time, it will be swapped in anyway.
519 *
520 *  XXXKSE - process with the thread with highest priority counts..
521 *
522 * Giant is still held at this point, to be released in tsleep.
523 */
524/* ARGSUSED*/
525static void
526scheduler(dummy)
527	void *dummy;
528{
529	struct proc *p;
530	struct thread *td;
531	int pri;
532	struct proc *pp;
533	int ppri;
534
535	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
536	/* GIANT_REQUIRED */
537
538loop:
539	if (vm_page_count_min()) {
540		VM_WAIT;
541		goto loop;
542	}
543
544	pp = NULL;
545	ppri = INT_MIN;
546	sx_slock(&allproc_lock);
547	FOREACH_PROC_IN_SYSTEM(p) {
548		struct ksegrp *kg;
549		if (p->p_sflag & (PS_INMEM | PS_SWAPPING)) {
550			continue;
551		}
552		mtx_lock_spin(&sched_lock);
553		FOREACH_THREAD_IN_PROC(p, td) {
554			/* Only consider runnable threads */
555			if (td->td_state == TDS_RUNQ) {
556				kg = td->td_ksegrp;
557				pri = p->p_swtime + kg->kg_slptime;
558				if ((p->p_sflag & PS_SWAPINREQ) == 0) {
559					pri -= kg->kg_nice * 8;
560				}
561
562				/*
563				 * if this ksegrp is higher priority
564				 * and there is enough space, then select
565				 * this process instead of the previous
566				 * selection.
567				 */
568				if (pri > ppri) {
569					pp = p;
570					ppri = pri;
571				}
572			}
573		}
574		mtx_unlock_spin(&sched_lock);
575	}
576	sx_sunlock(&allproc_lock);
577
578	/*
579	 * Nothing to do, back to sleep.
580	 */
581	if ((p = pp) == NULL) {
582		tsleep(&proc0, PVM, "sched", maxslp * hz / 2);
583		goto loop;
584	}
585	mtx_lock_spin(&sched_lock);
586	p->p_sflag &= ~PS_SWAPINREQ;
587	mtx_unlock_spin(&sched_lock);
588
589	/*
590	 * We would like to bring someone in. (only if there is space).
591	 * [What checks the space? ]
592	 */
593	PROC_LOCK(p);
594	faultin(p);
595	PROC_UNLOCK(p);
596	mtx_lock_spin(&sched_lock);
597	p->p_swtime = 0;
598	mtx_unlock_spin(&sched_lock);
599	goto loop;
600}
601
602#ifndef NO_SWAPPING
603
604/*
605 * Swap_idle_threshold1 is the guaranteed swapped in time for a process
606 */
607static int swap_idle_threshold1 = 2;
608SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1,
609	CTLFLAG_RW, &swap_idle_threshold1, 0, "");
610
611/*
612 * Swap_idle_threshold2 is the time that a process can be idle before
613 * it will be swapped out, if idle swapping is enabled.
614 */
615static int swap_idle_threshold2 = 10;
616SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2,
617	CTLFLAG_RW, &swap_idle_threshold2, 0, "");
618
619/*
620 * Swapout is driven by the pageout daemon.  Very simple, we find eligible
621 * procs and unwire their u-areas.  We try to always "swap" at least one
622 * process in case we need the room for a swapin.
623 * If any procs have been sleeping/stopped for at least maxslp seconds,
624 * they are swapped.  Else, we swap the longest-sleeping or stopped process,
625 * if any, otherwise the longest-resident process.
626 */
627void
628swapout_procs(action)
629int action;
630{
631	struct proc *p;
632	struct thread *td;
633	struct ksegrp *kg;
634	struct proc *outp, *outp2;
635	int outpri, outpri2;
636	int didswap = 0;
637
638	GIANT_REQUIRED;
639
640	outp = outp2 = NULL;
641	outpri = outpri2 = INT_MIN;
642retry:
643	sx_slock(&allproc_lock);
644	FOREACH_PROC_IN_SYSTEM(p) {
645		struct vmspace *vm;
646		int minslptime = 100000;
647
648		PROC_LOCK(p);
649		if (p->p_lock != 0 ||
650		    (p->p_flag & (P_STOPPED_SNGL|P_TRACED|P_SYSTEM|P_WEXIT)) != 0) {
651			PROC_UNLOCK(p);
652			continue;
653		}
654		/*
655		 * only aiod changes vmspace, however it will be
656		 * skipped because of the if statement above checking
657		 * for P_SYSTEM
658		 */
659		vm = p->p_vmspace;
660		mtx_lock_spin(&sched_lock);
661		if ((p->p_sflag & (PS_INMEM|PS_SWAPPING)) != PS_INMEM) {
662			mtx_unlock_spin(&sched_lock);
663			PROC_UNLOCK(p);
664			continue;
665		}
666
667		switch (p->p_state) {
668		default:
669			/* Don't swap out processes in any sort
670			 * of 'special' state. */
671			mtx_unlock_spin(&sched_lock);
672			PROC_UNLOCK(p);
673			continue;
674
675		case PRS_NORMAL:
676			/*
677			 * do not swapout a realtime process
678			 * Check all the thread groups..
679			 */
680			FOREACH_KSEGRP_IN_PROC(p, kg) {
681				if (PRI_IS_REALTIME(kg->kg_pri_class)) {
682					mtx_unlock_spin(&sched_lock);
683					PROC_UNLOCK(p);
684					goto nextproc;
685				}
686
687				/*
688				 * Do not swapout a process waiting
689				 * on a critical event of some kind.
690				 * Also guarantee swap_idle_threshold1
691				 * time in memory.
692				 */
693				if (kg->kg_slptime < swap_idle_threshold1) {
694					mtx_unlock_spin(&sched_lock);
695					PROC_UNLOCK(p);
696					goto nextproc;
697				}
698				FOREACH_THREAD_IN_PROC(p, td) {
699					if ((td->td_priority) < PSOCK) {
700						mtx_unlock_spin(&sched_lock);
701						PROC_UNLOCK(p);
702						goto nextproc;
703					}
704				}
705				/*
706				 * If the system is under memory stress,
707				 * or if we are swapping
708				 * idle processes >= swap_idle_threshold2,
709				 * then swap the process out.
710				 */
711				if (((action & VM_SWAP_NORMAL) == 0) &&
712				    (((action & VM_SWAP_IDLE) == 0) ||
713				    (kg->kg_slptime < swap_idle_threshold2))) {
714					mtx_unlock_spin(&sched_lock);
715					PROC_UNLOCK(p);
716					goto nextproc;
717				}
718				if (minslptime > kg->kg_slptime)
719					minslptime = kg->kg_slptime;
720			}
721
722			mtx_unlock_spin(&sched_lock);
723			++vm->vm_refcnt;
724			/*
725			 * do not swapout a process that
726			 * is waiting for VM
727			 * data structures there is a
728			 * possible deadlock.
729			 */
730			if (!vm_map_trylock(&vm->vm_map)) {
731				vmspace_free(vm);
732				PROC_UNLOCK(p);
733				goto nextproc;
734			}
735			vm_map_unlock(&vm->vm_map);
736			/*
737			 * If the process has been asleep for awhile and had
738			 * most of its pages taken away already, swap it out.
739			 */
740			if ((action & VM_SWAP_NORMAL) ||
741				((action & VM_SWAP_IDLE) &&
742				 (minslptime > swap_idle_threshold2))) {
743				sx_sunlock(&allproc_lock);
744				swapout(p);
745				vmspace_free(vm);
746				didswap++;
747				goto retry;
748			}
749			PROC_UNLOCK(p);
750			vmspace_free(vm);
751		}
752nextproc:
753		continue;
754	}
755	sx_sunlock(&allproc_lock);
756	/*
757	 * If we swapped something out, and another process needed memory,
758	 * then wakeup the sched process.
759	 */
760	if (didswap)
761		wakeup(&proc0);
762}
763
764static void
765swapout(p)
766	struct proc *p;
767{
768	struct thread *td;
769
770	PROC_LOCK_ASSERT(p, MA_OWNED);
771#if defined(SWAP_DEBUG)
772	printf("swapping out %d\n", p->p_pid);
773#endif
774	++p->p_stats->p_ru.ru_nswap;
775	/*
776	 * remember the process resident count
777	 */
778	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
779
780	mtx_lock_spin(&sched_lock);
781	p->p_sflag &= ~PS_INMEM;
782	p->p_sflag |= PS_SWAPPING;
783	PROC_UNLOCK(p);
784	FOREACH_THREAD_IN_PROC (p, td)
785		if (td->td_state == TDS_RUNQ)	/* XXXKSE */
786			remrunqueue(td);	/* XXXKSE */
787	mtx_unlock_spin(&sched_lock);
788
789	vm_proc_swapout(p);
790	FOREACH_THREAD_IN_PROC(p, td)
791		pmap_swapout_thread(td);
792	mtx_lock_spin(&sched_lock);
793	p->p_sflag &= ~PS_SWAPPING;
794	p->p_swtime = 0;
795	mtx_unlock_spin(&sched_lock);
796}
797#endif /* !NO_SWAPPING */
798