cb1b952b25d05d5423078f41820fdba9234e8b32
[dragonfly.git] / sys / vm / vm_glue.c
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: src/sys/vm/vm_glue.c,v 1.94.2.4 2003/01/13 22:51:17 dillon Exp $
63  * $DragonFly: src/sys/vm/vm_glue.c,v 1.49 2007/02/03 17:05:59 corecode Exp $
64  */
65
66 #include "opt_vm.h"
67
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/proc.h>
71 #include <sys/resourcevar.h>
72 #include <sys/buf.h>
73 #include <sys/shm.h>
74 #include <sys/vmmeter.h>
75 #include <sys/sysctl.h>
76
77 #include <sys/kernel.h>
78 #include <sys/unistd.h>
79
80 #include <machine/limits.h>
81
82 #include <vm/vm.h>
83 #include <vm/vm_param.h>
84 #include <sys/lock.h>
85 #include <vm/pmap.h>
86 #include <vm/vm_map.h>
87 #include <vm/vm_page.h>
88 #include <vm/vm_pageout.h>
89 #include <vm/vm_kern.h>
90 #include <vm/vm_extern.h>
91
92 #include <sys/user.h>
93 #include <vm/vm_page2.h>
94 #include <sys/thread2.h>
95
96 /*
97  * System initialization
98  *
99  * Note: proc0 from proc.h
100  */
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 #ifdef INVARIANTS
114
115 static int swap_debug = 0;
116 SYSCTL_INT(_vm, OID_AUTO, swap_debug,
117         CTLFLAG_RW, &swap_debug, 0, "");
118
119 #endif
120
121 static int scheduler_notify;
122
123 static void swapout (struct proc *);
124
125 int
126 kernacc(c_caddr_t addr, int len, int rw)
127 {
128         boolean_t rv;
129         vm_offset_t saddr, eaddr;
130         vm_prot_t prot;
131
132         KASSERT((rw & (~VM_PROT_ALL)) == 0,
133             ("illegal ``rw'' argument to kernacc (%x)\n", rw));
134
135         /*
136          * The globaldata space is not part of the kernel_map proper,
137          * check access separately.
138          */
139         if (is_globaldata_space((vm_offset_t)addr, (vm_offset_t)(addr + len)))
140                 return (TRUE);
141
142         /*
143          * Nominal kernel memory access - check access via kernel_map.
144          */
145         if ((vm_offset_t)addr + len > kernel_map.max_offset ||
146             (vm_offset_t)addr + len < (vm_offset_t)addr) {
147                 return (FALSE);
148         }
149         prot = rw;
150         saddr = trunc_page((vm_offset_t)addr);
151         eaddr = round_page((vm_offset_t)addr + len);
152         vm_map_lock_read(&kernel_map);
153         rv = vm_map_check_protection(&kernel_map, saddr, eaddr, prot);
154         vm_map_unlock_read(&kernel_map);
155         return (rv == TRUE);
156 }
157
158 int
159 useracc(c_caddr_t addr, int len, int rw)
160 {
161         boolean_t rv;
162         vm_prot_t prot;
163         vm_map_t map;
164         vm_map_entry_t save_hint;
165
166         KASSERT((rw & (~VM_PROT_ALL)) == 0,
167             ("illegal ``rw'' argument to useracc (%x)\n", rw));
168         prot = rw;
169         /*
170          * XXX - check separately to disallow access to user area and user
171          * page tables - they are in the map.
172          *
173          * XXX - VM_MAX_USER_ADDRESS is an end address, not a max.  It was once
174          * only used (as an end address) in trap.c.  Use it as an end address
175          * here too.  This bogusness has spread.  I just fixed where it was
176          * used as a max in vm_mmap.c.
177          */
178         if ((vm_offset_t) addr + len > /* XXX */ VM_MAX_USER_ADDRESS
179             || (vm_offset_t) addr + len < (vm_offset_t) addr) {
180                 return (FALSE);
181         }
182         map = &curproc->p_vmspace->vm_map;
183         vm_map_lock_read(map);
184         /*
185          * We save the map hint, and restore it.  Useracc appears to distort
186          * the map hint unnecessarily.
187          */
188         save_hint = map->hint;
189         rv = vm_map_check_protection(map,
190             trunc_page((vm_offset_t)addr), round_page((vm_offset_t)addr + len), prot);
191         map->hint = save_hint;
192         vm_map_unlock_read(map);
193         
194         return (rv == TRUE);
195 }
196
197 void
198 vslock(caddr_t addr, u_int len)
199 {
200         if (len) {
201                 vm_map_wire(&curproc->p_vmspace->vm_map,
202                             trunc_page((vm_offset_t)addr),
203                             round_page((vm_offset_t)addr + len), 0);
204         }
205 }
206
207 void
208 vsunlock(caddr_t addr, u_int len)
209 {
210         if (len) {
211                 vm_map_wire(&curproc->p_vmspace->vm_map,
212                             trunc_page((vm_offset_t)addr),
213                             round_page((vm_offset_t)addr + len),
214                             KM_PAGEABLE);
215         }
216 }
217
218 /*
219  * Implement fork's actions on an address space.
220  * Here we arrange for the address space to be copied or referenced,
221  * allocate a user struct (pcb and kernel stack), then call the
222  * machine-dependent layer to fill those in and make the new process
223  * ready to run.  The new process is set up so that it returns directly
224  * to user mode to avoid stack copying and relocation problems.
225  */
226 void
227 vm_fork(struct lwp *lp1, struct proc *p2, int flags)
228 {
229         struct user *up;
230         struct proc *p1 = lp1->lwp_proc;
231         struct thread *td2;
232
233         if ((flags & RFPROC) == 0) {
234                 /*
235                  * Divorce the memory, if it is shared, essentially
236                  * this changes shared memory amongst threads, into
237                  * COW locally.
238                  */
239                 if ((flags & RFMEM) == 0) {
240                         if (p1->p_vmspace->vm_refcnt > 1) {
241                                 vmspace_unshare(p1);
242                         }
243                 }
244                 cpu_fork(lp1, NULL, flags);
245                 return;
246         }
247
248         if (flags & RFMEM) {
249                 p2->p_vmspace = p1->p_vmspace;
250                 p1->p_vmspace->vm_refcnt++;
251         }
252
253         while (vm_page_count_severe()) {
254                 vm_wait();
255         }
256
257         if ((flags & RFMEM) == 0) {
258                 p2->p_vmspace = vmspace_fork(p1->p_vmspace);
259
260                 pmap_pinit2(vmspace_pmap(p2->p_vmspace));
261
262                 if (p1->p_vmspace->vm_shm)
263                         shmfork(p1, p2);
264         }
265
266         td2 = lwkt_alloc_thread(NULL, LWKT_THREAD_STACK, -1, 0);
267         pmap_init_proc(p2, td2);
268         lwkt_setpri(td2, TDPRI_KERN_USER);
269         lwkt_set_comm(td2, "%s", p1->p_comm);
270
271         up = p2->p_addr;
272
273         /*
274          * p_stats currently points at fields in the user struct
275          * but not at &u, instead at p_addr. Copy parts of
276          * p_stats; zero the rest of p_stats (statistics).
277          *
278          * If procsig->ps_refcnt is 1 and p2->p_sigacts is NULL we dont' need
279          * to share sigacts, so we use the up->u_sigacts.
280          */
281         if (p2->p_sigacts == NULL) {
282                 if (p2->p_procsig->ps_refcnt != 1)
283                         kprintf ("PID:%d NULL sigacts with refcnt not 1!\n",p2->p_pid);
284                 p2->p_sigacts = &up->u_sigacts;
285                 up->u_sigacts = *p1->p_sigacts;
286         }
287
288         /*
289          * cpu_fork will copy and update the pcb, set up the kernel stack,
290          * and make the child ready to run.
291          */
292         cpu_fork(lp1, td2->td_lwp, flags);
293 }
294
295 /*
296  * Called after process has been wait(2)'ed apon and is being reaped.
297  * The idea is to reclaim resources that we could not reclaim while  
298  * the process was still executing.
299  */
300 void
301 vm_waitproc(struct proc *p)
302 {
303         cpu_proc_wait(p);
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(void *udata)
315 {
316         struct proc *p = udata;
317         int rss_limit;
318
319         /*
320          * Set up the initial limits on process VM. Set the maximum resident
321          * set size to be half of (reasonably) available memory.  Since this
322          * is a soft limit, it comes into effect only when the system is out
323          * of memory - half of main memory helps to favor smaller processes,
324          * and reduces thrashing of the object cache.
325          */
326         p->p_rlimit[RLIMIT_STACK].rlim_cur = dflssiz;
327         p->p_rlimit[RLIMIT_STACK].rlim_max = maxssiz;
328         p->p_rlimit[RLIMIT_DATA].rlim_cur = dfldsiz;
329         p->p_rlimit[RLIMIT_DATA].rlim_max = maxdsiz;
330         /* limit the limit to no less than 2MB */
331         rss_limit = max(vmstats.v_free_count, 512);
332         p->p_rlimit[RLIMIT_RSS].rlim_cur = ptoa(rss_limit);
333         p->p_rlimit[RLIMIT_RSS].rlim_max = RLIM_INFINITY;
334 }
335
336 /*
337  * Faultin the specified process.  Note that the process can be in any
338  * state.  Just clear P_SWAPPEDOUT and call wakeup in case the process is
339  * sleeping.
340  */
341 void
342 faultin(struct proc *p)
343 {
344         if (p->p_flag & P_SWAPPEDOUT) {
345                 /*
346                  * The process is waiting in the kernel to return to user
347                  * mode but cannot until P_SWAPPEDOUT gets cleared.
348                  */
349                 crit_enter();
350                 p->p_flag &= ~(P_SWAPPEDOUT | P_SWAPWAIT);
351 #ifdef INVARIANTS
352                 if (swap_debug)
353                         kprintf("swapping in %d (%s)\n", p->p_pid, p->p_comm);
354 #endif
355                 wakeup(p);
356
357                 crit_exit();
358         }
359 }
360
361 /*
362  * Kernel initialization eventually falls through to this function,
363  * which is process 0.
364  *
365  * This swapin algorithm attempts to swap-in processes only if there
366  * is enough space for them.  Of course, if a process waits for a long
367  * time, it will be swapped in anyway.
368  */
369
370 struct scheduler_info {
371         struct proc *pp;
372         int ppri;
373 };
374
375 static int scheduler_callback(struct proc *p, void *data);
376
377 static void
378 scheduler(void *dummy)
379 {
380         struct scheduler_info info;
381         struct proc *p;
382
383         KKASSERT(!IN_CRITICAL_SECT(curthread));
384 loop:
385         scheduler_notify = 0;
386         /*
387          * Don't try to swap anything in if we are low on memory.
388          */
389         if (vm_page_count_min()) {
390                 vm_wait();
391                 goto loop;
392         }
393
394         /*
395          * Look for a good candidate to wake up
396          */
397         info.pp = NULL;
398         info.ppri = INT_MIN;
399         allproc_scan(scheduler_callback, &info);
400
401         /*
402          * Nothing to do, back to sleep for at least 1/10 of a second.  If
403          * we are woken up, immediately process the next request.  If
404          * multiple requests have built up the first is processed 
405          * immediately and the rest are staggered.
406          */
407         if ((p = info.pp) == NULL) {
408                 tsleep(&proc0, 0, "nowork", hz / 10);
409                 if (scheduler_notify == 0)
410                         tsleep(&scheduler_notify, 0, "nowork", 0);
411                 goto loop;
412         }
413
414         /*
415          * Fault the selected process in, then wait for a short period of
416          * time and loop up.
417          *
418          * XXX we need a heuristic to get a measure of system stress and
419          * then adjust our stagger wakeup delay accordingly.
420          */
421         faultin(p);
422         p->p_swtime = 0;
423         PRELE(p);
424         tsleep(&proc0, 0, "swapin", hz / 10);
425         goto loop;
426 }
427
428 static int
429 scheduler_callback(struct proc *p, void *data)
430 {
431         struct scheduler_info *info = data;
432         struct lwp *lp;
433         segsz_t pgs;
434         int pri;
435
436         if (p->p_flag & P_SWAPWAIT) {
437                 /* XXX lwp */
438                 lp = FIRST_LWP_IN_PROC(p);
439                 pri = p->p_swtime + lp->lwp_slptime - p->p_nice * 8;
440
441                 /*
442                  * The more pages paged out while we were swapped,
443                  * the more work we have to do to get up and running
444                  * again and the lower our wakeup priority.
445                  *
446                  * Each second of sleep time is worth ~1MB
447                  */
448                 pgs = vmspace_resident_count(p->p_vmspace);
449                 if (pgs < p->p_vmspace->vm_swrss) {
450                         pri -= (p->p_vmspace->vm_swrss - pgs) /
451                                 (1024 * 1024 / PAGE_SIZE);
452                 }
453
454                 /*
455                  * If this process is higher priority and there is
456                  * enough space, then select this process instead of
457                  * the previous selection.
458                  */
459                 if (pri > info->ppri) {
460                         if (info->pp)
461                                 PRELE(info->pp);
462                         PHOLD(p);
463                         info->pp = p;
464                         info->ppri = pri;
465                 }
466         }
467         return(0);
468 }
469
470 void
471 swapin_request(void)
472 {
473         if (scheduler_notify == 0) {
474                 scheduler_notify = 1;
475                 wakeup(&scheduler_notify);
476         }
477 }
478
479 #ifndef NO_SWAPPING
480
481 #define swappable(p) \
482         (((p)->p_lock == 0) && \
483         ((p)->p_flag & (P_TRACED|P_SYSTEM|P_SWAPPEDOUT|P_WEXIT)) == 0)
484
485
486 /*
487  * Swap_idle_threshold1 is the guaranteed swapped in time for a process
488  */
489 static int swap_idle_threshold1 = 15;
490 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold1,
491         CTLFLAG_RW, &swap_idle_threshold1, 0, "");
492
493 /*
494  * Swap_idle_threshold2 is the time that a process can be idle before
495  * it will be swapped out, if idle swapping is enabled.  Default is
496  * one minute.
497  */
498 static int swap_idle_threshold2 = 60;
499 SYSCTL_INT(_vm, OID_AUTO, swap_idle_threshold2,
500         CTLFLAG_RW, &swap_idle_threshold2, 0, "");
501
502 /*
503  * Swapout is driven by the pageout daemon.  Very simple, we find eligible
504  * procs and mark them as being swapped out.  This will cause the kernel
505  * to prefer to pageout those proc's pages first and the procs in question 
506  * will not return to user mode until the swapper tells them they can.
507  *
508  * If any procs have been sleeping/stopped for at least maxslp seconds,
509  * they are swapped.  Else, we swap the longest-sleeping or stopped process,
510  * if any, otherwise the longest-resident process.
511  */
512
513 static int swapout_procs_callback(struct proc *p, void *data);
514
515 void
516 swapout_procs(int action)
517 {
518         allproc_scan(swapout_procs_callback, &action);
519 }
520
521 static int
522 swapout_procs_callback(struct proc *p, void *data)
523 {
524         struct vmspace *vm;
525         struct lwp *lp;
526         int action = *(int *)data;
527
528         if (!swappable(p))
529                 return(0);
530
531         vm = p->p_vmspace;
532
533         if (p->p_stat == SSLEEP || p->p_stat == SRUN) {
534                 /*
535                  * do not swap out a realtime process
536                  */
537                 /* XXX lwp */
538                 lp = FIRST_LWP_IN_PROC(p);
539                 if (RTP_PRIO_IS_REALTIME(lp->lwp_rtprio.type))
540                         return(0);
541
542                 /*
543                  * Guarentee swap_idle_threshold time in memory
544                  */
545                 if (lp->lwp_slptime < swap_idle_threshold1)
546                         return(0);
547
548                 /*
549                  * If the system is under memory stress, or if we
550                  * are swapping 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                      (lp->lwp_slptime < swap_idle_threshold2))) {
556                         return(0);
557                 }
558
559                 ++vm->vm_refcnt;
560
561                 /*
562                  * If the process has been asleep for awhile, swap
563                  * it out.
564                  */
565                 if ((action & VM_SWAP_NORMAL) ||
566                     ((action & VM_SWAP_IDLE) &&
567                      (lp->lwp_slptime > swap_idle_threshold2))) {
568                         swapout(p);
569                 }
570
571                 /*
572                  * cleanup our reference
573                  */
574                 vmspace_free(vm);
575         }
576         return(0);
577 }
578
579 static void
580 swapout(struct proc *p)
581 {
582 #ifdef INVARIANTS
583         if (swap_debug)
584                 kprintf("swapping out %d (%s)\n", p->p_pid, p->p_comm);
585 #endif
586         ++p->p_ru.ru_nswap;
587         /*
588          * remember the process resident count
589          */
590         p->p_vmspace->vm_swrss = vmspace_resident_count(p->p_vmspace);
591         p->p_flag |= P_SWAPPEDOUT;
592         p->p_swtime = 0;
593 }
594
595 #endif /* !NO_SWAPPING */
596