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