kernel - MPSAFE work - first pass at tokenizing vm/vm_mmap.c
[dragonfly.git] / sys / vm / vm_mmap.c
1 /*
2  * Copyright (c) 1988 University of Utah.
3  * Copyright (c) 1991, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * the Systems Programming Group of the University of Utah Computer
8  * Science Department.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * from: Utah $Hdr: vm_mmap.c 1.6 91/10/21$
39  *
40  *      @(#)vm_mmap.c   8.4 (Berkeley) 1/12/94
41  * $FreeBSD: src/sys/vm/vm_mmap.c,v 1.108.2.6 2002/07/02 20:06:19 dillon Exp $
42  * $DragonFly: src/sys/vm/vm_mmap.c,v 1.39 2007/04/30 07:18:57 dillon Exp $
43  */
44
45 /*
46  * Mapped file (mmap) interface to VM
47  */
48
49 #include <sys/param.h>
50 #include <sys/kernel.h>
51 #include <sys/systm.h>
52 #include <sys/sysproto.h>
53 #include <sys/filedesc.h>
54 #include <sys/kern_syscall.h>
55 #include <sys/proc.h>
56 #include <sys/priv.h>
57 #include <sys/resource.h>
58 #include <sys/resourcevar.h>
59 #include <sys/vnode.h>
60 #include <sys/fcntl.h>
61 #include <sys/file.h>
62 #include <sys/mman.h>
63 #include <sys/conf.h>
64 #include <sys/stat.h>
65 #include <sys/vmmeter.h>
66 #include <sys/sysctl.h>
67
68 #include <vm/vm.h>
69 #include <vm/vm_param.h>
70 #include <sys/lock.h>
71 #include <vm/pmap.h>
72 #include <vm/vm_map.h>
73 #include <vm/vm_object.h>
74 #include <vm/vm_page.h>
75 #include <vm/vm_pager.h>
76 #include <vm/vm_pageout.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_page.h>
79 #include <vm/vm_kern.h>
80
81 #include <sys/file2.h>
82 #include <sys/thread.h>
83 #include <sys/thread2.h>
84
85 static int max_proc_mmap;
86 SYSCTL_INT(_vm, OID_AUTO, max_proc_mmap, CTLFLAG_RW, &max_proc_mmap, 0, "");
87 int vkernel_enable;
88 SYSCTL_INT(_vm, OID_AUTO, vkernel_enable, CTLFLAG_RW, &vkernel_enable, 0, "");
89
90 /*
91  * Set the maximum number of vm_map_entry structures per process.  Roughly
92  * speaking vm_map_entry structures are tiny, so allowing them to eat 1/100
93  * of our KVM malloc space still results in generous limits.  We want a 
94  * default that is good enough to prevent the kernel running out of resources
95  * if attacked from compromised user account but generous enough such that
96  * multi-threaded processes are not unduly inconvenienced.
97  */
98
99 static void vmmapentry_rsrc_init (void *);
100 SYSINIT(vmmersrc, SI_BOOT1_POST, SI_ORDER_ANY, vmmapentry_rsrc_init, NULL)
101
102 static void
103 vmmapentry_rsrc_init(void *dummy)
104 {
105     max_proc_mmap = KvaSize / sizeof(struct vm_map_entry);
106     max_proc_mmap /= 100;
107 }
108
109 /*
110  * MPSAFE
111  */
112 int
113 sys_sbrk(struct sbrk_args *uap)
114 {
115         /* Not yet implemented */
116         return (EOPNOTSUPP);
117 }
118
119 /*
120  * sstk_args(int incr)
121  *
122  * MPSAFE
123  */
124 int
125 sys_sstk(struct sstk_args *uap)
126 {
127         /* Not yet implemented */
128         return (EOPNOTSUPP);
129 }
130
131 /* 
132  * mmap_args(void *addr, size_t len, int prot, int flags, int fd,
133  *              long pad, off_t pos)
134  *
135  * Memory Map (mmap) system call.  Note that the file offset
136  * and address are allowed to be NOT page aligned, though if
137  * the MAP_FIXED flag it set, both must have the same remainder
138  * modulo the PAGE_SIZE (POSIX 1003.1b).  If the address is not
139  * page-aligned, the actual mapping starts at trunc_page(addr)
140  * and the return value is adjusted up by the page offset.
141  *
142  * Generally speaking, only character devices which are themselves
143  * memory-based, such as a video framebuffer, can be mmap'd.  Otherwise
144  * there would be no cache coherency between a descriptor and a VM mapping
145  * both to the same character device.
146  *
147  * Block devices can be mmap'd no matter what they represent.  Cache coherency
148  * is maintained as long as you do not write directly to the underlying
149  * character device.
150  *
151  * Requires caller to hold vm_token.
152  */
153 int
154 kern_mmap(struct vmspace *vms, caddr_t uaddr, size_t ulen,
155           int uprot, int uflags, int fd, off_t upos, void **res)
156 {
157         struct thread *td = curthread;
158         struct proc *p = td->td_proc;
159         struct file *fp = NULL;
160         struct vnode *vp;
161         vm_offset_t addr;
162         vm_offset_t tmpaddr;
163         vm_size_t size, pageoff;
164         vm_prot_t prot, maxprot;
165         void *handle;
166         int flags, error;
167         off_t pos;
168         vm_object_t obj;
169
170         KKASSERT(p);
171         ASSERT_LWKT_TOKEN_HELD(&vm_token);
172
173         addr = (vm_offset_t) uaddr;
174         size = ulen;
175         prot = uprot & VM_PROT_ALL;
176         flags = uflags;
177         pos = upos;
178
179         /*
180          * Make sure mapping fits into numeric range etc.
181          *
182          * NOTE: We support the full unsigned range for size now.
183          */
184         if (((flags & MAP_ANON) && (fd != -1 || pos != 0)))
185                 return (EINVAL);
186
187         if (flags & MAP_STACK) {
188                 if ((fd != -1) ||
189                     ((prot & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)))
190                         return (EINVAL);
191                 flags |= MAP_ANON;
192                 pos = 0;
193         }
194
195         /*
196          * Virtual page tables cannot be used with MAP_STACK.  Apart from
197          * it not making any sense, the aux union is used by both
198          * types.
199          *
200          * Because the virtual page table is stored in the backing object
201          * and might be updated by the kernel, the mapping must be R+W.
202          */
203         if (flags & MAP_VPAGETABLE) {
204                 if (vkernel_enable == 0)
205                         return (EOPNOTSUPP);
206                 if (flags & MAP_STACK)
207                         return (EINVAL);
208                 if ((prot & (PROT_READ|PROT_WRITE)) != (PROT_READ|PROT_WRITE))
209                         return (EINVAL);
210         }
211
212         /*
213          * Align the file position to a page boundary,
214          * and save its page offset component.
215          */
216         pageoff = (pos & PAGE_MASK);
217         pos -= pageoff;
218
219         /* Adjust size for rounding (on both ends). */
220         size += pageoff;                        /* low end... */
221         size = (vm_size_t) round_page(size);    /* hi end */
222         if (size < ulen)                        /* wrap */
223                 return(EINVAL);
224
225         /*
226          * Check for illegal addresses.  Watch out for address wrap... Note
227          * that VM_*_ADDRESS are not constants due to casts (argh).
228          */
229         if (flags & (MAP_FIXED | MAP_TRYFIXED)) {
230                 /*
231                  * The specified address must have the same remainder
232                  * as the file offset taken modulo PAGE_SIZE, so it
233                  * should be aligned after adjustment by pageoff.
234                  */
235                 addr -= pageoff;
236                 if (addr & PAGE_MASK)
237                         return (EINVAL);
238
239                 /*
240                  * Address range must be all in user VM space and not wrap.
241                  */
242                 tmpaddr = addr + size;
243                 if (tmpaddr < addr)
244                         return (EINVAL);
245                 if (VM_MAX_USER_ADDRESS > 0 && tmpaddr > VM_MAX_USER_ADDRESS)
246                         return (EINVAL);
247                 if (VM_MIN_USER_ADDRESS > 0 && addr < VM_MIN_USER_ADDRESS)
248                         return (EINVAL);
249         } else {
250                 /*
251                  * Set a reasonable start point for the hint if it was
252                  * not specified or if it falls within the heap space.
253                  * Hinted mmap()s do not allocate out of the heap space.
254                  */
255                 if (addr == 0 ||
256                     (addr >= round_page((vm_offset_t)vms->vm_taddr) &&
257                      addr < round_page((vm_offset_t)vms->vm_daddr + maxdsiz)))
258                         addr = round_page((vm_offset_t)vms->vm_daddr + maxdsiz);
259         }
260
261         if (flags & MAP_ANON) {
262                 /*
263                  * Mapping blank space is trivial.
264                  */
265                 handle = NULL;
266                 maxprot = VM_PROT_ALL;
267         } else {
268                 /*
269                  * Mapping file, get fp for validation. Obtain vnode and make
270                  * sure it is of appropriate type.
271                  */
272                 fp = holdfp(p->p_fd, fd, -1);
273                 if (fp == NULL)
274                         return (EBADF);
275                 if (fp->f_type != DTYPE_VNODE) {
276                         error = EINVAL;
277                         goto done;
278                 }
279                 /*
280                  * POSIX shared-memory objects are defined to have
281                  * kernel persistence, and are not defined to support
282                  * read(2)/write(2) -- or even open(2).  Thus, we can
283                  * use MAP_ASYNC to trade on-disk coherence for speed.
284                  * The shm_open(3) library routine turns on the FPOSIXSHM
285                  * flag to request this behavior.
286                  */
287                 if (fp->f_flag & FPOSIXSHM)
288                         flags |= MAP_NOSYNC;
289                 vp = (struct vnode *) fp->f_data;
290
291                 /*
292                  * Validate the vnode for the operation.
293                  */
294                 switch(vp->v_type) {
295                 case VREG:
296                         /*
297                          * Get the proper underlying object
298                          */
299                         if ((obj = vp->v_object) == NULL) {
300                                 error = EINVAL;
301                                 goto done;
302                         }
303                         KKASSERT((struct vnode *)obj->handle == vp);
304                         break;
305                 case VCHR:
306                         /*
307                          * Make sure a device has not been revoked.  
308                          * Mappability is handled by the device layer.
309                          */
310                         if (vp->v_rdev == NULL) {
311                                 error = EBADF;
312                                 goto done;
313                         }
314                         break;
315                 default:
316                         /*
317                          * Nothing else is mappable.
318                          */
319                         error = EINVAL;
320                         goto done;
321                 }
322
323                 /*
324                  * XXX hack to handle use of /dev/zero to map anon memory (ala
325                  * SunOS).
326                  */
327                 if (vp->v_type == VCHR && iszerodev(vp->v_rdev)) {
328                         handle = NULL;
329                         maxprot = VM_PROT_ALL;
330                         flags |= MAP_ANON;
331                         pos = 0;
332                 } else {
333                         /*
334                          * cdevs does not provide private mappings of any kind.
335                          */
336                         if (vp->v_type == VCHR &&
337                             (flags & (MAP_PRIVATE|MAP_COPY))) {
338                                 error = EINVAL;
339                                 goto done;
340                         }
341                         /*
342                          * Ensure that file and memory protections are
343                          * compatible.  Note that we only worry about
344                          * writability if mapping is shared; in this case,
345                          * current and max prot are dictated by the open file.
346                          * XXX use the vnode instead?  Problem is: what
347                          * credentials do we use for determination? What if
348                          * proc does a setuid?
349                          */
350                         maxprot = VM_PROT_EXECUTE;      /* ??? */
351                         if (fp->f_flag & FREAD) {
352                                 maxprot |= VM_PROT_READ;
353                         } else if (prot & PROT_READ) {
354                                 error = EACCES;
355                                 goto done;
356                         }
357                         /*
358                          * If we are sharing potential changes (either via
359                          * MAP_SHARED or via the implicit sharing of character
360                          * device mappings), and we are trying to get write
361                          * permission although we opened it without asking
362                          * for it, bail out.  Check for superuser, only if
363                          * we're at securelevel < 1, to allow the XIG X server
364                          * to continue to work.
365                          */
366                         if ((flags & MAP_SHARED) != 0 || vp->v_type == VCHR) {
367                                 if ((fp->f_flag & FWRITE) != 0) {
368                                         struct vattr va;
369                                         if ((error = VOP_GETATTR(vp, &va))) {
370                                                 goto done;
371                                         }
372                                         if ((va.va_flags &
373                                             (IMMUTABLE|APPEND)) == 0) {
374                                                 maxprot |= VM_PROT_WRITE;
375                                         } else if (prot & PROT_WRITE) {
376                                                 error = EPERM;
377                                                 goto done;
378                                         }
379                                 } else if ((prot & PROT_WRITE) != 0) {
380                                         error = EACCES;
381                                         goto done;
382                                 }
383                         } else {
384                                 maxprot |= VM_PROT_WRITE;
385                         }
386                         handle = (void *)vp;
387                 }
388         }
389
390         /*
391          * Do not allow more then a certain number of vm_map_entry structures
392          * per process.  Scale with the number of rforks sharing the map
393          * to make the limit reasonable for threads.
394          */
395         if (max_proc_mmap && 
396             vms->vm_map.nentries >= max_proc_mmap * vms->vm_sysref.refcnt) {
397                 error = ENOMEM;
398                 goto done;
399         }
400
401         error = vm_mmap(&vms->vm_map, &addr, size, prot, maxprot,
402                         flags, handle, pos);
403         if (error == 0)
404                 *res = (void *)(addr + pageoff);
405 done:
406         if (fp)
407                 fdrop(fp);
408         return (error);
409 }
410
411 /*
412  * mmap system call handler
413  *
414  * No requirements.
415  */
416 int
417 sys_mmap(struct mmap_args *uap)
418 {
419         int error;
420
421         lwkt_gettoken(&vm_token);
422         error = kern_mmap(curproc->p_vmspace, uap->addr, uap->len,
423                           uap->prot, uap->flags,
424                           uap->fd, uap->pos, &uap->sysmsg_resultp);
425         lwkt_reltoken(&vm_token);
426
427         return (error);
428 }
429
430 /*
431  * msync system call handler 
432  *
433  * msync_args(void *addr, size_t len, int flags)
434  *
435  * No requirements
436  */
437 int
438 sys_msync(struct msync_args *uap)
439 {
440         struct proc *p = curproc;
441         vm_offset_t addr;
442         vm_offset_t tmpaddr;
443         vm_size_t size, pageoff;
444         int flags;
445         vm_map_t map;
446         int rv;
447
448         addr = (vm_offset_t) uap->addr;
449         size = uap->len;
450         flags = uap->flags;
451
452         pageoff = (addr & PAGE_MASK);
453         addr -= pageoff;
454         size += pageoff;
455         size = (vm_size_t) round_page(size);
456         if (size < uap->len)            /* wrap */
457                 return(EINVAL);
458         tmpaddr = addr + size;          /* workaround gcc4 opt */
459         if (tmpaddr < addr)             /* wrap */
460                 return(EINVAL);
461
462         if ((flags & (MS_ASYNC|MS_INVALIDATE)) == (MS_ASYNC|MS_INVALIDATE))
463                 return (EINVAL);
464
465         lwkt_gettoken(&vm_token);
466         map = &p->p_vmspace->vm_map;
467
468         /*
469          * XXX Gak!  If size is zero we are supposed to sync "all modified
470          * pages with the region containing addr".  Unfortunately, we don't
471          * really keep track of individual mmaps so we approximate by flushing
472          * the range of the map entry containing addr. This can be incorrect
473          * if the region splits or is coalesced with a neighbor.
474          */
475         if (size == 0) {
476                 vm_map_entry_t entry;
477
478                 vm_map_lock_read(map);
479                 rv = vm_map_lookup_entry(map, addr, &entry);
480                 if (rv == FALSE) {
481                         vm_map_unlock_read(map);
482                         rv = KERN_INVALID_ADDRESS;
483                         goto done;
484                 }
485                 addr = entry->start;
486                 size = entry->end - entry->start;
487                 vm_map_unlock_read(map);
488         }
489
490         /*
491          * Clean the pages and interpret the return value.
492          */
493         rv = vm_map_clean(map, addr, addr + size, (flags & MS_ASYNC) == 0,
494                           (flags & MS_INVALIDATE) != 0);
495 done:
496         lwkt_reltoken(&vm_token);
497
498         switch (rv) {
499         case KERN_SUCCESS:
500                 break;
501         case KERN_INVALID_ADDRESS:
502                 return (EINVAL);        /* Sun returns ENOMEM? */
503         case KERN_FAILURE:
504                 return (EIO);
505         default:
506                 return (EINVAL);
507         }
508
509         return (0);
510 }
511
512 /*
513  * munmap system call handler
514  *
515  * munmap_args(void *addr, size_t len)
516  *
517  * No requirements
518  */
519 int
520 sys_munmap(struct munmap_args *uap)
521 {
522         struct proc *p = curproc;
523         vm_offset_t addr;
524         vm_offset_t tmpaddr;
525         vm_size_t size, pageoff;
526         vm_map_t map;
527
528         addr = (vm_offset_t) uap->addr;
529         size = uap->len;
530
531         pageoff = (addr & PAGE_MASK);
532         addr -= pageoff;
533         size += pageoff;
534         size = (vm_size_t) round_page(size);
535         if (size < uap->len)            /* wrap */
536                 return(EINVAL);
537         tmpaddr = addr + size;          /* workaround gcc4 opt */
538         if (tmpaddr < addr)             /* wrap */
539                 return(EINVAL);
540
541         if (size == 0)
542                 return (0);
543
544         /*
545          * Check for illegal addresses.  Watch out for address wrap... Note
546          * that VM_*_ADDRESS are not constants due to casts (argh).
547          */
548         if (VM_MAX_USER_ADDRESS > 0 && tmpaddr > VM_MAX_USER_ADDRESS)
549                 return (EINVAL);
550         if (VM_MIN_USER_ADDRESS > 0 && addr < VM_MIN_USER_ADDRESS)
551                 return (EINVAL);
552
553         lwkt_gettoken(&vm_token);
554         map = &p->p_vmspace->vm_map;
555         /*
556          * Make sure entire range is allocated.
557          */
558         if (!vm_map_check_protection(map, addr, addr + size,
559                                      VM_PROT_NONE, FALSE)) {
560                 lwkt_reltoken(&vm_token);
561                 return (EINVAL);
562         }
563         /* returns nothing but KERN_SUCCESS anyway */
564         vm_map_remove(map, addr, addr + size);
565         lwkt_reltoken(&vm_token);
566         return (0);
567 }
568
569 /*
570  * mprotect_args(const void *addr, size_t len, int prot)
571  *
572  * MPALMOSTSAFE
573  */
574 int
575 sys_mprotect(struct mprotect_args *uap)
576 {
577         struct proc *p = curproc;
578         vm_offset_t addr;
579         vm_offset_t tmpaddr;
580         vm_size_t size, pageoff;
581         vm_prot_t prot;
582         int error;
583
584         addr = (vm_offset_t) uap->addr;
585         size = uap->len;
586         prot = uap->prot & VM_PROT_ALL;
587 #if defined(VM_PROT_READ_IS_EXEC)
588         if (prot & VM_PROT_READ)
589                 prot |= VM_PROT_EXECUTE;
590 #endif
591
592         pageoff = (addr & PAGE_MASK);
593         addr -= pageoff;
594         size += pageoff;
595         size = (vm_size_t) round_page(size);
596         if (size < uap->len)            /* wrap */
597                 return(EINVAL);
598         tmpaddr = addr + size;          /* workaround gcc4 opt */
599         if (tmpaddr < addr)             /* wrap */
600                 return(EINVAL);
601
602         lwkt_gettoken(&vm_token);
603         switch (vm_map_protect(&p->p_vmspace->vm_map, addr, addr + size,
604                                prot, FALSE)) {
605         case KERN_SUCCESS:
606                 error = 0;
607                 break;
608         case KERN_PROTECTION_FAILURE:
609                 error = EACCES;
610                 break;
611         default:
612                 error = EINVAL;
613                 break;
614         }
615         lwkt_reltoken(&vm_token);
616         return (error);
617 }
618
619 /*
620  * minherit system call handler
621  *
622  * minherit_args(void *addr, size_t len, int inherit)
623  *
624  * No requirements.
625  */
626 int
627 sys_minherit(struct minherit_args *uap)
628 {
629         struct proc *p = curproc;
630         vm_offset_t addr;
631         vm_offset_t tmpaddr;
632         vm_size_t size, pageoff;
633         vm_inherit_t inherit;
634         int error;
635
636         addr = (vm_offset_t)uap->addr;
637         size = uap->len;
638         inherit = uap->inherit;
639
640         pageoff = (addr & PAGE_MASK);
641         addr -= pageoff;
642         size += pageoff;
643         size = (vm_size_t) round_page(size);
644         if (size < uap->len)            /* wrap */
645                 return(EINVAL);
646         tmpaddr = addr + size;          /* workaround gcc4 opt */
647         if (tmpaddr < addr)             /* wrap */
648                 return(EINVAL);
649
650         lwkt_gettoken(&vm_token);
651
652         switch (vm_map_inherit(&p->p_vmspace->vm_map, addr,
653                                addr + size, inherit)) {
654         case KERN_SUCCESS:
655                 error = 0;
656                 break;
657         case KERN_PROTECTION_FAILURE:
658                 error = EACCES;
659                 break;
660         default:
661                 error = EINVAL;
662                 break;
663         }
664         lwkt_reltoken(&vm_token);
665         return (error);
666 }
667
668 /*
669  * madvise system call handler
670  * 
671  * madvise_args(void *addr, size_t len, int behav)
672  *
673  * No requirements.
674  */
675 int
676 sys_madvise(struct madvise_args *uap)
677 {
678         struct proc *p = curproc;
679         vm_offset_t start, end;
680         vm_offset_t tmpaddr = (vm_offset_t)uap->addr + uap->len;
681         int error;
682
683         /*
684          * Check for illegal behavior
685          */
686         if (uap->behav < 0 || uap->behav >= MADV_CONTROL_END)
687                 return (EINVAL);
688         /*
689          * Check for illegal addresses.  Watch out for address wrap... Note
690          * that VM_*_ADDRESS are not constants due to casts (argh).
691          */
692         if (tmpaddr < (vm_offset_t)uap->addr)
693                 return (EINVAL);
694         if (VM_MAX_USER_ADDRESS > 0 && tmpaddr > VM_MAX_USER_ADDRESS)
695                 return (EINVAL);
696         if (VM_MIN_USER_ADDRESS > 0 && uap->addr < VM_MIN_USER_ADDRESS)
697                 return (EINVAL);
698
699         /*
700          * Since this routine is only advisory, we default to conservative
701          * behavior.
702          */
703         start = trunc_page((vm_offset_t)uap->addr);
704         end = round_page(tmpaddr);
705
706         lwkt_gettoken(&vm_token);
707         error = vm_map_madvise(&p->p_vmspace->vm_map, start, end,
708                                uap->behav, 0);
709         lwkt_reltoken(&vm_token);
710         return (error);
711 }
712
713 /*
714  * mcontrol system call handler
715  *
716  * mcontrol_args(void *addr, size_t len, int behav, off_t value)
717  *
718  * No requirements
719  */
720 int
721 sys_mcontrol(struct mcontrol_args *uap)
722 {
723         struct proc *p = curproc;
724         vm_offset_t start, end;
725         vm_offset_t tmpaddr = (vm_offset_t)uap->addr + uap->len;
726         int error;
727
728         /*
729          * Check for illegal behavior
730          */
731         if (uap->behav < 0 || uap->behav > MADV_CONTROL_END)
732                 return (EINVAL);
733         /*
734          * Check for illegal addresses.  Watch out for address wrap... Note
735          * that VM_*_ADDRESS are not constants due to casts (argh).
736          */
737         if (tmpaddr < (vm_offset_t) uap->addr)
738                 return (EINVAL);
739         if (VM_MAX_USER_ADDRESS > 0 && tmpaddr > VM_MAX_USER_ADDRESS)
740                 return (EINVAL);
741         if (VM_MIN_USER_ADDRESS > 0 && uap->addr < VM_MIN_USER_ADDRESS)
742                 return (EINVAL);
743
744         /*
745          * Since this routine is only advisory, we default to conservative
746          * behavior.
747          */
748         start = trunc_page((vm_offset_t)uap->addr);
749         end = round_page(tmpaddr);
750         
751         lwkt_gettoken(&vm_token);
752         error = vm_map_madvise(&p->p_vmspace->vm_map, start, end,
753                                uap->behav, uap->value);
754         lwkt_reltoken(&vm_token);
755         return (error);
756 }
757
758
759 /*
760  * mincore system call handler
761  *
762  * mincore_args(const void *addr, size_t len, char *vec)
763  *
764  * No requirements
765  */
766 int
767 sys_mincore(struct mincore_args *uap)
768 {
769         struct proc *p = curproc;
770         vm_offset_t addr, first_addr;
771         vm_offset_t end, cend;
772         pmap_t pmap;
773         vm_map_t map;
774         char *vec;
775         int error;
776         int vecindex, lastvecindex;
777         vm_map_entry_t current;
778         vm_map_entry_t entry;
779         int mincoreinfo;
780         unsigned int timestamp;
781
782         /*
783          * Make sure that the addresses presented are valid for user
784          * mode.
785          */
786         first_addr = addr = trunc_page((vm_offset_t) uap->addr);
787         end = addr + (vm_size_t)round_page(uap->len);
788         if (end < addr)
789                 return (EINVAL);
790         if (VM_MAX_USER_ADDRESS > 0 && end > VM_MAX_USER_ADDRESS)
791                 return (EINVAL);
792
793         /*
794          * Address of byte vector
795          */
796         vec = uap->vec;
797
798         map = &p->p_vmspace->vm_map;
799         pmap = vmspace_pmap(p->p_vmspace);
800
801         lwkt_gettoken(&vm_token);
802         vm_map_lock_read(map);
803 RestartScan:
804         timestamp = map->timestamp;
805
806         if (!vm_map_lookup_entry(map, addr, &entry))
807                 entry = entry->next;
808
809         /*
810          * Do this on a map entry basis so that if the pages are not
811          * in the current processes address space, we can easily look
812          * up the pages elsewhere.
813          */
814         lastvecindex = -1;
815         for(current = entry;
816                 (current != &map->header) && (current->start < end);
817                 current = current->next) {
818
819                 /*
820                  * ignore submaps (for now) or null objects
821                  */
822                 if (current->maptype != VM_MAPTYPE_NORMAL &&
823                     current->maptype != VM_MAPTYPE_VPAGETABLE) {
824                         continue;
825                 }
826                 if (current->object.vm_object == NULL)
827                         continue;
828                 
829                 /*
830                  * limit this scan to the current map entry and the
831                  * limits for the mincore call
832                  */
833                 if (addr < current->start)
834                         addr = current->start;
835                 cend = current->end;
836                 if (cend > end)
837                         cend = end;
838
839                 /*
840                  * scan this entry one page at a time
841                  */
842                 while (addr < cend) {
843                         /*
844                          * Check pmap first, it is likely faster, also
845                          * it can provide info as to whether we are the
846                          * one referencing or modifying the page.
847                          *
848                          * If we have to check the VM object, only mess
849                          * around with normal maps.  Do not mess around
850                          * with virtual page tables (XXX).
851                          */
852                         mincoreinfo = pmap_mincore(pmap, addr);
853                         if (mincoreinfo == 0 &&
854                             current->maptype == VM_MAPTYPE_NORMAL) {
855                                 vm_pindex_t pindex;
856                                 vm_ooffset_t offset;
857                                 vm_page_t m;
858
859                                 /*
860                                  * calculate the page index into the object
861                                  */
862                                 offset = current->offset + (addr - current->start);
863                                 pindex = OFF_TO_IDX(offset);
864
865                                 /*
866                                  * if the page is resident, then gather 
867                                  * information about it.  spl protection is
868                                  * required to maintain the object 
869                                  * association.  And XXX what if the page is
870                                  * busy?  What's the deal with that?
871                                  */
872                                 crit_enter();
873                                 m = vm_page_lookup(current->object.vm_object,
874                                                     pindex);
875                                 if (m && m->valid) {
876                                         mincoreinfo = MINCORE_INCORE;
877                                         if (m->dirty ||
878                                                 pmap_is_modified(m))
879                                                 mincoreinfo |= MINCORE_MODIFIED_OTHER;
880                                         if ((m->flags & PG_REFERENCED) ||
881                                                 pmap_ts_referenced(m)) {
882                                                 vm_page_flag_set(m, PG_REFERENCED);
883                                                 mincoreinfo |= MINCORE_REFERENCED_OTHER;
884                                         }
885                                 }
886                                 crit_exit();
887                         }
888
889                         /*
890                          * subyte may page fault.  In case it needs to modify
891                          * the map, we release the lock.
892                          */
893                         vm_map_unlock_read(map);
894
895                         /*
896                          * calculate index into user supplied byte vector
897                          */
898                         vecindex = OFF_TO_IDX(addr - first_addr);
899
900                         /*
901                          * If we have skipped map entries, we need to make sure that
902                          * the byte vector is zeroed for those skipped entries.
903                          */
904                         while((lastvecindex + 1) < vecindex) {
905                                 error = subyte( vec + lastvecindex, 0);
906                                 if (error) {
907                                         error = EFAULT;
908                                         goto done;
909                                 }
910                                 ++lastvecindex;
911                         }
912
913                         /*
914                          * Pass the page information to the user
915                          */
916                         error = subyte( vec + vecindex, mincoreinfo);
917                         if (error) {
918                                 error = EFAULT;
919                                 goto done;
920                         }
921
922                         /*
923                          * If the map has changed, due to the subyte, the previous
924                          * output may be invalid.
925                          */
926                         vm_map_lock_read(map);
927                         if (timestamp != map->timestamp)
928                                 goto RestartScan;
929
930                         lastvecindex = vecindex;
931                         addr += PAGE_SIZE;
932                 }
933         }
934
935         /*
936          * subyte may page fault.  In case it needs to modify
937          * the map, we release the lock.
938          */
939         vm_map_unlock_read(map);
940
941         /*
942          * Zero the last entries in the byte vector.
943          */
944         vecindex = OFF_TO_IDX(end - first_addr);
945         while((lastvecindex + 1) < vecindex) {
946                 error = subyte( vec + lastvecindex, 0);
947                 if (error) {
948                         error = EFAULT;
949                         goto done;
950                 }
951                 ++lastvecindex;
952         }
953         
954         /*
955          * If the map has changed, due to the subyte, the previous
956          * output may be invalid.
957          */
958         vm_map_lock_read(map);
959         if (timestamp != map->timestamp)
960                 goto RestartScan;
961         vm_map_unlock_read(map);
962
963         error = 0;
964 done:
965         lwkt_reltoken(&vm_token);
966         return (error);
967 }
968
969 /*
970  * mlock system call handler
971  *
972  * mlock_args(const void *addr, size_t len)
973  *
974  * No requirements
975  */
976 int
977 sys_mlock(struct mlock_args *uap)
978 {
979         vm_offset_t addr;
980         vm_offset_t tmpaddr;
981         vm_size_t size, pageoff;
982         struct thread *td = curthread;
983         struct proc *p = td->td_proc;
984         int error;
985
986         addr = (vm_offset_t) uap->addr;
987         size = uap->len;
988
989         pageoff = (addr & PAGE_MASK);
990         addr -= pageoff;
991         size += pageoff;
992         size = (vm_size_t) round_page(size);
993         if (size < uap->len)            /* wrap */
994                 return(EINVAL);
995         tmpaddr = addr + size;          /* workaround gcc4 opt */
996         if (tmpaddr < addr)             /* wrap */
997                 return (EINVAL);
998
999         if (atop(size) + vmstats.v_wire_count > vm_page_max_wired)
1000                 return (EAGAIN);
1001
1002         lwkt_gettoken(&vm_token);
1003 #ifdef pmap_wired_count
1004         if (size + ptoa(pmap_wired_count(vm_map_pmap(&p->p_vmspace->vm_map))) >
1005             p->p_rlimit[RLIMIT_MEMLOCK].rlim_cur) {
1006                 lwkt_reltoken(&vm_token);
1007                 return (ENOMEM);
1008         }
1009 #else
1010         error = priv_check_cred(td->td_ucred, PRIV_ROOT, 0);
1011         if (error) {
1012                 lwkt_reltoken(&vm_token);
1013                 return (error);
1014         }
1015 #endif
1016         error = vm_map_unwire(&p->p_vmspace->vm_map, addr, addr + size, FALSE);
1017         lwkt_reltoken(&vm_token);
1018         return (error == KERN_SUCCESS ? 0 : ENOMEM);
1019 }
1020
1021 /*
1022  * mlockall_args(int how)
1023  *
1024  * Dummy routine, doesn't actually do anything.
1025  *
1026  * No requirements
1027  */
1028 int
1029 sys_mlockall(struct mlockall_args *uap)
1030 {
1031         return (ENOSYS);
1032 }
1033
1034 /*
1035  * munlockall_args(void)
1036  *
1037  * Dummy routine, doesn't actually do anything.
1038  *
1039  * No requirements
1040  */
1041 int
1042 sys_munlockall(struct munlockall_args *uap)
1043 {
1044         return (ENOSYS);
1045 }
1046
1047 /*
1048  * munlock system call handler
1049  *
1050  * munlock_args(const void *addr, size_t len)
1051  *
1052  * No requirements
1053  */
1054 int
1055 sys_munlock(struct munlock_args *uap)
1056 {
1057         struct thread *td = curthread;
1058         struct proc *p = td->td_proc;
1059         vm_offset_t addr;
1060         vm_offset_t tmpaddr;
1061         vm_size_t size, pageoff;
1062         int error;
1063
1064         addr = (vm_offset_t) uap->addr;
1065         size = uap->len;
1066
1067         pageoff = (addr & PAGE_MASK);
1068         addr -= pageoff;
1069         size += pageoff;
1070         size = (vm_size_t) round_page(size);
1071
1072         tmpaddr = addr + size;
1073         if (tmpaddr < addr)             /* wrap */
1074                 return (EINVAL);
1075
1076 #ifndef pmap_wired_count
1077         error = priv_check(td, PRIV_ROOT);
1078         if (error)
1079                 return (error);
1080 #endif
1081
1082         lwkt_gettoken(&vm_token);
1083         error = vm_map_unwire(&p->p_vmspace->vm_map, addr, addr + size, TRUE);
1084         lwkt_reltoken(&vm_token);
1085         return (error == KERN_SUCCESS ? 0 : ENOMEM);
1086 }
1087
1088 /*
1089  * Internal version of mmap.
1090  * Currently used by mmap, exec, and sys5 shared memory.
1091  * Handle is either a vnode pointer or NULL for MAP_ANON.
1092  * 
1093  * Requires that the MP lock is held by the caller
1094  */
1095 int
1096 vm_mmap(vm_map_t map, vm_offset_t *addr, vm_size_t size, vm_prot_t prot,
1097         vm_prot_t maxprot, int flags, void *handle, vm_ooffset_t foff)
1098 {
1099         boolean_t fitit;
1100         vm_object_t object;
1101         vm_offset_t eaddr;
1102         vm_size_t   esize;
1103         struct vnode *vp;
1104         struct thread *td = curthread;
1105         struct proc *p;
1106         int rv = KERN_SUCCESS;
1107         off_t objsize;
1108         int docow;
1109
1110         if (size == 0)
1111                 return (0);
1112
1113         objsize = round_page(size);
1114         if (objsize < size)
1115                 return (EINVAL);
1116         size = objsize;
1117
1118         /*
1119          * XXX messy code, fixme
1120          *
1121          * NOTE: Overflow checks require discrete statements or GCC4
1122          * will optimize it out.
1123          */
1124         if ((p = curproc) != NULL && map == &p->p_vmspace->vm_map) {
1125                 esize = map->size + size;       /* workaround gcc4 opt */
1126                 if (esize < map->size ||
1127                     esize > p->p_rlimit[RLIMIT_VMEM].rlim_cur) {
1128                         return(ENOMEM);
1129                 }
1130         }
1131
1132         /*
1133          * We currently can only deal with page aligned file offsets.
1134          * The check is here rather than in the syscall because the
1135          * kernel calls this function internally for other mmaping
1136          * operations (such as in exec) and non-aligned offsets will
1137          * cause pmap inconsistencies...so we want to be sure to
1138          * disallow this in all cases.
1139          *
1140          * NOTE: Overflow checks require discrete statements or GCC4
1141          * will optimize it out.
1142          */
1143         if (foff & PAGE_MASK)
1144                 return (EINVAL);
1145
1146         if ((flags & (MAP_FIXED | MAP_TRYFIXED)) == 0) {
1147                 fitit = TRUE;
1148                 *addr = round_page(*addr);
1149         } else {
1150                 if (*addr != trunc_page(*addr))
1151                         return (EINVAL);
1152                 eaddr = *addr + size;
1153                 if (eaddr < *addr)
1154                         return (EINVAL);
1155                 fitit = FALSE;
1156                 if ((flags & MAP_TRYFIXED) == 0)
1157                         vm_map_remove(map, *addr, *addr + size);
1158         }
1159
1160         /*
1161          * Lookup/allocate object.
1162          */
1163         if (flags & MAP_ANON) {
1164                 /*
1165                  * Unnamed anonymous regions always start at 0.
1166                  */
1167                 if (handle) {
1168                         /*
1169                          * Default memory object
1170                          */
1171                         object = default_pager_alloc(handle, objsize,
1172                                                      prot, foff);
1173                         if (object == NULL)
1174                                 return(ENOMEM);
1175                         docow = MAP_PREFAULT_PARTIAL;
1176                 } else {
1177                         /*
1178                          * Implicit single instance of a default memory
1179                          * object, so we don't need a VM object yet.
1180                          */
1181                         foff = 0;
1182                         object = NULL;
1183                         docow = 0;
1184                 }
1185                 vp = NULL;
1186         } else {
1187                 vp = (struct vnode *)handle;
1188                 if (vp->v_type == VCHR) {
1189                         /*
1190                          * Device mappings (device size unknown?).
1191                          * Force them to be shared.
1192                          */
1193                         handle = (void *)(intptr_t)vp->v_rdev;
1194                         object = dev_pager_alloc(handle, objsize, prot, foff);
1195                         if (object == NULL)
1196                                 return(EINVAL);
1197                         docow = MAP_PREFAULT_PARTIAL;
1198                         flags &= ~(MAP_PRIVATE|MAP_COPY);
1199                         flags |= MAP_SHARED;
1200                 } else {
1201                         /*
1202                          * Regular file mapping (typically).  The attribute
1203                          * check is for the link count test only.  Mmapble
1204                          * vnodes must already have a VM object assigned.
1205                          */
1206                         struct vattr vat;
1207                         int error;
1208
1209                         error = VOP_GETATTR(vp, &vat);
1210                         if (error)
1211                                 return (error);
1212                         docow = MAP_PREFAULT_PARTIAL;
1213                         object = vnode_pager_reference(vp);
1214                         if (object == NULL && vp->v_type == VREG) {
1215                                 kprintf("Warning: cannot mmap vnode %p, no "
1216                                         "object\n", vp);
1217                                 return(EINVAL);
1218                         }
1219
1220                         /*
1221                          * If it is a regular file without any references
1222                          * we do not need to sync it.
1223                          */
1224                         if (vp->v_type == VREG && vat.va_nlink == 0) {
1225                                 flags |= MAP_NOSYNC;
1226                         }
1227                 }
1228         }
1229
1230         /*
1231          * Deal with the adjusted flags
1232          */
1233         if ((flags & (MAP_ANON|MAP_SHARED)) == 0)
1234                 docow |= MAP_COPY_ON_WRITE;
1235         if (flags & MAP_NOSYNC)
1236                 docow |= MAP_DISABLE_SYNCER;
1237         if (flags & MAP_NOCORE)
1238                 docow |= MAP_DISABLE_COREDUMP;
1239
1240 #if defined(VM_PROT_READ_IS_EXEC)
1241         if (prot & VM_PROT_READ)
1242                 prot |= VM_PROT_EXECUTE;
1243
1244         if (maxprot & VM_PROT_READ)
1245                 maxprot |= VM_PROT_EXECUTE;
1246 #endif
1247
1248         /*
1249          * This may place the area in its own page directory if (size) is
1250          * large enough, otherwise it typically returns its argument.
1251          */
1252         if (fitit) {
1253                 *addr = pmap_addr_hint(object, *addr, size);
1254         }
1255
1256         /*
1257          * Stack mappings need special attention.
1258          *
1259          * Mappings that use virtual page tables will default to storing
1260          * the page table at offset 0.
1261          */
1262         if (flags & MAP_STACK) {
1263                 rv = vm_map_stack(map, *addr, size, flags,
1264                                   prot, maxprot, docow);
1265         } else if (flags & MAP_VPAGETABLE) {
1266                 rv = vm_map_find(map, object, foff, addr, size, PAGE_SIZE,
1267                                  fitit, VM_MAPTYPE_VPAGETABLE,
1268                                  prot, maxprot, docow);
1269         } else {
1270                 rv = vm_map_find(map, object, foff, addr, size, PAGE_SIZE,
1271                                  fitit, VM_MAPTYPE_NORMAL,
1272                                  prot, maxprot, docow);
1273         }
1274
1275         if (rv != KERN_SUCCESS) {
1276                 /*
1277                  * Lose the object reference. Will destroy the
1278                  * object if it's an unnamed anonymous mapping
1279                  * or named anonymous without other references.
1280                  */
1281                 vm_object_deallocate(object);
1282                 goto out;
1283         }
1284
1285         /*
1286          * Shared memory is also shared with children.
1287          */
1288         if (flags & (MAP_SHARED|MAP_INHERIT)) {
1289                 rv = vm_map_inherit(map, *addr, *addr + size, VM_INHERIT_SHARE);
1290                 if (rv != KERN_SUCCESS) {
1291                         vm_map_remove(map, *addr, *addr + size);
1292                         goto out;
1293                 }
1294         }
1295
1296         /*
1297          * Set the access time on the vnode
1298          */
1299         if (vp != NULL)
1300                 vn_mark_atime(vp, td);
1301 out:
1302         switch (rv) {
1303         case KERN_SUCCESS:
1304                 return (0);
1305         case KERN_INVALID_ADDRESS:
1306         case KERN_NO_SPACE:
1307                 return (ENOMEM);
1308         case KERN_PROTECTION_FAILURE:
1309                 return (EACCES);
1310         default:
1311                 return (EINVAL);
1312         }
1313 }