vm_glue.c revision 90361
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 90361 2002-02-07 20:58:47Z julian $
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_kern.h>
91#include <vm/vm_extern.h>
92
93#include <sys/user.h>
94
95extern int maxslp;
96
97/*
98 * System initialization
99 *
100 * Note: proc0 from proc.h
101 */
102
103static void vm_init_limits __P((void *));
104SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
105
106/*
107 * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
108 *
109 * Note: run scheduling should be divorced from the vm system.
110 */
111static void scheduler __P((void *));
112SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, scheduler, NULL)
113
114#ifndef NO_SWAPPING
115static void swapout __P((struct proc *));
116#endif
117
118int
119kernacc(addr, len, rw)
120	caddr_t addr;
121	int len, rw;
122{
123	boolean_t rv;
124	vm_offset_t saddr, eaddr;
125	vm_prot_t prot;
126
127	KASSERT((rw & ~VM_PROT_ALL) == 0,
128	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
129	prot = rw;
130	saddr = trunc_page((vm_offset_t)addr);
131	eaddr = round_page((vm_offset_t)addr + len);
132	vm_map_lock_read(kernel_map);
133	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
134	vm_map_unlock_read(kernel_map);
135	return (rv == TRUE);
136}
137
138int
139useracc(addr, len, rw)
140	caddr_t addr;
141	int len, rw;
142{
143	boolean_t rv;
144	vm_prot_t prot;
145	vm_map_t map;
146	vm_map_entry_t save_hint;
147
148	GIANT_REQUIRED;
149
150	KASSERT((rw & ~VM_PROT_ALL) == 0,
151	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
152	prot = rw;
153	/*
154	 * XXX - check separately to disallow access to user area and user
155	 * page tables - they are in the map.
156	 *
157	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  It was once
158	 * only used (as an end address) in trap.c.  Use it as an end address
159	 * here too.  This bogusness has spread.  I just fixed where it was
160	 * used as a max in vm_mmap.c.
161	 */
162	if ((vm_offset_t) addr + len > /* XXX */ VM_MAXUSER_ADDRESS
163	    || (vm_offset_t) addr + len < (vm_offset_t) addr) {
164		return (FALSE);
165	}
166	map = &curproc->p_vmspace->vm_map;
167	vm_map_lock_read(map);
168	/*
169	 * We save the map hint, and restore it.  Useracc appears to distort
170	 * the map hint unnecessarily.
171	 */
172	save_hint = map->hint;
173	rv = vm_map_check_protection(map,
174	    trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len), prot);
175	map->hint = save_hint;
176	vm_map_unlock_read(map);
177
178	return (rv == TRUE);
179}
180
181void
182vslock(addr, len)
183	caddr_t addr;
184	u_int len;
185{
186	GIANT_REQUIRED;
187	vm_map_pageable(&curproc->p_vmspace->vm_map,
188	    trunc_page((vm_offset_t)addr),
189	    round_page((vm_offset_t)addr + len), FALSE);
190}
191
192void
193vsunlock(addr, len)
194	caddr_t addr;
195	u_int len;
196{
197	GIANT_REQUIRED;
198	vm_map_pageable(&curproc->p_vmspace->vm_map,
199	    trunc_page((vm_offset_t)addr),
200	    round_page((vm_offset_t)addr + len), TRUE);
201}
202
203/*
204 * Implement fork's actions on an address space.
205 * Here we arrange for the address space to be copied or referenced,
206 * allocate a user struct (pcb and kernel stack), then call the
207 * machine-dependent layer to fill those in and make the new process
208 * ready to run.  The new process is set up so that it returns directly
209 * to user mode to avoid stack copying and relocation problems.
210 */
211void
212vm_forkproc(td, p2, td2, flags)
213	struct thread *td;
214	struct proc *p2;
215	struct thread *td2;
216	int flags;
217{
218	struct proc *p1 = td->td_proc;
219	struct user *up;
220
221	GIANT_REQUIRED;
222
223	if ((flags & RFPROC) == 0) {
224		/*
225		 * Divorce the memory, if it is shared, essentially
226		 * this changes shared memory amongst threads, into
227		 * COW locally.
228		 */
229		if ((flags & RFMEM) == 0) {
230			if (p1->p_vmspace->vm_refcnt > 1) {
231				vmspace_unshare(p1);
232			}
233		}
234		cpu_fork(td, p2, td2, flags);
235		return;
236	}
237
238	if (flags & RFMEM) {
239		p2->p_vmspace = p1->p_vmspace;
240		p1->p_vmspace->vm_refcnt++;
241	}
242
243	while (vm_page_count_severe()) {
244		VM_WAIT;
245	}
246
247	if ((flags & RFMEM) == 0) {
248		p2->p_vmspace = vmspace_fork(p1->p_vmspace);
249
250		pmap_pinit2(vmspace_pmap(p2->p_vmspace));
251
252		if (p1->p_vmspace->vm_shm)
253			shmfork(p1, p2);
254	}
255
256	pmap_new_proc(p2);
257	pmap_new_thread(td2);		/* Initial thread */
258
259	/* XXXKSE this is unsatisfactory but should be adequate */
260	up = p2->p_uarea;
261
262	/*
263	 * p_stats currently points at fields in the user struct
264	 * but not at &u, instead at p_addr. Copy parts of
265	 * p_stats; zero the rest of p_stats (statistics).
266	 *
267	 * If procsig->ps_refcnt is 1 and p2->p_sigacts is NULL we dont' need
268	 * to share sigacts, so we use the up->u_sigacts.
269	 */
270	p2->p_stats = &up->u_stats;
271	if (p2->p_sigacts == NULL) {
272		if (p2->p_procsig->ps_refcnt != 1)
273			printf ("PID:%d NULL sigacts with refcnt not 1!\n",p2->p_pid);
274		p2->p_sigacts = &up->u_sigacts;
275		up->u_sigacts = *p1->p_sigacts;
276	}
277
278	bzero(&up->u_stats.pstat_startzero,
279	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
280		(caddr_t) &up->u_stats.pstat_startzero));
281	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
282	    ((caddr_t) &up->u_stats.pstat_endcopy -
283		(caddr_t) &up->u_stats.pstat_startcopy));
284
285
286	/*
287	 * cpu_fork will copy and update the pcb, set up the kernel stack,
288	 * and make the child ready to run.
289	 */
290	cpu_fork(td, p2, td2, flags);
291}
292
293/*
294 * Called after process has been wait(2)'ed apon and is being reaped.
295 * The idea is to reclaim resources that we could not reclaim while
296 * the process was still executing.
297 */
298void
299vm_waitproc(p)
300	struct proc *p;
301{
302	struct thread *td;
303
304	GIANT_REQUIRED;
305	cpu_wait(p);
306	pmap_dispose_proc(p);		/* drop per-process resources */
307	FOREACH_THREAD_IN_PROC(p, td)
308		pmap_dispose_thread(td);
309	vmspace_exitfree(p);		/* and clean-out the vmspace */
310}
311
312/*
313 * Set default limits for VM system.
314 * Called for proc 0, and then inherited by all others.
315 *
316 * XXX should probably act directly on proc0.
317 */
318static void
319vm_init_limits(udata)
320	void *udata;
321{
322	struct proc *p = udata;
323	int rss_limit;
324
325	/*
326	 * Set up the initial limits on process VM. Set the maximum resident
327	 * set size to be half of (reasonably) available memory.  Since this
328	 * is a soft limit, it comes into effect only when the system is out
329	 * of memory - half of main memory helps to favor smaller processes,
330	 * and reduces thrashing of the object cache.
331	 */
332	p->p_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
333	p->p_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
334	p->p_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
335	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
336	/* limit the limit to no less than 2MB */
337	rss_limit = max(cnt.v_free_count, 512);
338	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
339	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
340}
341
342void
343faultin(p)
344	struct proc *p;
345{
346	struct thread *td;
347	GIANT_REQUIRED;
348
349	PROC_LOCK_ASSERT(p, MA_OWNED);
350	mtx_lock_spin(&sched_lock);
351	if ((p->p_sflag & PS_INMEM) == 0) {
352		++p->p_lock;
353		mtx_unlock_spin(&sched_lock);
354		PROC_UNLOCK(p);
355
356		pmap_swapin_proc(p);
357		FOREACH_THREAD_IN_PROC (p, td)
358			pmap_swapin_thread(td);
359
360		PROC_LOCK(p);
361		mtx_lock_spin(&sched_lock);
362		FOREACH_THREAD_IN_PROC (p, td)
363			if (td->td_proc->p_stat == SRUN)	/* XXXKSE */
364				setrunqueue(td);
365
366		p->p_sflag |= PS_INMEM;
367
368		/* undo the effect of setting SLOCK above */
369		--p->p_lock;
370	}
371	mtx_unlock_spin(&sched_lock);
372}
373
374/*
375 * This swapin algorithm attempts to swap-in processes only if there
376 * is enough space for them.  Of course, if a process waits for a long
377 * time, it will be swapped in anyway.
378 *
379 *  XXXKSE - KSEGRP with highest priority counts..
380 *
381 * Giant is still held at this point, to be released in tsleep.
382 */
383/* ARGSUSED*/
384static void
385scheduler(dummy)
386	void *dummy;
387{
388	struct proc *p;
389	int pri;
390	struct proc *pp;
391	int ppri;
392
393	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
394	/* GIANT_REQUIRED */
395
396loop:
397	if (vm_page_count_min()) {
398		VM_WAIT;
399		goto loop;
400	}
401
402	pp = NULL;
403	ppri = INT_MIN;
404	sx_slock(&allproc_lock);
405	FOREACH_PROC_IN_SYSTEM(p) {
406		struct ksegrp *kg;
407		mtx_lock_spin(&sched_lock);
408		if (p->p_stat == SRUN
409		&& (p->p_sflag & (PS_INMEM | PS_SWAPPING)) == 0) {
410			/* Find the minimum sleeptime for the process */
411			FOREACH_KSEGRP_IN_PROC(p, kg) {
412				pri = p->p_swtime + kg->kg_slptime;
413				if ((p->p_sflag & PS_SWAPINREQ) == 0) {
414					pri -= kg->kg_nice * 8;
415				}
416
417
418				/*
419				 * if this ksegrp is higher priority
420				 * and there is enough space, then select
421				 * this process instead of the previous
422				 * selection.
423				 */
424				if (pri > ppri) {
425					pp = p;
426					ppri = pri;
427				}
428			}
429		}
430		mtx_unlock_spin(&sched_lock);
431	}
432	sx_sunlock(&allproc_lock);
433
434	/*
435	 * Nothing to do, back to sleep.
436	 */
437	if ((p = pp) == NULL) {
438		tsleep(&proc0, PVM, "sched", maxslp * hz / 2);
439		goto loop;
440	}
441	mtx_lock_spin(&sched_lock);
442	p->p_sflag &= ~PS_SWAPINREQ;
443	mtx_unlock_spin(&sched_lock);
444
445	/*
446	 * We would like to bring someone in. (only if there is space).
447	 */
448	PROC_LOCK(p);
449	faultin(p);
450	PROC_UNLOCK(p);
451	mtx_lock_spin(&sched_lock);
452	p->p_swtime = 0;
453	mtx_unlock_spin(&sched_lock);
454	goto loop;
455}
456
457#ifndef NO_SWAPPING
458
459/*
460 * Swap_idle_threshold1 is the guaranteed swapped in time for a process
461 */
462static int swap_idle_threshold1 = 2;
463SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1,
464	CTLFLAG_RW, &swap_idle_threshold1, 0, "");
465
466/*
467 * Swap_idle_threshold2 is the time that a process can be idle before
468 * it will be swapped out, if idle swapping is enabled.
469 */
470static int swap_idle_threshold2 = 10;
471SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2,
472	CTLFLAG_RW, &swap_idle_threshold2, 0, "");
473
474/*
475 * Swapout is driven by the pageout daemon.  Very simple, we find eligible
476 * procs and unwire their u-areas.  We try to always "swap" at least one
477 * process in case we need the room for a swapin.
478 * If any procs have been sleeping/stopped for at least maxslp seconds,
479 * they are swapped.  Else, we swap the longest-sleeping or stopped process,
480 * if any, otherwise the longest-resident process.
481 */
482void
483swapout_procs(action)
484int action;
485{
486	struct proc *p;
487	struct ksegrp *kg;
488	struct proc *outp, *outp2;
489	int outpri, outpri2;
490	int didswap = 0;
491
492	GIANT_REQUIRED;
493
494	outp = outp2 = NULL;
495	outpri = outpri2 = INT_MIN;
496retry:
497	sx_slock(&allproc_lock);
498	LIST_FOREACH(p, &allproc, p_list) {
499		struct vmspace *vm;
500		int minslptime = 100000;
501
502		PROC_LOCK(p);
503		if (p->p_lock != 0 ||
504		    (p->p_flag & (P_TRACED|P_SYSTEM|P_WEXIT)) != 0) {
505			PROC_UNLOCK(p);
506			continue;
507		}
508		/*
509		 * only aiod changes vmspace, however it will be
510		 * skipped because of the if statement above checking
511		 * for P_SYSTEM
512		 */
513		vm = p->p_vmspace;
514		mtx_lock_spin(&sched_lock);
515		if ((p->p_sflag & (PS_INMEM|PS_SWAPPING)) != PS_INMEM) {
516			mtx_unlock_spin(&sched_lock);
517			PROC_UNLOCK(p);
518			continue;
519		}
520
521		switch (p->p_stat) {
522		default:
523			mtx_unlock_spin(&sched_lock);
524			PROC_UNLOCK(p);
525			continue;
526
527		case SSLEEP:
528		case SSTOP:
529			/*
530			 * do not swapout a realtime process
531			 * Check all the thread groups..
532			 */
533			FOREACH_KSEGRP_IN_PROC(p, kg) {
534				if (PRI_IS_REALTIME(kg->kg_pri.pri_class)) {
535					mtx_unlock_spin(&sched_lock);
536					PROC_UNLOCK(p);
537					goto nextproc;
538				}
539
540				/*
541				 * Do not swapout a process waiting
542				 * on a critical event of some kind.
543				 * Also guarantee swap_idle_threshold1
544				 * time in memory.
545				 */
546				if (((kg->kg_pri.pri_level) < PSOCK) ||
547				    (kg->kg_slptime < swap_idle_threshold1)) {
548					mtx_unlock_spin(&sched_lock);
549					PROC_UNLOCK(p);
550					goto nextproc;
551				}
552
553				/*
554				 * If the system is under memory stress,
555				 * or if we are swapping
556				 * idle processes >= swap_idle_threshold2,
557				 * then swap the process out.
558				 */
559				if (((action & VM_SWAP_NORMAL) == 0) &&
560				    (((action & VM_SWAP_IDLE) == 0) ||
561				    (kg->kg_slptime < swap_idle_threshold2))) {
562					mtx_unlock_spin(&sched_lock);
563					PROC_UNLOCK(p);
564					goto nextproc;
565				}
566				if (minslptime > kg->kg_slptime)
567					minslptime = kg->kg_slptime;
568			}
569
570			mtx_unlock_spin(&sched_lock);
571			++vm->vm_refcnt;
572			/*
573			 * do not swapout a process that
574			 * is waiting for VM
575			 * data structures there is a
576			 * possible deadlock.
577			 */
578			if (lockmgr(&vm->vm_map.lock,
579					LK_EXCLUSIVE | LK_NOWAIT,
580					NULL, curthread)) {
581				vmspace_free(vm);
582				PROC_UNLOCK(p);
583				goto nextproc;
584			}
585			vm_map_unlock(&vm->vm_map);
586			/*
587			 * If the process has been asleep for awhile and had
588			 * most of its pages taken away already, swap it out.
589			 */
590			if ((action & VM_SWAP_NORMAL) ||
591				((action & VM_SWAP_IDLE) &&
592				 (minslptime > swap_idle_threshold2))) {
593				sx_sunlock(&allproc_lock);
594				swapout(p);
595				vmspace_free(vm);
596				didswap++;
597				goto retry;
598			}
599			PROC_UNLOCK(p);
600			vmspace_free(vm);
601		}
602nextproc:
603	}
604	sx_sunlock(&allproc_lock);
605	/*
606	 * If we swapped something out, and another process needed memory,
607	 * then wakeup the sched process.
608	 */
609	if (didswap)
610		wakeup(&proc0);
611}
612
613static void
614swapout(p)
615	struct proc *p;
616{
617	struct thread *td;
618
619	PROC_LOCK_ASSERT(p, MA_OWNED);
620#if defined(SWAP_DEBUG)
621	printf("swapping out %d\n", p->p_pid);
622#endif
623	++p->p_stats->p_ru.ru_nswap;
624	/*
625	 * remember the process resident count
626	 */
627	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
628
629	mtx_lock_spin(&sched_lock);
630	p->p_sflag &= ~PS_INMEM;
631	p->p_sflag |= PS_SWAPPING;
632	PROC_UNLOCK(p);
633	FOREACH_THREAD_IN_PROC (p, td)
634		if (td->td_proc->p_stat == SRUN)	/* XXXKSE */
635			remrunqueue(td);	/* XXXKSE */
636	mtx_unlock_spin(&sched_lock);
637
638	pmap_swapout_proc(p);
639	FOREACH_THREAD_IN_PROC(p, td)
640		pmap_swapout_thread(td);
641
642	mtx_lock_spin(&sched_lock);
643	p->p_sflag &= ~PS_SWAPPING;
644	p->p_swtime = 0;
645	mtx_unlock_spin(&sched_lock);
646}
647#endif /* !NO_SWAPPING */
648