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