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