Home | History | Annotate | Line # | Download | only in uvm
uvm_glue.c revision 1.117
      1 /*	$NetBSD: uvm_glue.c,v 1.117 2008/02/08 11:49:40 yamt 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.117 2008/02/08 11:49:40 yamt 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 }
    289 
    290 static int
    291 uarea_swapin(vaddr_t addr)
    292 {
    293 
    294 	return uvm_fault_wire(kernel_map, addr, addr + USPACE,
    295 	    VM_PROT_READ | VM_PROT_WRITE, 0);
    296 }
    297 
    298 static void
    299 uarea_swapout(vaddr_t addr)
    300 {
    301 
    302 	uvm_fault_unwire(kernel_map, addr, addr + USPACE);
    303 }
    304 
    305 #ifndef USPACE_ALIGN
    306 #define	USPACE_ALIGN	0
    307 #endif
    308 
    309 static pool_cache_t uvm_uarea_cache;
    310 
    311 static int
    312 uarea_ctor(void *arg, void *obj, int flags)
    313 {
    314 
    315 	KASSERT((flags & PR_WAITOK) != 0);
    316 	return uarea_swapin((vaddr_t)obj);
    317 }
    318 
    319 static void *
    320 uarea_poolpage_alloc(struct pool *pp, int flags)
    321 {
    322 
    323 	return (void *)uvm_km_alloc(kernel_map, pp->pr_alloc->pa_pagesz,
    324 	    USPACE_ALIGN, UVM_KMF_PAGEABLE |
    325 	    ((flags & PR_WAITOK) != 0 ? UVM_KMF_WAITVA :
    326 	    (UVM_KMF_NOWAIT | UVM_KMF_TRYLOCK)));
    327 }
    328 
    329 static void
    330 uarea_poolpage_free(struct pool *pp, void *addr)
    331 {
    332 
    333 	uvm_km_free(kernel_map, (vaddr_t)addr, pp->pr_alloc->pa_pagesz,
    334 	    UVM_KMF_PAGEABLE);
    335 }
    336 
    337 static struct pool_allocator uvm_uarea_allocator = {
    338 	.pa_alloc = uarea_poolpage_alloc,
    339 	.pa_free = uarea_poolpage_free,
    340 	.pa_pagesz = USPACE,
    341 };
    342 
    343 void
    344 uvm_uarea_init(void)
    345 {
    346 	int flags = PR_NOTOUCH;
    347 
    348 	/*
    349 	 * specify PR_NOALIGN unless the alignment provided by
    350 	 * the backend (USPACE_ALIGN) is sufficient to provide
    351 	 * pool page size (UPSACE) alignment.
    352 	 */
    353 
    354 	if ((USPACE_ALIGN == 0 && USPACE != PAGE_SIZE) ||
    355 	    (USPACE_ALIGN % USPACE) != 0) {
    356 		flags |= PR_NOALIGN;
    357 	}
    358 
    359 	uvm_uarea_cache = pool_cache_init(USPACE, USPACE_ALIGN, 0, flags,
    360 	    "uarea", &uvm_uarea_allocator, IPL_NONE, uarea_ctor, NULL, NULL);
    361 }
    362 
    363 /*
    364  * uvm_uarea_alloc: allocate a u-area
    365  */
    366 
    367 bool
    368 uvm_uarea_alloc(vaddr_t *uaddrp)
    369 {
    370 
    371 	*uaddrp = (vaddr_t)pool_cache_get(uvm_uarea_cache, PR_WAITOK);
    372 	return true;
    373 }
    374 
    375 /*
    376  * uvm_uarea_free: free a u-area
    377  */
    378 
    379 void
    380 uvm_uarea_free(vaddr_t uaddr, struct cpu_info *ci)
    381 {
    382 
    383 	pool_cache_put(uvm_uarea_cache, (void *)uaddr);
    384 }
    385 
    386 /*
    387  * uvm_exit: exit a virtual address space
    388  *
    389  * - the process passed to us is a dead (pre-zombie) process; we
    390  *   are running on a different context now (the reaper).
    391  * - borrow proc0's address space because freeing the vmspace
    392  *   of the dead process may block.
    393  */
    394 
    395 void
    396 uvm_proc_exit(struct proc *p)
    397 {
    398 	struct lwp *l = curlwp; /* XXX */
    399 	struct vmspace *ovm;
    400 
    401 	KASSERT(p == l->l_proc);
    402 	ovm = p->p_vmspace;
    403 
    404 	/*
    405 	 * borrow proc0's address space.
    406 	 */
    407 	pmap_deactivate(l);
    408 	p->p_vmspace = proc0.p_vmspace;
    409 	pmap_activate(l);
    410 
    411 	uvmspace_free(ovm);
    412 }
    413 
    414 void
    415 uvm_lwp_exit(struct lwp *l)
    416 {
    417 	vaddr_t va = USER_TO_UAREA(l->l_addr);
    418 
    419 	l->l_flag &= ~LW_INMEM;
    420 	uvm_uarea_free(va, l->l_cpu);
    421 	l->l_addr = NULL;
    422 }
    423 
    424 /*
    425  * uvm_init_limit: init per-process VM limits
    426  *
    427  * - called for process 0 and then inherited by all others.
    428  */
    429 
    430 void
    431 uvm_init_limits(struct proc *p)
    432 {
    433 
    434 	/*
    435 	 * Set up the initial limits on process VM.  Set the maximum
    436 	 * resident set size to be all of (reasonably) available memory.
    437 	 * This causes any single, large process to start random page
    438 	 * replacement once it fills memory.
    439 	 */
    440 
    441 	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
    442 	p->p_rlimit[RLIMIT_STACK].rlim_max = maxsmap;
    443 	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
    444 	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdmap;
    445 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(uvmexp.free);
    446 }
    447 
    448 #ifdef DEBUG
    449 int	enableswap = 1;
    450 int	swapdebug = 0;
    451 #define	SDB_FOLLOW	1
    452 #define SDB_SWAPIN	2
    453 #define SDB_SWAPOUT	4
    454 #endif
    455 
    456 /*
    457  * uvm_swapin: swap in an lwp's u-area.
    458  *
    459  * - must be called with the LWP's swap lock held.
    460  * - naturally, must not be called with l == curlwp
    461  */
    462 
    463 void
    464 uvm_swapin(struct lwp *l)
    465 {
    466 	int error;
    467 
    468 	/* XXXSMP notyet KASSERT(mutex_owned(&l->l_swaplock)); */
    469 	KASSERT(l != curlwp);
    470 
    471 	error = uarea_swapin(USER_TO_UAREA(l->l_addr));
    472 	if (error) {
    473 		panic("uvm_swapin: rewiring stack failed: %d", error);
    474 	}
    475 
    476 	/*
    477 	 * Some architectures need to be notified when the user area has
    478 	 * moved to new physical page(s) (e.g.  see mips/mips/vm_machdep.c).
    479 	 */
    480 	cpu_swapin(l);
    481 	lwp_lock(l);
    482 	if (l->l_stat == LSRUN)
    483 		sched_enqueue(l, false);
    484 	l->l_flag |= LW_INMEM;
    485 	l->l_swtime = 0;
    486 	lwp_unlock(l);
    487 	++uvmexp.swapins;
    488 }
    489 
    490 /*
    491  * uvm_kick_scheduler: kick the scheduler into action if not running.
    492  *
    493  * - called when swapped out processes have been awoken.
    494  */
    495 
    496 void
    497 uvm_kick_scheduler(void)
    498 {
    499 
    500 	if (uvm.swap_running == false)
    501 		return;
    502 
    503 	mutex_enter(&uvm_scheduler_mutex);
    504 	uvm.scheduler_kicked = true;
    505 	cv_signal(&uvm.scheduler_cv);
    506 	mutex_exit(&uvm_scheduler_mutex);
    507 }
    508 
    509 /*
    510  * uvm_scheduler: process zero main loop
    511  *
    512  * - attempt to swapin every swaped-out, runnable process in order of
    513  *	priority.
    514  * - if not enough memory, wake the pagedaemon and let it clear space.
    515  */
    516 
    517 void
    518 uvm_scheduler(void)
    519 {
    520 	struct lwp *l, *ll;
    521 	int pri;
    522 	int ppri;
    523 
    524 	l = curlwp;
    525 	lwp_lock(l);
    526 	l->l_priority = PRI_VM;
    527 	l->l_class = SCHED_FIFO;
    528 	lwp_unlock(l);
    529 
    530 	for (;;) {
    531 #ifdef DEBUG
    532 		mutex_enter(&uvm_scheduler_mutex);
    533 		while (!enableswap)
    534 			cv_wait(&uvm.scheduler_cv, &uvm_scheduler_mutex);
    535 		mutex_exit(&uvm_scheduler_mutex);
    536 #endif
    537 		ll = NULL;		/* process to choose */
    538 		ppri = INT_MIN;		/* its priority */
    539 
    540 		mutex_enter(&proclist_lock);
    541 		LIST_FOREACH(l, &alllwp, l_list) {
    542 			/* is it a runnable swapped out process? */
    543 			if (l->l_stat == LSRUN && !(l->l_flag & LW_INMEM)) {
    544 				pri = l->l_swtime + l->l_slptime -
    545 				    (l->l_proc->p_nice - NZERO) * 8;
    546 				if (pri > ppri) {   /* higher priority? */
    547 					ll = l;
    548 					ppri = pri;
    549 				}
    550 			}
    551 		}
    552 #ifdef DEBUG
    553 		if (swapdebug & SDB_FOLLOW)
    554 			printf("scheduler: running, procp %p pri %d\n", ll,
    555 			    ppri);
    556 #endif
    557 		/*
    558 		 * Nothing to do, back to sleep
    559 		 */
    560 		if ((l = ll) == NULL) {
    561 			mutex_exit(&proclist_lock);
    562 			mutex_enter(&uvm_scheduler_mutex);
    563 			if (uvm.scheduler_kicked == false)
    564 				cv_wait(&uvm.scheduler_cv,
    565 				    &uvm_scheduler_mutex);
    566 			uvm.scheduler_kicked = false;
    567 			mutex_exit(&uvm_scheduler_mutex);
    568 			continue;
    569 		}
    570 
    571 		/*
    572 		 * we have found swapped out process which we would like
    573 		 * to bring back in.
    574 		 *
    575 		 * XXX: this part is really bogus cuz we could deadlock
    576 		 * on memory despite our feeble check
    577 		 */
    578 		if (uvmexp.free > atop(USPACE)) {
    579 #ifdef DEBUG
    580 			if (swapdebug & SDB_SWAPIN)
    581 				printf("swapin: pid %d(%s)@%p, pri %d "
    582 				    "free %d\n", l->l_proc->p_pid,
    583 				    l->l_proc->p_comm, l->l_addr, ppri,
    584 				    uvmexp.free);
    585 #endif
    586 			mutex_enter(&l->l_swaplock);
    587 			mutex_exit(&proclist_lock);
    588 			uvm_swapin(l);
    589 			mutex_exit(&l->l_swaplock);
    590 			continue;
    591 		} else {
    592 			/*
    593 			 * not enough memory, jab the pageout daemon and
    594 			 * wait til the coast is clear
    595 			 */
    596 			mutex_exit(&proclist_lock);
    597 #ifdef DEBUG
    598 			if (swapdebug & SDB_FOLLOW)
    599 				printf("scheduler: no room for pid %d(%s),"
    600 				    " free %d\n", l->l_proc->p_pid,
    601 				    l->l_proc->p_comm, uvmexp.free);
    602 #endif
    603 			uvm_wait("schedpwait");
    604 #ifdef DEBUG
    605 			if (swapdebug & SDB_FOLLOW)
    606 				printf("scheduler: room again, free %d\n",
    607 				    uvmexp.free);
    608 #endif
    609 		}
    610 	}
    611 }
    612 
    613 /*
    614  * swappable: is LWP "l" swappable?
    615  */
    616 
    617 static bool
    618 swappable(struct lwp *l)
    619 {
    620 
    621 	if ((l->l_flag & (LW_INMEM|LW_RUNNING|LW_SYSTEM|LW_WEXIT)) != LW_INMEM)
    622 		return false;
    623 	if (l->l_holdcnt != 0)
    624 		return false;
    625 	if (l->l_syncobj == &rw_syncobj || l->l_syncobj == &mutex_syncobj)
    626 		return false;
    627 	return true;
    628 }
    629 
    630 /*
    631  * swapout_threads: find threads that can be swapped and unwire their
    632  *	u-areas.
    633  *
    634  * - called by the pagedaemon
    635  * - try and swap at least one processs
    636  * - processes that are sleeping or stopped for maxslp or more seconds
    637  *   are swapped... otherwise the longest-sleeping or stopped process
    638  *   is swapped, otherwise the longest resident process...
    639  */
    640 
    641 void
    642 uvm_swapout_threads(void)
    643 {
    644 	struct lwp *l;
    645 	struct lwp *outl, *outl2;
    646 	int outpri, outpri2;
    647 	int didswap = 0;
    648 	extern int maxslp;
    649 	bool gotit;
    650 
    651 	/* XXXCDC: should move off to uvmexp. or uvm., also in uvm_meter */
    652 
    653 #ifdef DEBUG
    654 	if (!enableswap)
    655 		return;
    656 #endif
    657 
    658 	/*
    659 	 * outl/outpri  : stop/sleep thread with largest sleeptime < maxslp
    660 	 * outl2/outpri2: the longest resident thread (its swap time)
    661 	 */
    662 	outl = outl2 = NULL;
    663 	outpri = outpri2 = 0;
    664 
    665  restart:
    666 	mutex_enter(&proclist_lock);
    667 	LIST_FOREACH(l, &alllwp, l_list) {
    668 		KASSERT(l->l_proc != NULL);
    669 		if (!mutex_tryenter(&l->l_swaplock))
    670 			continue;
    671 		if (!swappable(l)) {
    672 			mutex_exit(&l->l_swaplock);
    673 			continue;
    674 		}
    675 		switch (l->l_stat) {
    676 		case LSONPROC:
    677 			break;
    678 
    679 		case LSRUN:
    680 			if (l->l_swtime > outpri2) {
    681 				outl2 = l;
    682 				outpri2 = l->l_swtime;
    683 			}
    684 			break;
    685 
    686 		case LSSLEEP:
    687 		case LSSTOP:
    688 			if (l->l_slptime >= maxslp) {
    689 				mutex_exit(&proclist_lock);
    690 				uvm_swapout(l);
    691 				/*
    692 				 * Locking in the wrong direction -
    693 				 * try to prevent the LWP from exiting.
    694 				 */
    695 				gotit = mutex_tryenter(&proclist_lock);
    696 				mutex_exit(&l->l_swaplock);
    697 				didswap++;
    698 				if (!gotit)
    699 					goto restart;
    700 				continue;
    701 			} else if (l->l_slptime > outpri) {
    702 				outl = l;
    703 				outpri = l->l_slptime;
    704 			}
    705 			break;
    706 		}
    707 		mutex_exit(&l->l_swaplock);
    708 	}
    709 
    710 	/*
    711 	 * If we didn't get rid of any real duds, toss out the next most
    712 	 * likely sleeping/stopped or running candidate.  We only do this
    713 	 * if we are real low on memory since we don't gain much by doing
    714 	 * it (USPACE bytes).
    715 	 */
    716 	if (didswap == 0 && uvmexp.free <= atop(round_page(USPACE))) {
    717 		if ((l = outl) == NULL)
    718 			l = outl2;
    719 #ifdef DEBUG
    720 		if (swapdebug & SDB_SWAPOUT)
    721 			printf("swapout_threads: no duds, try procp %p\n", l);
    722 #endif
    723 		if (l) {
    724 			mutex_enter(&l->l_swaplock);
    725 			mutex_exit(&proclist_lock);
    726 			if (swappable(l))
    727 				uvm_swapout(l);
    728 			mutex_exit(&l->l_swaplock);
    729 			return;
    730 		}
    731 	}
    732 
    733 	mutex_exit(&proclist_lock);
    734 }
    735 
    736 /*
    737  * uvm_swapout: swap out lwp "l"
    738  *
    739  * - currently "swapout" means "unwire U-area" and "pmap_collect()"
    740  *   the pmap.
    741  * - must be called with l->l_swaplock held.
    742  * - XXXCDC: should deactivate all process' private anonymous memory
    743  */
    744 
    745 static void
    746 uvm_swapout(struct lwp *l)
    747 {
    748 	struct proc *p = l->l_proc;
    749 
    750 	KASSERT(mutex_owned(&l->l_swaplock));
    751 
    752 #ifdef DEBUG
    753 	if (swapdebug & SDB_SWAPOUT)
    754 		printf("swapout: lid %d.%d(%s)@%p, stat %x pri %d free %d\n",
    755 	   p->p_pid, l->l_lid, p->p_comm, l->l_addr, l->l_stat,
    756 	   l->l_slptime, uvmexp.free);
    757 #endif
    758 
    759 	/*
    760 	 * Mark it as (potentially) swapped out.
    761 	 */
    762 	lwp_lock(l);
    763 	if (!swappable(l)) {
    764 		KDASSERT(l->l_cpu != curcpu());
    765 		lwp_unlock(l);
    766 		return;
    767 	}
    768 	l->l_flag &= ~LW_INMEM;
    769 	l->l_swtime = 0;
    770 	if (l->l_stat == LSRUN)
    771 		sched_dequeue(l);
    772 	lwp_unlock(l);
    773 	p->p_stats->p_ru.ru_nswap++;	/* XXXSMP */
    774 	++uvmexp.swapouts;
    775 
    776 	/*
    777 	 * Do any machine-specific actions necessary before swapout.
    778 	 * This can include saving floating point state, etc.
    779 	 */
    780 	cpu_swapout(l);
    781 
    782 	/*
    783 	 * Unwire the to-be-swapped process's user struct and kernel stack.
    784 	 */
    785 	uarea_swapout(USER_TO_UAREA(l->l_addr));
    786 	pmap_collect(vm_map_pmap(&p->p_vmspace->vm_map));
    787 }
    788 
    789 /*
    790  * uvm_lwp_hold: prevent lwp "l" from being swapped out, and bring
    791  * back into memory if it is currently swapped.
    792  */
    793 
    794 void
    795 uvm_lwp_hold(struct lwp *l)
    796 {
    797 
    798 	if (l == curlwp) {
    799 		atomic_inc_uint(&l->l_holdcnt);
    800 	} else {
    801 		mutex_enter(&l->l_swaplock);
    802 		if (atomic_inc_uint_nv(&l->l_holdcnt) == 1 &&
    803 		    (l->l_flag & LW_INMEM) == 0)
    804 			uvm_swapin(l);
    805 		mutex_exit(&l->l_swaplock);
    806 	}
    807 }
    808 
    809 /*
    810  * uvm_lwp_rele: release a hold on lwp "l".  when the holdcount
    811  * drops to zero, it's eligable to be swapped.
    812  */
    813 
    814 void
    815 uvm_lwp_rele(struct lwp *l)
    816 {
    817 
    818 	KASSERT(l->l_holdcnt != 0);
    819 
    820 	atomic_dec_uint(&l->l_holdcnt);
    821 }
    822 
    823 #ifdef COREDUMP
    824 /*
    825  * uvm_coredump_walkmap: walk a process's map for the purpose of dumping
    826  * a core file.
    827  */
    828 
    829 int
    830 uvm_coredump_walkmap(struct proc *p, void *iocookie,
    831     int (*func)(struct proc *, void *, struct uvm_coredump_state *),
    832     void *cookie)
    833 {
    834 	struct uvm_coredump_state state;
    835 	struct vmspace *vm = p->p_vmspace;
    836 	struct vm_map *map = &vm->vm_map;
    837 	struct vm_map_entry *entry;
    838 	int error;
    839 
    840 	entry = NULL;
    841 	vm_map_lock_read(map);
    842 	state.end = 0;
    843 	for (;;) {
    844 		if (entry == NULL)
    845 			entry = map->header.next;
    846 		else if (!uvm_map_lookup_entry(map, state.end, &entry))
    847 			entry = entry->next;
    848 		if (entry == &map->header)
    849 			break;
    850 
    851 		state.cookie = cookie;
    852 		if (state.end > entry->start) {
    853 			state.start = state.end;
    854 		} else {
    855 			state.start = entry->start;
    856 		}
    857 		state.realend = entry->end;
    858 		state.end = entry->end;
    859 		state.prot = entry->protection;
    860 		state.flags = 0;
    861 
    862 		/*
    863 		 * Dump the region unless one of the following is true:
    864 		 *
    865 		 * (1) the region has neither object nor amap behind it
    866 		 *     (ie. it has never been accessed).
    867 		 *
    868 		 * (2) the region has no amap and is read-only
    869 		 *     (eg. an executable text section).
    870 		 *
    871 		 * (3) the region's object is a device.
    872 		 *
    873 		 * (4) the region is unreadable by the process.
    874 		 */
    875 
    876 		KASSERT(!UVM_ET_ISSUBMAP(entry));
    877 		KASSERT(state.start < VM_MAXUSER_ADDRESS);
    878 		KASSERT(state.end <= VM_MAXUSER_ADDRESS);
    879 		if (entry->object.uvm_obj == NULL &&
    880 		    entry->aref.ar_amap == NULL) {
    881 			state.realend = state.start;
    882 		} else if ((entry->protection & VM_PROT_WRITE) == 0 &&
    883 		    entry->aref.ar_amap == NULL) {
    884 			state.realend = state.start;
    885 		} else if (entry->object.uvm_obj != NULL &&
    886 		    UVM_OBJ_IS_DEVICE(entry->object.uvm_obj)) {
    887 			state.realend = state.start;
    888 		} else if ((entry->protection & VM_PROT_READ) == 0) {
    889 			state.realend = state.start;
    890 		} else {
    891 			if (state.start >= (vaddr_t)vm->vm_maxsaddr)
    892 				state.flags |= UVM_COREDUMP_STACK;
    893 
    894 			/*
    895 			 * If this an anonymous entry, only dump instantiated
    896 			 * pages.
    897 			 */
    898 			if (entry->object.uvm_obj == NULL) {
    899 				vaddr_t end;
    900 
    901 				amap_lock(entry->aref.ar_amap);
    902 				for (end = state.start;
    903 				     end < state.end; end += PAGE_SIZE) {
    904 					struct vm_anon *anon;
    905 					anon = amap_lookup(&entry->aref,
    906 					    end - entry->start);
    907 					/*
    908 					 * If we have already encountered an
    909 					 * uninstantiated page, stop at the
    910 					 * first instantied page.
    911 					 */
    912 					if (anon != NULL &&
    913 					    state.realend != state.end) {
    914 						state.end = end;
    915 						break;
    916 					}
    917 
    918 					/*
    919 					 * If this page is the first
    920 					 * uninstantiated page, mark this as
    921 					 * the real ending point.  Continue to
    922 					 * counting uninstantiated pages.
    923 					 */
    924 					if (anon == NULL &&
    925 					    state.realend == state.end) {
    926 						state.realend = end;
    927 					}
    928 				}
    929 				amap_unlock(entry->aref.ar_amap);
    930 			}
    931 		}
    932 
    933 
    934 		vm_map_unlock_read(map);
    935 		error = (*func)(p, iocookie, &state);
    936 		if (error)
    937 			return (error);
    938 		vm_map_lock_read(map);
    939 	}
    940 	vm_map_unlock_read(map);
    941 
    942 	return (0);
    943 }
    944 #endif /* COREDUMP */
    945