xref: /freebsd/sys/vm/vm_glue.c (revision 30d239bc4c510432e65a84fa1c14ed67a3ab1c92)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	from: @(#)vm_glue.c	8.6 (Berkeley) 1/5/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Permission to use, copy, modify and distribute this software and
39  * its documentation is hereby granted, provided that both the copyright
40  * notice and this permission notice appear in all copies of the
41  * software, derivative works or modified versions, and any portions
42  * thereof, and that both notices appear in supporting documentation.
43  *
44  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
45  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
46  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
47  *
48  * Carnegie Mellon requests users of this software to return to
49  *
50  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
51  *  School of Computer Science
52  *  Carnegie Mellon University
53  *  Pittsburgh PA 15213-3890
54  *
55  * any improvements or extensions that they make and grant Carnegie the
56  * rights to redistribute these changes.
57  */
58 
59 #include <sys/cdefs.h>
60 __FBSDID("$FreeBSD$");
61 
62 #include "opt_vm.h"
63 #include "opt_kstack_pages.h"
64 #include "opt_kstack_max_pages.h"
65 
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/limits.h>
69 #include <sys/lock.h>
70 #include <sys/mutex.h>
71 #include <sys/proc.h>
72 #include <sys/resourcevar.h>
73 #include <sys/sched.h>
74 #include <sys/sf_buf.h>
75 #include <sys/shm.h>
76 #include <sys/vmmeter.h>
77 #include <sys/sx.h>
78 #include <sys/sysctl.h>
79 
80 #include <sys/kernel.h>
81 #include <sys/ktr.h>
82 #include <sys/unistd.h>
83 
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_object.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
93 #include <vm/vm_pager.h>
94 #include <vm/swap_pager.h>
95 
96 extern int maxslp;
97 
98 /*
99  * System initialization
100  *
101  * Note: proc0 from proc.h
102  */
103 static void vm_init_limits(void *);
104 SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
105 
106 /*
107  * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
108  *
109  * Note: run scheduling should be divorced from the vm system.
110  */
111 static void scheduler(void *);
112 SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_ANY, scheduler, NULL)
113 
114 #ifndef NO_SWAPPING
115 static int swapout(struct proc *);
116 static void swapclear(struct proc *);
117 #endif
118 
119 
120 static volatile int proc0_rescan;
121 
122 
123 /*
124  * MPSAFE
125  *
126  * WARNING!  This code calls vm_map_check_protection() which only checks
127  * the associated vm_map_entry range.  It does not determine whether the
128  * contents of the memory is actually readable or writable.  In most cases
129  * just checking the vm_map_entry is sufficient within the kernel's address
130  * space.
131  */
132 int
133 kernacc(addr, len, rw)
134 	void *addr;
135 	int len, rw;
136 {
137 	boolean_t rv;
138 	vm_offset_t saddr, eaddr;
139 	vm_prot_t prot;
140 
141 	KASSERT((rw & ~VM_PROT_ALL) == 0,
142 	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
143 
144 	if ((vm_offset_t)addr + len > kernel_map->max_offset ||
145 	    (vm_offset_t)addr + len < (vm_offset_t)addr)
146 		return (FALSE);
147 
148 	prot = rw;
149 	saddr = trunc_page((vm_offset_t)addr);
150 	eaddr = round_page((vm_offset_t)addr + len);
151 	vm_map_lock_read(kernel_map);
152 	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
153 	vm_map_unlock_read(kernel_map);
154 	return (rv == TRUE);
155 }
156 
157 /*
158  * MPSAFE
159  *
160  * WARNING!  This code calls vm_map_check_protection() which only checks
161  * the associated vm_map_entry range.  It does not determine whether the
162  * contents of the memory is actually readable or writable.  vmapbuf(),
163  * vm_fault_quick(), or copyin()/copout()/su*()/fu*() functions should be
164  * used in conjuction with this call.
165  */
166 int
167 useracc(addr, len, rw)
168 	void *addr;
169 	int len, rw;
170 {
171 	boolean_t rv;
172 	vm_prot_t prot;
173 	vm_map_t map;
174 
175 	KASSERT((rw & ~VM_PROT_ALL) == 0,
176 	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
177 	prot = rw;
178 	map = &curproc->p_vmspace->vm_map;
179 	if ((vm_offset_t)addr + len > vm_map_max(map) ||
180 	    (vm_offset_t)addr + len < (vm_offset_t)addr) {
181 		return (FALSE);
182 	}
183 	vm_map_lock_read(map);
184 	rv = vm_map_check_protection(map, trunc_page((vm_offset_t)addr),
185 	    round_page((vm_offset_t)addr + len), prot);
186 	vm_map_unlock_read(map);
187 	return (rv == TRUE);
188 }
189 
190 int
191 vslock(void *addr, size_t len)
192 {
193 	vm_offset_t end, last, start;
194 	vm_size_t npages;
195 	int error;
196 
197 	last = (vm_offset_t)addr + len;
198 	start = trunc_page((vm_offset_t)addr);
199 	end = round_page(last);
200 	if (last < (vm_offset_t)addr || end < (vm_offset_t)addr)
201 		return (EINVAL);
202 	npages = atop(end - start);
203 	if (npages > vm_page_max_wired)
204 		return (ENOMEM);
205 	PROC_LOCK(curproc);
206 	if (ptoa(npages +
207 	    pmap_wired_count(vm_map_pmap(&curproc->p_vmspace->vm_map))) >
208 	    lim_cur(curproc, RLIMIT_MEMLOCK)) {
209 		PROC_UNLOCK(curproc);
210 		return (ENOMEM);
211 	}
212 	PROC_UNLOCK(curproc);
213 #if 0
214 	/*
215 	 * XXX - not yet
216 	 *
217 	 * The limit for transient usage of wired pages should be
218 	 * larger than for "permanent" wired pages (mlock()).
219 	 *
220 	 * Also, the sysctl code, which is the only present user
221 	 * of vslock(), does a hard loop on EAGAIN.
222 	 */
223 	if (npages + cnt.v_wire_count > vm_page_max_wired)
224 		return (EAGAIN);
225 #endif
226 	error = vm_map_wire(&curproc->p_vmspace->vm_map, start, end,
227 	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
228 	/*
229 	 * Return EFAULT on error to match copy{in,out}() behaviour
230 	 * rather than returning ENOMEM like mlock() would.
231 	 */
232 	return (error == KERN_SUCCESS ? 0 : EFAULT);
233 }
234 
235 void
236 vsunlock(void *addr, size_t len)
237 {
238 
239 	/* Rely on the parameter sanity checks performed by vslock(). */
240 	(void)vm_map_unwire(&curproc->p_vmspace->vm_map,
241 	    trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len),
242 	    VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
243 }
244 
245 /*
246  * Pin the page contained within the given object at the given offset.  If the
247  * page is not resident, allocate and load it using the given object's pager.
248  * Return the pinned page if successful; otherwise, return NULL.
249  */
250 static vm_page_t
251 vm_imgact_hold_page(vm_object_t object, vm_ooffset_t offset)
252 {
253 	vm_page_t m, ma[1];
254 	vm_pindex_t pindex;
255 	int rv;
256 
257 	VM_OBJECT_LOCK(object);
258 	pindex = OFF_TO_IDX(offset);
259 	m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
260 	if ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
261 		ma[0] = m;
262 		rv = vm_pager_get_pages(object, ma, 1, 0);
263 		m = vm_page_lookup(object, pindex);
264 		if (m == NULL)
265 			goto out;
266 		if (m->valid == 0 || rv != VM_PAGER_OK) {
267 			vm_page_lock_queues();
268 			vm_page_free(m);
269 			vm_page_unlock_queues();
270 			m = NULL;
271 			goto out;
272 		}
273 	}
274 	vm_page_lock_queues();
275 	vm_page_hold(m);
276 	vm_page_unlock_queues();
277 	vm_page_wakeup(m);
278 out:
279 	VM_OBJECT_UNLOCK(object);
280 	return (m);
281 }
282 
283 /*
284  * Return a CPU private mapping to the page at the given offset within the
285  * given object.  The page is pinned before it is mapped.
286  */
287 struct sf_buf *
288 vm_imgact_map_page(vm_object_t object, vm_ooffset_t offset)
289 {
290 	vm_page_t m;
291 
292 	m = vm_imgact_hold_page(object, offset);
293 	if (m == NULL)
294 		return (NULL);
295 	sched_pin();
296 	return (sf_buf_alloc(m, SFB_CPUPRIVATE));
297 }
298 
299 /*
300  * Destroy the given CPU private mapping and unpin the page that it mapped.
301  */
302 void
303 vm_imgact_unmap_page(struct sf_buf *sf)
304 {
305 	vm_page_t m;
306 
307 	m = sf_buf_page(sf);
308 	sf_buf_free(sf);
309 	sched_unpin();
310 	vm_page_lock_queues();
311 	vm_page_unhold(m);
312 	vm_page_unlock_queues();
313 }
314 
315 #ifndef KSTACK_MAX_PAGES
316 #define KSTACK_MAX_PAGES 32
317 #endif
318 
319 /*
320  * Create the kernel stack (including pcb for i386) for a new thread.
321  * This routine directly affects the fork perf for a process and
322  * create performance for a thread.
323  */
324 void
325 vm_thread_new(struct thread *td, int pages)
326 {
327 	vm_object_t ksobj;
328 	vm_offset_t ks;
329 	vm_page_t m, ma[KSTACK_MAX_PAGES];
330 	int i;
331 
332 	/* Bounds check */
333 	if (pages <= 1)
334 		pages = KSTACK_PAGES;
335 	else if (pages > KSTACK_MAX_PAGES)
336 		pages = KSTACK_MAX_PAGES;
337 	/*
338 	 * Allocate an object for the kstack.
339 	 */
340 	ksobj = vm_object_allocate(OBJT_DEFAULT, pages);
341 	td->td_kstack_obj = ksobj;
342 	/*
343 	 * Get a kernel virtual address for this thread's kstack.
344 	 */
345 	ks = kmem_alloc_nofault(kernel_map,
346 	   (pages + KSTACK_GUARD_PAGES) * PAGE_SIZE);
347 	if (ks == 0)
348 		panic("vm_thread_new: kstack allocation failed");
349 	if (KSTACK_GUARD_PAGES != 0) {
350 		pmap_qremove(ks, KSTACK_GUARD_PAGES);
351 		ks += KSTACK_GUARD_PAGES * PAGE_SIZE;
352 	}
353 	td->td_kstack = ks;
354 	/*
355 	 * Knowing the number of pages allocated is useful when you
356 	 * want to deallocate them.
357 	 */
358 	td->td_kstack_pages = pages;
359 	/*
360 	 * For the length of the stack, link in a real page of ram for each
361 	 * page of stack.
362 	 */
363 	VM_OBJECT_LOCK(ksobj);
364 	for (i = 0; i < pages; i++) {
365 		/*
366 		 * Get a kernel stack page.
367 		 */
368 		m = vm_page_grab(ksobj, i, VM_ALLOC_NOBUSY |
369 		    VM_ALLOC_NORMAL | VM_ALLOC_RETRY | VM_ALLOC_WIRED);
370 		ma[i] = m;
371 		m->valid = VM_PAGE_BITS_ALL;
372 	}
373 	VM_OBJECT_UNLOCK(ksobj);
374 	pmap_qenter(ks, ma, pages);
375 }
376 
377 /*
378  * Dispose of a thread's kernel stack.
379  */
380 void
381 vm_thread_dispose(struct thread *td)
382 {
383 	vm_object_t ksobj;
384 	vm_offset_t ks;
385 	vm_page_t m;
386 	int i, pages;
387 
388 	pages = td->td_kstack_pages;
389 	ksobj = td->td_kstack_obj;
390 	ks = td->td_kstack;
391 	pmap_qremove(ks, pages);
392 	VM_OBJECT_LOCK(ksobj);
393 	for (i = 0; i < pages; i++) {
394 		m = vm_page_lookup(ksobj, i);
395 		if (m == NULL)
396 			panic("vm_thread_dispose: kstack already missing?");
397 		vm_page_lock_queues();
398 		vm_page_unwire(m, 0);
399 		vm_page_free(m);
400 		vm_page_unlock_queues();
401 	}
402 	VM_OBJECT_UNLOCK(ksobj);
403 	vm_object_deallocate(ksobj);
404 	kmem_free(kernel_map, ks - (KSTACK_GUARD_PAGES * PAGE_SIZE),
405 	    (pages + KSTACK_GUARD_PAGES) * PAGE_SIZE);
406 }
407 
408 /*
409  * Allow a thread's kernel stack to be paged out.
410  */
411 void
412 vm_thread_swapout(struct thread *td)
413 {
414 	vm_object_t ksobj;
415 	vm_page_t m;
416 	int i, pages;
417 
418 	cpu_thread_swapout(td);
419 	pages = td->td_kstack_pages;
420 	ksobj = td->td_kstack_obj;
421 	pmap_qremove(td->td_kstack, pages);
422 	VM_OBJECT_LOCK(ksobj);
423 	for (i = 0; i < pages; i++) {
424 		m = vm_page_lookup(ksobj, i);
425 		if (m == NULL)
426 			panic("vm_thread_swapout: kstack already missing?");
427 		vm_page_lock_queues();
428 		vm_page_dirty(m);
429 		vm_page_unwire(m, 0);
430 		vm_page_unlock_queues();
431 	}
432 	VM_OBJECT_UNLOCK(ksobj);
433 }
434 
435 /*
436  * Bring the kernel stack for a specified thread back in.
437  */
438 void
439 vm_thread_swapin(struct thread *td)
440 {
441 	vm_object_t ksobj;
442 	vm_page_t m, ma[KSTACK_MAX_PAGES];
443 	int i, pages, rv;
444 
445 	pages = td->td_kstack_pages;
446 	ksobj = td->td_kstack_obj;
447 	VM_OBJECT_LOCK(ksobj);
448 	for (i = 0; i < pages; i++) {
449 		m = vm_page_grab(ksobj, i, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
450 		if (m->valid != VM_PAGE_BITS_ALL) {
451 			rv = vm_pager_get_pages(ksobj, &m, 1, 0);
452 			if (rv != VM_PAGER_OK)
453 				panic("vm_thread_swapin: cannot get kstack for proc: %d", td->td_proc->p_pid);
454 			m = vm_page_lookup(ksobj, i);
455 			m->valid = VM_PAGE_BITS_ALL;
456 		}
457 		ma[i] = m;
458 		vm_page_lock_queues();
459 		vm_page_wire(m);
460 		vm_page_unlock_queues();
461 		vm_page_wakeup(m);
462 	}
463 	VM_OBJECT_UNLOCK(ksobj);
464 	pmap_qenter(td->td_kstack, ma, pages);
465 	cpu_thread_swapin(td);
466 }
467 
468 /*
469  * Set up a variable-sized alternate kstack.
470  */
471 void
472 vm_thread_new_altkstack(struct thread *td, int pages)
473 {
474 
475 	td->td_altkstack = td->td_kstack;
476 	td->td_altkstack_obj = td->td_kstack_obj;
477 	td->td_altkstack_pages = td->td_kstack_pages;
478 
479 	vm_thread_new(td, pages);
480 }
481 
482 /*
483  * Restore the original kstack.
484  */
485 void
486 vm_thread_dispose_altkstack(struct thread *td)
487 {
488 
489 	vm_thread_dispose(td);
490 
491 	td->td_kstack = td->td_altkstack;
492 	td->td_kstack_obj = td->td_altkstack_obj;
493 	td->td_kstack_pages = td->td_altkstack_pages;
494 	td->td_altkstack = 0;
495 	td->td_altkstack_obj = NULL;
496 	td->td_altkstack_pages = 0;
497 }
498 
499 /*
500  * Implement fork's actions on an address space.
501  * Here we arrange for the address space to be copied or referenced,
502  * allocate a user struct (pcb and kernel stack), then call the
503  * machine-dependent layer to fill those in and make the new process
504  * ready to run.  The new process is set up so that it returns directly
505  * to user mode to avoid stack copying and relocation problems.
506  */
507 void
508 vm_forkproc(td, p2, td2, flags)
509 	struct thread *td;
510 	struct proc *p2;
511 	struct thread *td2;
512 	int flags;
513 {
514 	struct proc *p1 = td->td_proc;
515 
516 	if ((flags & RFPROC) == 0) {
517 		/*
518 		 * Divorce the memory, if it is shared, essentially
519 		 * this changes shared memory amongst threads, into
520 		 * COW locally.
521 		 */
522 		if ((flags & RFMEM) == 0) {
523 			if (p1->p_vmspace->vm_refcnt > 1) {
524 				vmspace_unshare(p1);
525 			}
526 		}
527 		cpu_fork(td, p2, td2, flags);
528 		return;
529 	}
530 
531 	if (flags & RFMEM) {
532 		p2->p_vmspace = p1->p_vmspace;
533 		atomic_add_int(&p1->p_vmspace->vm_refcnt, 1);
534 	}
535 
536 	while (vm_page_count_severe()) {
537 		VM_WAIT;
538 	}
539 
540 	if ((flags & RFMEM) == 0) {
541 		p2->p_vmspace = vmspace_fork(p1->p_vmspace);
542 		if (p1->p_vmspace->vm_shm)
543 			shmfork(p1, p2);
544 	}
545 
546 	/*
547 	 * cpu_fork will copy and update the pcb, set up the kernel stack,
548 	 * and make the child ready to run.
549 	 */
550 	cpu_fork(td, p2, td2, flags);
551 }
552 
553 /*
554  * Called after process has been wait(2)'ed apon and is being reaped.
555  * The idea is to reclaim resources that we could not reclaim while
556  * the process was still executing.
557  */
558 void
559 vm_waitproc(p)
560 	struct proc *p;
561 {
562 
563 	vmspace_exitfree(p);		/* and clean-out the vmspace */
564 }
565 
566 /*
567  * Set default limits for VM system.
568  * Called for proc 0, and then inherited by all others.
569  *
570  * XXX should probably act directly on proc0.
571  */
572 static void
573 vm_init_limits(udata)
574 	void *udata;
575 {
576 	struct proc *p = udata;
577 	struct plimit *limp;
578 	int rss_limit;
579 
580 	/*
581 	 * Set up the initial limits on process VM. Set the maximum resident
582 	 * set size to be half of (reasonably) available memory.  Since this
583 	 * is a soft limit, it comes into effect only when the system is out
584 	 * of memory - half of main memory helps to favor smaller processes,
585 	 * and reduces thrashing of the object cache.
586 	 */
587 	limp = p->p_limit;
588 	limp->pl_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
589 	limp->pl_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
590 	limp->pl_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
591 	limp->pl_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
592 	/* limit the limit to no less than 2MB */
593 	rss_limit = max(cnt.v_free_count, 512);
594 	limp->pl_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
595 	limp->pl_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
596 }
597 
598 void
599 faultin(p)
600 	struct proc *p;
601 {
602 #ifdef NO_SWAPPING
603 
604 	PROC_LOCK_ASSERT(p, MA_OWNED);
605 	if ((p->p_flag & P_INMEM) == 0)
606 		panic("faultin: proc swapped out with NO_SWAPPING!");
607 #else /* !NO_SWAPPING */
608 	struct thread *td;
609 
610 	PROC_LOCK_ASSERT(p, MA_OWNED);
611 	/*
612 	 * If another process is swapping in this process,
613 	 * just wait until it finishes.
614 	 */
615 	if (p->p_flag & P_SWAPPINGIN) {
616 		while (p->p_flag & P_SWAPPINGIN)
617 			msleep(&p->p_flag, &p->p_mtx, PVM, "faultin", 0);
618 		return;
619 	}
620 	if ((p->p_flag & P_INMEM) == 0) {
621 		/*
622 		 * Don't let another thread swap process p out while we are
623 		 * busy swapping it in.
624 		 */
625 		++p->p_lock;
626 		p->p_flag |= P_SWAPPINGIN;
627 		PROC_UNLOCK(p);
628 
629 		/*
630 		 * We hold no lock here because the list of threads
631 		 * can not change while all threads in the process are
632 		 * swapped out.
633 		 */
634 		FOREACH_THREAD_IN_PROC(p, td)
635 			vm_thread_swapin(td);
636 		PROC_LOCK(p);
637 		PROC_SLOCK(p);
638 		swapclear(p);
639 		p->p_swtick = ticks;
640 		PROC_SUNLOCK(p);
641 
642 		wakeup(&p->p_flag);
643 
644 		/* Allow other threads to swap p out now. */
645 		--p->p_lock;
646 	}
647 #endif /* NO_SWAPPING */
648 }
649 
650 /*
651  * This swapin algorithm attempts to swap-in processes only if there
652  * is enough space for them.  Of course, if a process waits for a long
653  * time, it will be swapped in anyway.
654  *
655  *  XXXKSE - process with the thread with highest priority counts..
656  *
657  * Giant is held on entry.
658  */
659 /* ARGSUSED*/
660 static void
661 scheduler(dummy)
662 	void *dummy;
663 {
664 	struct proc *p;
665 	struct thread *td;
666 	struct proc *pp;
667 	int slptime;
668 	int swtime;
669 	int ppri;
670 	int pri;
671 
672 	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
673 	mtx_unlock(&Giant);
674 
675 loop:
676 	if (vm_page_count_min()) {
677 		VM_WAIT;
678 		thread_lock(&thread0);
679 		proc0_rescan = 0;
680 		thread_unlock(&thread0);
681 		goto loop;
682 	}
683 
684 	pp = NULL;
685 	ppri = INT_MIN;
686 	sx_slock(&allproc_lock);
687 	FOREACH_PROC_IN_SYSTEM(p) {
688 		PROC_LOCK(p);
689 		if (p->p_flag & (P_SWAPPINGOUT | P_SWAPPINGIN | P_INMEM)) {
690 			PROC_UNLOCK(p);
691 			continue;
692 		}
693 		swtime = (ticks - p->p_swtick) / hz;
694 		PROC_SLOCK(p);
695 		FOREACH_THREAD_IN_PROC(p, td) {
696 			/*
697 			 * An otherwise runnable thread of a process
698 			 * swapped out has only the TDI_SWAPPED bit set.
699 			 *
700 			 */
701 			thread_lock(td);
702 			if (td->td_inhibitors == TDI_SWAPPED) {
703 				slptime = (ticks - td->td_slptick) / hz;
704 				pri = swtime + slptime;
705 				if ((td->td_flags & TDF_SWAPINREQ) == 0)
706 					pri -= p->p_nice * 8;
707 				/*
708 				 * if this thread is higher priority
709 				 * and there is enough space, then select
710 				 * this process instead of the previous
711 				 * selection.
712 				 */
713 				if (pri > ppri) {
714 					pp = p;
715 					ppri = pri;
716 				}
717 			}
718 			thread_unlock(td);
719 		}
720 		PROC_SUNLOCK(p);
721 		PROC_UNLOCK(p);
722 	}
723 	sx_sunlock(&allproc_lock);
724 
725 	/*
726 	 * Nothing to do, back to sleep.
727 	 */
728 	if ((p = pp) == NULL) {
729 		thread_lock(&thread0);
730 		if (!proc0_rescan) {
731 			TD_SET_IWAIT(&thread0);
732 			mi_switch(SW_VOL, NULL);
733 		}
734 		proc0_rescan = 0;
735 		thread_unlock(&thread0);
736 		goto loop;
737 	}
738 	PROC_LOCK(p);
739 
740 	/*
741 	 * Another process may be bringing or may have already
742 	 * brought this process in while we traverse all threads.
743 	 * Or, this process may even be being swapped out again.
744 	 */
745 	if (p->p_flag & (P_INMEM | P_SWAPPINGOUT | P_SWAPPINGIN)) {
746 		PROC_UNLOCK(p);
747 		thread_lock(&thread0);
748 		proc0_rescan = 0;
749 		thread_unlock(&thread0);
750 		goto loop;
751 	}
752 
753 	/*
754 	 * We would like to bring someone in. (only if there is space).
755 	 * [What checks the space? ]
756 	 */
757 	faultin(p);
758 	PROC_UNLOCK(p);
759 	thread_lock(&thread0);
760 	proc0_rescan = 0;
761 	thread_unlock(&thread0);
762 	goto loop;
763 }
764 
765 void kick_proc0(void)
766 {
767 	struct thread *td = &thread0;
768 
769 	/* XXX This will probably cause a LOR in some cases */
770 	thread_lock(td);
771 	if (TD_AWAITING_INTR(td)) {
772 		CTR2(KTR_INTR, "%s: sched_add %d", __func__, 0);
773 		TD_CLR_IWAIT(td);
774 		sched_add(td, SRQ_INTR);
775 	} else {
776 		proc0_rescan = 1;
777 		CTR2(KTR_INTR, "%s: state %d",
778 		    __func__, td->td_state);
779 	}
780 	thread_unlock(td);
781 
782 }
783 
784 
785 #ifndef NO_SWAPPING
786 
787 /*
788  * Swap_idle_threshold1 is the guaranteed swapped in time for a process
789  */
790 static int swap_idle_threshold1 = 2;
791 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1, CTLFLAG_RW,
792     &swap_idle_threshold1, 0, "Guaranteed swapped in time for a process");
793 
794 /*
795  * Swap_idle_threshold2 is the time that a process can be idle before
796  * it will be swapped out, if idle swapping is enabled.
797  */
798 static int swap_idle_threshold2 = 10;
799 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2, CTLFLAG_RW,
800     &swap_idle_threshold2, 0, "Time before a process will be swapped out");
801 
802 /*
803  * Swapout is driven by the pageout daemon.  Very simple, we find eligible
804  * procs and swap out their stacks.  We try to always "swap" at least one
805  * process in case we need the room for a swapin.
806  * If any procs have been sleeping/stopped for at least maxslp seconds,
807  * they are swapped.  Else, we swap the longest-sleeping or stopped process,
808  * if any, otherwise the longest-resident process.
809  */
810 void
811 swapout_procs(action)
812 int action;
813 {
814 	struct proc *p;
815 	struct thread *td;
816 	int didswap = 0;
817 
818 retry:
819 	sx_slock(&allproc_lock);
820 	FOREACH_PROC_IN_SYSTEM(p) {
821 		struct vmspace *vm;
822 		int minslptime = 100000;
823 		int slptime;
824 
825 		/*
826 		 * Watch out for a process in
827 		 * creation.  It may have no
828 		 * address space or lock yet.
829 		 */
830 		if (p->p_state == PRS_NEW)
831 			continue;
832 		/*
833 		 * An aio daemon switches its
834 		 * address space while running.
835 		 * Perform a quick check whether
836 		 * a process has P_SYSTEM.
837 		 */
838 		if ((p->p_flag & P_SYSTEM) != 0)
839 			continue;
840 		/*
841 		 * Do not swapout a process that
842 		 * is waiting for VM data
843 		 * structures as there is a possible
844 		 * deadlock.  Test this first as
845 		 * this may block.
846 		 *
847 		 * Lock the map until swapout
848 		 * finishes, or a thread of this
849 		 * process may attempt to alter
850 		 * the map.
851 		 */
852 		vm = vmspace_acquire_ref(p);
853 		if (vm == NULL)
854 			continue;
855 		if (!vm_map_trylock(&vm->vm_map))
856 			goto nextproc1;
857 
858 		PROC_LOCK(p);
859 		if (p->p_lock != 0 ||
860 		    (p->p_flag & (P_STOPPED_SINGLE|P_TRACED|P_SYSTEM|P_WEXIT)
861 		    ) != 0) {
862 			goto nextproc2;
863 		}
864 		/*
865 		 * only aiod changes vmspace, however it will be
866 		 * skipped because of the if statement above checking
867 		 * for P_SYSTEM
868 		 */
869 		if ((p->p_flag & (P_INMEM|P_SWAPPINGOUT|P_SWAPPINGIN)) != P_INMEM)
870 			goto nextproc2;
871 
872 		switch (p->p_state) {
873 		default:
874 			/* Don't swap out processes in any sort
875 			 * of 'special' state. */
876 			break;
877 
878 		case PRS_NORMAL:
879 			PROC_SLOCK(p);
880 			/*
881 			 * do not swapout a realtime process
882 			 * Check all the thread groups..
883 			 */
884 			FOREACH_THREAD_IN_PROC(p, td) {
885 				thread_lock(td);
886 				if (PRI_IS_REALTIME(td->td_pri_class)) {
887 					thread_unlock(td);
888 					goto nextproc;
889 				}
890 				slptime = (ticks - td->td_slptick) / hz;
891 				/*
892 				 * Guarantee swap_idle_threshold1
893 				 * time in memory.
894 				 */
895 				if (slptime < swap_idle_threshold1) {
896 					thread_unlock(td);
897 					goto nextproc;
898 				}
899 
900 				/*
901 				 * Do not swapout a process if it is
902 				 * waiting on a critical event of some
903 				 * kind or there is a thread whose
904 				 * pageable memory may be accessed.
905 				 *
906 				 * This could be refined to support
907 				 * swapping out a thread.
908 				 */
909 				if ((td->td_priority) < PSOCK ||
910 				    !thread_safetoswapout(td)) {
911 					thread_unlock(td);
912 					goto nextproc;
913 				}
914 				/*
915 				 * If the system is under memory stress,
916 				 * or if we are swapping
917 				 * idle processes >= swap_idle_threshold2,
918 				 * then swap the process out.
919 				 */
920 				if (((action & VM_SWAP_NORMAL) == 0) &&
921 				    (((action & VM_SWAP_IDLE) == 0) ||
922 				    (slptime < swap_idle_threshold2))) {
923 					thread_unlock(td);
924 					goto nextproc;
925 				}
926 
927 				if (minslptime > slptime)
928 					minslptime = slptime;
929 				thread_unlock(td);
930 			}
931 
932 			/*
933 			 * If the pageout daemon didn't free enough pages,
934 			 * or if this process is idle and the system is
935 			 * configured to swap proactively, swap it out.
936 			 */
937 			if ((action & VM_SWAP_NORMAL) ||
938 				((action & VM_SWAP_IDLE) &&
939 				 (minslptime > swap_idle_threshold2))) {
940 				if (swapout(p) == 0)
941 					didswap++;
942 				PROC_SUNLOCK(p);
943 				PROC_UNLOCK(p);
944 				vm_map_unlock(&vm->vm_map);
945 				vmspace_free(vm);
946 				sx_sunlock(&allproc_lock);
947 				goto retry;
948 			}
949 nextproc:
950 			PROC_SUNLOCK(p);
951 		}
952 nextproc2:
953 		PROC_UNLOCK(p);
954 		vm_map_unlock(&vm->vm_map);
955 nextproc1:
956 		vmspace_free(vm);
957 		continue;
958 	}
959 	sx_sunlock(&allproc_lock);
960 	/*
961 	 * If we swapped something out, and another process needed memory,
962 	 * then wakeup the sched process.
963 	 */
964 	if (didswap)
965 		wakeup(&proc0);
966 }
967 
968 static void
969 swapclear(p)
970 	struct proc *p;
971 {
972 	struct thread *td;
973 
974 	PROC_LOCK_ASSERT(p, MA_OWNED);
975 	PROC_SLOCK_ASSERT(p, MA_OWNED);
976 
977 	FOREACH_THREAD_IN_PROC(p, td) {
978 		thread_lock(td);
979 		td->td_flags |= TDF_INMEM;
980 		td->td_flags &= ~TDF_SWAPINREQ;
981 		TD_CLR_SWAPPED(td);
982 		if (TD_CAN_RUN(td))
983 			setrunnable(td);
984 		thread_unlock(td);
985 	}
986 	p->p_flag &= ~(P_SWAPPINGIN|P_SWAPPINGOUT);
987 	p->p_flag |= P_INMEM;
988 }
989 
990 static int
991 swapout(p)
992 	struct proc *p;
993 {
994 	struct thread *td;
995 
996 	PROC_LOCK_ASSERT(p, MA_OWNED);
997 	PROC_SLOCK_ASSERT(p, MA_OWNED | MA_NOTRECURSED);
998 #if defined(SWAP_DEBUG)
999 	printf("swapping out %d\n", p->p_pid);
1000 #endif
1001 
1002 	/*
1003 	 * The states of this process and its threads may have changed
1004 	 * by now.  Assuming that there is only one pageout daemon thread,
1005 	 * this process should still be in memory.
1006 	 */
1007 	KASSERT((p->p_flag & (P_INMEM|P_SWAPPINGOUT|P_SWAPPINGIN)) == P_INMEM,
1008 		("swapout: lost a swapout race?"));
1009 
1010 	/*
1011 	 * remember the process resident count
1012 	 */
1013 	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
1014 	/*
1015 	 * Check and mark all threads before we proceed.
1016 	 */
1017 	p->p_flag &= ~P_INMEM;
1018 	p->p_flag |= P_SWAPPINGOUT;
1019 	FOREACH_THREAD_IN_PROC(p, td) {
1020 		thread_lock(td);
1021 		if (!thread_safetoswapout(td)) {
1022 			thread_unlock(td);
1023 			swapclear(p);
1024 			return (EBUSY);
1025 		}
1026 		td->td_flags &= ~TDF_INMEM;
1027 		TD_SET_SWAPPED(td);
1028 		thread_unlock(td);
1029 	}
1030 	td = FIRST_THREAD_IN_PROC(p);
1031 	++td->td_ru.ru_nswap;
1032 	PROC_SUNLOCK(p);
1033 	PROC_UNLOCK(p);
1034 
1035 	/*
1036 	 * This list is stable because all threads are now prevented from
1037 	 * running.  The list is only modified in the context of a running
1038 	 * thread in this process.
1039 	 */
1040 	FOREACH_THREAD_IN_PROC(p, td)
1041 		vm_thread_swapout(td);
1042 
1043 	PROC_LOCK(p);
1044 	p->p_flag &= ~P_SWAPPINGOUT;
1045 	PROC_SLOCK(p);
1046 	p->p_swtick = ticks;
1047 	return (0);
1048 }
1049 #endif /* !NO_SWAPPING */
1050