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