Home | History | Annotate | Line # | Download | only in uvm
uvm_glue.c revision 1.104.2.5
      1 /*	$NetBSD: uvm_glue.c,v 1.104.2.5 2007/04/10 13:26:56 ad 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 <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: uvm_glue.c,v 1.104.2.5 2007/04/10 13:26:56 ad Exp $");
     71 
     72 #include "opt_coredump.h"
     73 #include "opt_kgdb.h"
     74 #include "opt_kstack.h"
     75 #include "opt_uvmhist.h"
     76 
     77 /*
     78  * uvm_glue.c: glue functions
     79  */
     80 
     81 #include <sys/param.h>
     82 #include <sys/systm.h>
     83 #include <sys/proc.h>
     84 #include <sys/resourcevar.h>
     85 #include <sys/buf.h>
     86 #include <sys/user.h>
     87 
     88 #include <uvm/uvm.h>
     89 
     90 #include <machine/cpu.h>
     91 
     92 /*
     93  * local prototypes
     94  */
     95 
     96 static void uvm_swapout(struct lwp *);
     97 
     98 #define UVM_NUAREA_MAX 16
     99 static vaddr_t uvm_uareas;
    100 static int uvm_nuarea;
    101 kmutex_t uvm_uareas_lock;
    102 #define	UAREA_NEXTFREE(uarea)	(*(vaddr_t *)(UAREA_TO_USER(uarea)))
    103 
    104 void uvm_uarea_free(vaddr_t);
    105 
    106 /*
    107  * XXXCDC: do these really belong here?
    108  */
    109 
    110 /*
    111  * uvm_kernacc: can the kernel access a region of memory
    112  *
    113  * - used only by /dev/kmem driver (mem.c)
    114  */
    115 
    116 bool
    117 uvm_kernacc(void *addr, size_t len, int rw)
    118 {
    119 	bool rv;
    120 	vaddr_t saddr, eaddr;
    121 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
    122 
    123 	saddr = trunc_page((vaddr_t)addr);
    124 	eaddr = round_page((vaddr_t)addr + len);
    125 	vm_map_lock_read(kernel_map);
    126 	rv = uvm_map_checkprot(kernel_map, saddr, eaddr, prot);
    127 	vm_map_unlock_read(kernel_map);
    128 
    129 	return(rv);
    130 }
    131 
    132 #ifdef KGDB
    133 /*
    134  * Change protections on kernel pages from addr to addr+len
    135  * (presumably so debugger can plant a breakpoint).
    136  *
    137  * We force the protection change at the pmap level.  If we were
    138  * to use vm_map_protect a change to allow writing would be lazily-
    139  * applied meaning we would still take a protection fault, something
    140  * we really don't want to do.  It would also fragment the kernel
    141  * map unnecessarily.  We cannot use pmap_protect since it also won't
    142  * enforce a write-enable request.  Using pmap_enter is the only way
    143  * we can ensure the change takes place properly.
    144  */
    145 void
    146 uvm_chgkprot(void *addr, size_t len, int rw)
    147 {
    148 	vm_prot_t prot;
    149 	paddr_t pa;
    150 	vaddr_t sva, eva;
    151 
    152 	prot = rw == B_READ ? VM_PROT_READ : VM_PROT_READ|VM_PROT_WRITE;
    153 	eva = round_page((vaddr_t)addr + len);
    154 	for (sva = trunc_page((vaddr_t)addr); sva < eva; sva += PAGE_SIZE) {
    155 		/*
    156 		 * Extract physical address for the page.
    157 		 */
    158 		if (pmap_extract(pmap_kernel(), sva, &pa) == false)
    159 			panic("chgkprot: invalid page");
    160 		pmap_enter(pmap_kernel(), sva, pa, prot, PMAP_WIRED);
    161 	}
    162 	pmap_update(pmap_kernel());
    163 }
    164 #endif
    165 
    166 /*
    167  * uvm_vslock: wire user memory for I/O
    168  *
    169  * - called from physio and sys___sysctl
    170  * - XXXCDC: consider nuking this (or making it a macro?)
    171  */
    172 
    173 int
    174 uvm_vslock(struct vmspace *vs, void *addr, size_t len, vm_prot_t access_type)
    175 {
    176 	struct vm_map *map;
    177 	vaddr_t start, end;
    178 	int error;
    179 
    180 	map = &vs->vm_map;
    181 	start = trunc_page((vaddr_t)addr);
    182 	end = round_page((vaddr_t)addr + len);
    183 	error = uvm_fault_wire(map, start, end, access_type, 0);
    184 	return error;
    185 }
    186 
    187 /*
    188  * uvm_vsunlock: unwire user memory wired by uvm_vslock()
    189  *
    190  * - called from physio and sys___sysctl
    191  * - XXXCDC: consider nuking this (or making it a macro?)
    192  */
    193 
    194 void
    195 uvm_vsunlock(struct vmspace *vs, void *addr, size_t len)
    196 {
    197 	uvm_fault_unwire(&vs->vm_map, trunc_page((vaddr_t)addr),
    198 		round_page((vaddr_t)addr + len));
    199 }
    200 
    201 /*
    202  * uvm_proc_fork: fork a virtual address space
    203  *
    204  * - the address space is copied as per parent map's inherit values
    205  */
    206 void
    207 uvm_proc_fork(struct proc *p1, struct proc *p2, bool shared)
    208 {
    209 
    210 	if (shared == true) {
    211 		p2->p_vmspace = NULL;
    212 		uvmspace_share(p1, p2);
    213 	} else {
    214 		p2->p_vmspace = uvmspace_fork(p1->p_vmspace);
    215 	}
    216 
    217 	cpu_proc_fork(p1, p2);
    218 }
    219 
    220 
    221 /*
    222  * uvm_lwp_fork: fork a thread
    223  *
    224  * - a new "user" structure is allocated for the child process
    225  *	[filled in by MD layer...]
    226  * - if specified, the child gets a new user stack described by
    227  *	stack and stacksize
    228  * - NOTE: the kernel stack may be at a different location in the child
    229  *	process, and thus addresses of automatic variables may be invalid
    230  *	after cpu_lwp_fork returns in the child process.  We do nothing here
    231  *	after cpu_lwp_fork returns.
    232  * - XXXCDC: we need a way for this to return a failure value rather
    233  *   than just hang
    234  */
    235 void
    236 uvm_lwp_fork(struct lwp *l1, struct lwp *l2, void *stack, size_t stacksize,
    237     void (*func)(void *), void *arg)
    238 {
    239 	int error;
    240 
    241 	/*
    242 	 * Wire down the U-area for the process, which contains the PCB
    243 	 * and the kernel stack.  Wired state is stored in l->l_flag's
    244 	 * L_INMEM bit rather than in the vm_map_entry's wired count
    245 	 * to prevent kernel_map fragmentation.  If we reused a cached U-area,
    246 	 * L_INMEM will already be set and we don't need to do anything.
    247 	 *
    248 	 * Note the kernel stack gets read/write accesses right off the bat.
    249 	 */
    250 
    251 	if ((l2->l_flag & LW_INMEM) == 0) {
    252 		vaddr_t uarea = USER_TO_UAREA(l2->l_addr);
    253 
    254 		error = uvm_fault_wire(kernel_map, uarea,
    255 		    uarea + USPACE, VM_PROT_READ | VM_PROT_WRITE, 0);
    256 		if (error)
    257 			panic("uvm_lwp_fork: uvm_fault_wire failed: %d", error);
    258 #ifdef PMAP_UAREA
    259 		/* Tell the pmap this is a u-area mapping */
    260 		PMAP_UAREA(uarea);
    261 #endif
    262 		l2->l_flag |= LW_INMEM;
    263 	}
    264 
    265 #ifdef KSTACK_CHECK_MAGIC
    266 	/*
    267 	 * fill stack with magic number
    268 	 */
    269 	kstack_setup_magic(l2);
    270 #endif
    271 
    272 	/*
    273 	 * cpu_lwp_fork() copy and update the pcb, and make the child ready
    274  	 * to run.  If this is a normal user fork, the child will exit
    275 	 * directly to user mode via child_return() on its first time
    276 	 * slice and will not return here.  If this is a kernel thread,
    277 	 * the specified entry point will be executed.
    278 	 */
    279 	cpu_lwp_fork(l1, l2, stack, stacksize, func, arg);
    280 }
    281 
    282 /*
    283  * uvm_uarea_alloc: allocate a u-area
    284  */
    285 
    286 bool
    287 uvm_uarea_alloc(vaddr_t *uaddrp)
    288 {
    289 	vaddr_t uaddr;
    290 
    291 #ifndef USPACE_ALIGN
    292 #define USPACE_ALIGN    0
    293 #endif
    294 
    295 	mutex_enter(&uvm_uareas_lock);
    296 	if (uvm_nuarea > 0) {
    297 		uaddr = uvm_uareas;
    298 		uvm_uareas = UAREA_NEXTFREE(uaddr);
    299 		uvm_nuarea--;
    300 		mutex_exit(&uvm_uareas_lock);
    301 		*uaddrp = uaddr;
    302 		return true;
    303 	} else {
    304 		mutex_exit(&uvm_uareas_lock);
    305 		*uaddrp = uvm_km_alloc(kernel_map, USPACE, USPACE_ALIGN,
    306 		    UVM_KMF_PAGEABLE);
    307 		return false;
    308 	}
    309 }
    310 
    311 /*
    312  * uvm_uarea_free: free a u-area; never blocks
    313  */
    314 
    315 void
    316 uvm_uarea_free(vaddr_t uaddr)
    317 {
    318 	mutex_enter(&uvm_uareas_lock);
    319 	UAREA_NEXTFREE(uaddr) = uvm_uareas;
    320 	uvm_uareas = uaddr;
    321 	uvm_nuarea++;
    322 	mutex_exit(&uvm_uareas_lock);
    323 }
    324 
    325 /*
    326  * uvm_uarea_drain: return memory of u-areas over limit
    327  * back to system
    328  */
    329 
    330 void
    331 uvm_uarea_drain(bool empty)
    332 {
    333 	int leave = empty ? 0 : UVM_NUAREA_MAX;
    334 	vaddr_t uaddr;
    335 
    336 	if (uvm_nuarea <= leave)
    337 		return;
    338 
    339 	mutex_enter(&uvm_uareas_lock);
    340 	while(uvm_nuarea > leave) {
    341 		uaddr = uvm_uareas;
    342 		uvm_uareas = UAREA_NEXTFREE(uaddr);
    343 		uvm_nuarea--;
    344 		mutex_exit(&uvm_uareas_lock);
    345 		uvm_km_free(kernel_map, uaddr, USPACE, UVM_KMF_PAGEABLE);
    346 		mutex_enter(&uvm_uareas_lock);
    347 	}
    348 	mutex_exit(&uvm_uareas_lock);
    349 }
    350 
    351 /*
    352  * uvm_exit: exit a virtual address space
    353  *
    354  * - the process passed to us is a dead (pre-zombie) process; we
    355  *   are running on a different context now (the reaper).
    356  * - borrow proc0's address space because freeing the vmspace
    357  *   of the dead process may block.
    358  */
    359 
    360 void
    361 uvm_proc_exit(struct proc *p)
    362 {
    363 	struct lwp *l = curlwp; /* XXX */
    364 	struct vmspace *ovm;
    365 
    366 	KASSERT(p == l->l_proc);
    367 	ovm = p->p_vmspace;
    368 
    369 	/*
    370 	 * borrow proc0's address space.
    371 	 */
    372 	pmap_deactivate(l);
    373 	p->p_vmspace = proc0.p_vmspace;
    374 	pmap_activate(l);
    375 
    376 	uvmspace_free(ovm);
    377 }
    378 
    379 void
    380 uvm_lwp_exit(struct lwp *l)
    381 {
    382 	vaddr_t va = USER_TO_UAREA(l->l_addr);
    383 
    384 	l->l_flag &= ~LW_INMEM;
    385 	uvm_uarea_free(va);
    386 	l->l_addr = NULL;
    387 }
    388 
    389 /*
    390  * uvm_init_limit: init per-process VM limits
    391  *
    392  * - called for process 0 and then inherited by all others.
    393  */
    394 
    395 void
    396 uvm_init_limits(struct proc *p)
    397 {
    398 
    399 	/*
    400 	 * Set up the initial limits on process VM.  Set the maximum
    401 	 * resident set size to be all of (reasonably) available memory.
    402 	 * This causes any single, large process to start random page
    403 	 * replacement once it fills memory.
    404 	 */
    405 
    406 	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
    407 	p->p_rlimit[RLIMIT_STACK].rlim_max = maxsmap;
    408 	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
    409 	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdmap;
    410 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(uvmexp.free);
    411 }
    412 
    413 #ifdef DEBUG
    414 int	enableswap = 1;
    415 int	swapdebug = 0;
    416 #define	SDB_FOLLOW	1
    417 #define SDB_SWAPIN	2
    418 #define SDB_SWAPOUT	4
    419 #endif
    420 
    421 /*
    422  * uvm_swapin: swap in an lwp's u-area.
    423  *
    424  * - must be called with the LWP's swap lock held.
    425  * - naturally, must not be called with l == curlwp
    426  */
    427 
    428 void
    429 uvm_swapin(struct lwp *l)
    430 {
    431 	vaddr_t addr;
    432 	int error;
    433 
    434 	KASSERT(mutex_owned(&l->l_swaplock));
    435 	KASSERT(l != curlwp);
    436 
    437 	addr = USER_TO_UAREA(l->l_addr);
    438 	/* make L_INMEM true */
    439 	error = uvm_fault_wire(kernel_map, addr, addr + USPACE,
    440 	    VM_PROT_READ | VM_PROT_WRITE, 0);
    441 	if (error) {
    442 		panic("uvm_swapin: rewiring stack failed: %d", error);
    443 	}
    444 
    445 	/*
    446 	 * Some architectures need to be notified when the user area has
    447 	 * moved to new physical page(s) (e.g.  see mips/mips/vm_machdep.c).
    448 	 */
    449 	cpu_swapin(l);
    450 	lwp_lock(l);
    451 	if (l->l_stat == LSRUN)
    452 		setrunqueue(l);
    453 	l->l_flag |= LW_INMEM;
    454 	l->l_swtime = 0;
    455 	lwp_unlock(l);
    456 	++uvmexp.swapins;
    457 }
    458 
    459 /*
    460  * uvm_kick_scheduler: kick the scheduler into action if not running.
    461  *
    462  * - called when swapped out processes have been awoken.
    463  */
    464 
    465 void
    466 uvm_kick_scheduler(void)
    467 {
    468 
    469 	if (uvm.swap_running == false)
    470 		return;
    471 
    472 	mutex_enter(&uvm_scheduler_mutex);
    473 	uvm.scheduler_kicked = true;
    474 	cv_signal(&uvm.scheduler_cv);
    475 	mutex_exit(&uvm_scheduler_mutex);
    476 }
    477 
    478 /*
    479  * uvm_scheduler: process zero main loop
    480  *
    481  * - attempt to swapin every swaped-out, runnable process in order of
    482  *	priority.
    483  * - if not enough memory, wake the pagedaemon and let it clear space.
    484  */
    485 
    486 void
    487 uvm_scheduler(void)
    488 {
    489 	struct lwp *l, *ll;
    490 	int pri;
    491 	int ppri;
    492 
    493 	l = curlwp;
    494 	lwp_lock(l);
    495 	l->l_priority = PVM;
    496 	l->l_usrpri = PVM;
    497 	lwp_unlock(l);
    498 
    499 	KERNEL_UNLOCK_LAST(l);	/* XXX */
    500 
    501 	for (;;) {
    502 #ifdef DEBUG
    503 		mutex_enter(&uvm_scheduler_mutex);
    504 		while (!enableswap)
    505 			cv_wait(&uvm.scheduler_cv, &uvm_scheduler_mutex);
    506 		mutex_exit(&uvm_scheduler_mutex);
    507 #endif
    508 		ll = NULL;		/* process to choose */
    509 		ppri = INT_MIN;		/* its priority */
    510 
    511 		mutex_enter(&proclist_lock);
    512 		LIST_FOREACH(l, &alllwp, l_list) {
    513 			/* is it a runnable swapped out process? */
    514 			if (l->l_stat == LSRUN && !(l->l_flag & LW_INMEM)) {
    515 				pri = l->l_swtime + l->l_slptime -
    516 				    (l->l_proc->p_nice - NZERO) * 8;
    517 				if (pri > ppri) {   /* higher priority? */
    518 					ll = l;
    519 					ppri = pri;
    520 				}
    521 			}
    522 		}
    523 #ifdef DEBUG
    524 		if (swapdebug & SDB_FOLLOW)
    525 			printf("scheduler: running, procp %p pri %d\n", ll,
    526 			    ppri);
    527 #endif
    528 		/*
    529 		 * Nothing to do, back to sleep
    530 		 */
    531 		if ((l = ll) == NULL) {
    532 			mutex_exit(&proclist_lock);
    533 			mutex_enter(&uvm_scheduler_mutex);
    534 			if (uvm.scheduler_kicked == false)
    535 				cv_wait(&uvm.scheduler_cv,
    536 				    &uvm_scheduler_mutex);
    537 			uvm.scheduler_kicked = false;
    538 			mutex_exit(&uvm_scheduler_mutex);
    539 			continue;
    540 		}
    541 
    542 		/*
    543 		 * we have found swapped out process which we would like
    544 		 * to bring back in.
    545 		 *
    546 		 * XXX: this part is really bogus cuz we could deadlock
    547 		 * on memory despite our feeble check
    548 		 */
    549 		if (uvmexp.free > atop(USPACE)) {
    550 #ifdef DEBUG
    551 			if (swapdebug & SDB_SWAPIN)
    552 				printf("swapin: pid %d(%s)@%p, pri %d "
    553 				    "free %d\n", l->l_proc->p_pid,
    554 				    l->l_proc->p_comm, l->l_addr, ppri,
    555 				    uvmexp.free);
    556 #endif
    557 			mutex_enter(&l->l_swaplock);
    558 			mutex_exit(&proclist_lock);
    559 			uvm_swapin(l);
    560 			mutex_exit(&l->l_swaplock);
    561 			continue;
    562 		} else {
    563 			/*
    564 			 * not enough memory, jab the pageout daemon and
    565 			 * wait til the coast is clear
    566 			 */
    567 			mutex_exit(&proclist_lock);
    568 #ifdef DEBUG
    569 			if (swapdebug & SDB_FOLLOW)
    570 				printf("scheduler: no room for pid %d(%s),"
    571 				    " free %d\n", l->l_proc->p_pid,
    572 				    l->l_proc->p_comm, uvmexp.free);
    573 #endif
    574 			uvm_wait("schedpwait");
    575 #ifdef DEBUG
    576 			if (swapdebug & SDB_FOLLOW)
    577 				printf("scheduler: room again, free %d\n",
    578 				    uvmexp.free);
    579 #endif
    580 		}
    581 	}
    582 }
    583 
    584 /*
    585  * swappable: is LWP "l" swappable?
    586  */
    587 
    588 #define	swappable(l)							\
    589 	(((l)->l_flag & (LW_INMEM | LW_SYSTEM)) == LW_INMEM &&		\
    590 	 (l)->l_holdcnt == 0 &&	(l)->l_cpu->ci_curlwp != (l))
    591 
    592 /*
    593  * swapout_threads: find threads that can be swapped and unwire their
    594  *	u-areas.
    595  *
    596  * - called by the pagedaemon
    597  * - try and swap at least one processs
    598  * - processes that are sleeping or stopped for maxslp or more seconds
    599  *   are swapped... otherwise the longest-sleeping or stopped process
    600  *   is swapped, otherwise the longest resident process...
    601  */
    602 
    603 void
    604 uvm_swapout_threads(void)
    605 {
    606 	struct lwp *l;
    607 	struct lwp *outl, *outl2;
    608 	int outpri, outpri2;
    609 	int didswap = 0;
    610 	extern int maxslp;
    611 	bool gotit;
    612 
    613 	/* XXXCDC: should move off to uvmexp. or uvm., also in uvm_meter */
    614 
    615 #ifdef DEBUG
    616 	if (!enableswap)
    617 		return;
    618 #endif
    619 
    620 	/*
    621 	 * outl/outpri  : stop/sleep thread with largest sleeptime < maxslp
    622 	 * outl2/outpri2: the longest resident thread (its swap time)
    623 	 */
    624 	outl = outl2 = NULL;
    625 	outpri = outpri2 = 0;
    626 
    627  restart:
    628 	mutex_enter(&proclist_lock);
    629 	LIST_FOREACH(l, &alllwp, l_list) {
    630 		KASSERT(l->l_proc != NULL);
    631 		if (!mutex_tryenter(&l->l_swaplock))
    632 			continue;
    633 		if (!swappable(l)) {
    634 			mutex_exit(&l->l_swaplock);
    635 			continue;
    636 		}
    637 		switch (l->l_stat) {
    638 		case LSONPROC:
    639 			break;
    640 
    641 		case LSRUN:
    642 			if (l->l_swtime > outpri2) {
    643 				outl2 = l;
    644 				outpri2 = l->l_swtime;
    645 			}
    646 			break;
    647 
    648 		case LSSLEEP:
    649 		case LSSTOP:
    650 			if (l->l_slptime >= maxslp) {
    651 				mutex_exit(&proclist_lock);
    652 				uvm_swapout(l);
    653 				/*
    654 				 * Locking in the wrong direction -
    655 				 * try to prevent the LWP from exiting.
    656 				 */
    657 				gotit = mutex_tryenter(&proclist_lock);
    658 				mutex_exit(&l->l_swaplock);
    659 				didswap++;
    660 				if (!gotit)
    661 					goto restart;
    662 				continue;
    663 			} else if (l->l_slptime > outpri) {
    664 				outl = l;
    665 				outpri = l->l_slptime;
    666 			}
    667 			break;
    668 		}
    669 		mutex_exit(&l->l_swaplock);
    670 	}
    671 
    672 	/*
    673 	 * If we didn't get rid of any real duds, toss out the next most
    674 	 * likely sleeping/stopped or running candidate.  We only do this
    675 	 * if we are real low on memory since we don't gain much by doing
    676 	 * it (USPACE bytes).
    677 	 */
    678 	if (didswap == 0 && uvmexp.free <= atop(round_page(USPACE))) {
    679 		if ((l = outl) == NULL)
    680 			l = outl2;
    681 #ifdef DEBUG
    682 		if (swapdebug & SDB_SWAPOUT)
    683 			printf("swapout_threads: no duds, try procp %p\n", l);
    684 #endif
    685 		if (l) {
    686 			mutex_enter(&l->l_swaplock);
    687 			mutex_exit(&proclist_lock);
    688 			if (swappable(l))
    689 				uvm_swapout(l);
    690 			mutex_exit(&l->l_swaplock);
    691 			return;
    692 		}
    693 	}
    694 
    695 	mutex_exit(&proclist_lock);
    696 }
    697 
    698 /*
    699  * uvm_swapout: swap out lwp "l"
    700  *
    701  * - currently "swapout" means "unwire U-area" and "pmap_collect()"
    702  *   the pmap.
    703  * - must be called with l->l_swaplock held.
    704  * - XXXCDC: should deactivate all process' private anonymous memory
    705  */
    706 
    707 static void
    708 uvm_swapout(struct lwp *l)
    709 {
    710 	vaddr_t addr;
    711 	struct proc *p = l->l_proc;
    712 
    713 	KASSERT(mutex_owned(&l->l_swaplock));
    714 
    715 #ifdef DEBUG
    716 	if (swapdebug & SDB_SWAPOUT)
    717 		printf("swapout: lid %d.%d(%s)@%p, stat %x pri %d free %d\n",
    718 	   p->p_pid, l->l_lid, p->p_comm, l->l_addr, l->l_stat,
    719 	   l->l_slptime, uvmexp.free);
    720 #endif
    721 
    722 	/*
    723 	 * Mark it as (potentially) swapped out.
    724 	 */
    725 	lwp_lock(l);
    726 	if (!swappable(l)) {
    727 		KDASSERT(l->l_cpu != curcpu());
    728 		lwp_unlock(l);
    729 		return;
    730 	}
    731 	l->l_flag &= ~LW_INMEM;
    732 	l->l_swtime = 0;
    733 	if (l->l_stat == LSRUN)
    734 		remrunqueue(l);
    735 	lwp_unlock(l);
    736 	p->p_stats->p_ru.ru_nswap++;	/* XXXSMP */
    737 	++uvmexp.swapouts;
    738 
    739 	/*
    740 	 * Do any machine-specific actions necessary before swapout.
    741 	 * This can include saving floating point state, etc.
    742 	 */
    743 	cpu_swapout(l);
    744 
    745 	/*
    746 	 * Unwire the to-be-swapped process's user struct and kernel stack.
    747 	 */
    748 	addr = USER_TO_UAREA(l->l_addr);
    749 	uvm_fault_unwire(kernel_map, addr, addr + USPACE); /* !L_INMEM */
    750 	pmap_collect(vm_map_pmap(&p->p_vmspace->vm_map));
    751 }
    752 
    753 /*
    754  * uvm_lwp_hold: prevent lwp "l" from being swapped out, and bring
    755  * back into memory if it is currently swapped.
    756  */
    757 
    758 void
    759 uvm_lwp_hold(struct lwp *l)
    760 {
    761 
    762 	mutex_enter(&l->l_swaplock);
    763 	if (l->l_holdcnt++ == 0 && (l->l_flag & LW_INMEM) == 0)
    764 		uvm_swapin(l);
    765 	mutex_exit(&l->l_swaplock);
    766 }
    767 
    768 /*
    769  * uvm_lwp_rele: release a hold on lwp "l".  when the holdcount
    770  * drops to zero, it's eligable to be swapped.
    771  */
    772 
    773 void
    774 uvm_lwp_rele(struct lwp *l)
    775 {
    776 
    777 	KASSERT(l->l_holdcnt != 0);
    778 
    779 	mutex_enter(&l->l_swaplock);
    780 	l->l_holdcnt--;
    781 	mutex_exit(&l->l_swaplock);
    782 }
    783 
    784 #ifdef COREDUMP
    785 /*
    786  * uvm_coredump_walkmap: walk a process's map for the purpose of dumping
    787  * a core file.
    788  */
    789 
    790 int
    791 uvm_coredump_walkmap(struct proc *p, void *iocookie,
    792     int (*func)(struct proc *, void *, struct uvm_coredump_state *),
    793     void *cookie)
    794 {
    795 	struct uvm_coredump_state state;
    796 	struct vmspace *vm = p->p_vmspace;
    797 	struct vm_map *map = &vm->vm_map;
    798 	struct vm_map_entry *entry;
    799 	int error;
    800 
    801 	entry = NULL;
    802 	vm_map_lock_read(map);
    803 	state.end = 0;
    804 	for (;;) {
    805 		if (entry == NULL)
    806 			entry = map->header.next;
    807 		else if (!uvm_map_lookup_entry(map, state.end, &entry))
    808 			entry = entry->next;
    809 		if (entry == &map->header)
    810 			break;
    811 
    812 		state.cookie = cookie;
    813 		if (state.end > entry->start) {
    814 			state.start = state.end;
    815 		} else {
    816 			state.start = entry->start;
    817 		}
    818 		state.realend = entry->end;
    819 		state.end = entry->end;
    820 		state.prot = entry->protection;
    821 		state.flags = 0;
    822 
    823 		/*
    824 		 * Dump the region unless one of the following is true:
    825 		 *
    826 		 * (1) the region has neither object nor amap behind it
    827 		 *     (ie. it has never been accessed).
    828 		 *
    829 		 * (2) the region has no amap and is read-only
    830 		 *     (eg. an executable text section).
    831 		 *
    832 		 * (3) the region's object is a device.
    833 		 *
    834 		 * (4) the region is unreadable by the process.
    835 		 */
    836 
    837 		KASSERT(!UVM_ET_ISSUBMAP(entry));
    838 		KASSERT(state.start < VM_MAXUSER_ADDRESS);
    839 		KASSERT(state.end <= VM_MAXUSER_ADDRESS);
    840 		if (entry->object.uvm_obj == NULL &&
    841 		    entry->aref.ar_amap == NULL) {
    842 			state.realend = state.start;
    843 		} else if ((entry->protection & VM_PROT_WRITE) == 0 &&
    844 		    entry->aref.ar_amap == NULL) {
    845 			state.realend = state.start;
    846 		} else if (entry->object.uvm_obj != NULL &&
    847 		    UVM_OBJ_IS_DEVICE(entry->object.uvm_obj)) {
    848 			state.realend = state.start;
    849 		} else if ((entry->protection & VM_PROT_READ) == 0) {
    850 			state.realend = state.start;
    851 		} else {
    852 			if (state.start >= (vaddr_t)vm->vm_maxsaddr)
    853 				state.flags |= UVM_COREDUMP_STACK;
    854 
    855 			/*
    856 			 * If this an anonymous entry, only dump instantiated
    857 			 * pages.
    858 			 */
    859 			if (entry->object.uvm_obj == NULL) {
    860 				vaddr_t end;
    861 
    862 				amap_lock(entry->aref.ar_amap);
    863 				for (end = state.start;
    864 				     end < state.end; end += PAGE_SIZE) {
    865 					struct vm_anon *anon;
    866 					anon = amap_lookup(&entry->aref,
    867 					    end - entry->start);
    868 					/*
    869 					 * If we have already encountered an
    870 					 * uninstantiated page, stop at the
    871 					 * first instantied page.
    872 					 */
    873 					if (anon != NULL &&
    874 					    state.realend != state.end) {
    875 						state.end = end;
    876 						break;
    877 					}
    878 
    879 					/*
    880 					 * If this page is the first
    881 					 * uninstantiated page, mark this as
    882 					 * the real ending point.  Continue to
    883 					 * counting uninstantiated pages.
    884 					 */
    885 					if (anon == NULL &&
    886 					    state.realend == state.end) {
    887 						state.realend = end;
    888 					}
    889 				}
    890 				amap_unlock(entry->aref.ar_amap);
    891 			}
    892 		}
    893 
    894 
    895 		vm_map_unlock_read(map);
    896 		error = (*func)(p, iocookie, &state);
    897 		if (error)
    898 			return (error);
    899 		vm_map_lock_read(map);
    900 	}
    901 	vm_map_unlock_read(map);
    902 
    903 	return (0);
    904 }
    905 #endif /* COREDUMP */
    906