1139825Simp/*-
21541Srgrimes * Copyright (c) 1991, 1993
31541Srgrimes *	The Regents of the University of California.  All rights reserved.
41541Srgrimes *
51541Srgrimes * This code is derived from software contributed to Berkeley by
61541Srgrimes * The Mach Operating System project at Carnegie-Mellon University.
71541Srgrimes *
81541Srgrimes * Redistribution and use in source and binary forms, with or without
91541Srgrimes * modification, are permitted provided that the following conditions
101541Srgrimes * are met:
111541Srgrimes * 1. Redistributions of source code must retain the above copyright
121541Srgrimes *    notice, this list of conditions and the following disclaimer.
131541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
141541Srgrimes *    notice, this list of conditions and the following disclaimer in the
151541Srgrimes *    documentation and/or other materials provided with the distribution.
161541Srgrimes * 4. Neither the name of the University nor the names of its contributors
171541Srgrimes *    may be used to endorse or promote products derived from this software
181541Srgrimes *    without specific prior written permission.
191541Srgrimes *
201541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
211541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
221541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
231541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
241541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
261541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
271541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
281541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
291541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
301541Srgrimes * SUCH DAMAGE.
311541Srgrimes *
321817Sdg *	from: @(#)vm_glue.c	8.6 (Berkeley) 1/5/94
331541Srgrimes *
341541Srgrimes *
351541Srgrimes * Copyright (c) 1987, 1990 Carnegie-Mellon University.
361541Srgrimes * All rights reserved.
375455Sdg *
381541Srgrimes * Permission to use, copy, modify and distribute this software and
391541Srgrimes * its documentation is hereby granted, provided that both the copyright
401541Srgrimes * notice and this permission notice appear in all copies of the
411541Srgrimes * software, derivative works or modified versions, and any portions
421541Srgrimes * thereof, and that both notices appear in supporting documentation.
435455Sdg *
445455Sdg * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
455455Sdg * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
461541Srgrimes * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
475455Sdg *
481541Srgrimes * Carnegie Mellon requests users of this software to return to
491541Srgrimes *
501541Srgrimes *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
511541Srgrimes *  School of Computer Science
521541Srgrimes *  Carnegie Mellon University
531541Srgrimes *  Pittsburgh PA 15213-3890
541541Srgrimes *
551541Srgrimes * any improvements or extensions that they make and grant Carnegie the
561541Srgrimes * rights to redistribute these changes.
571541Srgrimes */
581541Srgrimes
59116226Sobrien#include <sys/cdefs.h>
60116226Sobrien__FBSDID("$FreeBSD$");
61116226Sobrien
6239770Sabial#include "opt_vm.h"
63118234Speter#include "opt_kstack_pages.h"
64118234Speter#include "opt_kstack_max_pages.h"
6520821Sjoerg
661541Srgrimes#include <sys/param.h>
671541Srgrimes#include <sys/systm.h>
68114216Skan#include <sys/limits.h>
6976166Smarkm#include <sys/lock.h>
7076166Smarkm#include <sys/mutex.h>
711541Srgrimes#include <sys/proc.h>
72220373Strasz#include <sys/racct.h>
731541Srgrimes#include <sys/resourcevar.h>
74153485Salc#include <sys/sched.h>
75153485Salc#include <sys/sf_buf.h>
767430Sbde#include <sys/shm.h>
7712662Sdg#include <sys/vmmeter.h>
7874927Sjhb#include <sys/sx.h>
7931563Sdyson#include <sys/sysctl.h>
80229251Skib#include <sys/_kstack_cache.h>
81196730Skib#include <sys/eventhandler.h>
821549Srgrimes#include <sys/kernel.h>
8365557Sjasone#include <sys/ktr.h>
8424691Speter#include <sys/unistd.h>
851549Srgrimes
861541Srgrimes#include <vm/vm.h>
8712662Sdg#include <vm/vm_param.h>
8812662Sdg#include <vm/pmap.h>
8912662Sdg#include <vm/vm_map.h>
901541Srgrimes#include <vm/vm_page.h>
911549Srgrimes#include <vm/vm_pageout.h>
9299559Speter#include <vm/vm_object.h>
931541Srgrimes#include <vm/vm_kern.h>
9412662Sdg#include <vm/vm_extern.h>
9599559Speter#include <vm/vm_pager.h>
96107913Sdillon#include <vm/swap_pager.h>
971541Srgrimes
9889464Sbde#ifndef NO_SWAPPING
99172207Sjeffstatic int swapout(struct proc *);
100172207Sjeffstatic void swapclear(struct proc *);
101206483Salcstatic void vm_thread_swapin(struct thread *td);
102206483Salcstatic void vm_thread_swapout(struct thread *td);
10389464Sbde#endif
10412820Sphk
10598600Salc/*
10698600Salc * MPSAFE
107109572Sdillon *
108109572Sdillon * WARNING!  This code calls vm_map_check_protection() which only checks
109109572Sdillon * the associated vm_map_entry range.  It does not determine whether the
110109572Sdillon * contents of the memory is actually readable or writable.  In most cases
111109572Sdillon * just checking the vm_map_entry is sufficient within the kernel's address
112109572Sdillon * space.
11398600Salc */
1141541Srgrimesint
1151541Srgrimeskernacc(addr, len, rw)
116109630Salfred	void *addr;
1171541Srgrimes	int len, rw;
1181541Srgrimes{
1191541Srgrimes	boolean_t rv;
1201541Srgrimes	vm_offset_t saddr, eaddr;
12152644Sphk	vm_prot_t prot;
1221541Srgrimes
12389464Sbde	KASSERT((rw & ~VM_PROT_ALL) == 0,
12452644Sphk	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
125140622Salc
126140622Salc	if ((vm_offset_t)addr + len > kernel_map->max_offset ||
127140622Salc	    (vm_offset_t)addr + len < (vm_offset_t)addr)
128140622Salc		return (FALSE);
129140622Salc
13052644Sphk	prot = rw;
13140286Sdg	saddr = trunc_page((vm_offset_t)addr);
13240286Sdg	eaddr = round_page((vm_offset_t)addr + len);
133122384Salc	vm_map_lock_read(kernel_map);
1341541Srgrimes	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
135122384Salc	vm_map_unlock_read(kernel_map);
1365455Sdg	return (rv == TRUE);
1371541Srgrimes}
1381541Srgrimes
13998600Salc/*
14098600Salc * MPSAFE
141109572Sdillon *
142109572Sdillon * WARNING!  This code calls vm_map_check_protection() which only checks
143109572Sdillon * the associated vm_map_entry range.  It does not determine whether the
144109572Sdillon * contents of the memory is actually readable or writable.  vmapbuf(),
145109572Sdillon * vm_fault_quick(), or copyin()/copout()/su*()/fu*() functions should be
146109572Sdillon * used in conjuction with this call.
14798600Salc */
1481541Srgrimesint
1491541Srgrimesuseracc(addr, len, rw)
150109630Salfred	void *addr;
1511541Srgrimes	int len, rw;
1521541Srgrimes{
1531541Srgrimes	boolean_t rv;
15452644Sphk	vm_prot_t prot;
155103767Sjake	vm_map_t map;
1561541Srgrimes
15789464Sbde	KASSERT((rw & ~VM_PROT_ALL) == 0,
15852644Sphk	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
15952644Sphk	prot = rw;
160103767Sjake	map = &curproc->p_vmspace->vm_map;
161103767Sjake	if ((vm_offset_t)addr + len > vm_map_max(map) ||
162103767Sjake	    (vm_offset_t)addr + len < (vm_offset_t)addr) {
1631549Srgrimes		return (FALSE);
1641549Srgrimes	}
165122384Salc	vm_map_lock_read(map);
166103767Sjake	rv = vm_map_check_protection(map, trunc_page((vm_offset_t)addr),
167103767Sjake	    round_page((vm_offset_t)addr + len), prot);
168122384Salc	vm_map_unlock_read(map);
1695455Sdg	return (rv == TRUE);
1701541Srgrimes}
1711541Srgrimes
172126668Struckmanint
173127008Struckmanvslock(void *addr, size_t len)
174126668Struckman{
175127013Struckman	vm_offset_t end, last, start;
176127013Struckman	vm_size_t npages;
177127013Struckman	int error;
178126668Struckman
179127013Struckman	last = (vm_offset_t)addr + len;
180127007Struckman	start = trunc_page((vm_offset_t)addr);
181127013Struckman	end = round_page(last);
182127013Struckman	if (last < (vm_offset_t)addr || end < (vm_offset_t)addr)
183126668Struckman		return (EINVAL);
184126668Struckman	npages = atop(end - start);
185126668Struckman	if (npages > vm_page_max_wired)
186126668Struckman		return (ENOMEM);
187126668Struckman#if 0
188126668Struckman	/*
189126668Struckman	 * XXX - not yet
190126668Struckman	 *
191126668Struckman	 * The limit for transient usage of wired pages should be
192126668Struckman	 * larger than for "permanent" wired pages (mlock()).
193126668Struckman	 *
194126668Struckman	 * Also, the sysctl code, which is the only present user
195126668Struckman	 * of vslock(), does a hard loop on EAGAIN.
196126668Struckman	 */
197170170Sattilio	if (npages + cnt.v_wire_count > vm_page_max_wired)
198126668Struckman		return (EAGAIN);
199126668Struckman#endif
200127007Struckman	error = vm_map_wire(&curproc->p_vmspace->vm_map, start, end,
201129028Sgreen	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
202127007Struckman	/*
203127007Struckman	 * Return EFAULT on error to match copy{in,out}() behaviour
204127007Struckman	 * rather than returning ENOMEM like mlock() would.
205127007Struckman	 */
206127007Struckman	return (error == KERN_SUCCESS ? 0 : EFAULT);
207126668Struckman}
208126668Struckman
209127007Struckmanvoid
210127008Struckmanvsunlock(void *addr, size_t len)
211126668Struckman{
212126668Struckman
213127007Struckman	/* Rely on the parameter sanity checks performed by vslock(). */
214127007Struckman	(void)vm_map_unwire(&curproc->p_vmspace->vm_map,
215127007Struckman	    trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len),
216127008Struckman	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
217126668Struckman}
218126668Struckman
219153485Salc/*
220153485Salc * Pin the page contained within the given object at the given offset.  If the
221153485Salc * page is not resident, allocate and load it using the given object's pager.
222153485Salc * Return the pinned page if successful; otherwise, return NULL.
223153485Salc */
224153485Salcstatic vm_page_t
225153485Salcvm_imgact_hold_page(vm_object_t object, vm_ooffset_t offset)
226153485Salc{
227153485Salc	vm_page_t m, ma[1];
228153485Salc	vm_pindex_t pindex;
229153485Salc	int rv;
230153485Salc
231153485Salc	VM_OBJECT_LOCK(object);
232153485Salc	pindex = OFF_TO_IDX(offset);
233153485Salc	m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
234193643Salc	if (m->valid != VM_PAGE_BITS_ALL) {
235153485Salc		ma[0] = m;
236153485Salc		rv = vm_pager_get_pages(object, ma, 1, 0);
237153485Salc		m = vm_page_lookup(object, pindex);
238153485Salc		if (m == NULL)
239153485Salc			goto out;
240193593Salc		if (rv != VM_PAGER_OK) {
241207410Skmacy			vm_page_lock(m);
242153485Salc			vm_page_free(m);
243207410Skmacy			vm_page_unlock(m);
244153485Salc			m = NULL;
245153485Salc			goto out;
246153485Salc		}
247153485Salc	}
248207410Skmacy	vm_page_lock(m);
249153485Salc	vm_page_hold(m);
250207410Skmacy	vm_page_unlock(m);
251153485Salc	vm_page_wakeup(m);
252153485Salcout:
253153485Salc	VM_OBJECT_UNLOCK(object);
254153485Salc	return (m);
255153485Salc}
256153485Salc
257153485Salc/*
258153485Salc * Return a CPU private mapping to the page at the given offset within the
259153485Salc * given object.  The page is pinned before it is mapped.
260153485Salc */
261153485Salcstruct sf_buf *
262153485Salcvm_imgact_map_page(vm_object_t object, vm_ooffset_t offset)
263153485Salc{
264153485Salc	vm_page_t m;
265153485Salc
266153485Salc	m = vm_imgact_hold_page(object, offset);
267153485Salc	if (m == NULL)
268153485Salc		return (NULL);
269153485Salc	sched_pin();
270153485Salc	return (sf_buf_alloc(m, SFB_CPUPRIVATE));
271153485Salc}
272153485Salc
273153485Salc/*
274153485Salc * Destroy the given CPU private mapping and unpin the page that it mapped.
275153485Salc */
276153485Salcvoid
277153485Salcvm_imgact_unmap_page(struct sf_buf *sf)
278153485Salc{
279153485Salc	vm_page_t m;
280153485Salc
281153485Salc	m = sf_buf_page(sf);
282153485Salc	sf_buf_free(sf);
283153485Salc	sched_unpin();
284207410Skmacy	vm_page_lock(m);
285153485Salc	vm_page_unhold(m);
286207410Skmacy	vm_page_unlock(m);
287153485Salc}
288153485Salc
289198341Smarcelvoid
290198341Smarcelvm_sync_icache(vm_map_t map, vm_offset_t va, vm_offset_t sz)
291198341Smarcel{
292198341Smarcel
293198341Smarcel	pmap_sync_icache(map->pmap, va, sz);
294198341Smarcel}
295198341Smarcel
296229251Skibstruct kstack_cache_entry *kstack_cache;
297196730Skibstatic int kstack_cache_size = 128;
298196730Skibstatic int kstacks;
299196730Skibstatic struct mtx kstack_cache_mtx;
300196730SkibSYSCTL_INT(_vm, OID_AUTO, kstack_cache_size, CTLFLAG_RW, &kstack_cache_size, 0,
301196730Skib    "");
302196730SkibSYSCTL_INT(_vm, OID_AUTO, kstacks, CTLFLAG_RD, &kstacks, 0,
303196730Skib    "");
304196730Skib
305116355Salc#ifndef KSTACK_MAX_PAGES
306116355Salc#define KSTACK_MAX_PAGES 32
307116355Salc#endif
308116355Salc
30999559Speter/*
310116355Salc * Create the kernel stack (including pcb for i386) for a new thread.
311116355Salc * This routine directly affects the fork perf for a process and
312116355Salc * create performance for a thread.
313116355Salc */
314173361Skibint
315116355Salcvm_thread_new(struct thread *td, int pages)
316116355Salc{
317116355Salc	vm_object_t ksobj;
318116355Salc	vm_offset_t ks;
319116355Salc	vm_page_t m, ma[KSTACK_MAX_PAGES];
320196730Skib	struct kstack_cache_entry *ks_ce;
321116355Salc	int i;
322116355Salc
323116355Salc	/* Bounds check */
324116355Salc	if (pages <= 1)
325116355Salc		pages = KSTACK_PAGES;
326116355Salc	else if (pages > KSTACK_MAX_PAGES)
327116355Salc		pages = KSTACK_MAX_PAGES;
328196730Skib
329196730Skib	if (pages == KSTACK_PAGES) {
330196730Skib		mtx_lock(&kstack_cache_mtx);
331196730Skib		if (kstack_cache != NULL) {
332196730Skib			ks_ce = kstack_cache;
333196730Skib			kstack_cache = ks_ce->next_ks_entry;
334196730Skib			mtx_unlock(&kstack_cache_mtx);
335196730Skib
336196730Skib			td->td_kstack_obj = ks_ce->ksobj;
337196730Skib			td->td_kstack = (vm_offset_t)ks_ce;
338196730Skib			td->td_kstack_pages = KSTACK_PAGES;
339196730Skib			return (1);
340196730Skib		}
341196730Skib		mtx_unlock(&kstack_cache_mtx);
342196730Skib	}
343196730Skib
344116355Salc	/*
345116355Salc	 * Allocate an object for the kstack.
346116355Salc	 */
347116355Salc	ksobj = vm_object_allocate(OBJT_DEFAULT, pages);
348177368Sjeff
349116355Salc	/*
350116355Salc	 * Get a kernel virtual address for this thread's kstack.
351116355Salc	 */
352206819Sjmallett#if defined(__mips__)
353206819Sjmallett	/*
354206819Sjmallett	 * We need to align the kstack's mapped address to fit within
355206819Sjmallett	 * a single TLB entry.
356206819Sjmallett	 */
357206819Sjmallett	ks = kmem_alloc_nofault_space(kernel_map,
358206819Sjmallett	    (pages + KSTACK_GUARD_PAGES) * PAGE_SIZE, VMFS_TLB_ALIGNED_SPACE);
359206819Sjmallett#else
360116355Salc	ks = kmem_alloc_nofault(kernel_map,
361116355Salc	   (pages + KSTACK_GUARD_PAGES) * PAGE_SIZE);
362206819Sjmallett#endif
363173361Skib	if (ks == 0) {
364173361Skib		printf("vm_thread_new: kstack allocation failed\n");
365173361Skib		vm_object_deallocate(ksobj);
366173361Skib		return (0);
367173361Skib	}
368196730Skib
369196730Skib	atomic_add_int(&kstacks, 1);
370116355Salc	if (KSTACK_GUARD_PAGES != 0) {
371116355Salc		pmap_qremove(ks, KSTACK_GUARD_PAGES);
372116355Salc		ks += KSTACK_GUARD_PAGES * PAGE_SIZE;
373116355Salc	}
374173361Skib	td->td_kstack_obj = ksobj;
375116355Salc	td->td_kstack = ks;
376116355Salc	/*
377116355Salc	 * Knowing the number of pages allocated is useful when you
378116355Salc	 * want to deallocate them.
379116355Salc	 */
380116355Salc	td->td_kstack_pages = pages;
381116355Salc	/*
382116355Salc	 * For the length of the stack, link in a real page of ram for each
383116355Salc	 * page of stack.
384116355Salc	 */
385116355Salc	VM_OBJECT_LOCK(ksobj);
386116355Salc	for (i = 0; i < pages; i++) {
387116355Salc		/*
388116355Salc		 * Get a kernel stack page.
389116355Salc		 */
390136923Salc		m = vm_page_grab(ksobj, i, VM_ALLOC_NOBUSY |
391116355Salc		    VM_ALLOC_NORMAL | VM_ALLOC_RETRY | VM_ALLOC_WIRED);
392116355Salc		ma[i] = m;
393116355Salc		m->valid = VM_PAGE_BITS_ALL;
394116355Salc	}
395116355Salc	VM_OBJECT_UNLOCK(ksobj);
396116355Salc	pmap_qenter(ks, ma, pages);
397173361Skib	return (1);
398116355Salc}
399116355Salc
400196730Skibstatic void
401196730Skibvm_thread_stack_dispose(vm_object_t ksobj, vm_offset_t ks, int pages)
402116355Salc{
403116355Salc	vm_page_t m;
404196730Skib	int i;
405116355Salc
406196730Skib	atomic_add_int(&kstacks, -1);
407116355Salc	pmap_qremove(ks, pages);
408116355Salc	VM_OBJECT_LOCK(ksobj);
409116355Salc	for (i = 0; i < pages; i++) {
410116355Salc		m = vm_page_lookup(ksobj, i);
411116355Salc		if (m == NULL)
412116355Salc			panic("vm_thread_dispose: kstack already missing?");
413207410Skmacy		vm_page_lock(m);
414116355Salc		vm_page_unwire(m, 0);
415116355Salc		vm_page_free(m);
416207410Skmacy		vm_page_unlock(m);
417116355Salc	}
418116355Salc	VM_OBJECT_UNLOCK(ksobj);
419116355Salc	vm_object_deallocate(ksobj);
420116355Salc	kmem_free(kernel_map, ks - (KSTACK_GUARD_PAGES * PAGE_SIZE),
421116355Salc	    (pages + KSTACK_GUARD_PAGES) * PAGE_SIZE);
422196730Skib}
423196730Skib
424196730Skib/*
425196730Skib * Dispose of a thread's kernel stack.
426196730Skib */
427196730Skibvoid
428196730Skibvm_thread_dispose(struct thread *td)
429196730Skib{
430196730Skib	vm_object_t ksobj;
431196730Skib	vm_offset_t ks;
432196730Skib	struct kstack_cache_entry *ks_ce;
433196730Skib	int pages;
434196730Skib
435196730Skib	pages = td->td_kstack_pages;
436196730Skib	ksobj = td->td_kstack_obj;
437196730Skib	ks = td->td_kstack;
438173361Skib	td->td_kstack = 0;
439196730Skib	td->td_kstack_pages = 0;
440196730Skib	if (pages == KSTACK_PAGES && kstacks <= kstack_cache_size) {
441196730Skib		ks_ce = (struct kstack_cache_entry *)ks;
442196730Skib		ks_ce->ksobj = ksobj;
443196730Skib		mtx_lock(&kstack_cache_mtx);
444196730Skib		ks_ce->next_ks_entry = kstack_cache;
445196730Skib		kstack_cache = ks_ce;
446196730Skib		mtx_unlock(&kstack_cache_mtx);
447196730Skib		return;
448196730Skib	}
449196730Skib	vm_thread_stack_dispose(ksobj, ks, pages);
450116355Salc}
451116355Salc
452196730Skibstatic void
453196730Skibvm_thread_stack_lowmem(void *nulll)
454196730Skib{
455196730Skib	struct kstack_cache_entry *ks_ce, *ks_ce1;
456196730Skib
457196730Skib	mtx_lock(&kstack_cache_mtx);
458196730Skib	ks_ce = kstack_cache;
459196730Skib	kstack_cache = NULL;
460196730Skib	mtx_unlock(&kstack_cache_mtx);
461196730Skib
462196730Skib	while (ks_ce != NULL) {
463196730Skib		ks_ce1 = ks_ce;
464196730Skib		ks_ce = ks_ce->next_ks_entry;
465196730Skib
466196730Skib		vm_thread_stack_dispose(ks_ce1->ksobj, (vm_offset_t)ks_ce1,
467196730Skib		    KSTACK_PAGES);
468196730Skib	}
469196730Skib}
470196730Skib
471196730Skibstatic void
472196730Skibkstack_cache_init(void *nulll)
473196730Skib{
474196730Skib
475196730Skib	EVENTHANDLER_REGISTER(vm_lowmem, vm_thread_stack_lowmem, NULL,
476196730Skib	    EVENTHANDLER_PRI_ANY);
477196730Skib}
478196730Skib
479196730SkibMTX_SYSINIT(kstack_cache, &kstack_cache_mtx, "kstkch", MTX_DEF);
480196730SkibSYSINIT(vm_kstacks, SI_SUB_KTHREAD_INIT, SI_ORDER_ANY, kstack_cache_init, NULL);
481196730Skib
482206483Salc#ifndef NO_SWAPPING
483116355Salc/*
484116355Salc * Allow a thread's kernel stack to be paged out.
485116355Salc */
486206483Salcstatic void
487116355Salcvm_thread_swapout(struct thread *td)
488116355Salc{
489116355Salc	vm_object_t ksobj;
490116355Salc	vm_page_t m;
491116355Salc	int i, pages;
492116355Salc
493119004Smarcel	cpu_thread_swapout(td);
494116355Salc	pages = td->td_kstack_pages;
495116355Salc	ksobj = td->td_kstack_obj;
496116355Salc	pmap_qremove(td->td_kstack, pages);
497116355Salc	VM_OBJECT_LOCK(ksobj);
498116355Salc	for (i = 0; i < pages; i++) {
499116355Salc		m = vm_page_lookup(ksobj, i);
500116355Salc		if (m == NULL)
501116355Salc			panic("vm_thread_swapout: kstack already missing?");
502206823Salc		vm_page_dirty(m);
503207410Skmacy		vm_page_lock(m);
504116355Salc		vm_page_unwire(m, 0);
505207410Skmacy		vm_page_unlock(m);
506116355Salc	}
507116355Salc	VM_OBJECT_UNLOCK(ksobj);
508116355Salc}
509116355Salc
510116355Salc/*
511116355Salc * Bring the kernel stack for a specified thread back in.
512116355Salc */
513206483Salcstatic void
514116355Salcvm_thread_swapin(struct thread *td)
515116355Salc{
516116355Salc	vm_object_t ksobj;
517207365Skib	vm_page_t ma[KSTACK_MAX_PAGES];
518207365Skib	int i, j, k, pages, rv;
519116355Salc
520116355Salc	pages = td->td_kstack_pages;
521116355Salc	ksobj = td->td_kstack_obj;
522116355Salc	VM_OBJECT_LOCK(ksobj);
523207365Skib	for (i = 0; i < pages; i++)
524207365Skib		ma[i] = vm_page_grab(ksobj, i, VM_ALLOC_NORMAL | VM_ALLOC_RETRY |
525207365Skib		    VM_ALLOC_WIRED);
526116355Salc	for (i = 0; i < pages; i++) {
527207365Skib		if (ma[i]->valid != VM_PAGE_BITS_ALL) {
528207365Skib			KASSERT(ma[i]->oflags & VPO_BUSY,
529207365Skib			    ("lost busy 1"));
530207365Skib			vm_object_pip_add(ksobj, 1);
531207365Skib			for (j = i + 1; j < pages; j++) {
532207365Skib				KASSERT(ma[j]->valid == VM_PAGE_BITS_ALL ||
533207365Skib				    (ma[j]->oflags & VPO_BUSY),
534207365Skib				    ("lost busy 2"));
535207365Skib				if (ma[j]->valid == VM_PAGE_BITS_ALL)
536207365Skib					break;
537207365Skib			}
538207365Skib			rv = vm_pager_get_pages(ksobj, ma + i, j - i, 0);
539116355Salc			if (rv != VM_PAGER_OK)
540207365Skib	panic("vm_thread_swapin: cannot get kstack for proc: %d",
541207365Skib				    td->td_proc->p_pid);
542207365Skib			vm_object_pip_wakeup(ksobj);
543207365Skib			for (k = i; k < j; k++)
544207365Skib				ma[k] = vm_page_lookup(ksobj, k);
545207365Skib			vm_page_wakeup(ma[i]);
546207365Skib		} else if (ma[i]->oflags & VPO_BUSY)
547207365Skib			vm_page_wakeup(ma[i]);
548116355Salc	}
549116355Salc	VM_OBJECT_UNLOCK(ksobj);
550116355Salc	pmap_qenter(td->td_kstack, ma, pages);
551119004Smarcel	cpu_thread_swapin(td);
552116355Salc}
553206483Salc#endif /* !NO_SWAPPING */
554116355Salc
555116355Salc/*
5561541Srgrimes * Implement fork's actions on an address space.
5571541Srgrimes * Here we arrange for the address space to be copied or referenced,
5581541Srgrimes * allocate a user struct (pcb and kernel stack), then call the
5591541Srgrimes * machine-dependent layer to fill those in and make the new process
56024691Speter * ready to run.  The new process is set up so that it returns directly
56124691Speter * to user mode to avoid stack copying and relocation problems.
5621541Srgrimes */
563173361Skibint
564173361Skibvm_forkproc(td, p2, td2, vm2, flags)
56583366Sjulian	struct thread *td;
56683366Sjulian	struct proc *p2;
56790361Sjulian	struct thread *td2;
568173361Skib	struct vmspace *vm2;
56924691Speter	int flags;
5701541Srgrimes{
57183366Sjulian	struct proc *p1 = td->td_proc;
572173361Skib	int error;
5731541Srgrimes
57454188Sluoqi	if ((flags & RFPROC) == 0) {
57554188Sluoqi		/*
57654188Sluoqi		 * Divorce the memory, if it is shared, essentially
57754188Sluoqi		 * this changes shared memory amongst threads, into
57854188Sluoqi		 * COW locally.
57954188Sluoqi		 */
58054188Sluoqi		if ((flags & RFMEM) == 0) {
58154188Sluoqi			if (p1->p_vmspace->vm_refcnt > 1) {
582173361Skib				error = vmspace_unshare(p1);
583173361Skib				if (error)
584173361Skib					return (error);
58554188Sluoqi			}
58654188Sluoqi		}
58790361Sjulian		cpu_fork(td, p2, td2, flags);
588173361Skib		return (0);
58954188Sluoqi	}
59054188Sluoqi
59124848Sdyson	if (flags & RFMEM) {
59224848Sdyson		p2->p_vmspace = p1->p_vmspace;
593132684Salc		atomic_add_int(&p1->p_vmspace->vm_refcnt, 1);
59424848Sdyson	}
59524848Sdyson
59651337Sdillon	while (vm_page_count_severe()) {
5971549Srgrimes		VM_WAIT;
5985455Sdg	}
5991549Srgrimes
60024848Sdyson	if ((flags & RFMEM) == 0) {
601173361Skib		p2->p_vmspace = vm2;
60224691Speter		if (p1->p_vmspace->vm_shm)
60324691Speter			shmfork(p1, p2);
60424691Speter	}
6051541Srgrimes
60615018Sdyson	/*
60724691Speter	 * cpu_fork will copy and update the pcb, set up the kernel stack,
60824691Speter	 * and make the child ready to run.
6091541Srgrimes	 */
61090361Sjulian	cpu_fork(td, p2, td2, flags);
611173361Skib	return (0);
6121541Srgrimes}
6131541Srgrimes
6141541Srgrimes/*
61583276Speter * Called after process has been wait(2)'ed apon and is being reaped.
61683276Speter * The idea is to reclaim resources that we could not reclaim while
61783276Speter * the process was still executing.
61883276Speter */
61983276Spetervoid
62083276Spetervm_waitproc(p)
62183276Speter	struct proc *p;
62283276Speter{
62383276Speter
62490263Salfred	vmspace_exitfree(p);		/* and clean-out the vmspace */
62583276Speter}
62683276Speter
6271549Srgrimesvoid
6281549Srgrimesfaultin(p)
6295455Sdg	struct proc *p;
6301549Srgrimes{
631113918Sjhb#ifdef NO_SWAPPING
632113918Sjhb
633113918Sjhb	PROC_LOCK_ASSERT(p, MA_OWNED);
634172207Sjeff	if ((p->p_flag & P_INMEM) == 0)
635113918Sjhb		panic("faultin: proc swapped out with NO_SWAPPING!");
636113918Sjhb#else /* !NO_SWAPPING */
637113867Sjhb	struct thread *td;
63899559Speter
63976641Sjhb	PROC_LOCK_ASSERT(p, MA_OWNED);
640113867Sjhb	/*
641113867Sjhb	 * If another process is swapping in this process,
642113867Sjhb	 * just wait until it finishes.
643113867Sjhb	 */
644172207Sjeff	if (p->p_flag & P_SWAPPINGIN) {
645172207Sjeff		while (p->p_flag & P_SWAPPINGIN)
646172207Sjeff			msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
647172207Sjeff		return;
648172207Sjeff	}
649172207Sjeff	if ((p->p_flag & P_INMEM) == 0) {
650100884Sjulian		/*
651113867Sjhb		 * Don't let another thread swap process p out while we are
652113867Sjhb		 * busy swapping it in.
653100884Sjulian		 */
654113867Sjhb		++p->p_lock;
655172207Sjeff		p->p_flag |= P_SWAPPINGIN;
65671610Sjhb		PROC_UNLOCK(p);
6571549Srgrimes
658172207Sjeff		/*
659172207Sjeff		 * We hold no lock here because the list of threads
660172207Sjeff		 * can not change while all threads in the process are
661172207Sjeff		 * swapped out.
662172207Sjeff		 */
663113867Sjhb		FOREACH_THREAD_IN_PROC(p, td)
664116355Salc			vm_thread_swapin(td);
66571610Sjhb		PROC_LOCK(p);
666172207Sjeff		swapclear(p);
667172268Sjeff		p->p_swtick = ticks;
6681549Srgrimes
669172207Sjeff		wakeup(&p->p_flag);
6701549Srgrimes
671113867Sjhb		/* Allow other threads to swap p out now. */
6721549Srgrimes		--p->p_lock;
6731549Srgrimes	}
674113918Sjhb#endif /* NO_SWAPPING */
6755455Sdg}
6761549Srgrimes
6771541Srgrimes/*
6781549Srgrimes * This swapin algorithm attempts to swap-in processes only if there
6791549Srgrimes * is enough space for them.  Of course, if a process waits for a long
6801549Srgrimes * time, it will be swapped in anyway.
68165557Sjasone *
682146501Salc * Giant is held on entry.
6831541Srgrimes */
684254692Savgvoid
685254692Savgswapper(void)
6861541Srgrimes{
68779242Sdillon	struct proc *p;
68899072Sjulian	struct thread *td;
6891541Srgrimes	struct proc *pp;
690172268Sjeff	int slptime;
691172268Sjeff	int swtime;
6921541Srgrimes	int ppri;
693172268Sjeff	int pri;
6941541Srgrimes
6951541Srgrimesloop:
69651337Sdillon	if (vm_page_count_min()) {
6975455Sdg		VM_WAIT;
69851337Sdillon		goto loop;
6995455Sdg	}
7001549Srgrimes
7011541Srgrimes	pp = NULL;
7021541Srgrimes	ppri = INT_MIN;
70374927Sjhb	sx_slock(&allproc_lock);
70483366Sjulian	FOREACH_PROC_IN_SYSTEM(p) {
705172207Sjeff		PROC_LOCK(p);
706220390Sjhb		if (p->p_state == PRS_NEW ||
707220390Sjhb		    p->p_flag & (P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) {
708172207Sjeff			PROC_UNLOCK(p);
70999072Sjulian			continue;
71099072Sjulian		}
711172268Sjeff		swtime = (ticks - p->p_swtick) / hz;
71299072Sjulian		FOREACH_THREAD_IN_PROC(p, td) {
713100884Sjulian			/*
714103216Sjulian			 * An otherwise runnable thread of a process
715103216Sjulian			 * swapped out has only the TDI_SWAPPED bit set.
716103216Sjulian			 *
717100884Sjulian			 */
718170307Sjeff			thread_lock(td);
719103216Sjulian			if (td->td_inhibitors == TDI_SWAPPED) {
720172268Sjeff				slptime = (ticks - td->td_slptick) / hz;
721172268Sjeff				pri = swtime + slptime;
722172207Sjeff				if ((td->td_flags & TDF_SWAPINREQ) == 0)
723130551Sjulian					pri -= p->p_nice * 8;
72483366Sjulian				/*
725164936Sjulian				 * if this thread is higher priority
72683366Sjulian				 * and there is enough space, then select
72783366Sjulian				 * this process instead of the previous
72883366Sjulian				 * selection.
72983366Sjulian				 */
73083366Sjulian				if (pri > ppri) {
73183366Sjulian					pp = p;
73283366Sjulian					ppri = pri;
73383366Sjulian				}
73418974Sdyson			}
735170307Sjeff			thread_unlock(td);
7361541Srgrimes		}
737172207Sjeff		PROC_UNLOCK(p);
7381541Srgrimes	}
73974927Sjhb	sx_sunlock(&allproc_lock);
7401549Srgrimes
7411541Srgrimes	/*
74218974Sdyson	 * Nothing to do, back to sleep.
7431541Srgrimes	 */
7441541Srgrimes	if ((p = pp) == NULL) {
745254692Savg		tsleep(&proc0, PVM, "swapin", MAXSLP * hz / 2);
7461541Srgrimes		goto loop;
7471541Srgrimes	}
748100884Sjulian	PROC_LOCK(p);
749100884Sjulian
750100884Sjulian	/*
751100884Sjulian	 * Another process may be bringing or may have already
752100884Sjulian	 * brought this process in while we traverse all threads.
753100884Sjulian	 * Or, this process may even be being swapped out again.
754100884Sjulian	 */
755172207Sjeff	if (p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) {
756100884Sjulian		PROC_UNLOCK(p);
757100884Sjulian		goto loop;
758100884Sjulian	}
759100884Sjulian
7601541Srgrimes	/*
7611549Srgrimes	 * We would like to bring someone in. (only if there is space).
76299072Sjulian	 * [What checks the space? ]
7631541Srgrimes	 */
7645455Sdg	faultin(p);
76571610Sjhb	PROC_UNLOCK(p);
7661541Srgrimes	goto loop;
7671541Srgrimes}
7681541Srgrimes
769181334Sjhbvoid
770181334Sjhbkick_proc0(void)
771146554Sups{
772146554Sups
773181334Sjhb	wakeup(&proc0);
774146554Sups}
775146554Sups
77614178Sdg#ifndef NO_SWAPPING
77714178Sdg
7781541Srgrimes/*
77931563Sdyson * Swap_idle_threshold1 is the guaranteed swapped in time for a process
78031563Sdyson */
78133181Seivindstatic int swap_idle_threshold1 = 2;
782113600StrhodesSYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1, CTLFLAG_RW,
783113603Strhodes    &swap_idle_threshold1, 0, "Guaranteed swapped in time for a process");
78431563Sdyson
78531563Sdyson/*
78631563Sdyson * Swap_idle_threshold2 is the time that a process can be idle before
78731563Sdyson * it will be swapped out, if idle swapping is enabled.
78831563Sdyson */
78933181Seivindstatic int swap_idle_threshold2 = 10;
790113600StrhodesSYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2, CTLFLAG_RW,
791113603Strhodes    &swap_idle_threshold2, 0, "Time before a process will be swapped out");
79231563Sdyson
79331563Sdyson/*
794217192Skib * First, if any processes have been sleeping or stopped for at least
795217192Skib * "swap_idle_threshold1" seconds, they are swapped out.  If, however,
796217192Skib * no such processes exist, then the longest-sleeping or stopped
797217192Skib * process is swapped out.  Finally, and only as a last resort, if
798217192Skib * there are no sleeping or stopped processes, the longest-resident
799217192Skib * process is swapped out.
8001541Srgrimes */
8011541Srgrimesvoid
80231667Sdysonswapout_procs(action)
80331667Sdysonint action;
8041541Srgrimes{
80579242Sdillon	struct proc *p;
80699072Sjulian	struct thread *td;
8071541Srgrimes	int didswap = 0;
8081541Srgrimes
80977089Sjhbretry:
81074927Sjhb	sx_slock(&allproc_lock);
81199072Sjulian	FOREACH_PROC_IN_SYSTEM(p) {
81215809Sdyson		struct vmspace *vm;
81383366Sjulian		int minslptime = 100000;
814172268Sjeff		int slptime;
81571570Sjhb
816100913Stanimura		/*
817103123Stanimura		 * Watch out for a process in
818103123Stanimura		 * creation.  It may have no
819105695Sjhb		 * address space or lock yet.
820105695Sjhb		 */
821172207Sjeff		if (p->p_state == PRS_NEW)
822105695Sjhb			continue;
823105695Sjhb		/*
824103123Stanimura		 * An aio daemon switches its
825103123Stanimura		 * address space while running.
826103123Stanimura		 * Perform a quick check whether
827103123Stanimura		 * a process has P_SYSTEM.
828100913Stanimura		 */
829114030Sjhb		if ((p->p_flag & P_SYSTEM) != 0)
830103123Stanimura			continue;
831105695Sjhb		/*
832105695Sjhb		 * Do not swapout a process that
833105695Sjhb		 * is waiting for VM data
834105695Sjhb		 * structures as there is a possible
835105695Sjhb		 * deadlock.  Test this first as
836105695Sjhb		 * this may block.
837105695Sjhb		 *
838105695Sjhb		 * Lock the map until swapout
839105695Sjhb		 * finishes, or a thread of this
840105695Sjhb		 * process may attempt to alter
841105695Sjhb		 * the map.
842105695Sjhb		 */
843159054Stegge		vm = vmspace_acquire_ref(p);
844159054Stegge		if (vm == NULL)
845159054Stegge			continue;
846100913Stanimura		if (!vm_map_trylock(&vm->vm_map))
847100913Stanimura			goto nextproc1;
848100913Stanimura
84971570Sjhb		PROC_LOCK(p);
85071574Sjhb		if (p->p_lock != 0 ||
851102950Sdavidxu		    (p->p_flag & (P_STOPPED_SINGLE|P_TRACED|P_SYSTEM|P_WEXIT)
852102950Sdavidxu		    ) != 0) {
853177368Sjeff			goto nextproc;
85471570Sjhb		}
85576827Salfred		/*
85676827Salfred		 * only aiod changes vmspace, however it will be
85776827Salfred		 * skipped because of the if statement above checking
85876827Salfred		 * for P_SYSTEM
85976827Salfred		 */
860172207Sjeff		if ((p->p_flag & (P_INMEM|P_SWAPPINGOUT|P_SWAPPINGIN)) != P_INMEM)
861177368Sjeff			goto nextproc;
862113867Sjhb
86399072Sjulian		switch (p->p_state) {
8645455Sdg		default:
86599072Sjulian			/* Don't swap out processes in any sort
86699072Sjulian			 * of 'special' state. */
867114030Sjhb			break;
8685455Sdg
86999072Sjulian		case PRS_NORMAL:
8701549Srgrimes			/*
8715455Sdg			 * do not swapout a realtime process
87283366Sjulian			 * Check all the thread groups..
8735455Sdg			 */
874163709Sjb			FOREACH_THREAD_IN_PROC(p, td) {
875172207Sjeff				thread_lock(td);
876172207Sjeff				if (PRI_IS_REALTIME(td->td_pri_class)) {
877172207Sjeff					thread_unlock(td);
87883366Sjulian					goto nextproc;
879172207Sjeff				}
880172268Sjeff				slptime = (ticks - td->td_slptick) / hz;
88183366Sjulian				/*
882100913Stanimura				 * Guarantee swap_idle_threshold1
88383366Sjulian				 * time in memory.
88483366Sjulian				 */
885172268Sjeff				if (slptime < swap_idle_threshold1) {
886172207Sjeff					thread_unlock(td);
88783366Sjulian					goto nextproc;
888172207Sjeff				}
889100913Stanimura
890100884Sjulian				/*
891100913Stanimura				 * Do not swapout a process if it is
892100913Stanimura				 * waiting on a critical event of some
893100913Stanimura				 * kind or there is a thread whose
894100913Stanimura				 * pageable memory may be accessed.
895100884Sjulian				 *
896100884Sjulian				 * This could be refined to support
897100884Sjulian				 * swapping out a thread.
898100884Sjulian				 */
899177085Sjeff				if (!thread_safetoswapout(td)) {
900172207Sjeff					thread_unlock(td);
901163709Sjb					goto nextproc;
902172207Sjeff				}
90383366Sjulian				/*
90483366Sjulian				 * If the system is under memory stress,
90583366Sjulian				 * or if we are swapping
90683366Sjulian				 * idle processes >= swap_idle_threshold2,
90783366Sjulian				 * then swap the process out.
90883366Sjulian				 */
90983366Sjulian				if (((action & VM_SWAP_NORMAL) == 0) &&
91083366Sjulian				    (((action & VM_SWAP_IDLE) == 0) ||
911172268Sjeff				    (slptime < swap_idle_threshold2))) {
912172207Sjeff					thread_unlock(td);
91383366Sjulian					goto nextproc;
914172207Sjeff				}
915100913Stanimura
916172268Sjeff				if (minslptime > slptime)
917172268Sjeff					minslptime = slptime;
918172207Sjeff				thread_unlock(td);
91969509Sjhb			}
9205455Sdg
9215455Sdg			/*
922131163Sdas			 * If the pageout daemon didn't free enough pages,
923131163Sdas			 * or if this process is idle and the system is
924131163Sdas			 * configured to swap proactively, swap it out.
9252692Sdg			 */
92631563Sdyson			if ((action & VM_SWAP_NORMAL) ||
92731563Sdyson				((action & VM_SWAP_IDLE) &&
92883366Sjulian				 (minslptime > swap_idle_threshold2))) {
929172207Sjeff				if (swapout(p) == 0)
930172207Sjeff					didswap++;
931113867Sjhb				PROC_UNLOCK(p);
932100913Stanimura				vm_map_unlock(&vm->vm_map);
93331563Sdyson				vmspace_free(vm);
934100913Stanimura				sx_sunlock(&allproc_lock);
93531563Sdyson				goto retry;
93676641Sjhb			}
9371541Srgrimes		}
938177368Sjeffnextproc:
939100913Stanimura		PROC_UNLOCK(p);
940100913Stanimura		vm_map_unlock(&vm->vm_map);
941100913Stanimuranextproc1:
942100913Stanimura		vmspace_free(vm);
94392666Speter		continue;
9441541Srgrimes	}
94574927Sjhb	sx_sunlock(&allproc_lock);
9461541Srgrimes	/*
9471549Srgrimes	 * If we swapped something out, and another process needed memory,
9481549Srgrimes	 * then wakeup the sched process.
9491549Srgrimes	 */
9505455Sdg	if (didswap)
9519507Sdg		wakeup(&proc0);
9521541Srgrimes}
9531541Srgrimes
95412820Sphkstatic void
955172207Sjeffswapclear(p)
956172207Sjeff	struct proc *p;
957172207Sjeff{
958172207Sjeff	struct thread *td;
959172207Sjeff
960172207Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
961172207Sjeff
962172207Sjeff	FOREACH_THREAD_IN_PROC(p, td) {
963172207Sjeff		thread_lock(td);
964172207Sjeff		td->td_flags |= TDF_INMEM;
965172207Sjeff		td->td_flags &= ~TDF_SWAPINREQ;
966172207Sjeff		TD_CLR_SWAPPED(td);
967172207Sjeff		if (TD_CAN_RUN(td))
968181334Sjhb			if (setrunnable(td)) {
969181334Sjhb#ifdef INVARIANTS
970181334Sjhb				/*
971181334Sjhb				 * XXX: We just cleared TDI_SWAPPED
972181334Sjhb				 * above and set TDF_INMEM, so this
973181334Sjhb				 * should never happen.
974181334Sjhb				 */
975181334Sjhb				panic("not waking up swapper");
976181334Sjhb#endif
977181334Sjhb			}
978172207Sjeff		thread_unlock(td);
979172207Sjeff	}
980172207Sjeff	p->p_flag &= ~(P_SWAPPINGIN|P_SWAPPINGOUT);
981172207Sjeff	p->p_flag |= P_INMEM;
982172207Sjeff}
983172207Sjeff
984172207Sjeffstatic int
9851541Srgrimesswapout(p)
98679242Sdillon	struct proc *p;
9871541Srgrimes{
98883366Sjulian	struct thread *td;
9891541Srgrimes
99076778Sjhb	PROC_LOCK_ASSERT(p, MA_OWNED);
99115153Sdyson#if defined(SWAP_DEBUG)
99215153Sdyson	printf("swapping out %d\n", p->p_pid);
99315153Sdyson#endif
994100884Sjulian
995100884Sjulian	/*
996100913Stanimura	 * The states of this process and its threads may have changed
997100913Stanimura	 * by now.  Assuming that there is only one pageout daemon thread,
998100913Stanimura	 * this process should still be in memory.
999100913Stanimura	 */
1000172207Sjeff	KASSERT((p->p_flag & (P_INMEM|P_SWAPPINGOUT|P_SWAPPINGIN)) == P_INMEM,
1001100913Stanimura		("swapout: lost a swapout race?"));
1002100913Stanimura
1003100913Stanimura	/*
1004172207Sjeff	 * remember the process resident count
1005100884Sjulian	 */
1006172207Sjeff	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
10071541Srgrimes	/*
1008172207Sjeff	 * Check and mark all threads before we proceed.
10091541Srgrimes	 */
1010172207Sjeff	p->p_flag &= ~P_INMEM;
1011172207Sjeff	p->p_flag |= P_SWAPPINGOUT;
1012170307Sjeff	FOREACH_THREAD_IN_PROC(p, td) {
1013170307Sjeff		thread_lock(td);
1014172207Sjeff		if (!thread_safetoswapout(td)) {
1015172207Sjeff			thread_unlock(td);
1016172207Sjeff			swapclear(p);
1017172207Sjeff			return (EBUSY);
1018172207Sjeff		}
1019172207Sjeff		td->td_flags &= ~TDF_INMEM;
1020113867Sjhb		TD_SET_SWAPPED(td);
1021170307Sjeff		thread_unlock(td);
1022170307Sjeff	}
1023172207Sjeff	td = FIRST_THREAD_IN_PROC(p);
1024172207Sjeff	++td->td_ru.ru_nswap;
1025172207Sjeff	PROC_UNLOCK(p);
10261549Srgrimes
1027172207Sjeff	/*
1028172207Sjeff	 * This list is stable because all threads are now prevented from
1029172207Sjeff	 * running.  The list is only modified in the context of a running
1030172207Sjeff	 * thread in this process.
1031172207Sjeff	 */
1032113867Sjhb	FOREACH_THREAD_IN_PROC(p, td)
1033116355Salc		vm_thread_swapout(td);
1034113867Sjhb
1035113867Sjhb	PROC_LOCK(p);
1036172207Sjeff	p->p_flag &= ~P_SWAPPINGOUT;
1037172268Sjeff	p->p_swtick = ticks;
1038172207Sjeff	return (0);
10391541Srgrimes}
104014178Sdg#endif /* !NO_SWAPPING */
1041