xref: /freebsd/sys/vm/vm_glue.c (revision 09e8dea79366f1e5b3a73e8a271b26e4b6bf2e6a)
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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	from: @(#)vm_glue.c	8.6 (Berkeley) 1/5/94
37  *
38  *
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  *
62  * $FreeBSD$
63  */
64 
65 #include "opt_vm.h"
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/lock.h>
70 #include <sys/mutex.h>
71 #include <sys/proc.h>
72 #include <sys/resourcevar.h>
73 #include <sys/shm.h>
74 #include <sys/vmmeter.h>
75 #include <sys/sx.h>
76 #include <sys/sysctl.h>
77 
78 #include <sys/kernel.h>
79 #include <sys/ktr.h>
80 #include <sys/unistd.h>
81 
82 #include <machine/limits.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_kern.h>
91 #include <vm/vm_extern.h>
92 
93 #include <sys/user.h>
94 
95 extern int maxslp;
96 
97 /*
98  * System initialization
99  *
100  * Note: proc0 from proc.h
101  */
102 static void vm_init_limits(void *);
103 SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
104 
105 /*
106  * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
107  *
108  * Note: run scheduling should be divorced from the vm system.
109  */
110 static void scheduler(void *);
111 SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, scheduler, NULL)
112 
113 #ifndef NO_SWAPPING
114 static void swapout(struct proc *);
115 #endif
116 
117 /*
118  * MPSAFE
119  */
120 int
121 kernacc(addr, len, rw)
122 	caddr_t addr;
123 	int len, rw;
124 {
125 	boolean_t rv;
126 	vm_offset_t saddr, eaddr;
127 	vm_prot_t prot;
128 
129 	KASSERT((rw & ~VM_PROT_ALL) == 0,
130 	    ("illegal ``rw'' argument to kernacc (%x)\n", rw));
131 	prot = rw;
132 	saddr = trunc_page((vm_offset_t)addr);
133 	eaddr = round_page((vm_offset_t)addr + len);
134 	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
135 	return (rv == TRUE);
136 }
137 
138 /*
139  * MPSAFE
140  */
141 int
142 useracc(addr, len, rw)
143 	caddr_t addr;
144 	int len, rw;
145 {
146 	boolean_t rv;
147 	vm_prot_t prot;
148 
149 	KASSERT((rw & ~VM_PROT_ALL) == 0,
150 	    ("illegal ``rw'' argument to useracc (%x)\n", rw));
151 	prot = rw;
152 	/*
153 	 * XXX - check separately to disallow access to user area and user
154 	 * page tables - they are in the map.
155 	 *
156 	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  It was once
157 	 * only used (as an end address) in trap.c.  Use it as an end address
158 	 * here too.  This bogusness has spread.  I just fixed where it was
159 	 * used as a max in vm_mmap.c.
160 	 */
161 	if ((vm_offset_t) addr + len > /* XXX */ VM_MAXUSER_ADDRESS
162 	    || (vm_offset_t) addr + len < (vm_offset_t) addr) {
163 		return (FALSE);
164 	}
165 	rv = vm_map_check_protection(&curproc->p_vmspace->vm_map,
166 	    trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len),
167 	    prot);
168 	return (rv == TRUE);
169 }
170 
171 /*
172  * MPSAFE
173  */
174 void
175 vslock(addr, len)
176 	caddr_t addr;
177 	u_int len;
178 {
179 
180 	vm_map_wire(&curproc->p_vmspace->vm_map, trunc_page((vm_offset_t)addr),
181 	    round_page((vm_offset_t)addr + len), FALSE);
182 }
183 
184 /*
185  * MPSAFE
186  */
187 void
188 vsunlock(addr, len)
189 	caddr_t addr;
190 	u_int len;
191 {
192 
193 	vm_map_unwire(&curproc->p_vmspace->vm_map,
194 	    trunc_page((vm_offset_t)addr),
195 	    round_page((vm_offset_t)addr + len), FALSE);
196 }
197 
198 /*
199  * Implement fork's actions on an address space.
200  * Here we arrange for the address space to be copied or referenced,
201  * allocate a user struct (pcb and kernel stack), then call the
202  * machine-dependent layer to fill those in and make the new process
203  * ready to run.  The new process is set up so that it returns directly
204  * to user mode to avoid stack copying and relocation problems.
205  */
206 void
207 vm_forkproc(td, p2, td2, flags)
208 	struct thread *td;
209 	struct proc *p2;
210 	struct thread *td2;
211 	int flags;
212 {
213 	struct proc *p1 = td->td_proc;
214 	struct user *up;
215 
216 	GIANT_REQUIRED;
217 
218 	if ((flags & RFPROC) == 0) {
219 		/*
220 		 * Divorce the memory, if it is shared, essentially
221 		 * this changes shared memory amongst threads, into
222 		 * COW locally.
223 		 */
224 		if ((flags & RFMEM) == 0) {
225 			if (p1->p_vmspace->vm_refcnt > 1) {
226 				vmspace_unshare(p1);
227 			}
228 		}
229 		cpu_fork(td, p2, td2, flags);
230 		return;
231 	}
232 
233 	if (flags & RFMEM) {
234 		p2->p_vmspace = p1->p_vmspace;
235 		p1->p_vmspace->vm_refcnt++;
236 	}
237 
238 	while (vm_page_count_severe()) {
239 		VM_WAIT;
240 	}
241 
242 	if ((flags & RFMEM) == 0) {
243 		p2->p_vmspace = vmspace_fork(p1->p_vmspace);
244 
245 		pmap_pinit2(vmspace_pmap(p2->p_vmspace));
246 
247 		if (p1->p_vmspace->vm_shm)
248 			shmfork(p1, p2);
249 	}
250 
251 	pmap_new_proc(p2);
252 	pmap_new_thread(td2);		/* Initial thread */
253 
254 	/* XXXKSE this is unsatisfactory but should be adequate */
255 	up = p2->p_uarea;
256 
257 	/*
258 	 * p_stats currently points at fields in the user struct
259 	 * but not at &u, instead at p_addr. Copy parts of
260 	 * p_stats; zero the rest of p_stats (statistics).
261 	 *
262 	 * If procsig->ps_refcnt is 1 and p2->p_sigacts is NULL we dont' need
263 	 * to share sigacts, so we use the up->u_sigacts.
264 	 */
265 	p2->p_stats = &up->u_stats;
266 	if (p2->p_sigacts == NULL) {
267 		if (p2->p_procsig->ps_refcnt != 1)
268 			printf ("PID:%d NULL sigacts with refcnt not 1!\n",p2->p_pid);
269 		p2->p_sigacts = &up->u_sigacts;
270 		up->u_sigacts = *p1->p_sigacts;
271 	}
272 
273 	bzero(&up->u_stats.pstat_startzero,
274 	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
275 		(caddr_t) &up->u_stats.pstat_startzero));
276 	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
277 	    ((caddr_t) &up->u_stats.pstat_endcopy -
278 		(caddr_t) &up->u_stats.pstat_startcopy));
279 
280 
281 	/*
282 	 * cpu_fork will copy and update the pcb, set up the kernel stack,
283 	 * and make the child ready to run.
284 	 */
285 	cpu_fork(td, p2, td2, flags);
286 }
287 
288 /*
289  * Called after process has been wait(2)'ed apon and is being reaped.
290  * The idea is to reclaim resources that we could not reclaim while
291  * the process was still executing.
292  */
293 void
294 vm_waitproc(p)
295 	struct proc *p;
296 {
297 	struct thread *td;
298 
299 	GIANT_REQUIRED;
300 	cpu_wait(p);
301 	pmap_dispose_proc(p);		/* drop per-process resources */
302 	FOREACH_THREAD_IN_PROC(p, td)
303 		pmap_dispose_thread(td);
304 	vmspace_exitfree(p);		/* and clean-out the vmspace */
305 }
306 
307 /*
308  * Set default limits for VM system.
309  * Called for proc 0, and then inherited by all others.
310  *
311  * XXX should probably act directly on proc0.
312  */
313 static void
314 vm_init_limits(udata)
315 	void *udata;
316 {
317 	struct proc *p = udata;
318 	int rss_limit;
319 
320 	/*
321 	 * Set up the initial limits on process VM. Set the maximum resident
322 	 * set size to be half of (reasonably) available memory.  Since this
323 	 * is a soft limit, it comes into effect only when the system is out
324 	 * of memory - half of main memory helps to favor smaller processes,
325 	 * and reduces thrashing of the object cache.
326 	 */
327 	p->p_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
328 	p->p_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
329 	p->p_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
330 	p->p_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
331 	/* limit the limit to no less than 2MB */
332 	rss_limit = max(cnt.v_free_count, 512);
333 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
334 	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
335 }
336 
337 void
338 faultin(p)
339 	struct proc *p;
340 {
341 	struct thread *td;
342 	GIANT_REQUIRED;
343 
344 	PROC_LOCK_ASSERT(p, MA_OWNED);
345 	mtx_lock_spin(&sched_lock);
346 	if ((p->p_sflag & PS_INMEM) == 0) {
347 		++p->p_lock;
348 		mtx_unlock_spin(&sched_lock);
349 		PROC_UNLOCK(p);
350 
351 		pmap_swapin_proc(p);
352 		FOREACH_THREAD_IN_PROC (p, td)
353 			pmap_swapin_thread(td);
354 
355 		PROC_LOCK(p);
356 		mtx_lock_spin(&sched_lock);
357 		FOREACH_THREAD_IN_PROC (p, td)
358 			if (td->td_proc->p_stat == SRUN)	/* XXXKSE */
359 				setrunqueue(td);
360 
361 		p->p_sflag |= PS_INMEM;
362 
363 		/* undo the effect of setting SLOCK above */
364 		--p->p_lock;
365 	}
366 	mtx_unlock_spin(&sched_lock);
367 }
368 
369 /*
370  * This swapin algorithm attempts to swap-in processes only if there
371  * is enough space for them.  Of course, if a process waits for a long
372  * time, it will be swapped in anyway.
373  *
374  *  XXXKSE - KSEGRP with highest priority counts..
375  *
376  * Giant is still held at this point, to be released in tsleep.
377  */
378 /* ARGSUSED*/
379 static void
380 scheduler(dummy)
381 	void *dummy;
382 {
383 	struct proc *p;
384 	int pri;
385 	struct proc *pp;
386 	int ppri;
387 
388 	mtx_assert(&Giant, MA_OWNED | MA_NOTRECURSED);
389 	/* GIANT_REQUIRED */
390 
391 loop:
392 	if (vm_page_count_min()) {
393 		VM_WAIT;
394 		goto loop;
395 	}
396 
397 	pp = NULL;
398 	ppri = INT_MIN;
399 	sx_slock(&allproc_lock);
400 	FOREACH_PROC_IN_SYSTEM(p) {
401 		struct ksegrp *kg;
402 		mtx_lock_spin(&sched_lock);
403 		if (p->p_stat == SRUN
404 		&& (p->p_sflag & (PS_INMEM | PS_SWAPPING)) == 0) {
405 			/* Find the minimum sleeptime for the process */
406 			FOREACH_KSEGRP_IN_PROC(p, kg) {
407 				pri = p->p_swtime + kg->kg_slptime;
408 				if ((p->p_sflag & PS_SWAPINREQ) == 0) {
409 					pri -= kg->kg_nice * 8;
410 				}
411 
412 				/*
413 				 * if this ksegrp is higher priority
414 				 * and there is enough space, then select
415 				 * this process instead of the previous
416 				 * selection.
417 				 */
418 				if (pri > ppri) {
419 					pp = p;
420 					ppri = pri;
421 				}
422 			}
423 		}
424 		mtx_unlock_spin(&sched_lock);
425 	}
426 	sx_sunlock(&allproc_lock);
427 
428 	/*
429 	 * Nothing to do, back to sleep.
430 	 */
431 	if ((p = pp) == NULL) {
432 		tsleep(&proc0, PVM, "sched", maxslp * hz / 2);
433 		goto loop;
434 	}
435 	mtx_lock_spin(&sched_lock);
436 	p->p_sflag &= ~PS_SWAPINREQ;
437 	mtx_unlock_spin(&sched_lock);
438 
439 	/*
440 	 * We would like to bring someone in. (only if there is space).
441 	 */
442 	PROC_LOCK(p);
443 	faultin(p);
444 	PROC_UNLOCK(p);
445 	mtx_lock_spin(&sched_lock);
446 	p->p_swtime = 0;
447 	mtx_unlock_spin(&sched_lock);
448 	goto loop;
449 }
450 
451 #ifndef NO_SWAPPING
452 
453 /*
454  * Swap_idle_threshold1 is the guaranteed swapped in time for a process
455  */
456 static int swap_idle_threshold1 = 2;
457 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1,
458 	CTLFLAG_RW, &swap_idle_threshold1, 0, "");
459 
460 /*
461  * Swap_idle_threshold2 is the time that a process can be idle before
462  * it will be swapped out, if idle swapping is enabled.
463  */
464 static int swap_idle_threshold2 = 10;
465 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2,
466 	CTLFLAG_RW, &swap_idle_threshold2, 0, "");
467 
468 /*
469  * Swapout is driven by the pageout daemon.  Very simple, we find eligible
470  * procs and unwire their u-areas.  We try to always "swap" at least one
471  * process in case we need the room for a swapin.
472  * If any procs have been sleeping/stopped for at least maxslp seconds,
473  * they are swapped.  Else, we swap the longest-sleeping or stopped process,
474  * if any, otherwise the longest-resident process.
475  */
476 void
477 swapout_procs(action)
478 int action;
479 {
480 	struct proc *p;
481 	struct ksegrp *kg;
482 	struct proc *outp, *outp2;
483 	int outpri, outpri2;
484 	int didswap = 0;
485 
486 	GIANT_REQUIRED;
487 
488 	outp = outp2 = NULL;
489 	outpri = outpri2 = INT_MIN;
490 retry:
491 	sx_slock(&allproc_lock);
492 	LIST_FOREACH(p, &allproc, p_list) {
493 		struct vmspace *vm;
494 		int minslptime = 100000;
495 
496 		PROC_LOCK(p);
497 		if (p->p_lock != 0 ||
498 		    (p->p_flag & (P_TRACED|P_SYSTEM|P_WEXIT)) != 0) {
499 			PROC_UNLOCK(p);
500 			continue;
501 		}
502 		/*
503 		 * only aiod changes vmspace, however it will be
504 		 * skipped because of the if statement above checking
505 		 * for P_SYSTEM
506 		 */
507 		vm = p->p_vmspace;
508 		mtx_lock_spin(&sched_lock);
509 		if ((p->p_sflag & (PS_INMEM|PS_SWAPPING)) != PS_INMEM) {
510 			mtx_unlock_spin(&sched_lock);
511 			PROC_UNLOCK(p);
512 			continue;
513 		}
514 
515 		switch (p->p_stat) {
516 		default:
517 			mtx_unlock_spin(&sched_lock);
518 			PROC_UNLOCK(p);
519 			continue;
520 
521 		case SSLEEP:
522 		case SSTOP:
523 			/*
524 			 * do not swapout a realtime process
525 			 * Check all the thread groups..
526 			 */
527 			FOREACH_KSEGRP_IN_PROC(p, kg) {
528 				if (PRI_IS_REALTIME(kg->kg_pri_class)) {
529 					mtx_unlock_spin(&sched_lock);
530 					PROC_UNLOCK(p);
531 					goto nextproc;
532 				}
533 
534 				/*
535 				 * Do not swapout a process waiting
536 				 * on a critical event of some kind.
537 				 * Also guarantee swap_idle_threshold1
538 				 * time in memory.
539 				 */
540 				if (((FIRST_THREAD_IN_PROC(p)->td_priority) < PSOCK) ||
541 				    (kg->kg_slptime < swap_idle_threshold1)) {
542 					mtx_unlock_spin(&sched_lock);
543 					PROC_UNLOCK(p);
544 					goto nextproc;
545 				}
546 
547 				/*
548 				 * If the system is under memory stress,
549 				 * or if we are swapping
550 				 * idle processes >= swap_idle_threshold2,
551 				 * then swap the process out.
552 				 */
553 				if (((action & VM_SWAP_NORMAL) == 0) &&
554 				    (((action & VM_SWAP_IDLE) == 0) ||
555 				    (kg->kg_slptime < swap_idle_threshold2))) {
556 					mtx_unlock_spin(&sched_lock);
557 					PROC_UNLOCK(p);
558 					goto nextproc;
559 				}
560 				if (minslptime > kg->kg_slptime)
561 					minslptime = kg->kg_slptime;
562 			}
563 
564 			mtx_unlock_spin(&sched_lock);
565 			++vm->vm_refcnt;
566 			/*
567 			 * do not swapout a process that
568 			 * is waiting for VM
569 			 * data structures there is a
570 			 * possible deadlock.
571 			 */
572 			if (!vm_map_trylock(&vm->vm_map)) {
573 				vmspace_free(vm);
574 				PROC_UNLOCK(p);
575 				goto nextproc;
576 			}
577 			vm_map_unlock(&vm->vm_map);
578 			/*
579 			 * If the process has been asleep for awhile and had
580 			 * most of its pages taken away already, swap it out.
581 			 */
582 			if ((action & VM_SWAP_NORMAL) ||
583 				((action & VM_SWAP_IDLE) &&
584 				 (minslptime > swap_idle_threshold2))) {
585 				sx_sunlock(&allproc_lock);
586 				swapout(p);
587 				vmspace_free(vm);
588 				didswap++;
589 				goto retry;
590 			}
591 			PROC_UNLOCK(p);
592 			vmspace_free(vm);
593 		}
594 nextproc:
595 		continue;
596 	}
597 	sx_sunlock(&allproc_lock);
598 	/*
599 	 * If we swapped something out, and another process needed memory,
600 	 * then wakeup the sched process.
601 	 */
602 	if (didswap)
603 		wakeup(&proc0);
604 }
605 
606 static void
607 swapout(p)
608 	struct proc *p;
609 {
610 	struct thread *td;
611 
612 	PROC_LOCK_ASSERT(p, MA_OWNED);
613 #if defined(SWAP_DEBUG)
614 	printf("swapping out %d\n", p->p_pid);
615 #endif
616 	++p->p_stats->p_ru.ru_nswap;
617 	/*
618 	 * remember the process resident count
619 	 */
620 	p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
621 
622 	mtx_lock_spin(&sched_lock);
623 	p->p_sflag &= ~PS_INMEM;
624 	p->p_sflag |= PS_SWAPPING;
625 	PROC_UNLOCK(p);
626 	FOREACH_THREAD_IN_PROC (p, td)
627 		if (td->td_proc->p_stat == SRUN)	/* XXXKSE */
628 			remrunqueue(td);	/* XXXKSE */
629 	mtx_unlock_spin(&sched_lock);
630 
631 	pmap_swapout_proc(p);
632 	FOREACH_THREAD_IN_PROC(p, td)
633 		pmap_swapout_thread(td);
634 
635 	mtx_lock_spin(&sched_lock);
636 	p->p_sflag &= ~PS_SWAPPING;
637 	p->p_swtime = 0;
638 	mtx_unlock_spin(&sched_lock);
639 }
640 #endif /* !NO_SWAPPING */
641