vm_glue.c revision 99563
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 99563 2002-07-08 01:11:10Z 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
266	upobj = p->p_upages_obj;
267	if (upobj->resident_page_count != UAREA_PAGES)
268		panic("vm_proc_dispose: incorrect number of pages in upobj");
269	while ((m = TAILQ_FIRST(&upobj->memq)) != NULL) {
270		vm_page_busy(m);
271		vm_page_unwire(m, 0);
272		vm_page_free(m);
273	}
274	up = (vm_offset_t)p->p_uarea;
275	pmap_qremove(up, UAREA_PAGES);
276	kmem_free(kernel_map, up, UAREA_PAGES * PAGE_SIZE);
277	vm_object_deallocate(upobj);
278}
279
280#ifndef NO_SWAPPING
281/*
282 * Allow the U area for a process to be prejudicially paged out.
283 */
284void
285vm_proc_swapout(struct proc *p)
286{
287	vm_object_t upobj;
288	vm_offset_t up;
289	vm_page_t m;
290
291	upobj = p->p_upages_obj;
292	if (upobj->resident_page_count != UAREA_PAGES)
293		panic("vm_proc_dispose: incorrect number of pages in upobj");
294	TAILQ_FOREACH(m, &upobj->memq, listq) {
295		vm_page_dirty(m);
296		vm_page_unwire(m, 0);
297	}
298	up = (vm_offset_t)p->p_uarea;
299	pmap_qremove(up, UAREA_PAGES);
300}
301
302/*
303 * Bring the U area for a specified process back in.
304 */
305void
306vm_proc_swapin(struct proc *p)
307{
308	vm_page_t ma[UAREA_PAGES];
309	vm_object_t upobj;
310	vm_offset_t up;
311	vm_page_t m;
312	int rv;
313	int i;
314
315	upobj = p->p_upages_obj;
316	for (i = 0; i < UAREA_PAGES; i++) {
317		m = vm_page_grab(upobj, i, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
318		if (m->valid != VM_PAGE_BITS_ALL) {
319			rv = vm_pager_get_pages(upobj, &m, 1, 0);
320			if (rv != VM_PAGER_OK)
321				panic("vm_proc_swapin: cannot get upage");
322			m = vm_page_lookup(upobj, i);
323			m->valid = VM_PAGE_BITS_ALL;
324		}
325		ma[i] = m;
326		vm_page_wire(m);
327		vm_page_wakeup(m);
328		vm_page_flag_set(m, PG_MAPPED | PG_WRITEABLE);
329	}
330	up = (vm_offset_t)p->p_uarea;
331	pmap_qenter(up, ma, UAREA_PAGES);
332}
333#endif
334
335/*
336 * Implement fork's actions on an address space.
337 * Here we arrange for the address space to be copied or referenced,
338 * allocate a user struct (pcb and kernel stack), then call the
339 * machine-dependent layer to fill those in and make the new process
340 * ready to run.  The new process is set up so that it returns directly
341 * to user mode to avoid stack copying and relocation problems.
342 */
343void
344vm_forkproc(td, p2, td2, flags)
345	struct thread *td;
346	struct proc *p2;
347	struct thread *td2;
348	int flags;
349{
350	struct proc *p1 = td->td_proc;
351	struct user *up;
352
353	GIANT_REQUIRED;
354
355	if ((flags & RFPROC) == 0) {
356		/*
357		 * Divorce the memory, if it is shared, essentially
358		 * this changes shared memory amongst threads, into
359		 * COW locally.
360		 */
361		if ((flags & RFMEM) == 0) {
362			if (p1->p_vmspace->vm_refcnt > 1) {
363				vmspace_unshare(p1);
364			}
365		}
366		cpu_fork(td, p2, td2, flags);
367		return;
368	}
369
370	if (flags & RFMEM) {
371		p2->p_vmspace = p1->p_vmspace;
372		p1->p_vmspace->vm_refcnt++;
373	}
374
375	while (vm_page_count_severe()) {
376		VM_WAIT;
377	}
378
379	if ((flags & RFMEM) == 0) {
380		p2->p_vmspace = vmspace_fork(p1->p_vmspace);
381
382		pmap_pinit2(vmspace_pmap(p2->p_vmspace));
383
384		if (p1->p_vmspace->vm_shm)
385			shmfork(p1, p2);
386	}
387
388	/* XXXKSE this is unsatisfactory but should be adequate */
389	up = p2->p_uarea;
390
391	/*
392	 * p_stats currently points at fields in the user struct
393	 * but not at &u, instead at p_addr. Copy parts of
394	 * p_stats; zero the rest of p_stats (statistics).
395	 *
396	 * If procsig->ps_refcnt is 1 and p2->p_sigacts is NULL we dont' need
397	 * to share sigacts, so we use the up->u_sigacts.
398	 */
399	p2->p_stats = &up->u_stats;
400	if (p2->p_sigacts == NULL) {
401		if (p2->p_procsig->ps_refcnt != 1)
402			printf ("PID:%d NULL sigacts with refcnt not 1!\n",p2->p_pid);
403		p2->p_sigacts = &up->u_sigacts;
404		up->u_sigacts = *p1->p_sigacts;
405	}
406
407	bzero(&up->u_stats.pstat_startzero,
408	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
409		(caddr_t) &up->u_stats.pstat_startzero));
410	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
411	    ((caddr_t) &up->u_stats.pstat_endcopy -
412		(caddr_t) &up->u_stats.pstat_startcopy));
413
414
415	/*
416	 * cpu_fork will copy and update the pcb, set up the kernel stack,
417	 * and make the child ready to run.
418	 */
419	cpu_fork(td, p2, td2, flags);
420}
421
422/*
423 * Called after process has been wait(2)'ed apon and is being reaped.
424 * The idea is to reclaim resources that we could not reclaim while
425 * the process was still executing.
426 */
427void
428vm_waitproc(p)
429	struct proc *p;
430{
431	struct thread *td;
432
433	GIANT_REQUIRED;
434	cpu_wait(p);
435/* XXXKSE by here there should not be any threads left! */
436	FOREACH_THREAD_IN_PROC(p, td) {
437		panic("vm_waitproc: Survivor thread!");
438	}
439	vmspace_exitfree(p);		/* and clean-out the vmspace */
440}
441
442/*
443 * Set default limits for VM system.
444 * Called for proc 0, and then inherited by all others.
445 *
446 * XXX should probably act directly on proc0.
447 */
448static void
449vm_init_limits(udata)
450	void *udata;
451{
452	struct proc *p = udata;
453	int rss_limit;
454
455	/*
456	 * Set up the initial limits on process VM. Set the maximum resident
457	 * set size to be half of (reasonably) available memory.  Since this
458	 * is a soft limit, it comes into effect only when the system is out
459	 * of memory - half of main memory helps to favor smaller processes,
460	 * and reduces thrashing of the object cache.
461	 */
462	p->p_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
463	p->p_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
464	p->p_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
465	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
466	/* limit the limit to no less than 2MB */
467	rss_limit = max(cnt.v_free_count, 512);
468	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
469	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
470}
471
472void
473faultin(p)
474	struct proc *p;
475{
476
477	GIANT_REQUIRED;
478	PROC_LOCK_ASSERT(p, MA_OWNED);
479	mtx_lock_spin(&sched_lock);
480#ifdef NO_SWAPPING
481	if ((p->p_sflag & PS_INMEM) == 0)
482		panic("faultin: proc swapped out with NO_SWAPPING!");
483#else
484	if ((p->p_sflag & PS_INMEM) == 0) {
485		struct thread *td;
486
487		++p->p_lock;
488		mtx_unlock_spin(&sched_lock);
489		PROC_UNLOCK(p);
490
491		vm_proc_swapin(p);
492		FOREACH_THREAD_IN_PROC (p, td)
493			pmap_swapin_thread(td);
494
495		PROC_LOCK(p);
496		mtx_lock_spin(&sched_lock);
497		FOREACH_THREAD_IN_PROC (p, td)
498			if (td->td_state == TDS_RUNQ)	/* XXXKSE */
499				setrunqueue(td);
500
501		p->p_sflag |= PS_INMEM;
502
503		/* undo the effect of setting SLOCK above */
504		--p->p_lock;
505	}
506#endif
507	mtx_unlock_spin(&sched_lock);
508}
509
510/*
511 * This swapin algorithm attempts to swap-in processes only if there
512 * is enough space for them.  Of course, if a process waits for a long
513 * time, it will be swapped in anyway.
514 *
515 *  XXXKSE - process with the thread with highest priority counts..
516 *
517 * Giant is still held at this point, to be released in tsleep.
518 */
519/* ARGSUSED*/
520static void
521scheduler(dummy)
522	void *dummy;
523{
524	struct proc *p;
525	struct thread *td;
526	int pri;
527	struct proc *pp;
528	int ppri;
529
530	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
531	/* GIANT_REQUIRED */
532
533loop:
534	if (vm_page_count_min()) {
535		VM_WAIT;
536		goto loop;
537	}
538
539	pp = NULL;
540	ppri = INT_MIN;
541	sx_slock(&allproc_lock);
542	FOREACH_PROC_IN_SYSTEM(p) {
543		struct ksegrp *kg;
544		if (p->p_sflag & (PS_INMEM | PS_SWAPPING)) {
545			continue;
546		}
547		mtx_lock_spin(&sched_lock);
548		FOREACH_THREAD_IN_PROC(p, td) {
549			/* Only consider runnable threads */
550			if (td->td_state == TDS_RUNQ) {
551				kg = td->td_ksegrp;
552				pri = p->p_swtime + kg->kg_slptime;
553				if ((p->p_sflag & PS_SWAPINREQ) == 0) {
554					pri -= kg->kg_nice * 8;
555				}
556
557				/*
558				 * if this ksegrp is higher priority
559				 * and there is enough space, then select
560				 * this process instead of the previous
561				 * selection.
562				 */
563				if (pri > ppri) {
564					pp = p;
565					ppri = pri;
566				}
567			}
568		}
569		mtx_unlock_spin(&sched_lock);
570	}
571	sx_sunlock(&allproc_lock);
572
573	/*
574	 * Nothing to do, back to sleep.
575	 */
576	if ((p = pp) == NULL) {
577		tsleep(&proc0, PVM, "sched", maxslp * hz / 2);
578		goto loop;
579	}
580	mtx_lock_spin(&sched_lock);
581	p->p_sflag &= ~PS_SWAPINREQ;
582	mtx_unlock_spin(&sched_lock);
583
584	/*
585	 * We would like to bring someone in. (only if there is space).
586	 * [What checks the space? ]
587	 */
588	PROC_LOCK(p);
589	faultin(p);
590	PROC_UNLOCK(p);
591	mtx_lock_spin(&sched_lock);
592	p->p_swtime = 0;
593	mtx_unlock_spin(&sched_lock);
594	goto loop;
595}
596
597#ifndef NO_SWAPPING
598
599/*
600 * Swap_idle_threshold1 is the guaranteed swapped in time for a process
601 */
602static int swap_idle_threshold1 = 2;
603SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1,
604	CTLFLAG_RW, &swap_idle_threshold1, 0, "");
605
606/*
607 * Swap_idle_threshold2 is the time that a process can be idle before
608 * it will be swapped out, if idle swapping is enabled.
609 */
610static int swap_idle_threshold2 = 10;
611SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2,
612	CTLFLAG_RW, &swap_idle_threshold2, 0, "");
613
614/*
615 * Swapout is driven by the pageout daemon.  Very simple, we find eligible
616 * procs and unwire their u-areas.  We try to always "swap" at least one
617 * process in case we need the room for a swapin.
618 * If any procs have been sleeping/stopped for at least maxslp seconds,
619 * they are swapped.  Else, we swap the longest-sleeping or stopped process,
620 * if any, otherwise the longest-resident process.
621 */
622void
623swapout_procs(action)
624int action;
625{
626	struct proc *p;
627	struct thread *td;
628	struct ksegrp *kg;
629	struct proc *outp, *outp2;
630	int outpri, outpri2;
631	int didswap = 0;
632
633	GIANT_REQUIRED;
634
635	outp = outp2 = NULL;
636	outpri = outpri2 = INT_MIN;
637retry:
638	sx_slock(&allproc_lock);
639	FOREACH_PROC_IN_SYSTEM(p) {
640		struct vmspace *vm;
641		int minslptime = 100000;
642
643		PROC_LOCK(p);
644		if (p->p_lock != 0 ||
645		    (p->p_flag & (P_STOPPED_SNGL|P_TRACED|P_SYSTEM|P_WEXIT)) != 0) {
646			PROC_UNLOCK(p);
647			continue;
648		}
649		/*
650		 * only aiod changes vmspace, however it will be
651		 * skipped because of the if statement above checking
652		 * for P_SYSTEM
653		 */
654		vm = p->p_vmspace;
655		mtx_lock_spin(&sched_lock);
656		if ((p->p_sflag & (PS_INMEM|PS_SWAPPING)) != PS_INMEM) {
657			mtx_unlock_spin(&sched_lock);
658			PROC_UNLOCK(p);
659			continue;
660		}
661
662		switch (p->p_state) {
663		default:
664			/* Don't swap out processes in any sort
665			 * of 'special' state. */
666			mtx_unlock_spin(&sched_lock);
667			PROC_UNLOCK(p);
668			continue;
669
670		case PRS_NORMAL:
671			/*
672			 * do not swapout a realtime process
673			 * Check all the thread groups..
674			 */
675			FOREACH_KSEGRP_IN_PROC(p, kg) {
676				if (PRI_IS_REALTIME(kg->kg_pri_class)) {
677					mtx_unlock_spin(&sched_lock);
678					PROC_UNLOCK(p);
679					goto nextproc;
680				}
681
682				/*
683				 * Do not swapout a process waiting
684				 * on a critical event of some kind.
685				 * Also guarantee swap_idle_threshold1
686				 * time in memory.
687				 */
688				if (kg->kg_slptime < swap_idle_threshold1) {
689					mtx_unlock_spin(&sched_lock);
690					PROC_UNLOCK(p);
691					goto nextproc;
692				}
693				FOREACH_THREAD_IN_PROC(p, td) {
694					if ((td->td_priority) < PSOCK) {
695						mtx_unlock_spin(&sched_lock);
696						PROC_UNLOCK(p);
697						goto nextproc;
698					}
699				}
700				/*
701				 * If the system is under memory stress,
702				 * or if we are swapping
703				 * idle processes >= swap_idle_threshold2,
704				 * then swap the process out.
705				 */
706				if (((action & VM_SWAP_NORMAL) == 0) &&
707				    (((action & VM_SWAP_IDLE) == 0) ||
708				    (kg->kg_slptime < swap_idle_threshold2))) {
709					mtx_unlock_spin(&sched_lock);
710					PROC_UNLOCK(p);
711					goto nextproc;
712				}
713				if (minslptime > kg->kg_slptime)
714					minslptime = kg->kg_slptime;
715			}
716
717			mtx_unlock_spin(&sched_lock);
718			++vm->vm_refcnt;
719			/*
720			 * do not swapout a process that
721			 * is waiting for VM
722			 * data structures there is a
723			 * possible deadlock.
724			 */
725			if (!vm_map_trylock(&vm->vm_map)) {
726				vmspace_free(vm);
727				PROC_UNLOCK(p);
728				goto nextproc;
729			}
730			vm_map_unlock(&vm->vm_map);
731			/*
732			 * If the process has been asleep for awhile and had
733			 * most of its pages taken away already, swap it out.
734			 */
735			if ((action & VM_SWAP_NORMAL) ||
736				((action & VM_SWAP_IDLE) &&
737				 (minslptime > swap_idle_threshold2))) {
738				sx_sunlock(&allproc_lock);
739				swapout(p);
740				vmspace_free(vm);
741				didswap++;
742				goto retry;
743			}
744			PROC_UNLOCK(p);
745			vmspace_free(vm);
746		}
747nextproc:
748		continue;
749	}
750	sx_sunlock(&allproc_lock);
751	/*
752	 * If we swapped something out, and another process needed memory,
753	 * then wakeup the sched process.
754	 */
755	if (didswap)
756		wakeup(&proc0);
757}
758
759static void
760swapout(p)
761	struct proc *p;
762{
763	struct thread *td;
764
765	PROC_LOCK_ASSERT(p, MA_OWNED);
766#if defined(SWAP_DEBUG)
767	printf("swapping out %d\n", p->p_pid);
768#endif
769	++p->p_stats->p_ru.ru_nswap;
770	/*
771	 * remember the process resident count
772	 */
773	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
774
775	mtx_lock_spin(&sched_lock);
776	p->p_sflag &= ~PS_INMEM;
777	p->p_sflag |= PS_SWAPPING;
778	PROC_UNLOCK(p);
779	FOREACH_THREAD_IN_PROC (p, td)
780		if (td->td_state == TDS_RUNQ)	/* XXXKSE */
781			remrunqueue(td);	/* XXXKSE */
782	mtx_unlock_spin(&sched_lock);
783
784	vm_proc_swapout(p);
785	FOREACH_THREAD_IN_PROC(p, td)
786		pmap_swapout_thread(td);
787	mtx_lock_spin(&sched_lock);
788	p->p_sflag &= ~PS_SWAPPING;
789	p->p_swtime = 0;
790	mtx_unlock_spin(&sched_lock);
791}
792#endif /* !NO_SWAPPING */
793