Home | History | Annotate | Line # | Download | only in uvm
uvm_glue.c revision 1.46
      1 /*	$NetBSD: uvm_glue.c,v 1.46 2001/04/21 17:38:24 thorpej 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 		 * We use a cheezy hack to differentiate physical
    197 		 * page 0 from an invalid mapping, not that it
    198 		 * really matters...
    199 		 */
    200 		if (pmap_extract(pmap_kernel(), sva, &pa) == FALSE)
    201 			panic("chgkprot: invalid page");
    202 		pmap_enter(pmap_kernel(), sva, pa, prot, PMAP_WIRED);
    203 	}
    204 }
    205 #endif
    206 
    207 /*
    208  * vslock: wire user memory for I/O
    209  *
    210  * - called from physio and sys___sysctl
    211  * - XXXCDC: consider nuking this (or making it a macro?)
    212  */
    213 
    214 int
    215 uvm_vslock(p, addr, len, access_type)
    216 	struct proc *p;
    217 	caddr_t	addr;
    218 	size_t	len;
    219 	vm_prot_t access_type;
    220 {
    221 	vm_map_t map;
    222 	vaddr_t start, end;
    223 	int error;
    224 
    225 	map = &p->p_vmspace->vm_map;
    226 	start = trunc_page((vaddr_t)addr);
    227 	end = round_page((vaddr_t)addr + len);
    228 	error = uvm_fault_wire(map, start, end, access_type);
    229 	return error;
    230 }
    231 
    232 /*
    233  * vslock: wire user memory for I/O
    234  *
    235  * - called from physio and sys___sysctl
    236  * - XXXCDC: consider nuking this (or making it a macro?)
    237  */
    238 
    239 void
    240 uvm_vsunlock(p, addr, len)
    241 	struct proc *p;
    242 	caddr_t	addr;
    243 	size_t	len;
    244 {
    245 	uvm_fault_unwire(&p->p_vmspace->vm_map, trunc_page((vaddr_t)addr),
    246 		round_page((vaddr_t)addr + len));
    247 }
    248 
    249 /*
    250  * uvm_fork: fork a virtual address space
    251  *
    252  * - the address space is copied as per parent map's inherit values
    253  * - a new "user" structure is allocated for the child process
    254  *	[filled in by MD layer...]
    255  * - if specified, the child gets a new user stack described by
    256  *	stack and stacksize
    257  * - NOTE: the kernel stack may be at a different location in the child
    258  *	process, and thus addresses of automatic variables may be invalid
    259  *	after cpu_fork returns in the child process.  We do nothing here
    260  *	after cpu_fork returns.
    261  * - XXXCDC: we need a way for this to return a failure value rather
    262  *   than just hang
    263  */
    264 void
    265 uvm_fork(p1, p2, shared, stack, stacksize, func, arg)
    266 	struct proc *p1, *p2;
    267 	boolean_t shared;
    268 	void *stack;
    269 	size_t stacksize;
    270 	void (*func) __P((void *));
    271 	void *arg;
    272 {
    273 	struct user *up = p2->p_addr;
    274 	int error;
    275 
    276 	if (shared == TRUE) {
    277 		p2->p_vmspace = NULL;
    278 		uvmspace_share(p1, p2);			/* share vmspace */
    279 	} else
    280 		p2->p_vmspace = uvmspace_fork(p1->p_vmspace); /* fork vmspace */
    281 
    282 	/*
    283 	 * Wire down the U-area for the process, which contains the PCB
    284 	 * and the kernel stack.  Wired state is stored in p->p_flag's
    285 	 * P_INMEM bit rather than in the vm_map_entry's wired count
    286 	 * to prevent kernel_map fragmentation.
    287 	 *
    288 	 * Note the kernel stack gets read/write accesses right off
    289 	 * the bat.
    290 	 */
    291 	error = uvm_fault_wire(kernel_map, (vaddr_t)up,
    292 	    (vaddr_t)up + USPACE, VM_PROT_READ | VM_PROT_WRITE);
    293 	if (error)
    294 		panic("uvm_fork: uvm_fault_wire failed: %d", error);
    295 
    296 	/*
    297 	 * p_stats currently points at a field in the user struct.  Copy
    298 	 * parts of p_stats, and zero out the rest.
    299 	 */
    300 	p2->p_stats = &up->u_stats;
    301 	memset(&up->u_stats.pstat_startzero, 0,
    302 	       ((caddr_t)&up->u_stats.pstat_endzero -
    303 		(caddr_t)&up->u_stats.pstat_startzero));
    304 	memcpy(&up->u_stats.pstat_startcopy, &p1->p_stats->pstat_startcopy,
    305 	       ((caddr_t)&up->u_stats.pstat_endcopy -
    306 		(caddr_t)&up->u_stats.pstat_startcopy));
    307 
    308 	/*
    309 	 * cpu_fork() copy and update the pcb, and make the child ready
    310 	 * to run.  If this is a normal user fork, the child will exit
    311 	 * directly to user mode via child_return() on its first time
    312 	 * slice and will not return here.  If this is a kernel thread,
    313 	 * the specified entry point will be executed.
    314 	 */
    315 	cpu_fork(p1, p2, stack, stacksize, func, arg);
    316 }
    317 
    318 /*
    319  * uvm_exit: exit a virtual address space
    320  *
    321  * - the process passed to us is a dead (pre-zombie) process; we
    322  *   are running on a different context now (the reaper).
    323  * - we must run in a separate thread because freeing the vmspace
    324  *   of the dead process may block.
    325  */
    326 void
    327 uvm_exit(p)
    328 	struct proc *p;
    329 {
    330 	vaddr_t va = (vaddr_t)p->p_addr;
    331 
    332 	uvmspace_free(p->p_vmspace);
    333 	p->p_flag &= ~P_INMEM;
    334 	uvm_fault_unwire(kernel_map, va, va + USPACE);
    335 	uvm_km_free(kernel_map, va, USPACE);
    336 	p->p_addr = NULL;
    337 }
    338 
    339 /*
    340  * uvm_init_limit: init per-process VM limits
    341  *
    342  * - called for process 0 and then inherited by all others.
    343  */
    344 void
    345 uvm_init_limits(p)
    346 	struct proc *p;
    347 {
    348 
    349 	/*
    350 	 * Set up the initial limits on process VM.  Set the maximum
    351 	 * resident set size to be all of (reasonably) available memory.
    352 	 * This causes any single, large process to start random page
    353 	 * replacement once it fills memory.
    354 	 */
    355 
    356 	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
    357 	p->p_rlimit[RLIMIT_STACK].rlim_max = MAXSSIZ;
    358 	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
    359 	p->p_rlimit[RLIMIT_DATA].rlim_max = MAXDSIZ;
    360 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(uvmexp.free);
    361 }
    362 
    363 #ifdef DEBUG
    364 int	enableswap = 1;
    365 int	swapdebug = 0;
    366 #define	SDB_FOLLOW	1
    367 #define SDB_SWAPIN	2
    368 #define SDB_SWAPOUT	4
    369 #endif
    370 
    371 /*
    372  * uvm_swapin: swap in a process's u-area.
    373  */
    374 
    375 void
    376 uvm_swapin(p)
    377 	struct proc *p;
    378 {
    379 	vaddr_t addr;
    380 	int s;
    381 
    382 	addr = (vaddr_t)p->p_addr;
    383 	/* make P_INMEM true */
    384 	uvm_fault_wire(kernel_map, addr, addr + USPACE,
    385 	    VM_PROT_READ | VM_PROT_WRITE);
    386 
    387 	/*
    388 	 * Some architectures need to be notified when the user area has
    389 	 * moved to new physical page(s) (e.g.  see mips/mips/vm_machdep.c).
    390 	 */
    391 	cpu_swapin(p);
    392 	SCHED_LOCK(s);
    393 	if (p->p_stat == SRUN)
    394 		setrunqueue(p);
    395 	p->p_flag |= P_INMEM;
    396 	SCHED_UNLOCK(s);
    397 	p->p_swtime = 0;
    398 	++uvmexp.swapins;
    399 }
    400 
    401 /*
    402  * uvm_scheduler: process zero main loop
    403  *
    404  * - attempt to swapin every swaped-out, runnable process in order of
    405  *	priority.
    406  * - if not enough memory, wake the pagedaemon and let it clear space.
    407  */
    408 
    409 void
    410 uvm_scheduler()
    411 {
    412 	struct proc *p;
    413 	int pri;
    414 	struct proc *pp;
    415 	int ppri;
    416 
    417 loop:
    418 #ifdef DEBUG
    419 	while (!enableswap)
    420 		tsleep(&proc0, PVM, "noswap", 0);
    421 #endif
    422 	pp = NULL;		/* process to choose */
    423 	ppri = INT_MIN;	/* its priority */
    424 	proclist_lock_read();
    425 	LIST_FOREACH(p, &allproc, p_list) {
    426 
    427 		/* is it a runnable swapped out process? */
    428 		if (p->p_stat == SRUN && (p->p_flag & P_INMEM) == 0) {
    429 			pri = p->p_swtime + p->p_slptime -
    430 			    (p->p_nice - NZERO) * 8;
    431 			if (pri > ppri) {   /* higher priority?  remember it. */
    432 				pp = p;
    433 				ppri = pri;
    434 			}
    435 		}
    436 	}
    437 	/*
    438 	 * XXXSMP: possible unlock/sleep race between here and the
    439 	 * "scheduler" tsleep below..
    440 	 */
    441 	proclist_unlock_read();
    442 
    443 #ifdef DEBUG
    444 	if (swapdebug & SDB_FOLLOW)
    445 		printf("scheduler: running, procp %p pri %d\n", pp, ppri);
    446 #endif
    447 	/*
    448 	 * Nothing to do, back to sleep
    449 	 */
    450 	if ((p = pp) == NULL) {
    451 		tsleep(&proc0, PVM, "scheduler", 0);
    452 		goto loop;
    453 	}
    454 
    455 	/*
    456 	 * we have found swapped out process which we would like to bring
    457 	 * back in.
    458 	 *
    459 	 * XXX: this part is really bogus cuz we could deadlock on memory
    460 	 * despite our feeble check
    461 	 */
    462 	if (uvmexp.free > atop(USPACE)) {
    463 #ifdef DEBUG
    464 		if (swapdebug & SDB_SWAPIN)
    465 			printf("swapin: pid %d(%s)@%p, pri %d free %d\n",
    466 	     p->p_pid, p->p_comm, p->p_addr, ppri, uvmexp.free);
    467 #endif
    468 		uvm_swapin(p);
    469 		goto loop;
    470 	}
    471 	/*
    472 	 * not enough memory, jab the pageout daemon and wait til the coast
    473 	 * is clear
    474 	 */
    475 #ifdef DEBUG
    476 	if (swapdebug & SDB_FOLLOW)
    477 		printf("scheduler: no room for pid %d(%s), free %d\n",
    478 	   p->p_pid, p->p_comm, uvmexp.free);
    479 #endif
    480 	uvm_wait("schedpwait");
    481 #ifdef DEBUG
    482 	if (swapdebug & SDB_FOLLOW)
    483 		printf("scheduler: room again, free %d\n", uvmexp.free);
    484 #endif
    485 	goto loop;
    486 }
    487 
    488 /*
    489  * swappable: is process "p" swappable?
    490  */
    491 
    492 #define	swappable(p)							\
    493 	(((p)->p_flag & (P_SYSTEM | P_INMEM | P_WEXIT)) == P_INMEM &&	\
    494 	 (p)->p_holdcnt == 0)
    495 
    496 /*
    497  * swapout_threads: find threads that can be swapped and unwire their
    498  *	u-areas.
    499  *
    500  * - called by the pagedaemon
    501  * - try and swap at least one processs
    502  * - processes that are sleeping or stopped for maxslp or more seconds
    503  *   are swapped... otherwise the longest-sleeping or stopped process
    504  *   is swapped, otherwise the longest resident process...
    505  */
    506 void
    507 uvm_swapout_threads()
    508 {
    509 	struct proc *p;
    510 	struct proc *outp, *outp2;
    511 	int outpri, outpri2;
    512 	int didswap = 0;
    513 	extern int maxslp;
    514 	/* XXXCDC: should move off to uvmexp. or uvm., also in uvm_meter */
    515 
    516 #ifdef DEBUG
    517 	if (!enableswap)
    518 		return;
    519 #endif
    520 
    521 	/*
    522 	 * outp/outpri  : stop/sleep process with largest sleeptime < maxslp
    523 	 * outp2/outpri2: the longest resident process (its swap time)
    524 	 */
    525 	outp = outp2 = NULL;
    526 	outpri = outpri2 = 0;
    527 	proclist_lock_read();
    528 	LIST_FOREACH(p, &allproc, p_list) {
    529 		if (!swappable(p))
    530 			continue;
    531 		switch (p->p_stat) {
    532 		case SRUN:
    533 		case SONPROC:
    534 			if (p->p_swtime > outpri2) {
    535 				outp2 = p;
    536 				outpri2 = p->p_swtime;
    537 			}
    538 			continue;
    539 
    540 		case SSLEEP:
    541 		case SSTOP:
    542 			if (p->p_slptime >= maxslp) {
    543 				uvm_swapout(p);
    544 				didswap++;
    545 			} else if (p->p_slptime > outpri) {
    546 				outp = p;
    547 				outpri = p->p_slptime;
    548 			}
    549 			continue;
    550 		}
    551 	}
    552 	proclist_unlock_read();
    553 
    554 	/*
    555 	 * If we didn't get rid of any real duds, toss out the next most
    556 	 * likely sleeping/stopped or running candidate.  We only do this
    557 	 * if we are real low on memory since we don't gain much by doing
    558 	 * it (USPACE bytes).
    559 	 */
    560 	if (didswap == 0 && uvmexp.free <= atop(round_page(USPACE))) {
    561 		if ((p = outp) == NULL)
    562 			p = outp2;
    563 #ifdef DEBUG
    564 		if (swapdebug & SDB_SWAPOUT)
    565 			printf("swapout_threads: no duds, try procp %p\n", p);
    566 #endif
    567 		if (p)
    568 			uvm_swapout(p);
    569 	}
    570 }
    571 
    572 /*
    573  * uvm_swapout: swap out process "p"
    574  *
    575  * - currently "swapout" means "unwire U-area" and "pmap_collect()"
    576  *   the pmap.
    577  * - XXXCDC: should deactivate all process' private anonymous memory
    578  */
    579 
    580 static void
    581 uvm_swapout(p)
    582 	struct proc *p;
    583 {
    584 	vaddr_t addr;
    585 	int s;
    586 
    587 #ifdef DEBUG
    588 	if (swapdebug & SDB_SWAPOUT)
    589 		printf("swapout: pid %d(%s)@%p, stat %x pri %d free %d\n",
    590 	   p->p_pid, p->p_comm, p->p_addr, p->p_stat,
    591 	   p->p_slptime, uvmexp.free);
    592 #endif
    593 
    594 	/*
    595 	 * Do any machine-specific actions necessary before swapout.
    596 	 * This can include saving floating point state, etc.
    597 	 */
    598 	cpu_swapout(p);
    599 
    600 	/*
    601 	 * Mark it as (potentially) swapped out.
    602 	 */
    603 	SCHED_LOCK(s);
    604 	p->p_flag &= ~P_INMEM;
    605 	if (p->p_stat == SRUN)
    606 		remrunqueue(p);
    607 	SCHED_UNLOCK(s);
    608 	p->p_swtime = 0;
    609 	++uvmexp.swapouts;
    610 
    611 	/*
    612 	 * Unwire the to-be-swapped process's user struct and kernel stack.
    613 	 */
    614 	addr = (vaddr_t)p->p_addr;
    615 	uvm_fault_unwire(kernel_map, addr, addr + USPACE); /* !P_INMEM */
    616 	pmap_collect(vm_map_pmap(&p->p_vmspace->vm_map));
    617 }
    618 
    619