xref: /freebsd/sys/vm/vm_glue.c (revision 17ee9d00bc1ae1e598c38f25826f861e4bc6c3ce)
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  * $Id: vm_glue.c,v 1.16 1995/02/20 17:26:21 davidg Exp $
63  */
64 
65 #include <sys/param.h>
66 #include <sys/systm.h>
67 #include <sys/proc.h>
68 #include <sys/resourcevar.h>
69 #include <sys/buf.h>
70 #include <sys/user.h>
71 
72 #include <sys/kernel.h>
73 #include <sys/dkstat.h>
74 
75 #include <vm/vm.h>
76 #include <vm/vm_page.h>
77 #include <vm/vm_pageout.h>
78 #include <vm/vm_kern.h>
79 
80 #include <machine/stdarg.h>
81 #include <machine/cpu.h>
82 
83 extern char kstack[];
84 int avefree = 0;		/* XXX */
85 int readbuffers = 0;		/* XXX allow kgdb to read kernel buffer pool */
86 
87 /* vm_map_t upages_map; */
88 
89 int
90 kernacc(addr, len, rw)
91 	caddr_t addr;
92 	int len, rw;
93 {
94 	boolean_t rv;
95 	vm_offset_t saddr, eaddr;
96 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
97 
98 	saddr = trunc_page(addr);
99 	eaddr = round_page(addr + len);
100 	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
101 	return (rv == TRUE);
102 }
103 
104 int
105 useracc(addr, len, rw)
106 	caddr_t addr;
107 	int len, rw;
108 {
109 	boolean_t rv;
110 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
111 
112 	/*
113 	 * XXX - check separately to disallow access to user area and user
114 	 * page tables - they are in the map.
115 	 *
116 	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  It was once
117 	 * only used (as an end address) in trap.c.  Use it as an end address
118 	 * here too.  This bogusness has spread.  I just fixed where it was
119 	 * used as a max in vm_mmap.c.
120 	 */
121 	if ((vm_offset_t) addr + len > /* XXX */ VM_MAXUSER_ADDRESS
122 	    || (vm_offset_t) addr + len < (vm_offset_t) addr) {
123 		return (FALSE);
124 	}
125 	rv = vm_map_check_protection(&curproc->p_vmspace->vm_map,
126 	    trunc_page(addr), round_page(addr + len), prot);
127 	return (rv == TRUE);
128 }
129 
130 #ifdef KGDB
131 /*
132  * Change protections on kernel pages from addr to addr+len
133  * (presumably so debugger can plant a breakpoint).
134  * All addresses are assumed to reside in the Sysmap,
135  */
136 chgkprot(addr, len, rw)
137 	register caddr_t addr;
138 	int len, rw;
139 {
140 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
141 
142 	vm_map_protect(kernel_map, trunc_page(addr),
143 	    round_page(addr + len), prot, FALSE);
144 }
145 #endif
146 void
147 vslock(addr, len)
148 	caddr_t addr;
149 	u_int len;
150 {
151 	vm_map_pageable(&curproc->p_vmspace->vm_map, trunc_page(addr),
152 	    round_page(addr + len), FALSE);
153 }
154 
155 void
156 vsunlock(addr, len, dirtied)
157 	caddr_t addr;
158 	u_int len;
159 	int dirtied;
160 {
161 #ifdef	lint
162 	dirtied++;
163 #endif	/* lint */
164 	vm_map_pageable(&curproc->p_vmspace->vm_map, trunc_page(addr),
165 	    round_page(addr + len), TRUE);
166 }
167 
168 /*
169  * Implement fork's actions on an address space.
170  * Here we arrange for the address space to be copied or referenced,
171  * allocate a user struct (pcb and kernel stack), then call the
172  * machine-dependent layer to fill those in and make the new process
173  * ready to run.
174  * NOTE: the kernel stack may be at a different location in the child
175  * process, and thus addresses of automatic variables may be invalid
176  * after cpu_fork returns in the child process.  We do nothing here
177  * after cpu_fork returns.
178  */
179 int
180 vm_fork(p1, p2, isvfork)
181 	register struct proc *p1, *p2;
182 	int isvfork;
183 {
184 	register struct user *up;
185 	vm_offset_t addr, ptaddr;
186 	int i;
187 	struct vm_map *vp;
188 
189 	while ((cnt.v_free_count + cnt.v_cache_count) < cnt.v_free_min) {
190 		VM_WAIT;
191 	}
192 
193 	/*
194 	 * avoid copying any of the parent's pagetables or other per-process
195 	 * objects that reside in the map by marking all of them
196 	 * non-inheritable
197 	 */
198 	(void) vm_map_inherit(&p1->p_vmspace->vm_map,
199 	    UPT_MIN_ADDRESS - UPAGES * NBPG, VM_MAX_ADDRESS, VM_INHERIT_NONE);
200 	p2->p_vmspace = vmspace_fork(p1->p_vmspace);
201 
202 #ifdef SYSVSHM
203 	if (p1->p_vmspace->vm_shm)
204 		shmfork(p1, p2, isvfork);
205 #endif
206 
207 	/*
208 	 * Allocate a wired-down (for now) pcb and kernel stack for the
209 	 * process
210 	 */
211 
212 	addr = (vm_offset_t) kstack;
213 
214 	vp = &p2->p_vmspace->vm_map;
215 
216 	/* get new pagetables and kernel stack */
217 	(void) vm_map_find(vp, NULL, 0, &addr, UPT_MAX_ADDRESS - addr, FALSE);
218 
219 	/* force in the page table encompassing the UPAGES */
220 	ptaddr = trunc_page((u_int) vtopte(addr));
221 	vm_map_pageable(vp, ptaddr, ptaddr + NBPG, FALSE);
222 
223 	/* and force in (demand-zero) the UPAGES */
224 	vm_map_pageable(vp, addr, addr + UPAGES * NBPG, FALSE);
225 
226 	/* get a kernel virtual address for the UPAGES for this proc */
227 	up = (struct user *) kmem_alloc_pageable(u_map, UPAGES * NBPG);
228 	if (up == NULL)
229 		panic("vm_fork: u_map allocation failed");
230 
231 	/* and force-map the upages into the kernel pmap */
232 	for (i = 0; i < UPAGES; i++)
233 		pmap_enter(vm_map_pmap(u_map),
234 		    ((vm_offset_t) up) + NBPG * i,
235 		    pmap_extract(vp->pmap, addr + NBPG * i),
236 		    VM_PROT_READ | VM_PROT_WRITE, 1);
237 
238 	p2->p_addr = up;
239 
240 	/*
241 	 * p_stats and p_sigacts currently point at fields in the user struct
242 	 * but not at &u, instead at p_addr. Copy p_sigacts and parts of
243 	 * p_stats; zero the rest of p_stats (statistics).
244 	 */
245 	p2->p_stats = &up->u_stats;
246 	p2->p_sigacts = &up->u_sigacts;
247 	up->u_sigacts = *p1->p_sigacts;
248 	bzero(&up->u_stats.pstat_startzero,
249 	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
250 		(caddr_t) &up->u_stats.pstat_startzero));
251 	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
252 	    ((caddr_t) &up->u_stats.pstat_endcopy -
253 		(caddr_t) &up->u_stats.pstat_startcopy));
254 
255 
256 	/*
257 	 * cpu_fork will copy and update the kernel stack and pcb, and make
258 	 * the child ready to run.  It marks the child so that it can return
259 	 * differently than the parent. It returns twice, once in the parent
260 	 * process and once in the child.
261 	 */
262 	return (cpu_fork(p1, p2));
263 }
264 
265 /*
266  * Set default limits for VM system.
267  * Called for proc 0, and then inherited by all others.
268  */
269 void
270 vm_init_limits(p)
271 	register struct proc *p;
272 {
273 	int rss_limit;
274 
275 	/*
276 	 * Set up the initial limits on process VM. Set the maximum resident
277 	 * set size to be half of (reasonably) available memory.  Since this
278 	 * is a soft limit, it comes into effect only when the system is out
279 	 * of memory - half of main memory helps to favor smaller processes,
280 	 * and reduces thrashing of the object cache.
281 	 */
282 	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
283 	p->p_rlimit[RLIMIT_STACK].rlim_max = MAXSSIZ;
284 	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
285 	p->p_rlimit[RLIMIT_DATA].rlim_max = MAXDSIZ;
286 	/* limit the limit to no less than 2MB */
287 	rss_limit = max(cnt.v_free_count / 2, 512);
288 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
289 	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
290 }
291 
292 #ifdef DEBUG
293 int enableswap = 1;
294 int swapdebug = 0;
295 
296 #define	SDB_FOLLOW	1
297 #define SDB_SWAPIN	2
298 #define SDB_SWAPOUT	4
299 #endif
300 
301 void
302 faultin(p)
303 	struct proc *p;
304 {
305 	vm_offset_t i;
306 	vm_offset_t ptaddr;
307 	int s;
308 
309 	if ((p->p_flag & P_INMEM) == 0) {
310 		vm_map_t map;
311 
312 		++p->p_lock;
313 
314 		map = &p->p_vmspace->vm_map;
315 		/* force the page table encompassing the kernel stack (upages) */
316 		ptaddr = trunc_page((u_int) vtopte(kstack));
317 		vm_map_pageable(map, ptaddr, ptaddr + NBPG, FALSE);
318 
319 		/* wire in the UPAGES */
320 		vm_map_pageable(map, (vm_offset_t) kstack,
321 		    (vm_offset_t) kstack + UPAGES * NBPG, FALSE);
322 
323 		/* and map them nicely into the kernel pmap */
324 		for (i = 0; i < UPAGES; i++) {
325 			vm_offset_t off = i * NBPG;
326 			vm_offset_t pa = (vm_offset_t)
327 			pmap_extract(&p->p_vmspace->vm_pmap,
328 			    (vm_offset_t) kstack + off);
329 
330 			pmap_enter(vm_map_pmap(u_map),
331 			    ((vm_offset_t) p->p_addr) + off,
332 			    pa, VM_PROT_READ | VM_PROT_WRITE, 1);
333 		}
334 
335 		s = splhigh();
336 
337 		if (p->p_stat == SRUN)
338 			setrunqueue(p);
339 
340 		p->p_flag |= P_INMEM;
341 
342 		/* undo the effect of setting SLOCK above */
343 		--p->p_lock;
344 		splx(s);
345 
346 	}
347 }
348 
349 /*
350  * This swapin algorithm attempts to swap-in processes only if there
351  * is enough space for them.  Of course, if a process waits for a long
352  * time, it will be swapped in anyway.
353  */
354 void
355 scheduler()
356 {
357 	register struct proc *p;
358 	register int pri;
359 	struct proc *pp;
360 	int ppri;
361 
362 loop:
363 	while ((cnt.v_free_count + cnt.v_cache_count) < (cnt.v_free_reserved + UPAGES + 2)) {
364 		VM_WAIT;
365 		tsleep((caddr_t) &proc0, PVM, "schedm", 0);
366 	}
367 
368 	pp = NULL;
369 	ppri = INT_MIN;
370 	for (p = (struct proc *) allproc; p != NULL; p = p->p_next) {
371 		if (p->p_stat == SRUN && (p->p_flag & (P_INMEM | P_SWAPPING)) == 0) {
372 			int mempri;
373 
374 			pri = p->p_swtime + p->p_slptime - p->p_nice * 8;
375 			mempri = pri > 0 ? pri : 0;
376 			/*
377 			 * if this process is higher priority and there is
378 			 * enough space, then select this process instead of
379 			 * the previous selection.
380 			 */
381 			if (pri > ppri) {
382 				pp = p;
383 				ppri = pri;
384 			}
385 		}
386 	}
387 
388 	/*
389 	 * Nothing to do, back to sleep
390 	 */
391 	if ((p = pp) == NULL) {
392 		tsleep((caddr_t) &proc0, PVM, "sched", 0);
393 		goto loop;
394 	}
395 	/*
396 	 * We would like to bring someone in. (only if there is space).
397 	 */
398 	faultin(p);
399 	p->p_swtime = 0;
400 	goto loop;
401 }
402 
403 #define	swappable(p) \
404 	(((p)->p_lock == 0) && \
405 		((p)->p_flag & (P_TRACED|P_NOSWAP|P_SYSTEM|P_INMEM|P_WEXIT|P_PHYSIO|P_SWAPPING)) == P_INMEM)
406 
407 extern int vm_pageout_free_min;
408 
409 /*
410  * Swapout is driven by the pageout daemon.  Very simple, we find eligible
411  * procs and unwire their u-areas.  We try to always "swap" at least one
412  * process in case we need the room for a swapin.
413  * If any procs have been sleeping/stopped for at least maxslp seconds,
414  * they are swapped.  Else, we swap the longest-sleeping or stopped process,
415  * if any, otherwise the longest-resident process.
416  */
417 void
418 swapout_threads()
419 {
420 	register struct proc *p;
421 	struct proc *outp, *outp2;
422 	int outpri, outpri2;
423 	int didswap = 0;
424 
425 	outp = outp2 = NULL;
426 	outpri = outpri2 = INT_MIN;
427 retry:
428 	for (p = (struct proc *) allproc; p != NULL; p = p->p_next) {
429 		if (!swappable(p))
430 			continue;
431 		switch (p->p_stat) {
432 		default:
433 			continue;
434 
435 		case SSLEEP:
436 		case SSTOP:
437 			/*
438 			 * do not swapout a realtime process
439 			 */
440 			if (p->p_rtprio.type == RTP_PRIO_REALTIME)
441 				continue;
442 
443 			/*
444 			 * do not swapout a process waiting on a critical
445 			 * event of some kind
446 			 */
447 			if ((p->p_priority & 0x7f) < PSOCK)
448 				continue;
449 
450 			vm_map_reference(&p->p_vmspace->vm_map);
451 			/*
452 			 * do not swapout a process that is waiting for VM
453 			 * datastructures there is a possible deadlock.
454 			 */
455 			if (!lock_try_write(&p->p_vmspace->vm_map.lock)) {
456 				vm_map_deallocate(&p->p_vmspace->vm_map);
457 				continue;
458 			}
459 			vm_map_unlock(&p->p_vmspace->vm_map);
460 			/*
461 			 * If the process has been asleep for awhile and had
462 			 * most of its pages taken away already, swap it out.
463 			 */
464 			if (p->p_slptime > 4) {
465 				swapout(p);
466 				vm_map_deallocate(&p->p_vmspace->vm_map);
467 				didswap++;
468 				goto retry;
469 			}
470 			vm_map_deallocate(&p->p_vmspace->vm_map);
471 		}
472 	}
473 	/*
474 	 * If we swapped something out, and another process needed memory,
475 	 * then wakeup the sched process.
476 	 */
477 	if (didswap)
478 		wakeup((caddr_t) &proc0);
479 }
480 
481 void
482 swapout(p)
483 	register struct proc *p;
484 {
485 	vm_map_t map = &p->p_vmspace->vm_map;
486 	vm_offset_t ptaddr;
487 
488 	++p->p_stats->p_ru.ru_nswap;
489 	/*
490 	 * remember the process resident count
491 	 */
492 	p->p_vmspace->vm_swrss =
493 	    p->p_vmspace->vm_pmap.pm_stats.resident_count;
494 
495 	(void) splhigh();
496 	p->p_flag &= ~P_INMEM;
497 	if (p->p_stat == SRUN)
498 		remrq(p);
499 	(void) spl0();
500 
501 	p->p_flag |= P_SWAPPING;
502 	/*
503 	 * let the upages be paged
504 	 */
505 	pmap_remove(vm_map_pmap(u_map),
506 	    (vm_offset_t) p->p_addr, ((vm_offset_t) p->p_addr) + UPAGES * NBPG);
507 
508 	vm_map_pageable(map, (vm_offset_t) kstack,
509 	    (vm_offset_t) kstack + UPAGES * NBPG, TRUE);
510 
511 	ptaddr = trunc_page((u_int) vtopte(kstack));
512 	vm_map_pageable(map, ptaddr, ptaddr + NBPG, TRUE);
513 
514 	p->p_flag &= ~P_SWAPPING;
515 	p->p_swtime = 0;
516 }
517 
518 /*
519  * The rest of these routines fake thread handling
520  */
521 
522 #ifndef assert_wait
523 void
524 assert_wait(event, ruptible)
525 	int event;
526 	boolean_t ruptible;
527 {
528 #ifdef lint
529 	ruptible++;
530 #endif
531 	curproc->p_thread = event;
532 }
533 #endif
534 
535 void
536 thread_block(char *msg)
537 {
538 	if (curproc->p_thread)
539 		tsleep((caddr_t) curproc->p_thread, PVM, msg, 0);
540 }
541 
542 
543 void
544 thread_sleep_(event, lock, wmesg)
545 	int event;
546 	simple_lock_t lock;
547 	char *wmesg;
548 {
549 
550 	curproc->p_thread = event;
551 	simple_unlock(lock);
552 	if (curproc->p_thread) {
553 		tsleep((caddr_t) event, PVM, wmesg, 0);
554 	}
555 }
556 
557 #ifndef thread_wakeup
558 void
559 thread_wakeup(event)
560 	int event;
561 {
562 	wakeup((caddr_t) event);
563 }
564 #endif
565 
566 /*
567  * DEBUG stuff
568  */
569 
570 int indent = 0;
571 
572 #include <machine/stdarg.h>	/* see subr_prf.c */
573 
574 /*ARGSUSED2*/
575 void
576 #if __STDC__
577 iprintf(const char *fmt,...)
578 #else
579 iprintf(fmt /* , va_alist */ )
580 	char *fmt;
581 
582  /* va_dcl */
583 #endif
584 {
585 	register int i;
586 	va_list ap;
587 
588 	for (i = indent; i >= 8; i -= 8)
589 		printf("\t");
590 	while (--i >= 0)
591 		printf(" ");
592 	va_start(ap, fmt);
593 	printf("%r", fmt, ap);
594 	va_end(ap);
595 }
596