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