vm_glue.c revision 113918
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 113918 2003-04-23 18:21:41Z jhb $
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
98extern int maxslp;
99
100/*
101 * System initialization
102 *
103 * Note: proc0 from proc.h
104 */
105static void vm_init_limits(void *);
106SYSINIT(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 */
113static void scheduler(void *);
114SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, scheduler, NULL)
115
116#ifndef NO_SWAPPING
117static void swapout(struct proc *);
118static void vm_proc_swapin(struct proc *p);
119static 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 */
131int
132kernacc(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 */
158int
159useracc(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 */
183void
184vslock(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 */
196void
197vsunlock(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 */
211void
212vm_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 */
260void
261vm_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 */
287static void
288vm_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 */
310static void
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	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 */
347void
348vm_proc_swapin_all(int devidx)
349{
350	struct proc *p;
351	vm_object_t object;
352	vm_page_t m;
353
354retry:
355	sx_slock(&allproc_lock);
356	FOREACH_PROC_IN_SYSTEM(p) {
357		PROC_LOCK(p);
358
359		object = p->p_upages_obj;
360		if (object != NULL &&
361		    swap_pager_isswapped(p->p_upages_obj, devidx)) {
362			sx_sunlock(&allproc_lock);
363			faultin(p);
364			PROC_UNLOCK(p);
365			vm_page_lock_queues();
366			TAILQ_FOREACH(m, &object->memq, listq)
367				vm_page_dirty(m);
368			vm_page_unlock_queues();
369			swap_pager_freespace(object, 0,
370			    object->un_pager.swp.swp_bcount);
371			goto retry;
372		}
373
374		PROC_UNLOCK(p);
375	}
376	sx_sunlock(&allproc_lock);
377}
378#endif
379
380/*
381 * Implement fork's actions on an address space.
382 * Here we arrange for the address space to be copied or referenced,
383 * allocate a user struct (pcb and kernel stack), then call the
384 * machine-dependent layer to fill those in and make the new process
385 * ready to run.  The new process is set up so that it returns directly
386 * to user mode to avoid stack copying and relocation problems.
387 */
388void
389vm_forkproc(td, p2, td2, flags)
390	struct thread *td;
391	struct proc *p2;
392	struct thread *td2;
393	int flags;
394{
395	struct proc *p1 = td->td_proc;
396	struct user *up;
397
398	GIANT_REQUIRED;
399
400	if ((flags & RFPROC) == 0) {
401		/*
402		 * Divorce the memory, if it is shared, essentially
403		 * this changes shared memory amongst threads, into
404		 * COW locally.
405		 */
406		if ((flags & RFMEM) == 0) {
407			if (p1->p_vmspace->vm_refcnt > 1) {
408				vmspace_unshare(p1);
409			}
410		}
411		cpu_fork(td, p2, td2, flags);
412		return;
413	}
414
415	if (flags & RFMEM) {
416		p2->p_vmspace = p1->p_vmspace;
417		p1->p_vmspace->vm_refcnt++;
418	}
419
420	while (vm_page_count_severe()) {
421		VM_WAIT;
422	}
423
424	if ((flags & RFMEM) == 0) {
425		p2->p_vmspace = vmspace_fork(p1->p_vmspace);
426
427		pmap_pinit2(vmspace_pmap(p2->p_vmspace));
428
429		if (p1->p_vmspace->vm_shm)
430			shmfork(p1, p2);
431	}
432
433	/* XXXKSE this is unsatisfactory but should be adequate */
434	up = p2->p_uarea;
435
436	/*
437	 * p_stats currently points at fields in the user struct
438	 * but not at &u, instead at p_addr. Copy parts of
439	 * p_stats; zero the rest of p_stats (statistics).
440	 *
441	 * If procsig->ps_refcnt is 1 and p2->p_sigacts is NULL we dont' need
442	 * to share sigacts, so we use the up->u_sigacts.
443	 */
444	p2->p_stats = &up->u_stats;
445	if (p2->p_sigacts == NULL) {
446		if (p2->p_procsig->ps_refcnt != 1)
447			printf ("PID:%d NULL sigacts with refcnt not 1!\n",p2->p_pid);
448		p2->p_sigacts = &up->u_sigacts;
449		up->u_sigacts = *p1->p_sigacts;
450	}
451
452	bzero(&up->u_stats.pstat_startzero,
453	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
454		(caddr_t) &up->u_stats.pstat_startzero));
455	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
456	    ((caddr_t) &up->u_stats.pstat_endcopy -
457		(caddr_t) &up->u_stats.pstat_startcopy));
458
459
460	/*
461	 * cpu_fork will copy and update the pcb, set up the kernel stack,
462	 * and make the child ready to run.
463	 */
464	cpu_fork(td, p2, td2, flags);
465}
466
467/*
468 * Called after process has been wait(2)'ed apon and is being reaped.
469 * The idea is to reclaim resources that we could not reclaim while
470 * the process was still executing.
471 */
472void
473vm_waitproc(p)
474	struct proc *p;
475{
476
477	GIANT_REQUIRED;
478	cpu_wait(p);
479	vmspace_exitfree(p);		/* and clean-out the vmspace */
480}
481
482/*
483 * Set default limits for VM system.
484 * Called for proc 0, and then inherited by all others.
485 *
486 * XXX should probably act directly on proc0.
487 */
488static void
489vm_init_limits(udata)
490	void *udata;
491{
492	struct proc *p = udata;
493	int rss_limit;
494
495	/*
496	 * Set up the initial limits on process VM. Set the maximum resident
497	 * set size to be half of (reasonably) available memory.  Since this
498	 * is a soft limit, it comes into effect only when the system is out
499	 * of memory - half of main memory helps to favor smaller processes,
500	 * and reduces thrashing of the object cache.
501	 */
502	p->p_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
503	p->p_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
504	p->p_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
505	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
506	/* limit the limit to no less than 2MB */
507	rss_limit = max(cnt.v_free_count, 512);
508	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
509	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
510}
511
512void
513faultin(p)
514	struct proc *p;
515{
516#ifdef NO_SWAPPING
517
518	PROC_LOCK_ASSERT(p, MA_OWNED);
519	if ((p->p_sflag & PS_INMEM) == 0)
520		panic("faultin: proc swapped out with NO_SWAPPING!");
521#else /* !NO_SWAPPING */
522	struct thread *td;
523
524	GIANT_REQUIRED;
525	PROC_LOCK_ASSERT(p, MA_OWNED);
526	/*
527	 * If another process is swapping in this process,
528	 * just wait until it finishes.
529	 */
530	if (p->p_sflag & PS_SWAPPINGIN)
531		msleep(&p->p_sflag, &p->p_mtx, PVM, "faultin", 0);
532	else if ((p->p_sflag & PS_INMEM) == 0) {
533		/*
534		 * Don't let another thread swap process p out while we are
535		 * busy swapping it in.
536		 */
537		++p->p_lock;
538		mtx_lock_spin(&sched_lock);
539		p->p_sflag |= PS_SWAPPINGIN;
540		mtx_unlock_spin(&sched_lock);
541		PROC_UNLOCK(p);
542
543		vm_proc_swapin(p);
544		FOREACH_THREAD_IN_PROC(p, td)
545			pmap_swapin_thread(td);
546
547		PROC_LOCK(p);
548		mtx_lock_spin(&sched_lock);
549		p->p_sflag &= ~PS_SWAPPINGIN;
550		p->p_sflag |= PS_INMEM;
551		FOREACH_THREAD_IN_PROC(p, td) {
552			TD_CLR_SWAPPED(td);
553			if (TD_CAN_RUN(td))
554				setrunnable(td);
555		}
556		mtx_unlock_spin(&sched_lock);
557
558		wakeup(&p->p_sflag);
559
560		/* Allow other threads to swap p out now. */
561		--p->p_lock;
562	}
563#endif /* NO_SWAPPING */
564}
565
566/*
567 * This swapin algorithm attempts to swap-in processes only if there
568 * is enough space for them.  Of course, if a process waits for a long
569 * time, it will be swapped in anyway.
570 *
571 *  XXXKSE - process with the thread with highest priority counts..
572 *
573 * Giant is still held at this point, to be released in tsleep.
574 */
575/* ARGSUSED*/
576static void
577scheduler(dummy)
578	void *dummy;
579{
580	struct proc *p;
581	struct thread *td;
582	int pri;
583	struct proc *pp;
584	int ppri;
585
586	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
587	/* GIANT_REQUIRED */
588
589loop:
590	if (vm_page_count_min()) {
591		VM_WAIT;
592		goto loop;
593	}
594
595	pp = NULL;
596	ppri = INT_MIN;
597	sx_slock(&allproc_lock);
598	FOREACH_PROC_IN_SYSTEM(p) {
599		struct ksegrp *kg;
600		if (p->p_sflag & (PS_INMEM | PS_SWAPPINGOUT | PS_SWAPPINGIN)) {
601			continue;
602		}
603		mtx_lock_spin(&sched_lock);
604		FOREACH_THREAD_IN_PROC(p, td) {
605			/*
606			 * An otherwise runnable thread of a process
607			 * swapped out has only the TDI_SWAPPED bit set.
608			 *
609			 */
610			if (td->td_inhibitors == TDI_SWAPPED) {
611				kg = td->td_ksegrp;
612				pri = p->p_swtime + kg->kg_slptime;
613				if ((p->p_sflag & PS_SWAPINREQ) == 0) {
614					pri -= kg->kg_nice * 8;
615				}
616
617				/*
618				 * if this ksegrp is higher priority
619				 * and there is enough space, then select
620				 * this process instead of the previous
621				 * selection.
622				 */
623				if (pri > ppri) {
624					pp = p;
625					ppri = pri;
626				}
627			}
628		}
629		mtx_unlock_spin(&sched_lock);
630	}
631	sx_sunlock(&allproc_lock);
632
633	/*
634	 * Nothing to do, back to sleep.
635	 */
636	if ((p = pp) == NULL) {
637		tsleep(&proc0, PVM, "sched", maxslp * hz / 2);
638		goto loop;
639	}
640	PROC_LOCK(p);
641
642	/*
643	 * Another process may be bringing or may have already
644	 * brought this process in while we traverse all threads.
645	 * Or, this process may even be being swapped out again.
646	 */
647	if (p->p_sflag & (PS_INMEM | PS_SWAPPINGOUT | PS_SWAPPINGIN)) {
648		PROC_UNLOCK(p);
649		goto loop;
650	}
651
652	mtx_lock_spin(&sched_lock);
653	p->p_sflag &= ~PS_SWAPINREQ;
654	mtx_unlock_spin(&sched_lock);
655
656	/*
657	 * We would like to bring someone in. (only if there is space).
658	 * [What checks the space? ]
659	 */
660	faultin(p);
661	PROC_UNLOCK(p);
662	mtx_lock_spin(&sched_lock);
663	p->p_swtime = 0;
664	mtx_unlock_spin(&sched_lock);
665	goto loop;
666}
667
668#ifndef NO_SWAPPING
669
670/*
671 * Swap_idle_threshold1 is the guaranteed swapped in time for a process
672 */
673static int swap_idle_threshold1 = 2;
674SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1, CTLFLAG_RW,
675    &swap_idle_threshold1, 0, "Guaranteed swapped in time for a process");
676
677/*
678 * Swap_idle_threshold2 is the time that a process can be idle before
679 * it will be swapped out, if idle swapping is enabled.
680 */
681static int swap_idle_threshold2 = 10;
682SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2, CTLFLAG_RW,
683    &swap_idle_threshold2, 0, "Time before a process will be swapped out");
684
685/*
686 * Swapout is driven by the pageout daemon.  Very simple, we find eligible
687 * procs and unwire their u-areas.  We try to always "swap" at least one
688 * process in case we need the room for a swapin.
689 * If any procs have been sleeping/stopped for at least maxslp seconds,
690 * they are swapped.  Else, we swap the longest-sleeping or stopped process,
691 * if any, otherwise the longest-resident process.
692 */
693void
694swapout_procs(action)
695int action;
696{
697	struct proc *p;
698	struct thread *td;
699	struct ksegrp *kg;
700	struct proc *outp, *outp2;
701	int outpri, outpri2;
702	int didswap = 0;
703
704	GIANT_REQUIRED;
705
706	outp = outp2 = NULL;
707	outpri = outpri2 = INT_MIN;
708retry:
709	sx_slock(&allproc_lock);
710	FOREACH_PROC_IN_SYSTEM(p) {
711		struct vmspace *vm;
712		int minslptime = 100000;
713
714		/*
715		 * Watch out for a process in
716		 * creation.  It may have no
717		 * address space or lock yet.
718		 */
719		mtx_lock_spin(&sched_lock);
720		if (p->p_state == PRS_NEW) {
721			mtx_unlock_spin(&sched_lock);
722			continue;
723		}
724		mtx_unlock_spin(&sched_lock);
725
726		/*
727		 * An aio daemon switches its
728		 * address space while running.
729		 * Perform a quick check whether
730		 * a process has P_SYSTEM.
731		 */
732		PROC_LOCK(p);
733		if ((p->p_flag & P_SYSTEM) != 0) {
734			PROC_UNLOCK(p);
735			continue;
736		}
737
738		/*
739		 * Do not swapout a process that
740		 * is waiting for VM data
741		 * structures as there is a possible
742		 * deadlock.  Test this first as
743		 * this may block.
744		 *
745		 * Lock the map until swapout
746		 * finishes, or a thread of this
747		 * process may attempt to alter
748		 * the map.
749		 */
750		vm = p->p_vmspace;
751		KASSERT(vm != NULL,
752			("swapout_procs: a process has no address space"));
753		++vm->vm_refcnt;
754		PROC_UNLOCK(p);
755		if (!vm_map_trylock(&vm->vm_map))
756			goto nextproc1;
757
758		PROC_LOCK(p);
759		if (p->p_lock != 0 ||
760		    (p->p_flag & (P_STOPPED_SINGLE|P_TRACED|P_SYSTEM|P_WEXIT)
761		    ) != 0) {
762			goto nextproc2;
763		}
764		/*
765		 * only aiod changes vmspace, however it will be
766		 * skipped because of the if statement above checking
767		 * for P_SYSTEM
768		 */
769		if ((p->p_sflag & (PS_INMEM|PS_SWAPPINGOUT|PS_SWAPPINGIN)) != PS_INMEM)
770			goto nextproc2;
771
772		mtx_lock_spin(&sched_lock);
773		switch (p->p_state) {
774		default:
775			/* Don't swap out processes in any sort
776			 * of 'special' state. */
777			goto nextproc;
778
779		case PRS_NORMAL:
780			/*
781			 * do not swapout a realtime process
782			 * Check all the thread groups..
783			 */
784			FOREACH_KSEGRP_IN_PROC(p, kg) {
785				if (PRI_IS_REALTIME(kg->kg_pri_class))
786					goto nextproc;
787
788				/*
789				 * Guarantee swap_idle_threshold1
790				 * time in memory.
791				 */
792				if (kg->kg_slptime < swap_idle_threshold1)
793					goto nextproc;
794
795				/*
796				 * Do not swapout a process if it is
797				 * waiting on a critical event of some
798				 * kind or there is a thread whose
799				 * pageable memory may be accessed.
800				 *
801				 * This could be refined to support
802				 * swapping out a thread.
803				 */
804				FOREACH_THREAD_IN_GROUP(kg, td) {
805					if ((td->td_priority) < PSOCK ||
806					    !thread_safetoswapout(td))
807						goto nextproc;
808				}
809				/*
810				 * If the system is under memory stress,
811				 * or if we are swapping
812				 * idle processes >= swap_idle_threshold2,
813				 * then swap the process out.
814				 */
815				if (((action & VM_SWAP_NORMAL) == 0) &&
816				    (((action & VM_SWAP_IDLE) == 0) ||
817				    (kg->kg_slptime < swap_idle_threshold2)))
818					goto nextproc;
819
820				if (minslptime > kg->kg_slptime)
821					minslptime = kg->kg_slptime;
822			}
823
824			/*
825			 * If the process has been asleep for awhile and had
826			 * most of its pages taken away already, swap it out.
827			 */
828			if ((action & VM_SWAP_NORMAL) ||
829				((action & VM_SWAP_IDLE) &&
830				 (minslptime > swap_idle_threshold2))) {
831				swapout(p);
832				didswap++;
833				mtx_unlock_spin(&sched_lock);
834				PROC_UNLOCK(p);
835				vm_map_unlock(&vm->vm_map);
836				vmspace_free(vm);
837				sx_sunlock(&allproc_lock);
838				goto retry;
839			}
840		}
841nextproc:
842		mtx_unlock_spin(&sched_lock);
843nextproc2:
844		PROC_UNLOCK(p);
845		vm_map_unlock(&vm->vm_map);
846nextproc1:
847		vmspace_free(vm);
848		continue;
849	}
850	sx_sunlock(&allproc_lock);
851	/*
852	 * If we swapped something out, and another process needed memory,
853	 * then wakeup the sched process.
854	 */
855	if (didswap)
856		wakeup(&proc0);
857}
858
859static void
860swapout(p)
861	struct proc *p;
862{
863	struct thread *td;
864
865	PROC_LOCK_ASSERT(p, MA_OWNED);
866	mtx_assert(&sched_lock, MA_OWNED | MA_NOTRECURSED);
867#if defined(SWAP_DEBUG)
868	printf("swapping out %d\n", p->p_pid);
869#endif
870
871	/*
872	 * The states of this process and its threads may have changed
873	 * by now.  Assuming that there is only one pageout daemon thread,
874	 * this process should still be in memory.
875	 */
876	KASSERT((p->p_sflag & (PS_INMEM|PS_SWAPPINGOUT|PS_SWAPPINGIN)) == PS_INMEM,
877		("swapout: lost a swapout race?"));
878
879#if defined(INVARIANTS)
880	/*
881	 * Make sure that all threads are safe to be swapped out.
882	 *
883	 * Alternatively, we could swap out only safe threads.
884	 */
885	FOREACH_THREAD_IN_PROC(p, td) {
886		KASSERT(thread_safetoswapout(td),
887			("swapout: there is a thread not safe for swapout"));
888	}
889#endif /* INVARIANTS */
890
891	++p->p_stats->p_ru.ru_nswap;
892	/*
893	 * remember the process resident count
894	 */
895	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
896
897	p->p_sflag &= ~PS_INMEM;
898	p->p_sflag |= PS_SWAPPINGOUT;
899	PROC_UNLOCK(p);
900	FOREACH_THREAD_IN_PROC(p, td)
901		TD_SET_SWAPPED(td);
902	mtx_unlock_spin(&sched_lock);
903
904	vm_proc_swapout(p);
905	FOREACH_THREAD_IN_PROC(p, td)
906		pmap_swapout_thread(td);
907
908	PROC_LOCK(p);
909	mtx_lock_spin(&sched_lock);
910	p->p_sflag &= ~PS_SWAPPINGOUT;
911	p->p_swtime = 0;
912}
913#endif /* !NO_SWAPPING */
914