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