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