Home | History | Annotate | Line # | Download | only in uvm
uvm_glue.c revision 1.48
      1 /*	$NetBSD: uvm_glue.c,v 1.48 2001/05/25 04:06:13 chs Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997 Charles D. Cranor and Washington University.
      5  * Copyright (c) 1991, 1993, The Regents of the University of California.
      6  *
      7  * All rights reserved.
      8  *
      9  * This code is derived from software contributed to Berkeley by
     10  * The Mach Operating System project at Carnegie-Mellon University.
     11  *
     12  * Redistribution and use in source and binary forms, with or without
     13  * modification, are permitted provided that the following conditions
     14  * are met:
     15  * 1. Redistributions of source code must retain the above copyright
     16  *    notice, this list of conditions and the following disclaimer.
     17  * 2. Redistributions in binary form must reproduce the above copyright
     18  *    notice, this list of conditions and the following disclaimer in the
     19  *    documentation and/or other materials provided with the distribution.
     20  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by Charles D. Cranor,
     23  *      Washington University, the University of California, Berkeley and
     24  *      its contributors.
     25  * 4. Neither the name of the University nor the names of its contributors
     26  *    may be used to endorse or promote products derived from this software
     27  *    without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     39  * SUCH DAMAGE.
     40  *
     41  *	@(#)vm_glue.c	8.6 (Berkeley) 1/5/94
     42  * from: Id: uvm_glue.c,v 1.1.2.8 1998/02/07 01:16:54 chs Exp
     43  *
     44  *
     45  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
     46  * All rights reserved.
     47  *
     48  * Permission to use, copy, modify and distribute this software and
     49  * its documentation is hereby granted, provided that both the copyright
     50  * notice and this permission notice appear in all copies of the
     51  * software, derivative works or modified versions, and any portions
     52  * thereof, and that both notices appear in supporting documentation.
     53  *
     54  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
     55  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
     56  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
     57  *
     58  * Carnegie Mellon requests users of this software to return to
     59  *
     60  *  Software Distribution Coordinator  or  Software.Distribution (at) CS.CMU.EDU
     61  *  School of Computer Science
     62  *  Carnegie Mellon University
     63  *  Pittsburgh PA 15213-3890
     64  *
     65  * any improvements or extensions that they make and grant Carnegie the
     66  * rights to redistribute these changes.
     67  */
     68 
     69 #include "opt_uvmhist.h"
     70 #include "opt_sysv.h"
     71 
     72 /*
     73  * uvm_glue.c: glue functions
     74  */
     75 
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/proc.h>
     79 #include <sys/resourcevar.h>
     80 #include <sys/buf.h>
     81 #include <sys/user.h>
     82 #ifdef SYSVSHM
     83 #include <sys/shm.h>
     84 #endif
     85 
     86 #include <uvm/uvm.h>
     87 
     88 #include <machine/cpu.h>
     89 
     90 /*
     91  * local prototypes
     92  */
     93 
     94 static void uvm_swapout __P((struct proc *));
     95 
     96 /*
     97  * XXXCDC: do these really belong here?
     98  */
     99 
    100 int readbuffers = 0;		/* allow KGDB to read kern buffer pool */
    101 				/* XXX: see uvm_kernacc */
    102 
    103 
    104 /*
    105  * uvm_kernacc: can the kernel access a region of memory
    106  *
    107  * - called from malloc [DIAGNOSTIC], and /dev/kmem driver (mem.c)
    108  */
    109 
    110 boolean_t
    111 uvm_kernacc(addr, len, rw)
    112 	caddr_t addr;
    113 	size_t len;
    114 	int rw;
    115 {
    116 	boolean_t rv;
    117 	vaddr_t saddr, eaddr;
    118 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
    119 
    120 	saddr = trunc_page((vaddr_t)addr);
    121 	eaddr = round_page((vaddr_t)addr + len);
    122 	vm_map_lock_read(kernel_map);
    123 	rv = uvm_map_checkprot(kernel_map, saddr, eaddr, prot);
    124 	vm_map_unlock_read(kernel_map);
    125 
    126 	/*
    127 	 * XXX there are still some things (e.g. the buffer cache) that
    128 	 * are managed behind the VM system's back so even though an
    129 	 * address is accessible in the mind of the VM system, there may
    130 	 * not be physical pages where the VM thinks there is.  This can
    131 	 * lead to bogus allocation of pages in the kernel address space
    132 	 * or worse, inconsistencies at the pmap level.  We only worry
    133 	 * about the buffer cache for now.
    134 	 */
    135 	if (!readbuffers && rv && (eaddr > (vaddr_t)buffers &&
    136 			     saddr < (vaddr_t)buffers + MAXBSIZE * nbuf))
    137 		rv = FALSE;
    138 	return(rv);
    139 }
    140 
    141 /*
    142  * uvm_useracc: can the user access it?
    143  *
    144  * - called from physio() and sys___sysctl().
    145  */
    146 
    147 boolean_t
    148 uvm_useracc(addr, len, rw)
    149 	caddr_t addr;
    150 	size_t len;
    151 	int rw;
    152 {
    153 	vm_map_t map;
    154 	boolean_t rv;
    155 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
    156 
    157 	/* XXX curproc */
    158 	map = &curproc->p_vmspace->vm_map;
    159 
    160 	vm_map_lock_read(map);
    161 	rv = uvm_map_checkprot(map, trunc_page((vaddr_t)addr),
    162 	    round_page((vaddr_t)addr + len), prot);
    163 	vm_map_unlock_read(map);
    164 
    165 	return(rv);
    166 }
    167 
    168 #ifdef KGDB
    169 /*
    170  * Change protections on kernel pages from addr to addr+len
    171  * (presumably so debugger can plant a breakpoint).
    172  *
    173  * We force the protection change at the pmap level.  If we were
    174  * to use vm_map_protect a change to allow writing would be lazily-
    175  * applied meaning we would still take a protection fault, something
    176  * we really don't want to do.  It would also fragment the kernel
    177  * map unnecessarily.  We cannot use pmap_protect since it also won't
    178  * enforce a write-enable request.  Using pmap_enter is the only way
    179  * we can ensure the change takes place properly.
    180  */
    181 void
    182 uvm_chgkprot(addr, len, rw)
    183 	caddr_t addr;
    184 	size_t len;
    185 	int rw;
    186 {
    187 	vm_prot_t prot;
    188 	paddr_t pa;
    189 	vaddr_t sva, eva;
    190 
    191 	prot = rw == B_READ ? VM_PROT_READ : VM_PROT_READ|VM_PROT_WRITE;
    192 	eva = round_page((vaddr_t)addr + len);
    193 	for (sva = trunc_page((vaddr_t)addr); sva < eva; sva += PAGE_SIZE) {
    194 		/*
    195 		 * Extract physical address for the page.
    196 		 */
    197 		if (pmap_extract(pmap_kernel(), sva, &pa) == FALSE)
    198 			panic("chgkprot: invalid page");
    199 		pmap_enter(pmap_kernel(), sva, pa, prot, PMAP_WIRED);
    200 	}
    201 	pmap_update();
    202 }
    203 #endif
    204 
    205 /*
    206  * vslock: wire user memory for I/O
    207  *
    208  * - called from physio and sys___sysctl
    209  * - XXXCDC: consider nuking this (or making it a macro?)
    210  */
    211 
    212 int
    213 uvm_vslock(p, addr, len, access_type)
    214 	struct proc *p;
    215 	caddr_t	addr;
    216 	size_t	len;
    217 	vm_prot_t access_type;
    218 {
    219 	vm_map_t map;
    220 	vaddr_t start, end;
    221 	int error;
    222 
    223 	map = &p->p_vmspace->vm_map;
    224 	start = trunc_page((vaddr_t)addr);
    225 	end = round_page((vaddr_t)addr + len);
    226 	error = uvm_fault_wire(map, start, end, access_type);
    227 	return error;
    228 }
    229 
    230 /*
    231  * vslock: wire user memory for I/O
    232  *
    233  * - called from physio and sys___sysctl
    234  * - XXXCDC: consider nuking this (or making it a macro?)
    235  */
    236 
    237 void
    238 uvm_vsunlock(p, addr, len)
    239 	struct proc *p;
    240 	caddr_t	addr;
    241 	size_t	len;
    242 {
    243 	uvm_fault_unwire(&p->p_vmspace->vm_map, trunc_page((vaddr_t)addr),
    244 		round_page((vaddr_t)addr + len));
    245 }
    246 
    247 /*
    248  * uvm_fork: fork a virtual address space
    249  *
    250  * - the address space is copied as per parent map's inherit values
    251  * - a new "user" structure is allocated for the child process
    252  *	[filled in by MD layer...]
    253  * - if specified, the child gets a new user stack described by
    254  *	stack and stacksize
    255  * - NOTE: the kernel stack may be at a different location in the child
    256  *	process, and thus addresses of automatic variables may be invalid
    257  *	after cpu_fork returns in the child process.  We do nothing here
    258  *	after cpu_fork returns.
    259  * - XXXCDC: we need a way for this to return a failure value rather
    260  *   than just hang
    261  */
    262 void
    263 uvm_fork(p1, p2, shared, stack, stacksize, func, arg)
    264 	struct proc *p1, *p2;
    265 	boolean_t shared;
    266 	void *stack;
    267 	size_t stacksize;
    268 	void (*func) __P((void *));
    269 	void *arg;
    270 {
    271 	struct user *up = p2->p_addr;
    272 	int error;
    273 
    274 	if (shared == TRUE) {
    275 		p2->p_vmspace = NULL;
    276 		uvmspace_share(p1, p2);			/* share vmspace */
    277 	} else
    278 		p2->p_vmspace = uvmspace_fork(p1->p_vmspace); /* fork vmspace */
    279 
    280 	/*
    281 	 * Wire down the U-area for the process, which contains the PCB
    282 	 * and the kernel stack.  Wired state is stored in p->p_flag's
    283 	 * P_INMEM bit rather than in the vm_map_entry's wired count
    284 	 * to prevent kernel_map fragmentation.
    285 	 *
    286 	 * Note the kernel stack gets read/write accesses right off
    287 	 * the bat.
    288 	 */
    289 	error = uvm_fault_wire(kernel_map, (vaddr_t)up,
    290 	    (vaddr_t)up + USPACE, VM_PROT_READ | VM_PROT_WRITE);
    291 	if (error)
    292 		panic("uvm_fork: uvm_fault_wire failed: %d", error);
    293 
    294 	/*
    295 	 * p_stats currently points at a field in the user struct.  Copy
    296 	 * parts of p_stats, and zero out the rest.
    297 	 */
    298 	p2->p_stats = &up->u_stats;
    299 	memset(&up->u_stats.pstat_startzero, 0,
    300 	       ((caddr_t)&up->u_stats.pstat_endzero -
    301 		(caddr_t)&up->u_stats.pstat_startzero));
    302 	memcpy(&up->u_stats.pstat_startcopy, &p1->p_stats->pstat_startcopy,
    303 	       ((caddr_t)&up->u_stats.pstat_endcopy -
    304 		(caddr_t)&up->u_stats.pstat_startcopy));
    305 
    306 	/*
    307 	 * cpu_fork() copy and update the pcb, and make the child ready
    308 	 * to run.  If this is a normal user fork, the child will exit
    309 	 * directly to user mode via child_return() on its first time
    310 	 * slice and will not return here.  If this is a kernel thread,
    311 	 * the specified entry point will be executed.
    312 	 */
    313 	cpu_fork(p1, p2, stack, stacksize, func, arg);
    314 }
    315 
    316 /*
    317  * uvm_exit: exit a virtual address space
    318  *
    319  * - the process passed to us is a dead (pre-zombie) process; we
    320  *   are running on a different context now (the reaper).
    321  * - we must run in a separate thread because freeing the vmspace
    322  *   of the dead process may block.
    323  */
    324 void
    325 uvm_exit(p)
    326 	struct proc *p;
    327 {
    328 	vaddr_t va = (vaddr_t)p->p_addr;
    329 
    330 	uvmspace_free(p->p_vmspace);
    331 	p->p_flag &= ~P_INMEM;
    332 	uvm_fault_unwire(kernel_map, va, va + USPACE);
    333 	uvm_km_free(kernel_map, va, USPACE);
    334 	p->p_addr = NULL;
    335 }
    336 
    337 /*
    338  * uvm_init_limit: init per-process VM limits
    339  *
    340  * - called for process 0 and then inherited by all others.
    341  */
    342 void
    343 uvm_init_limits(p)
    344 	struct proc *p;
    345 {
    346 
    347 	/*
    348 	 * Set up the initial limits on process VM.  Set the maximum
    349 	 * resident set size to be all of (reasonably) available memory.
    350 	 * This causes any single, large process to start random page
    351 	 * replacement once it fills memory.
    352 	 */
    353 
    354 	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
    355 	p->p_rlimit[RLIMIT_STACK].rlim_max = MAXSSIZ;
    356 	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
    357 	p->p_rlimit[RLIMIT_DATA].rlim_max = MAXDSIZ;
    358 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(uvmexp.free);
    359 }
    360 
    361 #ifdef DEBUG
    362 int	enableswap = 1;
    363 int	swapdebug = 0;
    364 #define	SDB_FOLLOW	1
    365 #define SDB_SWAPIN	2
    366 #define SDB_SWAPOUT	4
    367 #endif
    368 
    369 /*
    370  * uvm_swapin: swap in a process's u-area.
    371  */
    372 
    373 void
    374 uvm_swapin(p)
    375 	struct proc *p;
    376 {
    377 	vaddr_t addr;
    378 	int s;
    379 
    380 	addr = (vaddr_t)p->p_addr;
    381 	/* make P_INMEM true */
    382 	uvm_fault_wire(kernel_map, addr, addr + USPACE,
    383 	    VM_PROT_READ | VM_PROT_WRITE);
    384 
    385 	/*
    386 	 * Some architectures need to be notified when the user area has
    387 	 * moved to new physical page(s) (e.g.  see mips/mips/vm_machdep.c).
    388 	 */
    389 	cpu_swapin(p);
    390 	SCHED_LOCK(s);
    391 	if (p->p_stat == SRUN)
    392 		setrunqueue(p);
    393 	p->p_flag |= P_INMEM;
    394 	SCHED_UNLOCK(s);
    395 	p->p_swtime = 0;
    396 	++uvmexp.swapins;
    397 }
    398 
    399 /*
    400  * uvm_scheduler: process zero main loop
    401  *
    402  * - attempt to swapin every swaped-out, runnable process in order of
    403  *	priority.
    404  * - if not enough memory, wake the pagedaemon and let it clear space.
    405  */
    406 
    407 void
    408 uvm_scheduler()
    409 {
    410 	struct proc *p;
    411 	int pri;
    412 	struct proc *pp;
    413 	int ppri;
    414 
    415 loop:
    416 #ifdef DEBUG
    417 	while (!enableswap)
    418 		tsleep(&proc0, PVM, "noswap", 0);
    419 #endif
    420 	pp = NULL;		/* process to choose */
    421 	ppri = INT_MIN;	/* its priority */
    422 	proclist_lock_read();
    423 	LIST_FOREACH(p, &allproc, p_list) {
    424 
    425 		/* is it a runnable swapped out process? */
    426 		if (p->p_stat == SRUN && (p->p_flag & P_INMEM) == 0) {
    427 			pri = p->p_swtime + p->p_slptime -
    428 			    (p->p_nice - NZERO) * 8;
    429 			if (pri > ppri) {   /* higher priority?  remember it. */
    430 				pp = p;
    431 				ppri = pri;
    432 			}
    433 		}
    434 	}
    435 	/*
    436 	 * XXXSMP: possible unlock/sleep race between here and the
    437 	 * "scheduler" tsleep below..
    438 	 */
    439 	proclist_unlock_read();
    440 
    441 #ifdef DEBUG
    442 	if (swapdebug & SDB_FOLLOW)
    443 		printf("scheduler: running, procp %p pri %d\n", pp, ppri);
    444 #endif
    445 	/*
    446 	 * Nothing to do, back to sleep
    447 	 */
    448 	if ((p = pp) == NULL) {
    449 		tsleep(&proc0, PVM, "scheduler", 0);
    450 		goto loop;
    451 	}
    452 
    453 	/*
    454 	 * we have found swapped out process which we would like to bring
    455 	 * back in.
    456 	 *
    457 	 * XXX: this part is really bogus cuz we could deadlock on memory
    458 	 * despite our feeble check
    459 	 */
    460 	if (uvmexp.free > atop(USPACE)) {
    461 #ifdef DEBUG
    462 		if (swapdebug & SDB_SWAPIN)
    463 			printf("swapin: pid %d(%s)@%p, pri %d free %d\n",
    464 	     p->p_pid, p->p_comm, p->p_addr, ppri, uvmexp.free);
    465 #endif
    466 		uvm_swapin(p);
    467 		goto loop;
    468 	}
    469 	/*
    470 	 * not enough memory, jab the pageout daemon and wait til the coast
    471 	 * is clear
    472 	 */
    473 #ifdef DEBUG
    474 	if (swapdebug & SDB_FOLLOW)
    475 		printf("scheduler: no room for pid %d(%s), free %d\n",
    476 	   p->p_pid, p->p_comm, uvmexp.free);
    477 #endif
    478 	uvm_wait("schedpwait");
    479 #ifdef DEBUG
    480 	if (swapdebug & SDB_FOLLOW)
    481 		printf("scheduler: room again, free %d\n", uvmexp.free);
    482 #endif
    483 	goto loop;
    484 }
    485 
    486 /*
    487  * swappable: is process "p" swappable?
    488  */
    489 
    490 #define	swappable(p)							\
    491 	(((p)->p_flag & (P_SYSTEM | P_INMEM | P_WEXIT)) == P_INMEM &&	\
    492 	 (p)->p_holdcnt == 0)
    493 
    494 /*
    495  * swapout_threads: find threads that can be swapped and unwire their
    496  *	u-areas.
    497  *
    498  * - called by the pagedaemon
    499  * - try and swap at least one processs
    500  * - processes that are sleeping or stopped for maxslp or more seconds
    501  *   are swapped... otherwise the longest-sleeping or stopped process
    502  *   is swapped, otherwise the longest resident process...
    503  */
    504 void
    505 uvm_swapout_threads()
    506 {
    507 	struct proc *p;
    508 	struct proc *outp, *outp2;
    509 	int outpri, outpri2;
    510 	int didswap = 0;
    511 	extern int maxslp;
    512 	/* XXXCDC: should move off to uvmexp. or uvm., also in uvm_meter */
    513 
    514 #ifdef DEBUG
    515 	if (!enableswap)
    516 		return;
    517 #endif
    518 
    519 	/*
    520 	 * outp/outpri  : stop/sleep process with largest sleeptime < maxslp
    521 	 * outp2/outpri2: the longest resident process (its swap time)
    522 	 */
    523 	outp = outp2 = NULL;
    524 	outpri = outpri2 = 0;
    525 	proclist_lock_read();
    526 	LIST_FOREACH(p, &allproc, p_list) {
    527 		if (!swappable(p))
    528 			continue;
    529 		switch (p->p_stat) {
    530 		case SRUN:
    531 		case SONPROC:
    532 			if (p->p_swtime > outpri2) {
    533 				outp2 = p;
    534 				outpri2 = p->p_swtime;
    535 			}
    536 			continue;
    537 
    538 		case SSLEEP:
    539 		case SSTOP:
    540 			if (p->p_slptime >= maxslp) {
    541 				uvm_swapout(p);
    542 				didswap++;
    543 			} else if (p->p_slptime > outpri) {
    544 				outp = p;
    545 				outpri = p->p_slptime;
    546 			}
    547 			continue;
    548 		}
    549 	}
    550 	proclist_unlock_read();
    551 
    552 	/*
    553 	 * If we didn't get rid of any real duds, toss out the next most
    554 	 * likely sleeping/stopped or running candidate.  We only do this
    555 	 * if we are real low on memory since we don't gain much by doing
    556 	 * it (USPACE bytes).
    557 	 */
    558 	if (didswap == 0 && uvmexp.free <= atop(round_page(USPACE))) {
    559 		if ((p = outp) == NULL)
    560 			p = outp2;
    561 #ifdef DEBUG
    562 		if (swapdebug & SDB_SWAPOUT)
    563 			printf("swapout_threads: no duds, try procp %p\n", p);
    564 #endif
    565 		if (p)
    566 			uvm_swapout(p);
    567 	}
    568 }
    569 
    570 /*
    571  * uvm_swapout: swap out process "p"
    572  *
    573  * - currently "swapout" means "unwire U-area" and "pmap_collect()"
    574  *   the pmap.
    575  * - XXXCDC: should deactivate all process' private anonymous memory
    576  */
    577 
    578 static void
    579 uvm_swapout(p)
    580 	struct proc *p;
    581 {
    582 	vaddr_t addr;
    583 	int s;
    584 
    585 #ifdef DEBUG
    586 	if (swapdebug & SDB_SWAPOUT)
    587 		printf("swapout: pid %d(%s)@%p, stat %x pri %d free %d\n",
    588 	   p->p_pid, p->p_comm, p->p_addr, p->p_stat,
    589 	   p->p_slptime, uvmexp.free);
    590 #endif
    591 
    592 	/*
    593 	 * Do any machine-specific actions necessary before swapout.
    594 	 * This can include saving floating point state, etc.
    595 	 */
    596 	cpu_swapout(p);
    597 
    598 	/*
    599 	 * Mark it as (potentially) swapped out.
    600 	 */
    601 	SCHED_LOCK(s);
    602 	p->p_flag &= ~P_INMEM;
    603 	if (p->p_stat == SRUN)
    604 		remrunqueue(p);
    605 	SCHED_UNLOCK(s);
    606 	p->p_swtime = 0;
    607 	++uvmexp.swapouts;
    608 
    609 	/*
    610 	 * Unwire the to-be-swapped process's user struct and kernel stack.
    611 	 */
    612 	addr = (vaddr_t)p->p_addr;
    613 	uvm_fault_unwire(kernel_map, addr, addr + USPACE); /* !P_INMEM */
    614 	pmap_collect(vm_map_pmap(&p->p_vmspace->vm_map));
    615 }
    616 
    617