xref: /netbsd-src/sys/uvm/uvm_glue.c (revision 6deb2c22d20de1d75d538e8a5c57b573926fd157)
1 /*	$NetBSD: uvm_glue.c,v 1.140 2009/08/10 16:50:18 matt 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.140 2009/08/10 16:50:18 matt 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 int uarea_swapin(vaddr_t);
97 static void uvm_swapout(struct lwp *);
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 
233 	/*
234 	 * Wire down the U-area for the process, which contains the PCB
235 	 * and the kernel stack.  Wired state is stored in l->l_flag's
236 	 * L_INMEM bit rather than in the vm_map_entry's wired count
237 	 * to prevent kernel_map fragmentation.  If we reused a cached U-area,
238 	 * L_INMEM will already be set and we don't need to do anything.
239 	 *
240 	 * Note the kernel stack gets read/write accesses right off the bat.
241 	 */
242 
243 	if ((l2->l_flag & LW_INMEM) == 0) {
244 #ifdef VMSWAP_UAREA
245 		vaddr_t uarea = USER_TO_UAREA(l2->l_addr);
246 		int error;
247 
248 		if ((error = uarea_swapin(uarea)) != 0)
249 			panic("%s: uvm_fault_wire failed: %d", __func__, error);
250 #ifdef PMAP_UAREA
251 		/* Tell the pmap this is a u-area mapping */
252 		PMAP_UAREA(uarea);
253 #endif
254 #endif /* VMSWAP_UAREA */
255 		l2->l_flag |= LW_INMEM;
256 	}
257 
258 	/* Fill stack with magic number. */
259 	kstack_setup_magic(l2);
260 
261 	/*
262 	 * cpu_lwp_fork() copy and update the pcb, and make the child ready
263  	 * to run.  If this is a normal user fork, the child will exit
264 	 * directly to user mode via child_return() on its first time
265 	 * slice and will not return here.  If this is a kernel thread,
266 	 * the specified entry point will be executed.
267 	 */
268 	cpu_lwp_fork(l1, l2, stack, stacksize, func, arg);
269 
270 	/* Inactive emap for new LWP. */
271 	l2->l_emap_gen = UVM_EMAP_INACTIVE;
272 }
273 
274 static int
275 uarea_swapin(vaddr_t addr)
276 {
277 
278 	return uvm_fault_wire(kernel_map, addr, addr + USPACE,
279 	    VM_PROT_READ | VM_PROT_WRITE, 0);
280 }
281 
282 #ifdef VMSWAP_UAREA
283 static void
284 uarea_swapout(vaddr_t addr)
285 {
286 
287 	uvm_fault_unwire(kernel_map, addr, addr + USPACE);
288 }
289 #endif /* VMSWAP_UAREA */
290 
291 #ifndef USPACE_ALIGN
292 #define	USPACE_ALIGN	0
293 #endif
294 
295 static pool_cache_t uvm_uarea_cache;
296 
297 static int
298 uarea_ctor(void *arg, void *obj, int flags)
299 {
300 #if defined(PMAP_MAP_POOLPAGE) && !defined(VMSWAP_UAREA)
301 	if (USPACE == PAGE_SIZE && USPACE_ALIGN == 0)
302 		return 0;
303 #endif
304 	KASSERT((flags & PR_WAITOK) != 0);
305 	return uarea_swapin((vaddr_t)obj);
306 }
307 
308 static void *
309 uarea_poolpage_alloc(struct pool *pp, int flags)
310 {
311 #if defined(PMAP_MAP_POOLPAGE) && !defined(VMSWAP_UAREA)
312 	if (USPACE == PAGE_SIZE && USPACE_ALIGN == 0) {
313 		struct vm_page *pg;
314 		vaddr_t va;
315 
316 		pg = uvm_pagealloc(NULL, 0, NULL,
317 		   ((flags & PR_WAITOK) == 0 ? UVM_KMF_NOWAIT : 0));
318 		if (pg == NULL)
319 			return NULL;
320 		va = PMAP_MAP_POOLPAGE(VM_PAGE_TO_PHYS(pg));
321 		if (va == 0)
322 			uvm_pagefree(pg);
323 		return (void *)va;
324 	}
325 #endif
326 	return (void *)uvm_km_alloc(kernel_map, pp->pr_alloc->pa_pagesz,
327 	    USPACE_ALIGN, UVM_KMF_PAGEABLE |
328 	    ((flags & PR_WAITOK) != 0 ? UVM_KMF_WAITVA :
329 	    (UVM_KMF_NOWAIT | UVM_KMF_TRYLOCK)));
330 }
331 
332 static void
333 uarea_poolpage_free(struct pool *pp, void *addr)
334 {
335 #if defined(PMAP_MAP_POOLPAGE) && !defined(VMSWAP_UAREA)
336 	if (USPACE == PAGE_SIZE && USPACE_ALIGN == 0) {
337 		paddr_t pa;
338 
339 		pa = PMAP_UNMAP_POOLPAGE((vaddr_t) addr);
340 		KASSERT(pa != 0);
341 		uvm_pagefree(PHYS_TO_VM_PAGE(pa));
342 		return;
343 	}
344 #endif
345 	uvm_km_free(kernel_map, (vaddr_t)addr, pp->pr_alloc->pa_pagesz,
346 	    UVM_KMF_PAGEABLE);
347 }
348 
349 static struct pool_allocator uvm_uarea_allocator = {
350 	.pa_alloc = uarea_poolpage_alloc,
351 	.pa_free = uarea_poolpage_free,
352 	.pa_pagesz = USPACE,
353 };
354 
355 void
356 uvm_uarea_init(void)
357 {
358 	int flags = PR_NOTOUCH;
359 
360 	/*
361 	 * specify PR_NOALIGN unless the alignment provided by
362 	 * the backend (USPACE_ALIGN) is sufficient to provide
363 	 * pool page size (UPSACE) alignment.
364 	 */
365 
366 	if ((USPACE_ALIGN == 0 && USPACE != PAGE_SIZE) ||
367 	    (USPACE_ALIGN % USPACE) != 0) {
368 		flags |= PR_NOALIGN;
369 	}
370 
371 	uvm_uarea_cache = pool_cache_init(USPACE, USPACE_ALIGN, 0, flags,
372 	    "uarea", &uvm_uarea_allocator, IPL_NONE, uarea_ctor, NULL, NULL);
373 }
374 
375 /*
376  * uvm_uarea_alloc: allocate a u-area
377  */
378 
379 bool
380 uvm_uarea_alloc(vaddr_t *uaddrp)
381 {
382 
383 	*uaddrp = (vaddr_t)pool_cache_get(uvm_uarea_cache, PR_WAITOK);
384 	return true;
385 }
386 
387 /*
388  * uvm_uarea_free: free a u-area
389  */
390 
391 void
392 uvm_uarea_free(vaddr_t uaddr, struct cpu_info *ci)
393 {
394 
395 	pool_cache_put(uvm_uarea_cache, (void *)uaddr);
396 }
397 
398 /*
399  * uvm_proc_exit: exit a virtual address space
400  *
401  * - borrow proc0's address space because freeing the vmspace
402  *   of the dead process may block.
403  */
404 
405 void
406 uvm_proc_exit(struct proc *p)
407 {
408 	struct lwp *l = curlwp; /* XXX */
409 	struct vmspace *ovm;
410 
411 	KASSERT(p == l->l_proc);
412 	ovm = p->p_vmspace;
413 
414 	/*
415 	 * borrow proc0's address space.
416 	 */
417 	KPREEMPT_DISABLE(l);
418 	pmap_deactivate(l);
419 	p->p_vmspace = proc0.p_vmspace;
420 	pmap_activate(l);
421 	KPREEMPT_ENABLE(l);
422 
423 	uvmspace_free(ovm);
424 }
425 
426 void
427 uvm_lwp_exit(struct lwp *l)
428 {
429 	vaddr_t va = USER_TO_UAREA(l->l_addr);
430 
431 	l->l_flag &= ~LW_INMEM;
432 	uvm_uarea_free(va, l->l_cpu);
433 	l->l_addr = NULL;
434 }
435 
436 /*
437  * uvm_init_limit: init per-process VM limits
438  *
439  * - called for process 0 and then inherited by all others.
440  */
441 
442 void
443 uvm_init_limits(struct proc *p)
444 {
445 
446 	/*
447 	 * Set up the initial limits on process VM.  Set the maximum
448 	 * resident set size to be all of (reasonably) available memory.
449 	 * This causes any single, large process to start random page
450 	 * replacement once it fills memory.
451 	 */
452 
453 	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
454 	p->p_rlimit[RLIMIT_STACK].rlim_max = maxsmap;
455 	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
456 	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdmap;
457 	p->p_rlimit[RLIMIT_AS].rlim_cur = RLIM_INFINITY;
458 	p->p_rlimit[RLIMIT_AS].rlim_max = RLIM_INFINITY;
459 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(uvmexp.free);
460 }
461 
462 #ifdef DEBUG
463 int	enableswap = 1;
464 int	swapdebug = 0;
465 #define	SDB_FOLLOW	1
466 #define SDB_SWAPIN	2
467 #define SDB_SWAPOUT	4
468 #endif
469 
470 /*
471  * uvm_swapin: swap in an lwp's u-area.
472  *
473  * - must be called with the LWP's swap lock held.
474  * - naturally, must not be called with l == curlwp
475  */
476 
477 void
478 uvm_swapin(struct lwp *l)
479 {
480 #ifdef VMSWAP_UAREA
481 	int error;
482 #endif
483 
484 	KASSERT(mutex_owned(&l->l_swaplock));
485 	KASSERT(l != curlwp);
486 
487 #ifdef VMSWAP_UAREA
488 	error = uarea_swapin(USER_TO_UAREA(l->l_addr));
489 	if (error) {
490 		panic("%s: rewiring stack failed: %d", __func__, error);
491 	}
492 
493 	/*
494 	 * Some architectures need to be notified when the user area has
495 	 * moved to new physical page(s) (e.g.  see mips/mips/vm_machdep.c).
496 	 */
497 	cpu_swapin(l);
498 #endif
499 	lwp_lock(l);
500 	if (l->l_stat == LSRUN)
501 		sched_enqueue(l, false);
502 	l->l_flag |= LW_INMEM;
503 	l->l_swtime = 0;
504 	lwp_unlock(l);
505 	++uvmexp.swapins;
506 }
507 
508 /*
509  * uvm_kick_scheduler: kick the scheduler into action if not running.
510  *
511  * - called when swapped out processes have been awoken.
512  */
513 
514 void
515 uvm_kick_scheduler(void)
516 {
517 
518 	if (uvm.swap_running == false)
519 		return;
520 
521 	mutex_enter(&uvm_scheduler_mutex);
522 	uvm.scheduler_kicked = true;
523 	cv_signal(&uvm.scheduler_cv);
524 	mutex_exit(&uvm_scheduler_mutex);
525 }
526 
527 /*
528  * uvm_scheduler: process zero main loop
529  *
530  * - attempt to swapin every swaped-out, runnable process in order of
531  *	priority.
532  * - if not enough memory, wake the pagedaemon and let it clear space.
533  */
534 
535 void
536 uvm_scheduler(void)
537 {
538 	struct lwp *l, *ll;
539 	int pri;
540 	int ppri;
541 
542 	l = curlwp;
543 	lwp_lock(l);
544 	l->l_priority = PRI_VM;
545 	l->l_class = SCHED_FIFO;
546 	lwp_unlock(l);
547 
548 	for (;;) {
549 #ifdef DEBUG
550 		mutex_enter(&uvm_scheduler_mutex);
551 		while (!enableswap)
552 			cv_wait(&uvm.scheduler_cv, &uvm_scheduler_mutex);
553 		mutex_exit(&uvm_scheduler_mutex);
554 #endif
555 		ll = NULL;		/* process to choose */
556 		ppri = INT_MIN;		/* its priority */
557 
558 		mutex_enter(proc_lock);
559 		LIST_FOREACH(l, &alllwp, l_list) {
560 			/* is it a runnable swapped out process? */
561 			if (l->l_stat == LSRUN && !(l->l_flag & LW_INMEM)) {
562 				pri = l->l_swtime + l->l_slptime -
563 				    (l->l_proc->p_nice - NZERO) * 8;
564 				if (pri > ppri) {   /* higher priority? */
565 					ll = l;
566 					ppri = pri;
567 				}
568 			}
569 		}
570 #ifdef DEBUG
571 		if (swapdebug & SDB_FOLLOW)
572 			printf("%s: running, procp %p pri %d\n", __func__, ll,
573 			    ppri);
574 #endif
575 		/*
576 		 * Nothing to do, back to sleep
577 		 */
578 		if ((l = ll) == NULL) {
579 			mutex_exit(proc_lock);
580 			mutex_enter(&uvm_scheduler_mutex);
581 			if (uvm.scheduler_kicked == false)
582 				cv_wait(&uvm.scheduler_cv,
583 				    &uvm_scheduler_mutex);
584 			uvm.scheduler_kicked = false;
585 			mutex_exit(&uvm_scheduler_mutex);
586 			continue;
587 		}
588 
589 		/*
590 		 * we have found swapped out process which we would like
591 		 * to bring back in.
592 		 *
593 		 * XXX: this part is really bogus cuz we could deadlock
594 		 * on memory despite our feeble check
595 		 */
596 		if (uvmexp.free > atop(USPACE)) {
597 #ifdef DEBUG
598 			if (swapdebug & SDB_SWAPIN)
599 				printf("swapin: pid %d(%s)@%p, pri %d "
600 				    "free %d\n", l->l_proc->p_pid,
601 				    l->l_proc->p_comm, l->l_addr, ppri,
602 				    uvmexp.free);
603 #endif
604 			mutex_enter(&l->l_swaplock);
605 			mutex_exit(proc_lock);
606 			uvm_swapin(l);
607 			mutex_exit(&l->l_swaplock);
608 			continue;
609 		} else {
610 			/*
611 			 * not enough memory, jab the pageout daemon and
612 			 * wait til the coast is clear
613 			 */
614 			mutex_exit(proc_lock);
615 #ifdef DEBUG
616 			if (swapdebug & SDB_FOLLOW)
617 				printf("%s: no room for pid %d(%s),"
618 				    " free %d\n", __func__, l->l_proc->p_pid,
619 				    l->l_proc->p_comm, uvmexp.free);
620 #endif
621 			uvm_wait("schedpwait");
622 #ifdef DEBUG
623 			if (swapdebug & SDB_FOLLOW)
624 				printf("%s: room again, free %d\n", __func__,
625 				    uvmexp.free);
626 #endif
627 		}
628 	}
629 }
630 
631 /*
632  * swappable: is LWP "l" swappable?
633  */
634 
635 static bool
636 swappable(struct lwp *l)
637 {
638 
639 	if ((l->l_flag & (LW_INMEM|LW_SYSTEM|LW_WEXIT)) != LW_INMEM)
640 		return false;
641 	if ((l->l_pflag & LP_RUNNING) != 0)
642 		return false;
643 	if (l->l_holdcnt != 0)
644 		return false;
645 	if (l->l_class != SCHED_OTHER)
646 		return false;
647 	if (l->l_syncobj == &rw_syncobj || l->l_syncobj == &mutex_syncobj)
648 		return false;
649 	if (l->l_proc->p_stat != SACTIVE && l->l_proc->p_stat != SSTOP)
650 		return false;
651 	return true;
652 }
653 
654 /*
655  * swapout_threads: find threads that can be swapped and unwire their
656  *	u-areas.
657  *
658  * - called by the pagedaemon
659  * - try and swap at least one processs
660  * - processes that are sleeping or stopped for maxslp or more seconds
661  *   are swapped... otherwise the longest-sleeping or stopped process
662  *   is swapped, otherwise the longest resident process...
663  */
664 
665 void
666 uvm_swapout_threads(void)
667 {
668 	struct lwp *l;
669 	struct lwp *outl, *outl2;
670 	int outpri, outpri2;
671 	int didswap = 0;
672 	extern int maxslp;
673 	bool gotit;
674 
675 	/* XXXCDC: should move off to uvmexp. or uvm., also in uvm_meter */
676 
677 #ifdef DEBUG
678 	if (!enableswap)
679 		return;
680 #endif
681 
682 	/*
683 	 * outl/outpri  : stop/sleep thread with largest sleeptime < maxslp
684 	 * outl2/outpri2: the longest resident thread (its swap time)
685 	 */
686 	outl = outl2 = NULL;
687 	outpri = outpri2 = 0;
688 
689  restart:
690 	mutex_enter(proc_lock);
691 	LIST_FOREACH(l, &alllwp, l_list) {
692 		KASSERT(l->l_proc != NULL);
693 		if (!mutex_tryenter(&l->l_swaplock))
694 			continue;
695 		if (!swappable(l)) {
696 			mutex_exit(&l->l_swaplock);
697 			continue;
698 		}
699 		switch (l->l_stat) {
700 		case LSONPROC:
701 			break;
702 
703 		case LSRUN:
704 			if (l->l_swtime > outpri2) {
705 				outl2 = l;
706 				outpri2 = l->l_swtime;
707 			}
708 			break;
709 
710 		case LSSLEEP:
711 		case LSSTOP:
712 			if (l->l_slptime >= maxslp) {
713 				mutex_exit(proc_lock);
714 				uvm_swapout(l);
715 				/*
716 				 * Locking in the wrong direction -
717 				 * try to prevent the LWP from exiting.
718 				 */
719 				gotit = mutex_tryenter(proc_lock);
720 				mutex_exit(&l->l_swaplock);
721 				didswap++;
722 				if (!gotit)
723 					goto restart;
724 				continue;
725 			} else if (l->l_slptime > outpri) {
726 				outl = l;
727 				outpri = l->l_slptime;
728 			}
729 			break;
730 		}
731 		mutex_exit(&l->l_swaplock);
732 	}
733 
734 	/*
735 	 * If we didn't get rid of any real duds, toss out the next most
736 	 * likely sleeping/stopped or running candidate.  We only do this
737 	 * if we are real low on memory since we don't gain much by doing
738 	 * it (USPACE bytes).
739 	 */
740 	if (didswap == 0 && uvmexp.free <= atop(round_page(USPACE))) {
741 		if ((l = outl) == NULL)
742 			l = outl2;
743 #ifdef DEBUG
744 		if (swapdebug & SDB_SWAPOUT)
745 			printf("%s: no duds, try procp %p\n", __func__, l);
746 #endif
747 		if (l) {
748 			mutex_enter(&l->l_swaplock);
749 			mutex_exit(proc_lock);
750 			if (swappable(l))
751 				uvm_swapout(l);
752 			mutex_exit(&l->l_swaplock);
753 			return;
754 		}
755 	}
756 
757 	mutex_exit(proc_lock);
758 }
759 
760 /*
761  * uvm_swapout: swap out lwp "l"
762  *
763  * - currently "swapout" means "unwire U-area" and "pmap_collect()"
764  *   the pmap.
765  * - must be called with l->l_swaplock held.
766  * - XXXCDC: should deactivate all process' private anonymous memory
767  */
768 
769 static void
770 uvm_swapout(struct lwp *l)
771 {
772 	struct vm_map *map;
773 
774 	KASSERT(mutex_owned(&l->l_swaplock));
775 
776 #ifdef DEBUG
777 	if (swapdebug & SDB_SWAPOUT)
778 		printf("%s: lid %d.%d(%s)@%p, stat %x pri %d free %d\n",
779 		   __func__, l->l_proc->p_pid, l->l_lid, l->l_proc->p_comm,
780 		   l->l_addr, l->l_stat, l->l_slptime, uvmexp.free);
781 #endif
782 
783 	/*
784 	 * Mark it as (potentially) swapped out.
785 	 */
786 	lwp_lock(l);
787 	if (!swappable(l)) {
788 		KDASSERT(l->l_cpu != curcpu());
789 		lwp_unlock(l);
790 		return;
791 	}
792 	l->l_flag &= ~LW_INMEM;
793 	l->l_swtime = 0;
794 	if (l->l_stat == LSRUN)
795 		sched_dequeue(l);
796 	lwp_unlock(l);
797 	l->l_ru.ru_nswap++;
798 	++uvmexp.swapouts;
799 
800 #ifdef VMSWAP_UAREA
801 	/*
802 	 * Do any machine-specific actions necessary before swapout.
803 	 * This can include saving floating point state, etc.
804 	 */
805 	cpu_swapout(l);
806 
807 	/*
808 	 * Unwire the to-be-swapped process's user struct and kernel stack.
809 	 */
810 	uarea_swapout(USER_TO_UAREA(l->l_addr));
811 #endif
812 	map = &l->l_proc->p_vmspace->vm_map;
813 	if (vm_map_lock_try(map)) {
814 		pmap_collect(vm_map_pmap(map));
815 		vm_map_unlock(map);
816 	}
817 }
818 
819 /*
820  * uvm_lwp_hold: prevent lwp "l" from being swapped out, and bring
821  * back into memory if it is currently swapped.
822  */
823 
824 void
825 uvm_lwp_hold(struct lwp *l)
826 {
827 
828 	if (l == curlwp) {
829 		atomic_inc_uint(&l->l_holdcnt);
830 	} else {
831 		mutex_enter(&l->l_swaplock);
832 		if (atomic_inc_uint_nv(&l->l_holdcnt) == 1 &&
833 		    (l->l_flag & LW_INMEM) == 0)
834 			uvm_swapin(l);
835 		mutex_exit(&l->l_swaplock);
836 	}
837 }
838 
839 /*
840  * uvm_lwp_rele: release a hold on lwp "l".  when the holdcount
841  * drops to zero, it's eligable to be swapped.
842  */
843 
844 void
845 uvm_lwp_rele(struct lwp *l)
846 {
847 
848 	KASSERT(l->l_holdcnt != 0);
849 
850 	atomic_dec_uint(&l->l_holdcnt);
851 }
852