xref: /freebsd/sys/vm/vm_glue.c (revision 89b57fcf01d895a82a24b97548116e924bca5efc)
160727d8bSWarner Losh /*-
2df8bae1dSRodney W. Grimes  * Copyright (c) 1991, 1993
3df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
4df8bae1dSRodney W. Grimes  *
5df8bae1dSRodney W. Grimes  * This code is derived from software contributed to Berkeley by
6df8bae1dSRodney W. Grimes  * The Mach Operating System project at Carnegie-Mellon University.
7df8bae1dSRodney W. Grimes  *
8df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
9df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
10df8bae1dSRodney W. Grimes  * are met:
11df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
12df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
13df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
14df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
15df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
16df8bae1dSRodney W. Grimes  * 4. Neither the name of the University nor the names of its contributors
17df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
18df8bae1dSRodney W. Grimes  *    without specific prior written permission.
19df8bae1dSRodney W. Grimes  *
20df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
31df8bae1dSRodney W. Grimes  *
323c4dd356SDavid Greenman  *	from: @(#)vm_glue.c	8.6 (Berkeley) 1/5/94
33df8bae1dSRodney W. Grimes  *
34df8bae1dSRodney W. Grimes  *
35df8bae1dSRodney W. Grimes  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36df8bae1dSRodney W. Grimes  * All rights reserved.
37df8bae1dSRodney W. Grimes  *
38df8bae1dSRodney W. Grimes  * Permission to use, copy, modify and distribute this software and
39df8bae1dSRodney W. Grimes  * its documentation is hereby granted, provided that both the copyright
40df8bae1dSRodney W. Grimes  * notice and this permission notice appear in all copies of the
41df8bae1dSRodney W. Grimes  * software, derivative works or modified versions, and any portions
42df8bae1dSRodney W. Grimes  * thereof, and that both notices appear in supporting documentation.
43df8bae1dSRodney W. Grimes  *
44df8bae1dSRodney W. Grimes  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
45df8bae1dSRodney W. Grimes  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
46df8bae1dSRodney W. Grimes  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
47df8bae1dSRodney W. Grimes  *
48df8bae1dSRodney W. Grimes  * Carnegie Mellon requests users of this software to return to
49df8bae1dSRodney W. Grimes  *
50df8bae1dSRodney W. Grimes  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
51df8bae1dSRodney W. Grimes  *  School of Computer Science
52df8bae1dSRodney W. Grimes  *  Carnegie Mellon University
53df8bae1dSRodney W. Grimes  *  Pittsburgh PA 15213-3890
54df8bae1dSRodney W. Grimes  *
55df8bae1dSRodney W. Grimes  * any improvements or extensions that they make and grant Carnegie the
56df8bae1dSRodney W. Grimes  * rights to redistribute these changes.
57df8bae1dSRodney W. Grimes  */
58df8bae1dSRodney W. Grimes 
59874651b1SDavid E. O'Brien #include <sys/cdefs.h>
60874651b1SDavid E. O'Brien __FBSDID("$FreeBSD$");
61874651b1SDavid E. O'Brien 
62faa5f8d8SAndrzej Bialecki #include "opt_vm.h"
6315a7ad60SPeter Wemm #include "opt_kstack_pages.h"
6415a7ad60SPeter Wemm #include "opt_kstack_max_pages.h"
65e9822d92SJoerg Wunsch 
66df8bae1dSRodney W. Grimes #include <sys/param.h>
67df8bae1dSRodney W. Grimes #include <sys/systm.h>
68104a9b7eSAlexander Kabaev #include <sys/limits.h>
69fb919e4dSMark Murray #include <sys/lock.h>
70fb919e4dSMark Murray #include <sys/mutex.h>
71df8bae1dSRodney W. Grimes #include <sys/proc.h>
72df8bae1dSRodney W. Grimes #include <sys/resourcevar.h>
73da61b9a6SAlan Cox #include <sys/sched.h>
74da61b9a6SAlan Cox #include <sys/sf_buf.h>
753aa12267SBruce Evans #include <sys/shm.h>
76efeaf95aSDavid Greenman #include <sys/vmmeter.h>
771005a129SJohn Baldwin #include <sys/sx.h>
78ceb0cf87SJohn Dyson #include <sys/sysctl.h>
79df8bae1dSRodney W. Grimes 
8026f9a767SRodney W. Grimes #include <sys/kernel.h>
810384fff8SJason Evans #include <sys/ktr.h>
82a2a1c95cSPeter Wemm #include <sys/unistd.h>
8326f9a767SRodney W. Grimes 
84df8bae1dSRodney W. Grimes #include <vm/vm.h>
85efeaf95aSDavid Greenman #include <vm/vm_param.h>
86efeaf95aSDavid Greenman #include <vm/pmap.h>
87efeaf95aSDavid Greenman #include <vm/vm_map.h>
88df8bae1dSRodney W. Grimes #include <vm/vm_page.h>
8926f9a767SRodney W. Grimes #include <vm/vm_pageout.h>
90a136efe9SPeter Wemm #include <vm/vm_object.h>
91df8bae1dSRodney W. Grimes #include <vm/vm_kern.h>
92efeaf95aSDavid Greenman #include <vm/vm_extern.h>
93a136efe9SPeter Wemm #include <vm/vm_pager.h>
9492da00bbSMatthew Dillon #include <vm/swap_pager.h>
95efeaf95aSDavid Greenman 
96ea754954SJohn Baldwin extern int maxslp;
97ea754954SJohn Baldwin 
982b14f991SJulian Elischer /*
992b14f991SJulian Elischer  * System initialization
1002b14f991SJulian Elischer  *
1012b14f991SJulian Elischer  * Note: proc0 from proc.h
1022b14f991SJulian Elischer  */
10311caded3SAlfred Perlstein static void vm_init_limits(void *);
1044590fd3aSDavid Greenman SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
1052b14f991SJulian Elischer 
1062b14f991SJulian Elischer /*
1072b14f991SJulian Elischer  * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
1082b14f991SJulian Elischer  *
1092b14f991SJulian Elischer  * Note: run scheduling should be divorced from the vm system.
1102b14f991SJulian Elischer  */
11111caded3SAlfred Perlstein static void scheduler(void *);
1129a44a82bSBruce Evans SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_ANY, scheduler, NULL)
1132b14f991SJulian Elischer 
114e50f5c2eSBruce Evans #ifndef NO_SWAPPING
115b61ce5b0SJeff Roberson static int swapout(struct proc *);
116b61ce5b0SJeff Roberson static void swapclear(struct proc *);
117e50f5c2eSBruce Evans #endif
118f708ef1bSPoul-Henning Kamp 
119d13ec713SStephan Uphoff 
120d13ec713SStephan Uphoff static volatile int proc0_rescan;
121d13ec713SStephan Uphoff 
122d13ec713SStephan Uphoff 
12343a90f3aSAlan Cox /*
12443a90f3aSAlan Cox  * MPSAFE
1252d5c7e45SMatthew Dillon  *
1262d5c7e45SMatthew Dillon  * WARNING!  This code calls vm_map_check_protection() which only checks
1272d5c7e45SMatthew Dillon  * the associated vm_map_entry range.  It does not determine whether the
1282d5c7e45SMatthew Dillon  * contents of the memory is actually readable or writable.  In most cases
1292d5c7e45SMatthew Dillon  * just checking the vm_map_entry is sufficient within the kernel's address
1302d5c7e45SMatthew Dillon  * space.
13143a90f3aSAlan Cox  */
132df8bae1dSRodney W. Grimes int
133df8bae1dSRodney W. Grimes kernacc(addr, len, rw)
134c3dfdfd1SAlfred Perlstein 	void *addr;
135df8bae1dSRodney W. Grimes 	int len, rw;
136df8bae1dSRodney W. Grimes {
137df8bae1dSRodney W. Grimes 	boolean_t rv;
138df8bae1dSRodney W. Grimes 	vm_offset_t saddr, eaddr;
13902c58685SPoul-Henning Kamp 	vm_prot_t prot;
140df8bae1dSRodney W. Grimes 
141e50f5c2eSBruce Evans 	KASSERT((rw & ~VM_PROT_ALL) == 0,
14202c58685SPoul-Henning Kamp 	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
14375337a56SAlan Cox 
14475337a56SAlan Cox 	if ((vm_offset_t)addr + len > kernel_map->max_offset ||
14575337a56SAlan Cox 	    (vm_offset_t)addr + len < (vm_offset_t)addr)
14675337a56SAlan Cox 		return (FALSE);
14775337a56SAlan Cox 
14802c58685SPoul-Henning Kamp 	prot = rw;
1496cde7a16SDavid Greenman 	saddr = trunc_page((vm_offset_t)addr);
1506cde7a16SDavid Greenman 	eaddr = round_page((vm_offset_t)addr + len);
151d8834602SAlan Cox 	vm_map_lock_read(kernel_map);
152df8bae1dSRodney W. Grimes 	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
153d8834602SAlan Cox 	vm_map_unlock_read(kernel_map);
154df8bae1dSRodney W. Grimes 	return (rv == TRUE);
155df8bae1dSRodney W. Grimes }
156df8bae1dSRodney W. Grimes 
15743a90f3aSAlan Cox /*
15843a90f3aSAlan Cox  * MPSAFE
1592d5c7e45SMatthew Dillon  *
1602d5c7e45SMatthew Dillon  * WARNING!  This code calls vm_map_check_protection() which only checks
1612d5c7e45SMatthew Dillon  * the associated vm_map_entry range.  It does not determine whether the
1622d5c7e45SMatthew Dillon  * contents of the memory is actually readable or writable.  vmapbuf(),
1632d5c7e45SMatthew Dillon  * vm_fault_quick(), or copyin()/copout()/su*()/fu*() functions should be
1642d5c7e45SMatthew Dillon  * used in conjuction with this call.
16543a90f3aSAlan Cox  */
166df8bae1dSRodney W. Grimes int
167df8bae1dSRodney W. Grimes useracc(addr, len, rw)
168c3dfdfd1SAlfred Perlstein 	void *addr;
169df8bae1dSRodney W. Grimes 	int len, rw;
170df8bae1dSRodney W. Grimes {
171df8bae1dSRodney W. Grimes 	boolean_t rv;
17202c58685SPoul-Henning Kamp 	vm_prot_t prot;
17305ba50f5SJake Burkholder 	vm_map_t map;
174df8bae1dSRodney W. Grimes 
175e50f5c2eSBruce Evans 	KASSERT((rw & ~VM_PROT_ALL) == 0,
17602c58685SPoul-Henning Kamp 	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
17702c58685SPoul-Henning Kamp 	prot = rw;
17805ba50f5SJake Burkholder 	map = &curproc->p_vmspace->vm_map;
17905ba50f5SJake Burkholder 	if ((vm_offset_t)addr + len > vm_map_max(map) ||
18005ba50f5SJake Burkholder 	    (vm_offset_t)addr + len < (vm_offset_t)addr) {
18126f9a767SRodney W. Grimes 		return (FALSE);
18226f9a767SRodney W. Grimes 	}
183d8834602SAlan Cox 	vm_map_lock_read(map);
18405ba50f5SJake Burkholder 	rv = vm_map_check_protection(map, trunc_page((vm_offset_t)addr),
18505ba50f5SJake Burkholder 	    round_page((vm_offset_t)addr + len), prot);
186d8834602SAlan Cox 	vm_map_unlock_read(map);
187df8bae1dSRodney W. Grimes 	return (rv == TRUE);
188df8bae1dSRodney W. Grimes }
189df8bae1dSRodney W. Grimes 
19016929939SDon Lewis int
191f0ea4612SDon Lewis vslock(void *addr, size_t len)
19216929939SDon Lewis {
193bb734798SDon Lewis 	vm_offset_t end, last, start;
194bb734798SDon Lewis 	vm_size_t npages;
195bb734798SDon Lewis 	int error;
19616929939SDon Lewis 
197bb734798SDon Lewis 	last = (vm_offset_t)addr + len;
198ce8660e3SDon Lewis 	start = trunc_page((vm_offset_t)addr);
199bb734798SDon Lewis 	end = round_page(last);
200bb734798SDon Lewis 	if (last < (vm_offset_t)addr || end < (vm_offset_t)addr)
20116929939SDon Lewis 		return (EINVAL);
20216929939SDon Lewis 	npages = atop(end - start);
20316929939SDon Lewis 	if (npages > vm_page_max_wired)
20416929939SDon Lewis 		return (ENOMEM);
205ce8660e3SDon Lewis 	PROC_LOCK(curproc);
206bb734798SDon Lewis 	if (ptoa(npages +
207bb734798SDon Lewis 	    pmap_wired_count(vm_map_pmap(&curproc->p_vmspace->vm_map))) >
208bb734798SDon Lewis 	    lim_cur(curproc, RLIMIT_MEMLOCK)) {
209ce8660e3SDon Lewis 		PROC_UNLOCK(curproc);
21016929939SDon Lewis 		return (ENOMEM);
21116929939SDon Lewis 	}
212ce8660e3SDon Lewis 	PROC_UNLOCK(curproc);
21316929939SDon Lewis #if 0
21416929939SDon Lewis 	/*
21516929939SDon Lewis 	 * XXX - not yet
21616929939SDon Lewis 	 *
21716929939SDon Lewis 	 * The limit for transient usage of wired pages should be
21816929939SDon Lewis 	 * larger than for "permanent" wired pages (mlock()).
21916929939SDon Lewis 	 *
22016929939SDon Lewis 	 * Also, the sysctl code, which is the only present user
22116929939SDon Lewis 	 * of vslock(), does a hard loop on EAGAIN.
22216929939SDon Lewis 	 */
2232feb50bfSAttilio Rao 	if (npages + cnt.v_wire_count > vm_page_max_wired)
22416929939SDon Lewis 		return (EAGAIN);
22516929939SDon Lewis #endif
226ce8660e3SDon Lewis 	error = vm_map_wire(&curproc->p_vmspace->vm_map, start, end,
227d9b2500eSBrian Feldman 	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
228ce8660e3SDon Lewis 	/*
229ce8660e3SDon Lewis 	 * Return EFAULT on error to match copy{in,out}() behaviour
230ce8660e3SDon Lewis 	 * rather than returning ENOMEM like mlock() would.
231ce8660e3SDon Lewis 	 */
232ce8660e3SDon Lewis 	return (error == KERN_SUCCESS ? 0 : EFAULT);
23316929939SDon Lewis }
23416929939SDon Lewis 
235ce8660e3SDon Lewis void
236f0ea4612SDon Lewis vsunlock(void *addr, size_t len)
23716929939SDon Lewis {
23816929939SDon Lewis 
239ce8660e3SDon Lewis 	/* Rely on the parameter sanity checks performed by vslock(). */
240ce8660e3SDon Lewis 	(void)vm_map_unwire(&curproc->p_vmspace->vm_map,
241ce8660e3SDon Lewis 	    trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len),
24216929939SDon Lewis 	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
24316929939SDon Lewis }
24416929939SDon Lewis 
245da61b9a6SAlan Cox /*
246da61b9a6SAlan Cox  * Pin the page contained within the given object at the given offset.  If the
247da61b9a6SAlan Cox  * page is not resident, allocate and load it using the given object's pager.
248da61b9a6SAlan Cox  * Return the pinned page if successful; otherwise, return NULL.
249da61b9a6SAlan Cox  */
250da61b9a6SAlan Cox static vm_page_t
251da61b9a6SAlan Cox vm_imgact_hold_page(vm_object_t object, vm_ooffset_t offset)
252da61b9a6SAlan Cox {
253da61b9a6SAlan Cox 	vm_page_t m, ma[1];
254da61b9a6SAlan Cox 	vm_pindex_t pindex;
255da61b9a6SAlan Cox 	int rv;
256da61b9a6SAlan Cox 
257da61b9a6SAlan Cox 	VM_OBJECT_LOCK(object);
258da61b9a6SAlan Cox 	pindex = OFF_TO_IDX(offset);
259da61b9a6SAlan Cox 	m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
260da61b9a6SAlan Cox 	if ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
261da61b9a6SAlan Cox 		ma[0] = m;
262da61b9a6SAlan Cox 		rv = vm_pager_get_pages(object, ma, 1, 0);
263da61b9a6SAlan Cox 		m = vm_page_lookup(object, pindex);
264da61b9a6SAlan Cox 		if (m == NULL)
265da61b9a6SAlan Cox 			goto out;
266da61b9a6SAlan Cox 		if (m->valid == 0 || rv != VM_PAGER_OK) {
267da61b9a6SAlan Cox 			vm_page_lock_queues();
268da61b9a6SAlan Cox 			vm_page_free(m);
269da61b9a6SAlan Cox 			vm_page_unlock_queues();
270da61b9a6SAlan Cox 			m = NULL;
271da61b9a6SAlan Cox 			goto out;
272da61b9a6SAlan Cox 		}
273da61b9a6SAlan Cox 	}
274da61b9a6SAlan Cox 	vm_page_lock_queues();
275da61b9a6SAlan Cox 	vm_page_hold(m);
276da61b9a6SAlan Cox 	vm_page_unlock_queues();
27766bdd5d6SAlan Cox 	vm_page_wakeup(m);
278da61b9a6SAlan Cox out:
279da61b9a6SAlan Cox 	VM_OBJECT_UNLOCK(object);
280da61b9a6SAlan Cox 	return (m);
281da61b9a6SAlan Cox }
282da61b9a6SAlan Cox 
283da61b9a6SAlan Cox /*
284da61b9a6SAlan Cox  * Return a CPU private mapping to the page at the given offset within the
285da61b9a6SAlan Cox  * given object.  The page is pinned before it is mapped.
286da61b9a6SAlan Cox  */
287da61b9a6SAlan Cox struct sf_buf *
288da61b9a6SAlan Cox vm_imgact_map_page(vm_object_t object, vm_ooffset_t offset)
289da61b9a6SAlan Cox {
290da61b9a6SAlan Cox 	vm_page_t m;
291da61b9a6SAlan Cox 
292da61b9a6SAlan Cox 	m = vm_imgact_hold_page(object, offset);
293da61b9a6SAlan Cox 	if (m == NULL)
294da61b9a6SAlan Cox 		return (NULL);
295da61b9a6SAlan Cox 	sched_pin();
296da61b9a6SAlan Cox 	return (sf_buf_alloc(m, SFB_CPUPRIVATE));
297da61b9a6SAlan Cox }
298da61b9a6SAlan Cox 
299da61b9a6SAlan Cox /*
300da61b9a6SAlan Cox  * Destroy the given CPU private mapping and unpin the page that it mapped.
301da61b9a6SAlan Cox  */
302da61b9a6SAlan Cox void
303da61b9a6SAlan Cox vm_imgact_unmap_page(struct sf_buf *sf)
304da61b9a6SAlan Cox {
305da61b9a6SAlan Cox 	vm_page_t m;
306da61b9a6SAlan Cox 
307da61b9a6SAlan Cox 	m = sf_buf_page(sf);
308da61b9a6SAlan Cox 	sf_buf_free(sf);
309da61b9a6SAlan Cox 	sched_unpin();
310da61b9a6SAlan Cox 	vm_page_lock_queues();
311da61b9a6SAlan Cox 	vm_page_unhold(m);
312da61b9a6SAlan Cox 	vm_page_unlock_queues();
313da61b9a6SAlan Cox }
314da61b9a6SAlan Cox 
31549a2507bSAlan Cox #ifndef KSTACK_MAX_PAGES
31649a2507bSAlan Cox #define KSTACK_MAX_PAGES 32
31749a2507bSAlan Cox #endif
31849a2507bSAlan Cox 
31949a2507bSAlan Cox /*
32049a2507bSAlan Cox  * Create the kernel stack (including pcb for i386) for a new thread.
32149a2507bSAlan Cox  * This routine directly affects the fork perf for a process and
32249a2507bSAlan Cox  * create performance for a thread.
32349a2507bSAlan Cox  */
32489b57fcfSKonstantin Belousov int
32549a2507bSAlan Cox vm_thread_new(struct thread *td, int pages)
32649a2507bSAlan Cox {
32749a2507bSAlan Cox 	vm_object_t ksobj;
32849a2507bSAlan Cox 	vm_offset_t ks;
32949a2507bSAlan Cox 	vm_page_t m, ma[KSTACK_MAX_PAGES];
33049a2507bSAlan Cox 	int i;
33149a2507bSAlan Cox 
33249a2507bSAlan Cox 	/* Bounds check */
33349a2507bSAlan Cox 	if (pages <= 1)
33449a2507bSAlan Cox 		pages = KSTACK_PAGES;
33549a2507bSAlan Cox 	else if (pages > KSTACK_MAX_PAGES)
33649a2507bSAlan Cox 		pages = KSTACK_MAX_PAGES;
33749a2507bSAlan Cox 	/*
33849a2507bSAlan Cox 	 * Allocate an object for the kstack.
33949a2507bSAlan Cox 	 */
34049a2507bSAlan Cox 	ksobj = vm_object_allocate(OBJT_DEFAULT, pages);
34149a2507bSAlan Cox 	/*
34249a2507bSAlan Cox 	 * Get a kernel virtual address for this thread's kstack.
34349a2507bSAlan Cox 	 */
34449a2507bSAlan Cox 	ks = kmem_alloc_nofault(kernel_map,
34549a2507bSAlan Cox 	   (pages + KSTACK_GUARD_PAGES) * PAGE_SIZE);
34689b57fcfSKonstantin Belousov 	if (ks == 0) {
34789b57fcfSKonstantin Belousov 		printf("vm_thread_new: kstack allocation failed\n");
34889b57fcfSKonstantin Belousov 		vm_object_deallocate(ksobj);
34989b57fcfSKonstantin Belousov 		return (0);
35089b57fcfSKonstantin Belousov 	}
35189b57fcfSKonstantin Belousov 
35249a2507bSAlan Cox 	if (KSTACK_GUARD_PAGES != 0) {
35349a2507bSAlan Cox 		pmap_qremove(ks, KSTACK_GUARD_PAGES);
35449a2507bSAlan Cox 		ks += KSTACK_GUARD_PAGES * PAGE_SIZE;
35549a2507bSAlan Cox 	}
35689b57fcfSKonstantin Belousov 	td->td_kstack_obj = ksobj;
35749a2507bSAlan Cox 	td->td_kstack = ks;
35849a2507bSAlan Cox 	/*
35949a2507bSAlan Cox 	 * Knowing the number of pages allocated is useful when you
36049a2507bSAlan Cox 	 * want to deallocate them.
36149a2507bSAlan Cox 	 */
36249a2507bSAlan Cox 	td->td_kstack_pages = pages;
36349a2507bSAlan Cox 	/*
36449a2507bSAlan Cox 	 * For the length of the stack, link in a real page of ram for each
36549a2507bSAlan Cox 	 * page of stack.
36649a2507bSAlan Cox 	 */
36749a2507bSAlan Cox 	VM_OBJECT_LOCK(ksobj);
36849a2507bSAlan Cox 	for (i = 0; i < pages; i++) {
36949a2507bSAlan Cox 		/*
37049a2507bSAlan Cox 		 * Get a kernel stack page.
37149a2507bSAlan Cox 		 */
372ddf4bb37SAlan Cox 		m = vm_page_grab(ksobj, i, VM_ALLOC_NOBUSY |
37349a2507bSAlan Cox 		    VM_ALLOC_NORMAL | VM_ALLOC_RETRY | VM_ALLOC_WIRED);
37449a2507bSAlan Cox 		ma[i] = m;
37549a2507bSAlan Cox 		m->valid = VM_PAGE_BITS_ALL;
37649a2507bSAlan Cox 	}
37749a2507bSAlan Cox 	VM_OBJECT_UNLOCK(ksobj);
37849a2507bSAlan Cox 	pmap_qenter(ks, ma, pages);
37989b57fcfSKonstantin Belousov 	return (1);
38049a2507bSAlan Cox }
38149a2507bSAlan Cox 
38249a2507bSAlan Cox /*
38349a2507bSAlan Cox  * Dispose of a thread's kernel stack.
38449a2507bSAlan Cox  */
38549a2507bSAlan Cox void
38649a2507bSAlan Cox vm_thread_dispose(struct thread *td)
38749a2507bSAlan Cox {
38849a2507bSAlan Cox 	vm_object_t ksobj;
38949a2507bSAlan Cox 	vm_offset_t ks;
39049a2507bSAlan Cox 	vm_page_t m;
39149a2507bSAlan Cox 	int i, pages;
39249a2507bSAlan Cox 
39349a2507bSAlan Cox 	pages = td->td_kstack_pages;
39449a2507bSAlan Cox 	ksobj = td->td_kstack_obj;
39549a2507bSAlan Cox 	ks = td->td_kstack;
39649a2507bSAlan Cox 	pmap_qremove(ks, pages);
39749a2507bSAlan Cox 	VM_OBJECT_LOCK(ksobj);
39849a2507bSAlan Cox 	for (i = 0; i < pages; i++) {
39949a2507bSAlan Cox 		m = vm_page_lookup(ksobj, i);
40049a2507bSAlan Cox 		if (m == NULL)
40149a2507bSAlan Cox 			panic("vm_thread_dispose: kstack already missing?");
40249a2507bSAlan Cox 		vm_page_lock_queues();
40349a2507bSAlan Cox 		vm_page_unwire(m, 0);
40449a2507bSAlan Cox 		vm_page_free(m);
40549a2507bSAlan Cox 		vm_page_unlock_queues();
40649a2507bSAlan Cox 	}
40749a2507bSAlan Cox 	VM_OBJECT_UNLOCK(ksobj);
40849a2507bSAlan Cox 	vm_object_deallocate(ksobj);
40949a2507bSAlan Cox 	kmem_free(kernel_map, ks - (KSTACK_GUARD_PAGES * PAGE_SIZE),
41049a2507bSAlan Cox 	    (pages + KSTACK_GUARD_PAGES) * PAGE_SIZE);
41189b57fcfSKonstantin Belousov 	td->td_kstack = 0;
41249a2507bSAlan Cox }
41349a2507bSAlan Cox 
41449a2507bSAlan Cox /*
41549a2507bSAlan Cox  * Allow a thread's kernel stack to be paged out.
41649a2507bSAlan Cox  */
41749a2507bSAlan Cox void
41849a2507bSAlan Cox vm_thread_swapout(struct thread *td)
41949a2507bSAlan Cox {
42049a2507bSAlan Cox 	vm_object_t ksobj;
42149a2507bSAlan Cox 	vm_page_t m;
42249a2507bSAlan Cox 	int i, pages;
42349a2507bSAlan Cox 
424710338e9SMarcel Moolenaar 	cpu_thread_swapout(td);
42549a2507bSAlan Cox 	pages = td->td_kstack_pages;
42649a2507bSAlan Cox 	ksobj = td->td_kstack_obj;
42749a2507bSAlan Cox 	pmap_qremove(td->td_kstack, pages);
42849a2507bSAlan Cox 	VM_OBJECT_LOCK(ksobj);
42949a2507bSAlan Cox 	for (i = 0; i < pages; i++) {
43049a2507bSAlan Cox 		m = vm_page_lookup(ksobj, i);
43149a2507bSAlan Cox 		if (m == NULL)
43249a2507bSAlan Cox 			panic("vm_thread_swapout: kstack already missing?");
43349a2507bSAlan Cox 		vm_page_lock_queues();
43449a2507bSAlan Cox 		vm_page_dirty(m);
43549a2507bSAlan Cox 		vm_page_unwire(m, 0);
43649a2507bSAlan Cox 		vm_page_unlock_queues();
43749a2507bSAlan Cox 	}
43849a2507bSAlan Cox 	VM_OBJECT_UNLOCK(ksobj);
43949a2507bSAlan Cox }
44049a2507bSAlan Cox 
44149a2507bSAlan Cox /*
44249a2507bSAlan Cox  * Bring the kernel stack for a specified thread back in.
44349a2507bSAlan Cox  */
44449a2507bSAlan Cox void
44549a2507bSAlan Cox vm_thread_swapin(struct thread *td)
44649a2507bSAlan Cox {
44749a2507bSAlan Cox 	vm_object_t ksobj;
44849a2507bSAlan Cox 	vm_page_t m, ma[KSTACK_MAX_PAGES];
44949a2507bSAlan Cox 	int i, pages, rv;
45049a2507bSAlan Cox 
45149a2507bSAlan Cox 	pages = td->td_kstack_pages;
45249a2507bSAlan Cox 	ksobj = td->td_kstack_obj;
45349a2507bSAlan Cox 	VM_OBJECT_LOCK(ksobj);
45449a2507bSAlan Cox 	for (i = 0; i < pages; i++) {
45549a2507bSAlan Cox 		m = vm_page_grab(ksobj, i, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
45649a2507bSAlan Cox 		if (m->valid != VM_PAGE_BITS_ALL) {
45749a2507bSAlan Cox 			rv = vm_pager_get_pages(ksobj, &m, 1, 0);
45849a2507bSAlan Cox 			if (rv != VM_PAGER_OK)
45949a2507bSAlan Cox 				panic("vm_thread_swapin: cannot get kstack for proc: %d", td->td_proc->p_pid);
46049a2507bSAlan Cox 			m = vm_page_lookup(ksobj, i);
46149a2507bSAlan Cox 			m->valid = VM_PAGE_BITS_ALL;
46249a2507bSAlan Cox 		}
46349a2507bSAlan Cox 		ma[i] = m;
46449a2507bSAlan Cox 		vm_page_lock_queues();
46549a2507bSAlan Cox 		vm_page_wire(m);
46649a2507bSAlan Cox 		vm_page_unlock_queues();
46766bdd5d6SAlan Cox 		vm_page_wakeup(m);
46849a2507bSAlan Cox 	}
46949a2507bSAlan Cox 	VM_OBJECT_UNLOCK(ksobj);
47049a2507bSAlan Cox 	pmap_qenter(td->td_kstack, ma, pages);
471710338e9SMarcel Moolenaar 	cpu_thread_swapin(td);
47249a2507bSAlan Cox }
47349a2507bSAlan Cox 
474a136efe9SPeter Wemm /*
47589f4fca2SAlan Cox  * Set up a variable-sized alternate kstack.
47689f4fca2SAlan Cox  */
47789b57fcfSKonstantin Belousov int
47889f4fca2SAlan Cox vm_thread_new_altkstack(struct thread *td, int pages)
47989f4fca2SAlan Cox {
48089f4fca2SAlan Cox 
48189f4fca2SAlan Cox 	td->td_altkstack = td->td_kstack;
48289f4fca2SAlan Cox 	td->td_altkstack_obj = td->td_kstack_obj;
48389f4fca2SAlan Cox 	td->td_altkstack_pages = td->td_kstack_pages;
48489f4fca2SAlan Cox 
48589b57fcfSKonstantin Belousov 	return (vm_thread_new(td, pages));
48689f4fca2SAlan Cox }
48789f4fca2SAlan Cox 
48889f4fca2SAlan Cox /*
48989f4fca2SAlan Cox  * Restore the original kstack.
49089f4fca2SAlan Cox  */
49189f4fca2SAlan Cox void
49289f4fca2SAlan Cox vm_thread_dispose_altkstack(struct thread *td)
49389f4fca2SAlan Cox {
49489f4fca2SAlan Cox 
49549a2507bSAlan Cox 	vm_thread_dispose(td);
49689f4fca2SAlan Cox 
49789f4fca2SAlan Cox 	td->td_kstack = td->td_altkstack;
49889f4fca2SAlan Cox 	td->td_kstack_obj = td->td_altkstack_obj;
49989f4fca2SAlan Cox 	td->td_kstack_pages = td->td_altkstack_pages;
50089f4fca2SAlan Cox 	td->td_altkstack = 0;
50189f4fca2SAlan Cox 	td->td_altkstack_obj = NULL;
50289f4fca2SAlan Cox 	td->td_altkstack_pages = 0;
50389f4fca2SAlan Cox }
50489f4fca2SAlan Cox 
50589f4fca2SAlan Cox /*
506df8bae1dSRodney W. Grimes  * Implement fork's actions on an address space.
507df8bae1dSRodney W. Grimes  * Here we arrange for the address space to be copied or referenced,
508df8bae1dSRodney W. Grimes  * allocate a user struct (pcb and kernel stack), then call the
509df8bae1dSRodney W. Grimes  * machine-dependent layer to fill those in and make the new process
510a2a1c95cSPeter Wemm  * ready to run.  The new process is set up so that it returns directly
511a2a1c95cSPeter Wemm  * to user mode to avoid stack copying and relocation problems.
512df8bae1dSRodney W. Grimes  */
51389b57fcfSKonstantin Belousov int
51489b57fcfSKonstantin Belousov vm_forkproc(td, p2, td2, vm2, flags)
515b40ce416SJulian Elischer 	struct thread *td;
516b40ce416SJulian Elischer 	struct proc *p2;
517079b7badSJulian Elischer 	struct thread *td2;
51889b57fcfSKonstantin Belousov 	struct vmspace *vm2;
519a2a1c95cSPeter Wemm 	int flags;
520df8bae1dSRodney W. Grimes {
521b40ce416SJulian Elischer 	struct proc *p1 = td->td_proc;
52289b57fcfSKonstantin Belousov 	int error;
523df8bae1dSRodney W. Grimes 
52491c28bfdSLuoqi Chen 	if ((flags & RFPROC) == 0) {
52591c28bfdSLuoqi Chen 		/*
52691c28bfdSLuoqi Chen 		 * Divorce the memory, if it is shared, essentially
52791c28bfdSLuoqi Chen 		 * this changes shared memory amongst threads, into
52891c28bfdSLuoqi Chen 		 * COW locally.
52991c28bfdSLuoqi Chen 		 */
53091c28bfdSLuoqi Chen 		if ((flags & RFMEM) == 0) {
53191c28bfdSLuoqi Chen 			if (p1->p_vmspace->vm_refcnt > 1) {
53289b57fcfSKonstantin Belousov 				error = vmspace_unshare(p1);
53389b57fcfSKonstantin Belousov 				if (error)
53489b57fcfSKonstantin Belousov 					return (error);
53591c28bfdSLuoqi Chen 			}
53691c28bfdSLuoqi Chen 		}
537079b7badSJulian Elischer 		cpu_fork(td, p2, td2, flags);
53889b57fcfSKonstantin Belousov 		return (0);
53991c28bfdSLuoqi Chen 	}
54091c28bfdSLuoqi Chen 
5415856e12eSJohn Dyson 	if (flags & RFMEM) {
5425856e12eSJohn Dyson 		p2->p_vmspace = p1->p_vmspace;
5431a276a3fSAlan Cox 		atomic_add_int(&p1->p_vmspace->vm_refcnt, 1);
5445856e12eSJohn Dyson 	}
5455856e12eSJohn Dyson 
54690ecac61SMatthew Dillon 	while (vm_page_count_severe()) {
54726f9a767SRodney W. Grimes 		VM_WAIT;
5480d94caffSDavid Greenman 	}
54926f9a767SRodney W. Grimes 
5505856e12eSJohn Dyson 	if ((flags & RFMEM) == 0) {
55189b57fcfSKonstantin Belousov 		p2->p_vmspace = vm2;
552df8bae1dSRodney W. Grimes 		if (p1->p_vmspace->vm_shm)
553dabee6feSPeter Wemm 			shmfork(p1, p2);
554a2a1c95cSPeter Wemm 	}
555df8bae1dSRodney W. Grimes 
55639fb8e6bSJulian Elischer 	/*
557a2a1c95cSPeter Wemm 	 * cpu_fork will copy and update the pcb, set up the kernel stack,
558a2a1c95cSPeter Wemm 	 * and make the child ready to run.
559df8bae1dSRodney W. Grimes 	 */
560079b7badSJulian Elischer 	cpu_fork(td, p2, td2, flags);
56189b57fcfSKonstantin Belousov 	return (0);
562df8bae1dSRodney W. Grimes }
563df8bae1dSRodney W. Grimes 
564df8bae1dSRodney W. Grimes /*
565eb30c1c0SPeter Wemm  * Called after process has been wait(2)'ed apon and is being reaped.
566eb30c1c0SPeter Wemm  * The idea is to reclaim resources that we could not reclaim while
567eb30c1c0SPeter Wemm  * the process was still executing.
568eb30c1c0SPeter Wemm  */
569eb30c1c0SPeter Wemm void
570eb30c1c0SPeter Wemm vm_waitproc(p)
571eb30c1c0SPeter Wemm 	struct proc *p;
572eb30c1c0SPeter Wemm {
573eb30c1c0SPeter Wemm 
574582ec34cSAlfred Perlstein 	vmspace_exitfree(p);		/* and clean-out the vmspace */
575eb30c1c0SPeter Wemm }
576eb30c1c0SPeter Wemm 
577eb30c1c0SPeter Wemm /*
578df8bae1dSRodney W. Grimes  * Set default limits for VM system.
579df8bae1dSRodney W. Grimes  * Called for proc 0, and then inherited by all others.
5802b14f991SJulian Elischer  *
5812b14f991SJulian Elischer  * XXX should probably act directly on proc0.
582df8bae1dSRodney W. Grimes  */
5832b14f991SJulian Elischer static void
5842b14f991SJulian Elischer vm_init_limits(udata)
5854590fd3aSDavid Greenman 	void *udata;
586df8bae1dSRodney W. Grimes {
58754d92145SMatthew Dillon 	struct proc *p = udata;
58891d5354aSJohn Baldwin 	struct plimit *limp;
589bbc0ec52SDavid Greenman 	int rss_limit;
590df8bae1dSRodney W. Grimes 
591df8bae1dSRodney W. Grimes 	/*
5920d94caffSDavid Greenman 	 * Set up the initial limits on process VM. Set the maximum resident
5930d94caffSDavid Greenman 	 * set size to be half of (reasonably) available memory.  Since this
5940d94caffSDavid Greenman 	 * is a soft limit, it comes into effect only when the system is out
5950d94caffSDavid Greenman 	 * of memory - half of main memory helps to favor smaller processes,
596bbc0ec52SDavid Greenman 	 * and reduces thrashing of the object cache.
597df8bae1dSRodney W. Grimes 	 */
59891d5354aSJohn Baldwin 	limp = p->p_limit;
59991d5354aSJohn Baldwin 	limp->pl_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
60091d5354aSJohn Baldwin 	limp->pl_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
60191d5354aSJohn Baldwin 	limp->pl_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
60291d5354aSJohn Baldwin 	limp->pl_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
603dd0bd066SDavid Greenman 	/* limit the limit to no less than 2MB */
6042feb50bfSAttilio Rao 	rss_limit = max(cnt.v_free_count, 512);
60591d5354aSJohn Baldwin 	limp->pl_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
60691d5354aSJohn Baldwin 	limp->pl_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
607df8bae1dSRodney W. Grimes }
608df8bae1dSRodney W. Grimes 
60926f9a767SRodney W. Grimes void
61026f9a767SRodney W. Grimes faultin(p)
61126f9a767SRodney W. Grimes 	struct proc *p;
61226f9a767SRodney W. Grimes {
61311edc1e0SJohn Baldwin #ifdef NO_SWAPPING
61411edc1e0SJohn Baldwin 
61511edc1e0SJohn Baldwin 	PROC_LOCK_ASSERT(p, MA_OWNED);
616b61ce5b0SJeff Roberson 	if ((p->p_flag & P_INMEM) == 0)
61711edc1e0SJohn Baldwin 		panic("faultin: proc swapped out with NO_SWAPPING!");
61811edc1e0SJohn Baldwin #else /* !NO_SWAPPING */
619664f718bSJohn Baldwin 	struct thread *td;
62026f9a767SRodney W. Grimes 
621c96d52a9SJohn Baldwin 	PROC_LOCK_ASSERT(p, MA_OWNED);
6221d7b9ed2SJulian Elischer 	/*
6231d7b9ed2SJulian Elischer 	 * If another process is swapping in this process,
6241d7b9ed2SJulian Elischer 	 * just wait until it finishes.
6251d7b9ed2SJulian Elischer 	 */
626b61ce5b0SJeff Roberson 	if (p->p_flag & P_SWAPPINGIN) {
627b61ce5b0SJeff Roberson 		while (p->p_flag & P_SWAPPINGIN)
628b61ce5b0SJeff Roberson 			msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
629b61ce5b0SJeff Roberson 		return;
630b61ce5b0SJeff Roberson 	}
631b61ce5b0SJeff Roberson 	if ((p->p_flag & P_INMEM) == 0) {
632664f718bSJohn Baldwin 		/*
633664f718bSJohn Baldwin 		 * Don't let another thread swap process p out while we are
634664f718bSJohn Baldwin 		 * busy swapping it in.
635664f718bSJohn Baldwin 		 */
636664f718bSJohn Baldwin 		++p->p_lock;
637b61ce5b0SJeff Roberson 		p->p_flag |= P_SWAPPINGIN;
63845ece682SJohn Baldwin 		PROC_UNLOCK(p);
63926f9a767SRodney W. Grimes 
640b61ce5b0SJeff Roberson 		/*
641b61ce5b0SJeff Roberson 		 * We hold no lock here because the list of threads
642b61ce5b0SJeff Roberson 		 * can not change while all threads in the process are
643b61ce5b0SJeff Roberson 		 * swapped out.
644b61ce5b0SJeff Roberson 		 */
645664f718bSJohn Baldwin 		FOREACH_THREAD_IN_PROC(p, td)
64649a2507bSAlan Cox 			vm_thread_swapin(td);
64745ece682SJohn Baldwin 		PROC_LOCK(p);
648982d11f8SJeff Roberson 		PROC_SLOCK(p);
649b61ce5b0SJeff Roberson 		swapclear(p);
650258853abSJeff Roberson 		p->p_swtick = ticks;
651982d11f8SJeff Roberson 		PROC_SUNLOCK(p);
65226f9a767SRodney W. Grimes 
653b61ce5b0SJeff Roberson 		wakeup(&p->p_flag);
65426f9a767SRodney W. Grimes 
655664f718bSJohn Baldwin 		/* Allow other threads to swap p out now. */
65626f9a767SRodney W. Grimes 		--p->p_lock;
65726f9a767SRodney W. Grimes 	}
65811edc1e0SJohn Baldwin #endif /* NO_SWAPPING */
65926f9a767SRodney W. Grimes }
66026f9a767SRodney W. Grimes 
661df8bae1dSRodney W. Grimes /*
66226f9a767SRodney W. Grimes  * This swapin algorithm attempts to swap-in processes only if there
66326f9a767SRodney W. Grimes  * is enough space for them.  Of course, if a process waits for a long
66426f9a767SRodney W. Grimes  * time, it will be swapped in anyway.
6650384fff8SJason Evans  *
666e602ba25SJulian Elischer  *  XXXKSE - process with the thread with highest priority counts..
667b40ce416SJulian Elischer  *
66810c447faSAlan Cox  * Giant is held on entry.
669df8bae1dSRodney W. Grimes  */
6702b14f991SJulian Elischer /* ARGSUSED*/
6712b14f991SJulian Elischer static void
672d841aaa7SBruce Evans scheduler(dummy)
673d841aaa7SBruce Evans 	void *dummy;
674df8bae1dSRodney W. Grimes {
67554d92145SMatthew Dillon 	struct proc *p;
676e602ba25SJulian Elischer 	struct thread *td;
677df8bae1dSRodney W. Grimes 	struct proc *pp;
678258853abSJeff Roberson 	int slptime;
679258853abSJeff Roberson 	int swtime;
680df8bae1dSRodney W. Grimes 	int ppri;
681258853abSJeff Roberson 	int pri;
682df8bae1dSRodney W. Grimes 
683c96d52a9SJohn Baldwin 	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
68410c447faSAlan Cox 	mtx_unlock(&Giant);
6850384fff8SJason Evans 
686df8bae1dSRodney W. Grimes loop:
68790ecac61SMatthew Dillon 	if (vm_page_count_min()) {
6880d94caffSDavid Greenman 		VM_WAIT;
689982d11f8SJeff Roberson 		thread_lock(&thread0);
690d13ec713SStephan Uphoff 		proc0_rescan = 0;
691982d11f8SJeff Roberson 		thread_unlock(&thread0);
69290ecac61SMatthew Dillon 		goto loop;
6930d94caffSDavid Greenman 	}
69426f9a767SRodney W. Grimes 
695df8bae1dSRodney W. Grimes 	pp = NULL;
696df8bae1dSRodney W. Grimes 	ppri = INT_MIN;
6971005a129SJohn Baldwin 	sx_slock(&allproc_lock);
698b40ce416SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
699b61ce5b0SJeff Roberson 		PROC_LOCK(p);
700b61ce5b0SJeff Roberson 		if (p->p_flag & (P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) {
701b61ce5b0SJeff Roberson 			PROC_UNLOCK(p);
702e602ba25SJulian Elischer 			continue;
703e602ba25SJulian Elischer 		}
704258853abSJeff Roberson 		swtime = (ticks - p->p_swtick) / hz;
705982d11f8SJeff Roberson 		PROC_SLOCK(p);
706e602ba25SJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td) {
7071d7b9ed2SJulian Elischer 			/*
70871fad9fdSJulian Elischer 			 * An otherwise runnable thread of a process
70971fad9fdSJulian Elischer 			 * swapped out has only the TDI_SWAPPED bit set.
71071fad9fdSJulian Elischer 			 *
7111d7b9ed2SJulian Elischer 			 */
712982d11f8SJeff Roberson 			thread_lock(td);
71371fad9fdSJulian Elischer 			if (td->td_inhibitors == TDI_SWAPPED) {
714258853abSJeff Roberson 				slptime = (ticks - td->td_slptick) / hz;
715258853abSJeff Roberson 				pri = swtime + slptime;
716b61ce5b0SJeff Roberson 				if ((td->td_flags & TDF_SWAPINREQ) == 0)
717fa885116SJulian Elischer 					pri -= p->p_nice * 8;
71826f9a767SRodney W. Grimes 				/*
719ad1e7d28SJulian Elischer 				 * if this thread is higher priority
720b40ce416SJulian Elischer 				 * and there is enough space, then select
721b40ce416SJulian Elischer 				 * this process instead of the previous
722b40ce416SJulian Elischer 				 * selection.
72326f9a767SRodney W. Grimes 				 */
7240d94caffSDavid Greenman 				if (pri > ppri) {
725df8bae1dSRodney W. Grimes 					pp = p;
726df8bae1dSRodney W. Grimes 					ppri = pri;
727df8bae1dSRodney W. Grimes 				}
728df8bae1dSRodney W. Grimes 			}
729982d11f8SJeff Roberson 			thread_unlock(td);
730b40ce416SJulian Elischer 		}
731982d11f8SJeff Roberson 		PROC_SUNLOCK(p);
732b61ce5b0SJeff Roberson 		PROC_UNLOCK(p);
733df8bae1dSRodney W. Grimes 	}
7341005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
73526f9a767SRodney W. Grimes 
736df8bae1dSRodney W. Grimes 	/*
737a669a6e9SJohn Dyson 	 * Nothing to do, back to sleep.
738df8bae1dSRodney W. Grimes 	 */
739df8bae1dSRodney W. Grimes 	if ((p = pp) == NULL) {
740982d11f8SJeff Roberson 		thread_lock(&thread0);
741d13ec713SStephan Uphoff 		if (!proc0_rescan) {
742d13ec713SStephan Uphoff 			TD_SET_IWAIT(&thread0);
743d13ec713SStephan Uphoff 			mi_switch(SW_VOL, NULL);
744d13ec713SStephan Uphoff 		}
745d13ec713SStephan Uphoff 		proc0_rescan = 0;
746982d11f8SJeff Roberson 		thread_unlock(&thread0);
747df8bae1dSRodney W. Grimes 		goto loop;
748df8bae1dSRodney W. Grimes 	}
7491d7b9ed2SJulian Elischer 	PROC_LOCK(p);
7501d7b9ed2SJulian Elischer 
7511d7b9ed2SJulian Elischer 	/*
7521d7b9ed2SJulian Elischer 	 * Another process may be bringing or may have already
7531d7b9ed2SJulian Elischer 	 * brought this process in while we traverse all threads.
7541d7b9ed2SJulian Elischer 	 * Or, this process may even be being swapped out again.
7551d7b9ed2SJulian Elischer 	 */
756b61ce5b0SJeff Roberson 	if (p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) {
7571d7b9ed2SJulian Elischer 		PROC_UNLOCK(p);
758982d11f8SJeff Roberson 		thread_lock(&thread0);
759d13ec713SStephan Uphoff 		proc0_rescan = 0;
760982d11f8SJeff Roberson 		thread_unlock(&thread0);
7611d7b9ed2SJulian Elischer 		goto loop;
7621d7b9ed2SJulian Elischer 	}
7631d7b9ed2SJulian Elischer 
764df8bae1dSRodney W. Grimes 	/*
76526f9a767SRodney W. Grimes 	 * We would like to bring someone in. (only if there is space).
766e602ba25SJulian Elischer 	 * [What checks the space? ]
767df8bae1dSRodney W. Grimes 	 */
76826f9a767SRodney W. Grimes 	faultin(p);
76945ece682SJohn Baldwin 	PROC_UNLOCK(p);
770982d11f8SJeff Roberson 	thread_lock(&thread0);
771d13ec713SStephan Uphoff 	proc0_rescan = 0;
772982d11f8SJeff Roberson 	thread_unlock(&thread0);
773df8bae1dSRodney W. Grimes 	goto loop;
774df8bae1dSRodney W. Grimes }
775df8bae1dSRodney W. Grimes 
776d13ec713SStephan Uphoff void kick_proc0(void)
777d13ec713SStephan Uphoff {
778d13ec713SStephan Uphoff 	struct thread *td = &thread0;
779d13ec713SStephan Uphoff 
780982d11f8SJeff Roberson 	/* XXX This will probably cause a LOR in some cases */
781982d11f8SJeff Roberson 	thread_lock(td);
782d13ec713SStephan Uphoff 	if (TD_AWAITING_INTR(td)) {
783f0393f06SJeff Roberson 		CTR2(KTR_INTR, "%s: sched_add %d", __func__, 0);
784d13ec713SStephan Uphoff 		TD_CLR_IWAIT(td);
785f0393f06SJeff Roberson 		sched_add(td, SRQ_INTR);
786d13ec713SStephan Uphoff 	} else {
787d13ec713SStephan Uphoff 		proc0_rescan = 1;
788d13ec713SStephan Uphoff 		CTR2(KTR_INTR, "%s: state %d",
789d13ec713SStephan Uphoff 		    __func__, td->td_state);
790d13ec713SStephan Uphoff 	}
791982d11f8SJeff Roberson 	thread_unlock(td);
792d13ec713SStephan Uphoff 
793d13ec713SStephan Uphoff }
794d13ec713SStephan Uphoff 
795d13ec713SStephan Uphoff 
7965afce282SDavid Greenman #ifndef NO_SWAPPING
7975afce282SDavid Greenman 
798ceb0cf87SJohn Dyson /*
799ceb0cf87SJohn Dyson  * Swap_idle_threshold1 is the guaranteed swapped in time for a process
800ceb0cf87SJohn Dyson  */
801303b270bSEivind Eklund static int swap_idle_threshold1 = 2;
8022a3eeaa2STom Rhodes SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1, CTLFLAG_RW,
8039faaf3b3STom Rhodes     &swap_idle_threshold1, 0, "Guaranteed swapped in time for a process");
804ceb0cf87SJohn Dyson 
805ceb0cf87SJohn Dyson /*
806ceb0cf87SJohn Dyson  * Swap_idle_threshold2 is the time that a process can be idle before
807ceb0cf87SJohn Dyson  * it will be swapped out, if idle swapping is enabled.
808ceb0cf87SJohn Dyson  */
809303b270bSEivind Eklund static int swap_idle_threshold2 = 10;
8102a3eeaa2STom Rhodes SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2, CTLFLAG_RW,
8119faaf3b3STom Rhodes     &swap_idle_threshold2, 0, "Time before a process will be swapped out");
812ceb0cf87SJohn Dyson 
813df8bae1dSRodney W. Grimes /*
814df8bae1dSRodney W. Grimes  * Swapout is driven by the pageout daemon.  Very simple, we find eligible
815b61ce5b0SJeff Roberson  * procs and swap out their stacks.  We try to always "swap" at least one
816df8bae1dSRodney W. Grimes  * process in case we need the room for a swapin.
817df8bae1dSRodney W. Grimes  * If any procs have been sleeping/stopped for at least maxslp seconds,
818df8bae1dSRodney W. Grimes  * they are swapped.  Else, we swap the longest-sleeping or stopped process,
819df8bae1dSRodney W. Grimes  * if any, otherwise the longest-resident process.
820df8bae1dSRodney W. Grimes  */
821df8bae1dSRodney W. Grimes void
8223a2dc656SJohn Dyson swapout_procs(action)
8233a2dc656SJohn Dyson int action;
824df8bae1dSRodney W. Grimes {
82554d92145SMatthew Dillon 	struct proc *p;
826e602ba25SJulian Elischer 	struct thread *td;
827df8bae1dSRodney W. Grimes 	int didswap = 0;
828df8bae1dSRodney W. Grimes 
8290d94caffSDavid Greenman retry:
8303a2189d4SJohn Baldwin 	sx_slock(&allproc_lock);
831e602ba25SJulian Elischer 	FOREACH_PROC_IN_SYSTEM(p) {
832b18bfc3dSJohn Dyson 		struct vmspace *vm;
833b40ce416SJulian Elischer 		int minslptime = 100000;
834258853abSJeff Roberson 		int slptime;
835b18bfc3dSJohn Dyson 
8369eb881f8SSeigo Tanimura 		/*
837b1f99ebeSSeigo Tanimura 		 * Watch out for a process in
838b1f99ebeSSeigo Tanimura 		 * creation.  It may have no
8391c865ac7SJohn Baldwin 		 * address space or lock yet.
8401c865ac7SJohn Baldwin 		 */
841b61ce5b0SJeff Roberson 		if (p->p_state == PRS_NEW)
8421c865ac7SJohn Baldwin 			continue;
8431c865ac7SJohn Baldwin 		/*
844b1f99ebeSSeigo Tanimura 		 * An aio daemon switches its
845b1f99ebeSSeigo Tanimura 		 * address space while running.
846b1f99ebeSSeigo Tanimura 		 * Perform a quick check whether
847b1f99ebeSSeigo Tanimura 		 * a process has P_SYSTEM.
8489eb881f8SSeigo Tanimura 		 */
8498f887403SJohn Baldwin 		if ((p->p_flag & P_SYSTEM) != 0)
850b1f99ebeSSeigo Tanimura 			continue;
8511c865ac7SJohn Baldwin 		/*
8521c865ac7SJohn Baldwin 		 * Do not swapout a process that
8531c865ac7SJohn Baldwin 		 * is waiting for VM data
8541c865ac7SJohn Baldwin 		 * structures as there is a possible
8551c865ac7SJohn Baldwin 		 * deadlock.  Test this first as
8561c865ac7SJohn Baldwin 		 * this may block.
8571c865ac7SJohn Baldwin 		 *
8581c865ac7SJohn Baldwin 		 * Lock the map until swapout
8591c865ac7SJohn Baldwin 		 * finishes, or a thread of this
8601c865ac7SJohn Baldwin 		 * process may attempt to alter
8611c865ac7SJohn Baldwin 		 * the map.
8621c865ac7SJohn Baldwin 		 */
86357051fdcSTor Egge 		vm = vmspace_acquire_ref(p);
86457051fdcSTor Egge 		if (vm == NULL)
86557051fdcSTor Egge 			continue;
8669eb881f8SSeigo Tanimura 		if (!vm_map_trylock(&vm->vm_map))
8679eb881f8SSeigo Tanimura 			goto nextproc1;
8689eb881f8SSeigo Tanimura 
8695074aecdSJohn Baldwin 		PROC_LOCK(p);
87069b40456SJohn Baldwin 		if (p->p_lock != 0 ||
8711279572aSDavid Xu 		    (p->p_flag & (P_STOPPED_SINGLE|P_TRACED|P_SYSTEM|P_WEXIT)
8721279572aSDavid Xu 		    ) != 0) {
8739eb881f8SSeigo Tanimura 			goto nextproc2;
8745074aecdSJohn Baldwin 		}
87523955314SAlfred Perlstein 		/*
87623955314SAlfred Perlstein 		 * only aiod changes vmspace, however it will be
87723955314SAlfred Perlstein 		 * skipped because of the if statement above checking
87823955314SAlfred Perlstein 		 * for P_SYSTEM
87923955314SAlfred Perlstein 		 */
880b61ce5b0SJeff Roberson 		if ((p->p_flag & (P_INMEM|P_SWAPPINGOUT|P_SWAPPINGIN)) != P_INMEM)
881664f718bSJohn Baldwin 			goto nextproc2;
88269b40456SJohn Baldwin 
883e602ba25SJulian Elischer 		switch (p->p_state) {
8840d94caffSDavid Greenman 		default:
885e602ba25SJulian Elischer 			/* Don't swap out processes in any sort
886e602ba25SJulian Elischer 			 * of 'special' state. */
8878f887403SJohn Baldwin 			break;
888df8bae1dSRodney W. Grimes 
889e602ba25SJulian Elischer 		case PRS_NORMAL:
890982d11f8SJeff Roberson 			PROC_SLOCK(p);
89126f9a767SRodney W. Grimes 			/*
892bfbfac11SDavid Greenman 			 * do not swapout a realtime process
893b40ce416SJulian Elischer 			 * Check all the thread groups..
894bfbfac11SDavid Greenman 			 */
8958460a577SJohn Birrell 			FOREACH_THREAD_IN_PROC(p, td) {
896b61ce5b0SJeff Roberson 				thread_lock(td);
897b61ce5b0SJeff Roberson 				if (PRI_IS_REALTIME(td->td_pri_class)) {
898b61ce5b0SJeff Roberson 					thread_unlock(td);
899b40ce416SJulian Elischer 					goto nextproc;
900b61ce5b0SJeff Roberson 				}
901258853abSJeff Roberson 				slptime = (ticks - td->td_slptick) / hz;
902bfbfac11SDavid Greenman 				/*
9039eb881f8SSeigo Tanimura 				 * Guarantee swap_idle_threshold1
904ceb0cf87SJohn Dyson 				 * time in memory.
9050d94caffSDavid Greenman 				 */
906258853abSJeff Roberson 				if (slptime < swap_idle_threshold1) {
907b61ce5b0SJeff Roberson 					thread_unlock(td);
908b40ce416SJulian Elischer 					goto nextproc;
909b61ce5b0SJeff Roberson 				}
9109eb881f8SSeigo Tanimura 
9111d7b9ed2SJulian Elischer 				/*
9129eb881f8SSeigo Tanimura 				 * Do not swapout a process if it is
9139eb881f8SSeigo Tanimura 				 * waiting on a critical event of some
9149eb881f8SSeigo Tanimura 				 * kind or there is a thread whose
9159eb881f8SSeigo Tanimura 				 * pageable memory may be accessed.
9161d7b9ed2SJulian Elischer 				 *
9171d7b9ed2SJulian Elischer 				 * This could be refined to support
9181d7b9ed2SJulian Elischer 				 * swapping out a thread.
9191d7b9ed2SJulian Elischer 				 */
9201d7b9ed2SJulian Elischer 				if ((td->td_priority) < PSOCK ||
921b61ce5b0SJeff Roberson 				    !thread_safetoswapout(td)) {
922b61ce5b0SJeff Roberson 					thread_unlock(td);
923e602ba25SJulian Elischer 					goto nextproc;
924b61ce5b0SJeff Roberson 				}
925ceb0cf87SJohn Dyson 				/*
926b40ce416SJulian Elischer 				 * If the system is under memory stress,
927b40ce416SJulian Elischer 				 * or if we are swapping
928b40ce416SJulian Elischer 				 * idle processes >= swap_idle_threshold2,
929b40ce416SJulian Elischer 				 * then swap the process out.
930ceb0cf87SJohn Dyson 				 */
931ceb0cf87SJohn Dyson 				if (((action & VM_SWAP_NORMAL) == 0) &&
932ceb0cf87SJohn Dyson 				    (((action & VM_SWAP_IDLE) == 0) ||
933258853abSJeff Roberson 				    (slptime < swap_idle_threshold2))) {
934b61ce5b0SJeff Roberson 					thread_unlock(td);
935b40ce416SJulian Elischer 					goto nextproc;
936b61ce5b0SJeff Roberson 				}
9379eb881f8SSeigo Tanimura 
938258853abSJeff Roberson 				if (minslptime > slptime)
939258853abSJeff Roberson 					minslptime = slptime;
940b61ce5b0SJeff Roberson 				thread_unlock(td);
941b40ce416SJulian Elischer 			}
9420d94caffSDavid Greenman 
94311b224dcSDavid Greenman 			/*
94417d9d0d0SDavid Schultz 			 * If the pageout daemon didn't free enough pages,
94517d9d0d0SDavid Schultz 			 * or if this process is idle and the system is
94617d9d0d0SDavid Schultz 			 * configured to swap proactively, swap it out.
94711b224dcSDavid Greenman 			 */
948ceb0cf87SJohn Dyson 			if ((action & VM_SWAP_NORMAL) ||
949ceb0cf87SJohn Dyson 				((action & VM_SWAP_IDLE) &&
950b40ce416SJulian Elischer 				 (minslptime > swap_idle_threshold2))) {
951b61ce5b0SJeff Roberson 				if (swapout(p) == 0)
952df8bae1dSRodney W. Grimes 					didswap++;
953982d11f8SJeff Roberson 				PROC_SUNLOCK(p);
954664f718bSJohn Baldwin 				PROC_UNLOCK(p);
9559eb881f8SSeigo Tanimura 				vm_map_unlock(&vm->vm_map);
9569eb881f8SSeigo Tanimura 				vmspace_free(vm);
9579eb881f8SSeigo Tanimura 				sx_sunlock(&allproc_lock);
9580d94caffSDavid Greenman 				goto retry;
959c96d52a9SJohn Baldwin 			}
960b40ce416SJulian Elischer nextproc:
961982d11f8SJeff Roberson 			PROC_SUNLOCK(p);
9628f887403SJohn Baldwin 		}
9639eb881f8SSeigo Tanimura nextproc2:
9649eb881f8SSeigo Tanimura 		PROC_UNLOCK(p);
9659eb881f8SSeigo Tanimura 		vm_map_unlock(&vm->vm_map);
9669eb881f8SSeigo Tanimura nextproc1:
9679eb881f8SSeigo Tanimura 		vmspace_free(vm);
96830171114SPeter Wemm 		continue;
969ceb0cf87SJohn Dyson 	}
9701005a129SJohn Baldwin 	sx_sunlock(&allproc_lock);
97126f9a767SRodney W. Grimes 	/*
97226f9a767SRodney W. Grimes 	 * If we swapped something out, and another process needed memory,
97326f9a767SRodney W. Grimes 	 * then wakeup the sched process.
97426f9a767SRodney W. Grimes 	 */
9750d94caffSDavid Greenman 	if (didswap)
97624a1cce3SDavid Greenman 		wakeup(&proc0);
977df8bae1dSRodney W. Grimes }
978df8bae1dSRodney W. Grimes 
979f708ef1bSPoul-Henning Kamp static void
980b61ce5b0SJeff Roberson swapclear(p)
981b61ce5b0SJeff Roberson 	struct proc *p;
982b61ce5b0SJeff Roberson {
983b61ce5b0SJeff Roberson 	struct thread *td;
984b61ce5b0SJeff Roberson 
985b61ce5b0SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
986b61ce5b0SJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED);
987b61ce5b0SJeff Roberson 
988b61ce5b0SJeff Roberson 	FOREACH_THREAD_IN_PROC(p, td) {
989b61ce5b0SJeff Roberson 		thread_lock(td);
990b61ce5b0SJeff Roberson 		td->td_flags |= TDF_INMEM;
991b61ce5b0SJeff Roberson 		td->td_flags &= ~TDF_SWAPINREQ;
992b61ce5b0SJeff Roberson 		TD_CLR_SWAPPED(td);
993b61ce5b0SJeff Roberson 		if (TD_CAN_RUN(td))
994b61ce5b0SJeff Roberson 			setrunnable(td);
995b61ce5b0SJeff Roberson 		thread_unlock(td);
996b61ce5b0SJeff Roberson 	}
997b61ce5b0SJeff Roberson 	p->p_flag &= ~(P_SWAPPINGIN|P_SWAPPINGOUT);
998b61ce5b0SJeff Roberson 	p->p_flag |= P_INMEM;
999b61ce5b0SJeff Roberson }
1000b61ce5b0SJeff Roberson 
1001b61ce5b0SJeff Roberson static int
1002df8bae1dSRodney W. Grimes swapout(p)
100354d92145SMatthew Dillon 	struct proc *p;
1004df8bae1dSRodney W. Grimes {
1005b40ce416SJulian Elischer 	struct thread *td;
1006df8bae1dSRodney W. Grimes 
1007ea754954SJohn Baldwin 	PROC_LOCK_ASSERT(p, MA_OWNED);
1008b61ce5b0SJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED | MA_NOTRECURSED);
1009d3a34985SJohn Dyson #if defined(SWAP_DEBUG)
1010d3a34985SJohn Dyson 	printf("swapping out %d\n", p->p_pid);
1011d3a34985SJohn Dyson #endif
10121d7b9ed2SJulian Elischer 
10131d7b9ed2SJulian Elischer 	/*
10149eb881f8SSeigo Tanimura 	 * The states of this process and its threads may have changed
10159eb881f8SSeigo Tanimura 	 * by now.  Assuming that there is only one pageout daemon thread,
10169eb881f8SSeigo Tanimura 	 * this process should still be in memory.
10179eb881f8SSeigo Tanimura 	 */
1018b61ce5b0SJeff Roberson 	KASSERT((p->p_flag & (P_INMEM|P_SWAPPINGOUT|P_SWAPPINGIN)) == P_INMEM,
10199eb881f8SSeigo Tanimura 		("swapout: lost a swapout race?"));
10209eb881f8SSeigo Tanimura 
1021df8bae1dSRodney W. Grimes 	/*
102226f9a767SRodney W. Grimes 	 * remember the process resident count
1023df8bae1dSRodney W. Grimes 	 */
1024b1028ad1SLuoqi Chen 	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
1025b61ce5b0SJeff Roberson 	/*
1026b61ce5b0SJeff Roberson 	 * Check and mark all threads before we proceed.
1027b61ce5b0SJeff Roberson 	 */
1028b61ce5b0SJeff Roberson 	p->p_flag &= ~P_INMEM;
1029b61ce5b0SJeff Roberson 	p->p_flag |= P_SWAPPINGOUT;
1030982d11f8SJeff Roberson 	FOREACH_THREAD_IN_PROC(p, td) {
1031982d11f8SJeff Roberson 		thread_lock(td);
1032b61ce5b0SJeff Roberson 		if (!thread_safetoswapout(td)) {
1033b61ce5b0SJeff Roberson 			thread_unlock(td);
1034b61ce5b0SJeff Roberson 			swapclear(p);
1035b61ce5b0SJeff Roberson 			return (EBUSY);
1036b61ce5b0SJeff Roberson 		}
1037b61ce5b0SJeff Roberson 		td->td_flags &= ~TDF_INMEM;
1038664f718bSJohn Baldwin 		TD_SET_SWAPPED(td);
1039982d11f8SJeff Roberson 		thread_unlock(td);
1040982d11f8SJeff Roberson 	}
1041b61ce5b0SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
1042b61ce5b0SJeff Roberson 	++td->td_ru.ru_nswap;
1043982d11f8SJeff Roberson 	PROC_SUNLOCK(p);
1044b61ce5b0SJeff Roberson 	PROC_UNLOCK(p);
104526f9a767SRodney W. Grimes 
1046b61ce5b0SJeff Roberson 	/*
1047b61ce5b0SJeff Roberson 	 * This list is stable because all threads are now prevented from
1048b61ce5b0SJeff Roberson 	 * running.  The list is only modified in the context of a running
1049b61ce5b0SJeff Roberson 	 * thread in this process.
1050b61ce5b0SJeff Roberson 	 */
1051664f718bSJohn Baldwin 	FOREACH_THREAD_IN_PROC(p, td)
105249a2507bSAlan Cox 		vm_thread_swapout(td);
1053664f718bSJohn Baldwin 
1054664f718bSJohn Baldwin 	PROC_LOCK(p);
1055b61ce5b0SJeff Roberson 	p->p_flag &= ~P_SWAPPINGOUT;
1056982d11f8SJeff Roberson 	PROC_SLOCK(p);
1057258853abSJeff Roberson 	p->p_swtick = ticks;
1058b61ce5b0SJeff Roberson 	return (0);
1059df8bae1dSRodney W. Grimes }
10605afce282SDavid Greenman #endif /* !NO_SWAPPING */
1061