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