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