vm_glue.c revision 10653
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 * $Id: vm_glue.c,v 1.24 1995/08/28 09:19:22 julian Exp $
63 */
64
65#include <sys/param.h>
66#include <sys/systm.h>
67#include <sys/proc.h>
68#include <sys/resourcevar.h>
69#include <sys/buf.h>
70#include <sys/shm.h>
71#include <sys/user.h>
72
73#include <sys/kernel.h>
74#include <sys/dkstat.h>
75
76#include <vm/vm.h>
77#include <vm/vm_page.h>
78#include <vm/vm_pageout.h>
79#include <vm/vm_kern.h>
80
81#include <machine/stdarg.h>
82#include <machine/cpu.h>
83
84/*
85 * System initialization
86 *
87 * Note: proc0 from proc.h
88 */
89
90static void vm_init_limits __P((void *));
91SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
92
93/*
94 * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
95 *
96 * Note: run scheduling should be divorced from the vm system.
97 */
98static void scheduler __P((void *));
99SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, scheduler, NULL)
100
101
102extern char kstack[];
103
104/* vm_map_t upages_map; */
105
106int
107kernacc(addr, len, rw)
108	caddr_t addr;
109	int len, rw;
110{
111	boolean_t rv;
112	vm_offset_t saddr, eaddr;
113	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
114
115	saddr = trunc_page(addr);
116	eaddr = round_page(addr + len);
117	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
118	return (rv == TRUE);
119}
120
121int
122useracc(addr, len, rw)
123	caddr_t addr;
124	int len, rw;
125{
126	boolean_t rv;
127	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
128
129	/*
130	 * XXX - check separately to disallow access to user area and user
131	 * page tables - they are in the map.
132	 *
133	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  It was once
134	 * only used (as an end address) in trap.c.  Use it as an end address
135	 * here too.  This bogusness has spread.  I just fixed where it was
136	 * used as a max in vm_mmap.c.
137	 */
138	if ((vm_offset_t) addr + len > /* XXX */ VM_MAXUSER_ADDRESS
139	    || (vm_offset_t) addr + len < (vm_offset_t) addr) {
140		return (FALSE);
141	}
142	rv = vm_map_check_protection(&curproc->p_vmspace->vm_map,
143	    trunc_page(addr), round_page(addr + len), prot);
144	return (rv == TRUE);
145}
146
147#ifdef KGDB
148/*
149 * Change protections on kernel pages from addr to addr+len
150 * (presumably so debugger can plant a breakpoint).
151 * All addresses are assumed to reside in the Sysmap,
152 */
153chgkprot(addr, len, rw)
154	register caddr_t addr;
155	int len, rw;
156{
157	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
158
159	vm_map_protect(kernel_map, trunc_page(addr),
160	    round_page(addr + len), prot, FALSE);
161}
162#endif
163void
164vslock(addr, len)
165	caddr_t addr;
166	u_int len;
167{
168	vm_map_pageable(&curproc->p_vmspace->vm_map, trunc_page(addr),
169	    round_page(addr + len), FALSE);
170}
171
172void
173vsunlock(addr, len, dirtied)
174	caddr_t addr;
175	u_int len;
176	int dirtied;
177{
178#ifdef	lint
179	dirtied++;
180#endif	/* lint */
181	vm_map_pageable(&curproc->p_vmspace->vm_map, trunc_page(addr),
182	    round_page(addr + len), TRUE);
183}
184
185/*
186 * Implement fork's actions on an address space.
187 * Here we arrange for the address space to be copied or referenced,
188 * allocate a user struct (pcb and kernel stack), then call the
189 * machine-dependent layer to fill those in and make the new process
190 * ready to run.
191 * NOTE: the kernel stack may be at a different location in the child
192 * process, and thus addresses of automatic variables may be invalid
193 * after cpu_fork returns in the child process.  We do nothing here
194 * after cpu_fork returns.
195 */
196int
197vm_fork(p1, p2, isvfork)
198	register struct proc *p1, *p2;
199	int isvfork;
200{
201	register struct user *up;
202	vm_offset_t addr, ptaddr;
203	int i;
204	struct vm_map *vp;
205
206	while ((cnt.v_free_count + cnt.v_cache_count) < cnt.v_free_min) {
207		VM_WAIT;
208	}
209
210	/*
211	 * avoid copying any of the parent's pagetables or other per-process
212	 * objects that reside in the map by marking all of them
213	 * non-inheritable
214	 */
215	(void) vm_map_inherit(&p1->p_vmspace->vm_map,
216	    UPT_MIN_ADDRESS - UPAGES * NBPG, VM_MAX_ADDRESS, VM_INHERIT_NONE);
217	p2->p_vmspace = vmspace_fork(p1->p_vmspace);
218
219#ifdef SYSVSHM
220	if (p1->p_vmspace->vm_shm)
221		shmfork(p1, p2, isvfork);
222#endif
223
224	/*
225	 * Allocate a wired-down (for now) pcb and kernel stack for the
226	 * process
227	 */
228
229	addr = (vm_offset_t) kstack;
230
231	vp = &p2->p_vmspace->vm_map;
232
233	/* get new pagetables and kernel stack */
234	(void) vm_map_find(vp, NULL, 0, &addr, UPT_MAX_ADDRESS - addr, FALSE);
235
236	/* force in the page table encompassing the UPAGES */
237	ptaddr = trunc_page((u_int) vtopte(addr));
238	vm_map_pageable(vp, ptaddr, ptaddr + NBPG, FALSE);
239
240	/* and force in (demand-zero) the UPAGES */
241	vm_map_pageable(vp, addr, addr + UPAGES * NBPG, FALSE);
242
243	/* get a kernel virtual address for the UPAGES for this proc */
244	up = (struct user *) kmem_alloc_pageable(u_map, UPAGES * NBPG);
245	if (up == NULL)
246		panic("vm_fork: u_map allocation failed");
247
248	/* and force-map the upages into the kernel pmap */
249	for (i = 0; i < UPAGES; i++)
250		pmap_enter(vm_map_pmap(u_map),
251		    ((vm_offset_t) up) + NBPG * i,
252		    pmap_extract(vp->pmap, addr + NBPG * i),
253		    VM_PROT_READ | VM_PROT_WRITE, 1);
254
255	p2->p_addr = up;
256
257	/*
258	 * p_stats and p_sigacts currently point at fields in the user struct
259	 * but not at &u, instead at p_addr. Copy p_sigacts and parts of
260	 * p_stats; zero the rest of p_stats (statistics).
261	 */
262	p2->p_stats = &up->u_stats;
263	p2->p_sigacts = &up->u_sigacts;
264	up->u_sigacts = *p1->p_sigacts;
265	bzero(&up->u_stats.pstat_startzero,
266	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
267		(caddr_t) &up->u_stats.pstat_startzero));
268	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
269	    ((caddr_t) &up->u_stats.pstat_endcopy -
270		(caddr_t) &up->u_stats.pstat_startcopy));
271
272
273	/*
274	 * cpu_fork will copy and update the kernel stack and pcb, and make
275	 * the child ready to run.  It marks the child so that it can return
276	 * differently than the parent. It returns twice, once in the parent
277	 * process and once in the child.
278	 */
279	return (cpu_fork(p1, p2));
280}
281
282/*
283 * Set default limits for VM system.
284 * Called for proc 0, and then inherited by all others.
285 *
286 * XXX should probably act directly on proc0.
287 */
288static void
289vm_init_limits(udata)
290	void *udata;
291{
292	register struct proc *p = (struct proc *)udata;
293	int rss_limit;
294
295	/*
296	 * Set up the initial limits on process VM. Set the maximum resident
297	 * set size to be half of (reasonably) available memory.  Since this
298	 * is a soft limit, it comes into effect only when the system is out
299	 * of memory - half of main memory helps to favor smaller processes,
300	 * and reduces thrashing of the object cache.
301	 */
302	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
303	p->p_rlimit[RLIMIT_STACK].rlim_max = MAXSSIZ;
304	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
305	p->p_rlimit[RLIMIT_DATA].rlim_max = MAXDSIZ;
306	/* limit the limit to no less than 2MB */
307	rss_limit = max(cnt.v_free_count, 512);
308	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
309	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
310}
311
312void
313faultin(p)
314	struct proc *p;
315{
316	vm_offset_t i;
317	vm_offset_t ptaddr;
318	int s;
319
320	if ((p->p_flag & P_INMEM) == 0) {
321		vm_map_t map;
322
323		++p->p_lock;
324
325		map = &p->p_vmspace->vm_map;
326		/* force the page table encompassing the kernel stack (upages) */
327		ptaddr = trunc_page((u_int) vtopte(kstack));
328		vm_map_pageable(map, ptaddr, ptaddr + NBPG, FALSE);
329
330		/* wire in the UPAGES */
331		vm_map_pageable(map, (vm_offset_t) kstack,
332		    (vm_offset_t) kstack + UPAGES * NBPG, FALSE);
333
334		/* and map them nicely into the kernel pmap */
335		for (i = 0; i < UPAGES; i++) {
336			vm_offset_t off = i * NBPG;
337			vm_offset_t pa = (vm_offset_t)
338			pmap_extract(&p->p_vmspace->vm_pmap,
339			    (vm_offset_t) kstack + off);
340
341			pmap_enter(vm_map_pmap(u_map),
342			    ((vm_offset_t) p->p_addr) + off,
343			    pa, VM_PROT_READ | VM_PROT_WRITE, 1);
344		}
345
346		s = splhigh();
347
348		if (p->p_stat == SRUN)
349			setrunqueue(p);
350
351		p->p_flag |= P_INMEM;
352
353		/* undo the effect of setting SLOCK above */
354		--p->p_lock;
355		splx(s);
356
357	}
358}
359
360/*
361 * This swapin algorithm attempts to swap-in processes only if there
362 * is enough space for them.  Of course, if a process waits for a long
363 * time, it will be swapped in anyway.
364 */
365/* ARGSUSED*/
366static void
367scheduler(udata)
368	void *udata;		/* not used*/
369{
370	register struct proc *p;
371	register int pri;
372	struct proc *pp;
373	int ppri;
374
375loop:
376	while ((cnt.v_free_count + cnt.v_cache_count) < (cnt.v_free_reserved + UPAGES + 2)) {
377		VM_WAIT;
378		tsleep(&proc0, PVM, "schedm", 0);
379	}
380
381	pp = NULL;
382	ppri = INT_MIN;
383	for (p = (struct proc *) allproc; p != NULL; p = p->p_next) {
384		if (p->p_stat == SRUN && (p->p_flag & (P_INMEM | P_SWAPPING)) == 0) {
385			int mempri;
386
387			pri = p->p_swtime + p->p_slptime - p->p_nice * 8;
388			mempri = pri > 0 ? pri : 0;
389			/*
390			 * if this process is higher priority and there is
391			 * enough space, then select this process instead of
392			 * the previous selection.
393			 */
394			if (pri > ppri) {
395				pp = p;
396				ppri = pri;
397			}
398		}
399	}
400
401	/*
402	 * Nothing to do, back to sleep
403	 */
404	if ((p = pp) == NULL) {
405		tsleep(&proc0, PVM, "sched", 0);
406		goto loop;
407	}
408	/*
409	 * We would like to bring someone in. (only if there is space).
410	 */
411	faultin(p);
412	p->p_swtime = 0;
413	goto loop;
414}
415
416#define	swappable(p) \
417	(((p)->p_lock == 0) && \
418		((p)->p_flag & (P_TRACED|P_NOSWAP|P_SYSTEM|P_INMEM|P_WEXIT|P_PHYSIO|P_SWAPPING)) == P_INMEM)
419
420extern int vm_pageout_free_min;
421
422/*
423 * Swapout is driven by the pageout daemon.  Very simple, we find eligible
424 * procs and unwire their u-areas.  We try to always "swap" at least one
425 * process in case we need the room for a swapin.
426 * If any procs have been sleeping/stopped for at least maxslp seconds,
427 * they are swapped.  Else, we swap the longest-sleeping or stopped process,
428 * if any, otherwise the longest-resident process.
429 */
430void
431swapout_procs()
432{
433	register struct proc *p;
434	struct proc *outp, *outp2;
435	int outpri, outpri2;
436	int didswap = 0;
437
438	outp = outp2 = NULL;
439	outpri = outpri2 = INT_MIN;
440retry:
441	for (p = (struct proc *) allproc; p != NULL; p = p->p_next) {
442		if (!swappable(p))
443			continue;
444		switch (p->p_stat) {
445		default:
446			continue;
447
448		case SSLEEP:
449		case SSTOP:
450			/*
451			 * do not swapout a realtime process
452			 */
453			if (p->p_rtprio.type == RTP_PRIO_REALTIME)
454				continue;
455
456			/*
457			 * do not swapout a process waiting on a critical
458			 * event of some kind
459			 */
460			if ((p->p_priority & 0x7f) < PSOCK)
461				continue;
462
463			vm_map_reference(&p->p_vmspace->vm_map);
464			/*
465			 * do not swapout a process that is waiting for VM
466			 * datastructures there is a possible deadlock.
467			 */
468			if (!lock_try_write(&p->p_vmspace->vm_map.lock)) {
469				vm_map_deallocate(&p->p_vmspace->vm_map);
470				continue;
471			}
472			vm_map_unlock(&p->p_vmspace->vm_map);
473			/*
474			 * If the process has been asleep for awhile and had
475			 * most of its pages taken away already, swap it out.
476			 */
477			if (p->p_slptime > 4) {
478				swapout(p);
479				vm_map_deallocate(&p->p_vmspace->vm_map);
480				didswap++;
481				goto retry;
482			}
483			vm_map_deallocate(&p->p_vmspace->vm_map);
484		}
485	}
486	/*
487	 * If we swapped something out, and another process needed memory,
488	 * then wakeup the sched process.
489	 */
490	if (didswap)
491		wakeup(&proc0);
492}
493
494void
495swapout(p)
496	register struct proc *p;
497{
498	vm_map_t map = &p->p_vmspace->vm_map;
499	vm_offset_t ptaddr;
500
501	++p->p_stats->p_ru.ru_nswap;
502	/*
503	 * remember the process resident count
504	 */
505	p->p_vmspace->vm_swrss =
506	    p->p_vmspace->vm_pmap.pm_stats.resident_count;
507
508	(void) splhigh();
509	p->p_flag &= ~P_INMEM;
510	if (p->p_stat == SRUN)
511		remrq(p);
512	(void) spl0();
513
514	p->p_flag |= P_SWAPPING;
515	/*
516	 * let the upages be paged
517	 */
518	pmap_remove(vm_map_pmap(u_map),
519	    (vm_offset_t) p->p_addr, ((vm_offset_t) p->p_addr) + UPAGES * NBPG);
520
521	vm_map_pageable(map, (vm_offset_t) kstack,
522	    (vm_offset_t) kstack + UPAGES * NBPG, TRUE);
523
524	ptaddr = trunc_page((u_int) vtopte(kstack));
525	vm_map_pageable(map, ptaddr, ptaddr + NBPG, TRUE);
526
527	p->p_flag &= ~P_SWAPPING;
528	p->p_swtime = 0;
529}
530
531#ifdef DDB
532/*
533 * DEBUG stuff
534 */
535
536int indent;
537
538#include <machine/stdarg.h>	/* see subr_prf.c */
539
540/*ARGSUSED2*/
541void
542#if __STDC__
543iprintf(const char *fmt,...)
544#else
545iprintf(fmt /* , va_alist */ )
546	char *fmt;
547
548 /* va_dcl */
549#endif
550{
551	register int i;
552	va_list ap;
553
554	for (i = indent; i >= 8; i -= 8)
555		printf("\t");
556	while (--i >= 0)
557		printf(" ");
558	va_start(ap, fmt);
559	printf("%r", fmt, ap);
560	va_end(ap);
561}
562#endif /* DDB */
563