xref: /freebsd/sys/vm/vm_glue.c (revision dd106ca74239cc01c195cebf818fa771a80d64ea)
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.52 1996/07/02 02:07:56 dyson 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/shm.h>
71 #include <sys/vmmeter.h>
72 
73 #include <sys/kernel.h>
74 #include <sys/dkstat.h>
75 
76 #include <vm/vm.h>
77 #include <vm/vm_param.h>
78 #include <vm/vm_inherit.h>
79 #include <vm/vm_prot.h>
80 #include <vm/lock.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_page.h>
84 #include <vm/vm_pageout.h>
85 #include <vm/vm_kern.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_pager.h>
89 
90 #include <sys/user.h>
91 
92 /*
93  * System initialization
94  *
95  * Note: proc0 from proc.h
96  */
97 
98 static void vm_init_limits __P((void *));
99 SYSINIT(vm_limits, SI_SUB_VM_CONF, SI_ORDER_FIRST, vm_init_limits, &proc0)
100 
101 /*
102  * THIS MUST BE THE LAST INITIALIZATION ITEM!!!
103  *
104  * Note: run scheduling should be divorced from the vm system.
105  */
106 static void scheduler __P((void *));
107 SYSINIT(scheduler, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, scheduler, NULL)
108 
109 
110 static void swapout __P((struct proc *));
111 
112 extern char kstack[];
113 
114 /* vm_map_t upages_map; */
115 
116 int
117 kernacc(addr, len, rw)
118 	caddr_t addr;
119 	int len, rw;
120 {
121 	boolean_t rv;
122 	vm_offset_t saddr, eaddr;
123 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
124 
125 	saddr = trunc_page(addr);
126 	eaddr = round_page(addr + len);
127 	rv = vm_map_check_protection(kernel_map, saddr, eaddr, prot);
128 	return (rv == TRUE);
129 }
130 
131 int
132 useracc(addr, len, rw)
133 	caddr_t addr;
134 	int len, rw;
135 {
136 	boolean_t rv;
137 	vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
138 
139 	/*
140 	 * XXX - check separately to disallow access to user area and user
141 	 * page tables - they are in the map.
142 	 *
143 	 * XXX - VM_MAXUSER_ADDRESS is an end address, not a max.  It was once
144 	 * only used (as an end address) in trap.c.  Use it as an end address
145 	 * here too.  This bogusness has spread.  I just fixed where it was
146 	 * used as a max in vm_mmap.c.
147 	 */
148 	if ((vm_offset_t) addr + len > /* XXX */ VM_MAXUSER_ADDRESS
149 	    || (vm_offset_t) addr + len < (vm_offset_t) addr) {
150 		return (FALSE);
151 	}
152 	rv = vm_map_check_protection(&curproc->p_vmspace->vm_map,
153 	    trunc_page(addr), round_page(addr + len), prot);
154 	return (rv == TRUE);
155 }
156 
157 void
158 vslock(addr, len)
159 	caddr_t addr;
160 	u_int len;
161 {
162 	vm_map_pageable(&curproc->p_vmspace->vm_map, trunc_page(addr),
163 	    round_page(addr + len), FALSE);
164 }
165 
166 void
167 vsunlock(addr, len, dirtied)
168 	caddr_t addr;
169 	u_int len;
170 	int dirtied;
171 {
172 #ifdef	lint
173 	dirtied++;
174 #endif	/* lint */
175 	vm_map_pageable(&curproc->p_vmspace->vm_map, trunc_page(addr),
176 	    round_page(addr + len), TRUE);
177 }
178 
179 /*
180  * Implement fork's actions on an address space.
181  * Here we arrange for the address space to be copied or referenced,
182  * allocate a user struct (pcb and kernel stack), then call the
183  * machine-dependent layer to fill those in and make the new process
184  * ready to run.
185  * NOTE: the kernel stack may be at a different location in the child
186  * process, and thus addresses of automatic variables may be invalid
187  * after cpu_fork returns in the child process.  We do nothing here
188  * after cpu_fork returns.
189  */
190 int
191 vm_fork(p1, p2)
192 	register struct proc *p1, *p2;
193 {
194 	register struct user *up;
195 	int i;
196 	pmap_t pvp;
197 	vm_object_t upobj;
198 
199 	while ((cnt.v_free_count + cnt.v_cache_count) < cnt.v_free_min) {
200 		VM_WAIT;
201 	}
202 
203 	p2->p_vmspace = vmspace_fork(p1->p_vmspace);
204 
205 	if (p1->p_vmspace->vm_shm)
206 		shmfork(p1, p2);
207 
208 	/*
209 	 * Allocate a wired-down (for now) pcb and kernel stack for the
210 	 * process
211 	 */
212 
213 	pvp = &p2->p_vmspace->vm_pmap;
214 
215 	/*
216 	 * allocate object for the upages
217 	 */
218 	p2->p_vmspace->vm_upages_obj = upobj = vm_object_allocate( OBJT_DEFAULT,
219 		UPAGES);
220 
221 	/* get a kernel virtual address for the UPAGES for this proc */
222 	up = (struct user *) kmem_alloc_pageable(u_map, UPAGES * PAGE_SIZE);
223 	if (up == NULL)
224 		panic("vm_fork: u_map allocation failed");
225 
226 	for(i=0;i<UPAGES;i++) {
227 		vm_page_t m;
228 
229 		/*
230 		 * Get a kernel stack page
231 		 */
232 		while ((m = vm_page_alloc(upobj,
233 			i, VM_ALLOC_NORMAL)) == NULL) {
234 			VM_WAIT;
235 		}
236 
237 		/*
238 		 * Wire the page
239 		 */
240 		vm_page_wire(m);
241 		PAGE_WAKEUP(m);
242 
243 		/*
244 		 * Enter the page into both the kernel and the process
245 		 * address space.
246 		 */
247 		pmap_enter( pvp, (vm_offset_t) kstack + i * PAGE_SIZE,
248 			VM_PAGE_TO_PHYS(m), VM_PROT_READ|VM_PROT_WRITE, TRUE);
249 		pmap_kenter(((vm_offset_t) up) + i * PAGE_SIZE,
250 			VM_PAGE_TO_PHYS(m));
251 		m->flags &= ~PG_ZERO;
252 		m->flags |= PG_MAPPED|PG_WRITEABLE;
253 		m->valid = VM_PAGE_BITS_ALL;
254 	}
255 
256 	p2->p_addr = up;
257 
258 	/*
259 	 * p_stats and p_sigacts currently point at fields in the user struct
260 	 * but not at &u, instead at p_addr. Copy p_sigacts and parts of
261 	 * p_stats; zero the rest of p_stats (statistics).
262 	 */
263 	p2->p_stats = &up->u_stats;
264 	p2->p_sigacts = &up->u_sigacts;
265 	up->u_sigacts = *p1->p_sigacts;
266 	bzero(&up->u_stats.pstat_startzero,
267 	    (unsigned) ((caddr_t) &up->u_stats.pstat_endzero -
268 		(caddr_t) &up->u_stats.pstat_startzero));
269 	bcopy(&p1->p_stats->pstat_startcopy, &up->u_stats.pstat_startcopy,
270 	    ((caddr_t) &up->u_stats.pstat_endcopy -
271 		(caddr_t) &up->u_stats.pstat_startcopy));
272 
273 
274 	/*
275 	 * cpu_fork will copy and update the kernel stack and pcb, and make
276 	 * the child ready to run.  It marks the child so that it can return
277 	 * differently than the parent. It returns twice, once in the parent
278 	 * process and once in the child.
279 	 */
280 	return (cpu_fork(p1, p2));
281 }
282 
283 /*
284  * Set default limits for VM system.
285  * Called for proc 0, and then inherited by all others.
286  *
287  * XXX should probably act directly on proc0.
288  */
289 static void
290 vm_init_limits(udata)
291 	void *udata;
292 {
293 	register struct proc *p = udata;
294 	int rss_limit;
295 
296 	/*
297 	 * Set up the initial limits on process VM. Set the maximum resident
298 	 * set size to be half of (reasonably) available memory.  Since this
299 	 * is a soft limit, it comes into effect only when the system is out
300 	 * of memory - half of main memory helps to favor smaller processes,
301 	 * and reduces thrashing of the object cache.
302 	 */
303 	p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
304 	p->p_rlimit[RLIMIT_STACK].rlim_max = MAXSSIZ;
305 	p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
306 	p->p_rlimit[RLIMIT_DATA].rlim_max = MAXDSIZ;
307 	/* limit the limit to no less than 2MB */
308 	rss_limit = max(cnt.v_free_count, 512);
309 	p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
310 	p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
311 }
312 
313 void
314 faultin(p)
315 	struct proc *p;
316 {
317 	vm_offset_t i;
318 	int s;
319 
320 	if ((p->p_flag & P_INMEM) == 0) {
321 		pmap_t pmap = &p->p_vmspace->vm_pmap;
322 		vm_page_t m;
323 		vm_object_t upobj = p->p_vmspace->vm_upages_obj;
324 
325 		++p->p_lock;
326 #if defined(SWAP_DEBUG)
327 		printf("swapping in %d\n", p->p_pid);
328 #endif
329 
330 		for(i=0;i<UPAGES;i++) {
331 			int s;
332 			s = splvm();
333 retry:
334 			if ((m = vm_page_lookup(upobj, i)) == NULL) {
335 				if ((m = vm_page_alloc(upobj, i, VM_ALLOC_NORMAL)) == NULL) {
336 					VM_WAIT;
337 					goto retry;
338 				}
339 			} else {
340 				if ((m->flags & PG_BUSY) || m->busy) {
341 					m->flags |= PG_WANTED;
342 					tsleep(m, PVM, "swinuw",0);
343 					goto retry;
344 				}
345 				m->flags |= PG_BUSY;
346 			}
347 			vm_page_wire(m);
348 			splx(s);
349 
350 			pmap_enter( pmap, (vm_offset_t) kstack + i * PAGE_SIZE,
351 				VM_PAGE_TO_PHYS(m), VM_PROT_READ|VM_PROT_WRITE, TRUE);
352 			pmap_kenter(((vm_offset_t) p->p_addr) + i * PAGE_SIZE,
353 				VM_PAGE_TO_PHYS(m));
354 			if (m->valid != VM_PAGE_BITS_ALL) {
355 				int rv;
356 				rv = vm_pager_get_pages(upobj,
357 					&m, 1, 0);
358 				if (rv != VM_PAGER_OK)
359 					panic("faultin: cannot get upages for proc: %d\n", p->p_pid);
360 				m->valid = VM_PAGE_BITS_ALL;
361 			}
362 			PAGE_WAKEUP(m);
363 			m->flags |= PG_MAPPED|PG_WRITEABLE;
364 		}
365 
366 		s = splhigh();
367 
368 		if (p->p_stat == SRUN)
369 			setrunqueue(p);
370 
371 		p->p_flag |= P_INMEM;
372 
373 		/* undo the effect of setting SLOCK above */
374 		--p->p_lock;
375 		splx(s);
376 
377 	}
378 }
379 
380 /*
381  * This swapin algorithm attempts to swap-in processes only if there
382  * is enough space for them.  Of course, if a process waits for a long
383  * time, it will be swapped in anyway.
384  */
385 /* ARGSUSED*/
386 static void
387 scheduler(dummy)
388 	void *dummy;
389 {
390 	register struct proc *p;
391 	register int pri;
392 	struct proc *pp;
393 	int ppri;
394 
395 	spl0();
396 loop:
397 	while ((cnt.v_free_count + cnt.v_cache_count) < cnt.v_free_min) {
398 		VM_WAIT;
399 	}
400 
401 	pp = NULL;
402 	ppri = INT_MIN;
403 	for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
404 		if (p->p_stat == SRUN &&
405 			(p->p_flag & (P_INMEM | P_SWAPPING)) == 0) {
406 			int mempri;
407 
408 			pri = p->p_swtime + p->p_slptime - p->p_nice * 8;
409 			mempri = pri > 0 ? pri : 0;
410 			/*
411 			 * if this process is higher priority and there is
412 			 * enough space, then select this process instead of
413 			 * the previous selection.
414 			 */
415 			if (pri > ppri) {
416 				pp = p;
417 				ppri = pri;
418 			}
419 		}
420 	}
421 
422 	/*
423 	 * Nothing to do, back to sleep
424 	 */
425 	if ((p = pp) == NULL) {
426 		tsleep(&proc0, PVM, "sched", 0);
427 		goto loop;
428 	}
429 	/*
430 	 * We would like to bring someone in. (only if there is space).
431 	 */
432 	faultin(p);
433 	p->p_swtime = 0;
434 	goto loop;
435 }
436 
437 #ifndef NO_SWAPPING
438 
439 #define	swappable(p) \
440 	(((p)->p_lock == 0) && \
441 		((p)->p_flag & (P_TRACED|P_NOSWAP|P_SYSTEM|P_INMEM|P_WEXIT|P_PHYSIO|P_SWAPPING)) == P_INMEM)
442 
443 /*
444  * Swapout is driven by the pageout daemon.  Very simple, we find eligible
445  * procs and unwire their u-areas.  We try to always "swap" at least one
446  * process in case we need the room for a swapin.
447  * If any procs have been sleeping/stopped for at least maxslp seconds,
448  * they are swapped.  Else, we swap the longest-sleeping or stopped process,
449  * if any, otherwise the longest-resident process.
450  */
451 void
452 swapout_procs()
453 {
454 	register struct proc *p;
455 	struct proc *outp, *outp2;
456 	int outpri, outpri2;
457 	int didswap = 0;
458 
459 	outp = outp2 = NULL;
460 	outpri = outpri2 = INT_MIN;
461 retry:
462 	for (p = allproc.lh_first; p != 0; p = p->p_list.le_next) {
463 		struct vmspace *vm;
464 		if (!swappable(p))
465 			continue;
466 
467 		vm = p->p_vmspace;
468 
469 		switch (p->p_stat) {
470 		default:
471 			continue;
472 
473 		case SSLEEP:
474 		case SSTOP:
475 			/*
476 			 * do not swapout a realtime process
477 			 */
478 			if (p->p_rtprio.type == RTP_PRIO_REALTIME)
479 				continue;
480 
481 			/*
482 			 * do not swapout a process waiting on a critical
483 			 * event of some kind
484 			 */
485 			if (((p->p_priority & 0x7f) < PSOCK) ||
486 				(p->p_slptime <= 10))
487 				continue;
488 
489 			++vm->vm_refcnt;
490 			vm_map_reference(&vm->vm_map);
491 			/*
492 			 * do not swapout a process that is waiting for VM
493 			 * datastructures there is a possible deadlock.
494 			 */
495 			if (!lock_try_write(&vm->vm_map.lock)) {
496 				vm_map_deallocate(&vm->vm_map);
497 				vmspace_free(vm);
498 				continue;
499 			}
500 			vm_map_unlock(&vm->vm_map);
501 			/*
502 			 * If the process has been asleep for awhile and had
503 			 * most of its pages taken away already, swap it out.
504 			 */
505 			swapout(p);
506 			vm_map_deallocate(&vm->vm_map);
507 			vmspace_free(vm);
508 			didswap++;
509 			goto retry;
510 		}
511 	}
512 	/*
513 	 * If we swapped something out, and another process needed memory,
514 	 * then wakeup the sched process.
515 	 */
516 	if (didswap)
517 		wakeup(&proc0);
518 }
519 
520 static void
521 swapout(p)
522 	register struct proc *p;
523 {
524 	pmap_t pmap = &p->p_vmspace->vm_pmap;
525 	int i;
526 
527 #if defined(SWAP_DEBUG)
528 	printf("swapping out %d\n", p->p_pid);
529 #endif
530 	++p->p_stats->p_ru.ru_nswap;
531 	/*
532 	 * remember the process resident count
533 	 */
534 	p->p_vmspace->vm_swrss =
535 	    p->p_vmspace->vm_pmap.pm_stats.resident_count;
536 
537 	(void) splhigh();
538 	p->p_flag &= ~P_INMEM;
539 	p->p_flag |= P_SWAPPING;
540 	if (p->p_stat == SRUN)
541 		remrq(p);
542 	(void) spl0();
543 
544 	/*
545 	 * let the upages be paged
546 	 */
547 	for(i=0;i<UPAGES;i++) {
548 		vm_page_t m;
549 		if ((m = vm_page_lookup(p->p_vmspace->vm_upages_obj, i)) == NULL)
550 			panic("swapout: upage already missing???");
551 		m->dirty = VM_PAGE_BITS_ALL;
552 		vm_page_unwire(m);
553 		vm_page_deactivate(m);
554 		pmap_kremove( (vm_offset_t) p->p_addr + PAGE_SIZE * i);
555 	}
556 	pmap_remove(pmap, (vm_offset_t) kstack,
557 		(vm_offset_t) kstack + PAGE_SIZE * UPAGES);
558 
559 	p->p_flag &= ~P_SWAPPING;
560 	p->p_swtime = 0;
561 }
562 #endif /* !NO_SWAPPING */
563