1 /* $OpenBSD: uvm_glue.c,v 1.39 2004/02/23 06:19:32 drahn Exp $ */
2 /* $NetBSD: uvm_glue.c,v 1.44 2001/02/06 19:54:44 eeh Exp $ */
3
4 /*
5 * Copyright (c) 1997 Charles D. Cranor and Washington University.
6 * Copyright (c) 1991, 1993, The Regents of the University of California.
7 *
8 * All rights reserved.
9 *
10 * This code is derived from software contributed to Berkeley by
11 * The Mach Operating System project at Carnegie-Mellon University.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. All advertising materials mentioning features or use of this software
22 * must display the following acknowledgement:
23 * This product includes software developed by Charles D. Cranor,
24 * Washington University, the University of California, Berkeley and
25 * its contributors.
26 * 4. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * SUCH DAMAGE.
41 *
42 * @(#)vm_glue.c 8.6 (Berkeley) 1/5/94
43 * from: Id: uvm_glue.c,v 1.1.2.8 1998/02/07 01:16:54 chs Exp
44 *
45 *
46 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
47 * All rights reserved.
48 *
49 * Permission to use, copy, modify and distribute this software and
50 * its documentation is hereby granted, provided that both the copyright
51 * notice and this permission notice appear in all copies of the
52 * software, derivative works or modified versions, and any portions
53 * thereof, and that both notices appear in supporting documentation.
54 *
55 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
56 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
57 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
58 *
59 * Carnegie Mellon requests users of this software to return to
60 *
61 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
62 * School of Computer Science
63 * Carnegie Mellon University
64 * Pittsburgh PA 15213-3890
65 *
66 * any improvements or extensions that they make and grant Carnegie the
67 * rights to redistribute these changes.
68 */
69
70 /*
71 * uvm_glue.c: glue functions
72 */
73
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/proc.h>
77 #include <sys/resourcevar.h>
78 #include <sys/buf.h>
79 #include <sys/user.h>
80 #ifdef SYSVSHM
81 #include <sys/shm.h>
82 #endif
83
84 #include <uvm/uvm.h>
85
86 #include <machine/cpu.h>
87
88 /*
89 * local prototypes
90 */
91
92 static void uvm_swapout(struct proc *);
93
94 /*
95 * XXXCDC: do these really belong here?
96 */
97
98 int readbuffers = 0; /* allow KGDB to read kern buffer pool */
99 /* XXX: see uvm_kernacc */
100
101
102 /*
103 * uvm_kernacc: can the kernel access a region of memory
104 *
105 * - called from malloc [DIAGNOSTIC], and /dev/kmem driver (mem.c)
106 */
107
108 boolean_t
uvm_kernacc(addr,len,rw)109 uvm_kernacc(addr, len, rw)
110 caddr_t addr;
111 size_t len;
112 int rw;
113 {
114 boolean_t rv;
115 vaddr_t saddr, eaddr;
116 vm_prot_t prot = rw == B_READ ? VM_PROT_READ : VM_PROT_WRITE;
117
118 saddr = trunc_page((vaddr_t)addr);
119 eaddr = round_page((vaddr_t)addr + len);
120 vm_map_lock_read(kernel_map);
121 rv = uvm_map_checkprot(kernel_map, saddr, eaddr, prot);
122 vm_map_unlock_read(kernel_map);
123
124 /*
125 * XXX there are still some things (e.g. the buffer cache) that
126 * are managed behind the VM system's back so even though an
127 * address is accessible in the mind of the VM system, there may
128 * not be physical pages where the VM thinks there is. This can
129 * lead to bogus allocation of pages in the kernel address space
130 * or worse, inconsistencies at the pmap level. We only worry
131 * about the buffer cache for now.
132 */
133 if (!readbuffers && rv && (eaddr > (vaddr_t)buffers &&
134 saddr < (vaddr_t)buffers + MAXBSIZE * nbuf))
135 rv = FALSE;
136 return(rv);
137 }
138
139 #ifdef KGDB
140 /*
141 * Change protections on kernel pages from addr to addr+len
142 * (presumably so debugger can plant a breakpoint).
143 *
144 * We force the protection change at the pmap level. If we were
145 * to use vm_map_protect a change to allow writing would be lazily-
146 * applied meaning we would still take a protection fault, something
147 * we really don't want to do. It would also fragment the kernel
148 * map unnecessarily. We cannot use pmap_protect since it also won't
149 * enforce a write-enable request. Using pmap_enter is the only way
150 * we can ensure the change takes place properly.
151 */
152 void
uvm_chgkprot(addr,len,rw)153 uvm_chgkprot(addr, len, rw)
154 caddr_t addr;
155 size_t len;
156 int rw;
157 {
158 vm_prot_t prot;
159 paddr_t pa;
160 vaddr_t sva, eva;
161
162 prot = rw == B_READ ? VM_PROT_READ : VM_PROT_READ|VM_PROT_WRITE;
163 eva = round_page((vaddr_t)addr + len);
164 for (sva = trunc_page((vaddr_t)addr); sva < eva; sva += PAGE_SIZE) {
165 /*
166 * Extract physical address for the page.
167 * We use a cheezy hack to differentiate physical
168 * page 0 from an invalid mapping, not that it
169 * really matters...
170 */
171 if (pmap_extract(pmap_kernel(), sva, &pa) == FALSE)
172 panic("chgkprot: invalid page");
173 pmap_enter(pmap_kernel(), sva, pa, prot, PMAP_WIRED);
174 }
175 pmap_update(pmap_kernel());
176 }
177 #endif
178
179 /*
180 * uvm_vslock: wire user memory for I/O
181 *
182 * - called from physio and sys___sysctl
183 * - XXXCDC: consider nuking this (or making it a macro?)
184 */
185
186 int
uvm_vslock(p,addr,len,access_type)187 uvm_vslock(p, addr, len, access_type)
188 struct proc *p;
189 caddr_t addr;
190 size_t len;
191 vm_prot_t access_type;
192 {
193 vm_map_t map;
194 vaddr_t start, end;
195 int rv;
196
197 map = &p->p_vmspace->vm_map;
198 start = trunc_page((vaddr_t)addr);
199 end = round_page((vaddr_t)addr + len);
200 if (end <= start)
201 return (EINVAL);
202
203 rv = uvm_fault_wire(map, start, end, access_type);
204
205 return (rv);
206 }
207
208 /*
209 * uvm_vsunlock: unwire user memory wired by uvm_vslock()
210 *
211 * - called from physio and sys___sysctl
212 * - XXXCDC: consider nuking this (or making it a macro?)
213 */
214
215 void
uvm_vsunlock(p,addr,len)216 uvm_vsunlock(p, addr, len)
217 struct proc *p;
218 caddr_t addr;
219 size_t len;
220 {
221 vaddr_t start, end;
222
223 start = trunc_page((vaddr_t)addr);
224 end = round_page((vaddr_t)addr + len);
225 if (end <= start)
226 return;
227
228 uvm_fault_unwire(&p->p_vmspace->vm_map, start, end);
229 }
230
231 /*
232 * uvm_fork: fork a virtual address space
233 *
234 * - the address space is copied as per parent map's inherit values
235 * - a new "user" structure is allocated for the child process
236 * [filled in by MD layer...]
237 * - if specified, the child gets a new user stack described by
238 * stack and stacksize
239 * - NOTE: the kernel stack may be at a different location in the child
240 * process, and thus addresses of automatic variables may be invalid
241 * after cpu_fork returns in the child process. We do nothing here
242 * after cpu_fork returns.
243 * - XXXCDC: we need a way for this to return a failure value rather
244 * than just hang
245 */
246 void
uvm_fork(p1,p2,shared,stack,stacksize,func,arg)247 uvm_fork(p1, p2, shared, stack, stacksize, func, arg)
248 struct proc *p1, *p2;
249 boolean_t shared;
250 void *stack;
251 size_t stacksize;
252 void (*func)(void *);
253 void *arg;
254 {
255 struct user *up = p2->p_addr;
256 int rv;
257
258 if (shared == TRUE) {
259 p2->p_vmspace = NULL;
260 uvmspace_share(p1, p2); /* share vmspace */
261 } else
262 p2->p_vmspace = uvmspace_fork(p1->p_vmspace); /* fork vmspace */
263
264 /*
265 * Wire down the U-area for the process, which contains the PCB
266 * and the kernel stack. Wired state is stored in p->p_flag's
267 * P_INMEM bit rather than in the vm_map_entry's wired count
268 * to prevent kernel_map fragmentation.
269 *
270 * Note the kernel stack gets read/write accesses right off
271 * the bat.
272 */
273 rv = uvm_fault_wire(kernel_map, (vaddr_t)up,
274 (vaddr_t)up + USPACE, VM_PROT_READ | VM_PROT_WRITE);
275 if (rv != KERN_SUCCESS)
276 panic("uvm_fork: uvm_fault_wire failed: %d", rv);
277
278 /*
279 * p_stats currently points at a field in the user struct. Copy
280 * parts of p_stats, and zero out the rest.
281 */
282 p2->p_stats = &up->u_stats;
283 memset(&up->u_stats.pstat_startzero, 0,
284 ((caddr_t)&up->u_stats.pstat_endzero -
285 (caddr_t)&up->u_stats.pstat_startzero));
286 memcpy(&up->u_stats.pstat_startcopy, &p1->p_stats->pstat_startcopy,
287 ((caddr_t)&up->u_stats.pstat_endcopy -
288 (caddr_t)&up->u_stats.pstat_startcopy));
289
290 /*
291 * cpu_fork() copy and update the pcb, and make the child ready
292 * to run. If this is a normal user fork, the child will exit
293 * directly to user mode via child_return() on its first time
294 * slice and will not return here. If this is a kernel thread,
295 * the specified entry point will be executed.
296 */
297 cpu_fork(p1, p2, stack, stacksize, func, arg);
298 }
299
300 /*
301 * uvm_exit: exit a virtual address space
302 *
303 * - the process passed to us is a dead (pre-zombie) process; we
304 * are running on a different context now (the reaper).
305 * - we must run in a separate thread because freeing the vmspace
306 * of the dead process may block.
307 */
308 void
uvm_exit(p)309 uvm_exit(p)
310 struct proc *p;
311 {
312 vaddr_t va = (vaddr_t)p->p_addr;
313
314 uvmspace_free(p->p_vmspace);
315 p->p_flag &= ~P_INMEM;
316 uvm_fault_unwire(kernel_map, va, va + USPACE);
317 uvm_km_free(kernel_map, va, USPACE);
318 p->p_addr = NULL;
319 }
320
321 /*
322 * uvm_init_limit: init per-process VM limits
323 *
324 * - called for process 0 and then inherited by all others.
325 */
326 void
uvm_init_limits(p)327 uvm_init_limits(p)
328 struct proc *p;
329 {
330
331 /*
332 * Set up the initial limits on process VM. Set the maximum
333 * resident set size to be all of (reasonably) available memory.
334 * This causes any single, large process to start random page
335 * replacement once it fills memory.
336 */
337
338 p->p_rlimit[RLIMIT_STACK].rlim_cur = DFLSSIZ;
339 p->p_rlimit[RLIMIT_STACK].rlim_max = MAXSSIZ;
340 p->p_rlimit[RLIMIT_DATA].rlim_cur = DFLDSIZ;
341 p->p_rlimit[RLIMIT_DATA].rlim_max = MAXDSIZ;
342 p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(uvmexp.free);
343 }
344
345 #ifdef DEBUG
346 int enableswap = 1;
347 int swapdebug = 0;
348 #define SDB_FOLLOW 1
349 #define SDB_SWAPIN 2
350 #define SDB_SWAPOUT 4
351 #endif
352
353 /*
354 * uvm_swapin: swap in a process's u-area.
355 */
356
357 void
uvm_swapin(p)358 uvm_swapin(p)
359 struct proc *p;
360 {
361 vaddr_t addr;
362 int rv, s;
363
364 s = splstatclock();
365 if (p->p_flag & P_SWAPIN) {
366 splx(s);
367 return;
368 }
369 p->p_flag |= P_SWAPIN;
370 splx(s);
371
372 addr = (vaddr_t)p->p_addr;
373 /* make P_INMEM true */
374 if ((rv = uvm_fault_wire(kernel_map, addr, addr + USPACE,
375 VM_PROT_READ | VM_PROT_WRITE)) != KERN_SUCCESS)
376 panic("uvm_swapin: uvm_fault_wire failed: %d", rv);
377
378 /*
379 * Some architectures need to be notified when the user area has
380 * moved to new physical page(s) (e.g. see mips/mips/vm_machdep.c).
381 */
382 cpu_swapin(p);
383 s = splstatclock();
384 if (p->p_stat == SRUN)
385 setrunqueue(p);
386 p->p_flag |= P_INMEM;
387 p->p_flag &= ~P_SWAPIN;
388 splx(s);
389 p->p_swtime = 0;
390 ++uvmexp.swapins;
391 }
392
393 /*
394 * uvm_scheduler: process zero main loop
395 *
396 * - attempt to swapin every swaped-out, runnable process in order of
397 * priority.
398 * - if not enough memory, wake the pagedaemon and let it clear space.
399 */
400
401 void
uvm_scheduler()402 uvm_scheduler()
403 {
404 struct proc *p;
405 int pri;
406 struct proc *pp;
407 int ppri;
408
409 loop:
410 #ifdef DEBUG
411 while (!enableswap)
412 tsleep(&proc0, PVM, "noswap", 0);
413 #endif
414 pp = NULL; /* process to choose */
415 ppri = INT_MIN; /* its priority */
416 LIST_FOREACH(p, &allproc, p_list) {
417
418 /* is it a runnable swapped out process? */
419 if (p->p_stat == SRUN && (p->p_flag & P_INMEM) == 0) {
420 pri = p->p_swtime + p->p_slptime -
421 (p->p_nice - NZERO) * 8;
422 if (pri > ppri) { /* higher priority? remember it. */
423 pp = p;
424 ppri = pri;
425 }
426 }
427 }
428
429 #ifdef DEBUG
430 if (swapdebug & SDB_FOLLOW)
431 printf("scheduler: running, procp %p pri %d\n", pp, ppri);
432 #endif
433 /*
434 * Nothing to do, back to sleep
435 */
436 if ((p = pp) == NULL) {
437 tsleep(&proc0, PVM, "scheduler", 0);
438 goto loop;
439 }
440
441 /*
442 * we have found swapped out process which we would like to bring
443 * back in.
444 *
445 * XXX: this part is really bogus because we could deadlock on memory
446 * despite our feeble check
447 */
448 if (uvmexp.free > atop(USPACE)) {
449 #ifdef DEBUG
450 if (swapdebug & SDB_SWAPIN)
451 printf("swapin: pid %d(%s)@%p, pri %d free %d\n",
452 p->p_pid, p->p_comm, p->p_addr, ppri, uvmexp.free);
453 #endif
454 uvm_swapin(p);
455 goto loop;
456 }
457 /*
458 * not enough memory, jab the pageout daemon and wait til the coast
459 * is clear
460 */
461 #ifdef DEBUG
462 if (swapdebug & SDB_FOLLOW)
463 printf("scheduler: no room for pid %d(%s), free %d\n",
464 p->p_pid, p->p_comm, uvmexp.free);
465 #endif
466 uvm_wait("schedpwait");
467 #ifdef DEBUG
468 if (swapdebug & SDB_FOLLOW)
469 printf("scheduler: room again, free %d\n", uvmexp.free);
470 #endif
471 goto loop;
472 }
473
474 /*
475 * swappable: is process "p" swappable?
476 */
477
478 #define swappable(p) \
479 (((p)->p_flag & (P_SYSTEM | P_INMEM | P_WEXIT)) == P_INMEM && \
480 (p)->p_holdcnt == 0)
481
482 /*
483 * swapout_threads: find threads that can be swapped and unwire their
484 * u-areas.
485 *
486 * - called by the pagedaemon
487 * - try and swap at least one processs
488 * - processes that are sleeping or stopped for maxslp or more seconds
489 * are swapped... otherwise the longest-sleeping or stopped process
490 * is swapped, otherwise the longest resident process...
491 */
492 void
uvm_swapout_threads()493 uvm_swapout_threads()
494 {
495 struct proc *p;
496 struct proc *outp, *outp2;
497 int outpri, outpri2;
498 int didswap = 0;
499 extern int maxslp;
500 /* XXXCDC: should move off to uvmexp. or uvm., also in uvm_meter */
501
502 #ifdef DEBUG
503 if (!enableswap)
504 return;
505 #endif
506
507 /*
508 * outp/outpri : stop/sleep process with largest sleeptime < maxslp
509 * outp2/outpri2: the longest resident process (its swap time)
510 */
511 outp = outp2 = NULL;
512 outpri = outpri2 = 0;
513 LIST_FOREACH(p, &allproc, p_list) {
514 if (!swappable(p))
515 continue;
516 switch (p->p_stat) {
517 case SRUN:
518 if (p->p_swtime > outpri2) {
519 outp2 = p;
520 outpri2 = p->p_swtime;
521 }
522 continue;
523
524 case SSLEEP:
525 case SSTOP:
526 if (p->p_slptime >= maxslp) {
527 uvm_swapout(p);
528 didswap++;
529 } else if (p->p_slptime > outpri) {
530 outp = p;
531 outpri = p->p_slptime;
532 }
533 continue;
534 }
535 }
536
537 /*
538 * If we didn't get rid of any real duds, toss out the next most
539 * likely sleeping/stopped or running candidate. We only do this
540 * if we are real low on memory since we don't gain much by doing
541 * it (USPACE bytes).
542 */
543 if (didswap == 0 && uvmexp.free <= atop(round_page(USPACE))) {
544 if ((p = outp) == NULL)
545 p = outp2;
546 #ifdef DEBUG
547 if (swapdebug & SDB_SWAPOUT)
548 printf("swapout_threads: no duds, try procp %p\n", p);
549 #endif
550 if (p)
551 uvm_swapout(p);
552 }
553 }
554
555 /*
556 * uvm_swapout: swap out process "p"
557 *
558 * - currently "swapout" means "unwire U-area" and "pmap_collect()"
559 * the pmap.
560 * - XXXCDC: should deactivate all process' private anonymous memory
561 */
562
563 static void
uvm_swapout(p)564 uvm_swapout(p)
565 struct proc *p;
566 {
567 vaddr_t addr;
568 int s;
569
570 #ifdef DEBUG
571 if (swapdebug & SDB_SWAPOUT)
572 printf("swapout: pid %d(%s)@%p, stat %x pri %d free %d\n",
573 p->p_pid, p->p_comm, p->p_addr, p->p_stat,
574 p->p_slptime, uvmexp.free);
575 #endif
576
577 /*
578 * Mark it as (potentially) swapped out.
579 */
580 s = splstatclock();
581 if (!(p->p_flag & P_INMEM)) {
582 splx(s);
583 return;
584 }
585 p->p_flag &= ~P_INMEM;
586 if (p->p_stat == SRUN)
587 remrunqueue(p);
588 splx(s);
589 p->p_swtime = 0;
590 ++uvmexp.swapouts;
591
592 /*
593 * Do any machine-specific actions necessary before swapout.
594 * This can include saving floating point state, etc.
595 */
596 cpu_swapout(p);
597
598 /*
599 * Unwire the to-be-swapped process's user struct and kernel stack.
600 */
601 addr = (vaddr_t)p->p_addr;
602 uvm_fault_unwire(kernel_map, addr, addr + USPACE); /* !P_INMEM */
603 pmap_collect(vm_map_pmap(&p->p_vmspace->vm_map));
604 }
605
606