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