]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/vm/vm_mmap.c
MFC 253471,253620,254430,254538:
[FreeBSD/stable/9.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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  * from: Utah $Hdr: vm_mmap.c 1.6 91/10/21$
35  *
36  *      @(#)vm_mmap.c   8.4 (Berkeley) 1/12/94
37  */
38
39 /*
40  * Mapped file (mmap) interface to VM
41  */
42
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45
46 #include "opt_compat.h"
47 #include "opt_hwpmc_hooks.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/capability.h>
52 #include <sys/kernel.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/sysproto.h>
56 #include <sys/filedesc.h>
57 #include <sys/priv.h>
58 #include <sys/proc.h>
59 #include <sys/racct.h>
60 #include <sys/resource.h>
61 #include <sys/resourcevar.h>
62 #include <sys/sysctl.h>
63 #include <sys/vnode.h>
64 #include <sys/fcntl.h>
65 #include <sys/file.h>
66 #include <sys/mman.h>
67 #include <sys/mount.h>
68 #include <sys/conf.h>
69 #include <sys/stat.h>
70 #include <sys/sysent.h>
71 #include <sys/vmmeter.h>
72
73 #include <security/mac/mac_framework.h>
74
75 #include <vm/vm.h>
76 #include <vm/vm_param.h>
77 #include <vm/pmap.h>
78 #include <vm/vm_map.h>
79 #include <vm/vm_object.h>
80 #include <vm/vm_page.h>
81 #include <vm/vm_pager.h>
82 #include <vm/vm_pageout.h>
83 #include <vm/vm_extern.h>
84 #include <vm/vm_page.h>
85 #include <vm/vnode_pager.h>
86
87 #ifdef HWPMC_HOOKS
88 #include <sys/pmckern.h>
89 #endif
90
91 int old_mlock = 1;
92 SYSCTL_INT(_vm, OID_AUTO, old_mlock, CTLFLAG_RW | CTLFLAG_TUN, &old_mlock, 0,
93     "Do not apply RLIMIT_MEMLOCK on mlockall");
94 TUNABLE_INT("vm.old_mlock", &old_mlock);
95
96 #ifndef _SYS_SYSPROTO_H_
97 struct sbrk_args {
98         int incr;
99 };
100 #endif
101
102 static int vm_mmap_vnode(struct thread *, vm_size_t, vm_prot_t, vm_prot_t *,
103     int *, struct vnode *, vm_ooffset_t *, vm_object_t *, boolean_t *);
104 static int vm_mmap_cdev(struct thread *, vm_size_t, vm_prot_t, vm_prot_t *,
105     int *, struct cdev *, vm_ooffset_t *, vm_object_t *);
106 static int vm_mmap_shm(struct thread *, vm_size_t, vm_prot_t, vm_prot_t *,
107     int *, struct shmfd *, vm_ooffset_t, vm_object_t *);
108
109 /*
110  * MPSAFE
111  */
112 /* ARGSUSED */
113 int
114 sys_sbrk(td, uap)
115         struct thread *td;
116         struct sbrk_args *uap;
117 {
118         /* Not yet implemented */
119         return (EOPNOTSUPP);
120 }
121
122 #ifndef _SYS_SYSPROTO_H_
123 struct sstk_args {
124         int incr;
125 };
126 #endif
127
128 /*
129  * MPSAFE
130  */
131 /* ARGSUSED */
132 int
133 sys_sstk(td, uap)
134         struct thread *td;
135         struct sstk_args *uap;
136 {
137         /* Not yet implemented */
138         return (EOPNOTSUPP);
139 }
140
141 #if defined(COMPAT_43)
142 #ifndef _SYS_SYSPROTO_H_
143 struct getpagesize_args {
144         int dummy;
145 };
146 #endif
147
148 /* ARGSUSED */
149 int
150 ogetpagesize(td, uap)
151         struct thread *td;
152         struct getpagesize_args *uap;
153 {
154         /* MP SAFE */
155         td->td_retval[0] = PAGE_SIZE;
156         return (0);
157 }
158 #endif                          /* COMPAT_43 */
159
160
161 /*
162  * Memory Map (mmap) system call.  Note that the file offset
163  * and address are allowed to be NOT page aligned, though if
164  * the MAP_FIXED flag it set, both must have the same remainder
165  * modulo the PAGE_SIZE (POSIX 1003.1b).  If the address is not
166  * page-aligned, the actual mapping starts at trunc_page(addr)
167  * and the return value is adjusted up by the page offset.
168  *
169  * Generally speaking, only character devices which are themselves
170  * memory-based, such as a video framebuffer, can be mmap'd.  Otherwise
171  * there would be no cache coherency between a descriptor and a VM mapping
172  * both to the same character device.
173  */
174 #ifndef _SYS_SYSPROTO_H_
175 struct mmap_args {
176         void *addr;
177         size_t len;
178         int prot;
179         int flags;
180         int fd;
181         long pad;
182         off_t pos;
183 };
184 #endif
185
186 /*
187  * MPSAFE
188  */
189 int
190 sys_mmap(td, uap)
191         struct thread *td;
192         struct mmap_args *uap;
193 {
194 #ifdef HWPMC_HOOKS
195         struct pmckern_map_in pkm;
196 #endif
197         struct file *fp;
198         struct vnode *vp;
199         vm_offset_t addr;
200         vm_size_t size, pageoff;
201         vm_prot_t cap_maxprot, prot, maxprot;
202         void *handle;
203         objtype_t handle_type;
204         int align, error, flags;
205         off_t pos;
206         struct vmspace *vms = td->td_proc->p_vmspace;
207         cap_rights_t rights;
208
209         addr = (vm_offset_t) uap->addr;
210         size = uap->len;
211         prot = uap->prot & VM_PROT_ALL;
212         flags = uap->flags;
213         pos = uap->pos;
214
215         fp = NULL;
216
217         /*
218          * Enforce the constraints.
219          * Mapping of length 0 is only allowed for old binaries.
220          * Anonymous mapping shall specify -1 as filedescriptor and
221          * zero position for new code. Be nice to ancient a.out
222          * binaries and correct pos for anonymous mapping, since old
223          * ld.so sometimes issues anonymous map requests with non-zero
224          * pos.
225          */
226         if (!SV_CURPROC_FLAG(SV_AOUT)) {
227                 if ((uap->len == 0 && curproc->p_osrel >= P_OSREL_MAP_ANON) ||
228                     ((flags & MAP_ANON) != 0 && (uap->fd != -1 || pos != 0)))
229                         return (EINVAL);
230         } else {
231                 if ((flags & MAP_ANON) != 0)
232                         pos = 0;
233         }
234
235         if (flags & MAP_STACK) {
236                 if ((uap->fd != -1) ||
237                     ((prot & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)))
238                         return (EINVAL);
239                 flags |= MAP_ANON;
240                 pos = 0;
241         }
242
243         /*
244          * Align the file position to a page boundary,
245          * and save its page offset component.
246          */
247         pageoff = (pos & PAGE_MASK);
248         pos -= pageoff;
249
250         /* Adjust size for rounding (on both ends). */
251         size += pageoff;                        /* low end... */
252         size = (vm_size_t) round_page(size);    /* hi end */
253
254         /* Ensure alignment is at least a page and fits in a pointer. */
255         align = flags & MAP_ALIGNMENT_MASK;
256         if (align != 0 && align != MAP_ALIGNED_SUPER &&
257             (align >> MAP_ALIGNMENT_SHIFT >= sizeof(void *) * NBBY ||
258             align >> MAP_ALIGNMENT_SHIFT < PAGE_SHIFT))
259                 return (EINVAL);
260
261         /*
262          * Check for illegal addresses.  Watch out for address wrap... Note
263          * that VM_*_ADDRESS are not constants due to casts (argh).
264          */
265         if (flags & MAP_FIXED) {
266                 /*
267                  * The specified address must have the same remainder
268                  * as the file offset taken modulo PAGE_SIZE, so it
269                  * should be aligned after adjustment by pageoff.
270                  */
271                 addr -= pageoff;
272                 if (addr & PAGE_MASK)
273                         return (EINVAL);
274
275                 /* Address range must be all in user VM space. */
276                 if (addr < vm_map_min(&vms->vm_map) ||
277                     addr + size > vm_map_max(&vms->vm_map))
278                         return (EINVAL);
279                 if (addr + size < addr)
280                         return (EINVAL);
281         } else {
282                 /*
283                  * XXX for non-fixed mappings where no hint is provided or
284                  * the hint would fall in the potential heap space,
285                  * place it after the end of the largest possible heap.
286                  *
287                  * There should really be a pmap call to determine a reasonable
288                  * location.
289                  */
290                 PROC_LOCK(td->td_proc);
291                 if (addr == 0 ||
292                     (addr >= round_page((vm_offset_t)vms->vm_taddr) &&
293                     addr < round_page((vm_offset_t)vms->vm_daddr +
294                     lim_max(td->td_proc, RLIMIT_DATA))))
295                         addr = round_page((vm_offset_t)vms->vm_daddr +
296                             lim_max(td->td_proc, RLIMIT_DATA));
297                 PROC_UNLOCK(td->td_proc);
298         }
299         if (flags & MAP_ANON) {
300                 /*
301                  * Mapping blank space is trivial.
302                  */
303                 handle = NULL;
304                 handle_type = OBJT_DEFAULT;
305                 maxprot = VM_PROT_ALL;
306                 cap_maxprot = VM_PROT_ALL;
307         } else {
308                 /*
309                  * Mapping file, get fp for validation and don't let the
310                  * descriptor disappear on us if we block. Check capability
311                  * rights, but also return the maximum rights to be combined
312                  * with maxprot later.
313                  */
314                 rights = CAP_MMAP;
315                 if (prot & PROT_READ)
316                         rights |= CAP_READ;
317                 if ((flags & MAP_SHARED) != 0) {
318                         if (prot & PROT_WRITE)
319                                 rights |= CAP_WRITE;
320                 }
321                 if (prot & PROT_EXEC)
322                         rights |= CAP_MAPEXEC;
323                 if ((error = fget_mmap(td, uap->fd, rights, &cap_maxprot,
324                     &fp)) != 0)
325                         goto done;
326                 if (fp->f_type == DTYPE_SHM) {
327                         handle = fp->f_data;
328                         handle_type = OBJT_SWAP;
329                         maxprot = VM_PROT_NONE;
330
331                         /* FREAD should always be set. */
332                         if (fp->f_flag & FREAD)
333                                 maxprot |= VM_PROT_EXECUTE | VM_PROT_READ;
334                         if (fp->f_flag & FWRITE)
335                                 maxprot |= VM_PROT_WRITE;
336                         goto map;
337                 }
338                 if (fp->f_type != DTYPE_VNODE) {
339                         error = ENODEV;
340                         goto done;
341                 }
342 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
343     defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
344                 /*
345                  * POSIX shared-memory objects are defined to have
346                  * kernel persistence, and are not defined to support
347                  * read(2)/write(2) -- or even open(2).  Thus, we can
348                  * use MAP_ASYNC to trade on-disk coherence for speed.
349                  * The shm_open(3) library routine turns on the FPOSIXSHM
350                  * flag to request this behavior.
351                  */
352                 if (fp->f_flag & FPOSIXSHM)
353                         flags |= MAP_NOSYNC;
354 #endif
355                 vp = fp->f_vnode;
356                 /*
357                  * Ensure that file and memory protections are
358                  * compatible.  Note that we only worry about
359                  * writability if mapping is shared; in this case,
360                  * current and max prot are dictated by the open file.
361                  * XXX use the vnode instead?  Problem is: what
362                  * credentials do we use for determination? What if
363                  * proc does a setuid?
364                  */
365                 if (vp->v_mount != NULL && vp->v_mount->mnt_flag & MNT_NOEXEC)
366                         maxprot = VM_PROT_NONE;
367                 else
368                         maxprot = VM_PROT_EXECUTE;
369                 if (fp->f_flag & FREAD) {
370                         maxprot |= VM_PROT_READ;
371                 } else if (prot & PROT_READ) {
372                         error = EACCES;
373                         goto done;
374                 }
375                 /*
376                  * If we are sharing potential changes (either via
377                  * MAP_SHARED or via the implicit sharing of character
378                  * device mappings), and we are trying to get write
379                  * permission although we opened it without asking
380                  * for it, bail out.
381                  */
382                 if ((flags & MAP_SHARED) != 0) {
383                         if ((fp->f_flag & FWRITE) != 0) {
384                                 maxprot |= VM_PROT_WRITE;
385                         } else if ((prot & PROT_WRITE) != 0) {
386                                 error = EACCES;
387                                 goto done;
388                         }
389                 } else if (vp->v_type != VCHR || (fp->f_flag & FWRITE) != 0) {
390                         maxprot |= VM_PROT_WRITE;
391                         cap_maxprot |= VM_PROT_WRITE;
392                 }
393                 handle = (void *)vp;
394                 handle_type = OBJT_VNODE;
395         }
396 map:
397         td->td_fpop = fp;
398         maxprot &= cap_maxprot;
399         error = vm_mmap(&vms->vm_map, &addr, size, prot, maxprot,
400             flags, handle_type, handle, pos);
401         td->td_fpop = NULL;
402 #ifdef HWPMC_HOOKS
403         /* inform hwpmc(4) if an executable is being mapped */
404         if (error == 0 && handle_type == OBJT_VNODE &&
405             (prot & PROT_EXEC)) {
406                 pkm.pm_file = handle;
407                 pkm.pm_address = (uintptr_t) addr;
408                 PMC_CALL_HOOK(td, PMC_FN_MMAP, (void *) &pkm);
409         }
410 #endif
411         if (error == 0)
412                 td->td_retval[0] = (register_t) (addr + pageoff);
413 done:
414         if (fp)
415                 fdrop(fp, td);
416
417         return (error);
418 }
419
420 int
421 freebsd6_mmap(struct thread *td, struct freebsd6_mmap_args *uap)
422 {
423         struct mmap_args oargs;
424
425         oargs.addr = uap->addr;
426         oargs.len = uap->len;
427         oargs.prot = uap->prot;
428         oargs.flags = uap->flags;
429         oargs.fd = uap->fd;
430         oargs.pos = uap->pos;
431         return (sys_mmap(td, &oargs));
432 }
433
434 #ifdef COMPAT_43
435 #ifndef _SYS_SYSPROTO_H_
436 struct ommap_args {
437         caddr_t addr;
438         int len;
439         int prot;
440         int flags;
441         int fd;
442         long pos;
443 };
444 #endif
445 int
446 ommap(td, uap)
447         struct thread *td;
448         struct ommap_args *uap;
449 {
450         struct mmap_args nargs;
451         static const char cvtbsdprot[8] = {
452                 0,
453                 PROT_EXEC,
454                 PROT_WRITE,
455                 PROT_EXEC | PROT_WRITE,
456                 PROT_READ,
457                 PROT_EXEC | PROT_READ,
458                 PROT_WRITE | PROT_READ,
459                 PROT_EXEC | PROT_WRITE | PROT_READ,
460         };
461
462 #define OMAP_ANON       0x0002
463 #define OMAP_COPY       0x0020
464 #define OMAP_SHARED     0x0010
465 #define OMAP_FIXED      0x0100
466
467         nargs.addr = uap->addr;
468         nargs.len = uap->len;
469         nargs.prot = cvtbsdprot[uap->prot & 0x7];
470 #ifdef COMPAT_FREEBSD32
471 #if defined(__amd64__) || defined(__ia64__)
472         if (i386_read_exec && SV_PROC_FLAG(td->td_proc, SV_ILP32) &&
473             nargs.prot != 0)
474                 nargs.prot |= PROT_EXEC;
475 #endif
476 #endif
477         nargs.flags = 0;
478         if (uap->flags & OMAP_ANON)
479                 nargs.flags |= MAP_ANON;
480         if (uap->flags & OMAP_COPY)
481                 nargs.flags |= MAP_COPY;
482         if (uap->flags & OMAP_SHARED)
483                 nargs.flags |= MAP_SHARED;
484         else
485                 nargs.flags |= MAP_PRIVATE;
486         if (uap->flags & OMAP_FIXED)
487                 nargs.flags |= MAP_FIXED;
488         nargs.fd = uap->fd;
489         nargs.pos = uap->pos;
490         return (sys_mmap(td, &nargs));
491 }
492 #endif                          /* COMPAT_43 */
493
494
495 #ifndef _SYS_SYSPROTO_H_
496 struct msync_args {
497         void *addr;
498         size_t len;
499         int flags;
500 };
501 #endif
502 /*
503  * MPSAFE
504  */
505 int
506 sys_msync(td, uap)
507         struct thread *td;
508         struct msync_args *uap;
509 {
510         vm_offset_t addr;
511         vm_size_t size, pageoff;
512         int flags;
513         vm_map_t map;
514         int rv;
515
516         addr = (vm_offset_t) uap->addr;
517         size = uap->len;
518         flags = uap->flags;
519
520         pageoff = (addr & PAGE_MASK);
521         addr -= pageoff;
522         size += pageoff;
523         size = (vm_size_t) round_page(size);
524         if (addr + size < addr)
525                 return (EINVAL);
526
527         if ((flags & (MS_ASYNC|MS_INVALIDATE)) == (MS_ASYNC|MS_INVALIDATE))
528                 return (EINVAL);
529
530         map = &td->td_proc->p_vmspace->vm_map;
531
532         /*
533          * Clean the pages and interpret the return value.
534          */
535         rv = vm_map_sync(map, addr, addr + size, (flags & MS_ASYNC) == 0,
536             (flags & MS_INVALIDATE) != 0);
537         switch (rv) {
538         case KERN_SUCCESS:
539                 return (0);
540         case KERN_INVALID_ADDRESS:
541                 return (EINVAL);        /* Sun returns ENOMEM? */
542         case KERN_INVALID_ARGUMENT:
543                 return (EBUSY);
544         case KERN_FAILURE:
545                 return (EIO);
546         default:
547                 return (EINVAL);
548         }
549 }
550
551 #ifndef _SYS_SYSPROTO_H_
552 struct munmap_args {
553         void *addr;
554         size_t len;
555 };
556 #endif
557 /*
558  * MPSAFE
559  */
560 int
561 sys_munmap(td, uap)
562         struct thread *td;
563         struct munmap_args *uap;
564 {
565 #ifdef HWPMC_HOOKS
566         struct pmckern_map_out pkm;
567         vm_map_entry_t entry;
568 #endif
569         vm_offset_t addr;
570         vm_size_t size, pageoff;
571         vm_map_t map;
572
573         addr = (vm_offset_t) uap->addr;
574         size = uap->len;
575         if (size == 0)
576                 return (EINVAL);
577
578         pageoff = (addr & PAGE_MASK);
579         addr -= pageoff;
580         size += pageoff;
581         size = (vm_size_t) round_page(size);
582         if (addr + size < addr)
583                 return (EINVAL);
584
585         /*
586          * Check for illegal addresses.  Watch out for address wrap...
587          */
588         map = &td->td_proc->p_vmspace->vm_map;
589         if (addr < vm_map_min(map) || addr + size > vm_map_max(map))
590                 return (EINVAL);
591         vm_map_lock(map);
592 #ifdef HWPMC_HOOKS
593         /*
594          * Inform hwpmc if the address range being unmapped contains
595          * an executable region.
596          */
597         pkm.pm_address = (uintptr_t) NULL;
598         if (vm_map_lookup_entry(map, addr, &entry)) {
599                 for (;
600                      entry != &map->header && entry->start < addr + size;
601                      entry = entry->next) {
602                         if (vm_map_check_protection(map, entry->start,
603                                 entry->end, VM_PROT_EXECUTE) == TRUE) {
604                                 pkm.pm_address = (uintptr_t) addr;
605                                 pkm.pm_size = (size_t) size;
606                                 break;
607                         }
608                 }
609         }
610 #endif
611         vm_map_delete(map, addr, addr + size);
612
613 #ifdef HWPMC_HOOKS
614         /* downgrade the lock to prevent a LOR with the pmc-sx lock */
615         vm_map_lock_downgrade(map);
616         if (pkm.pm_address != (uintptr_t) NULL)
617                 PMC_CALL_HOOK(td, PMC_FN_MUNMAP, (void *) &pkm);
618         vm_map_unlock_read(map);
619 #else
620         vm_map_unlock(map);
621 #endif
622         /* vm_map_delete returns nothing but KERN_SUCCESS anyway */
623         return (0);
624 }
625
626 #ifndef _SYS_SYSPROTO_H_
627 struct mprotect_args {
628         const void *addr;
629         size_t len;
630         int prot;
631 };
632 #endif
633 /*
634  * MPSAFE
635  */
636 int
637 sys_mprotect(td, uap)
638         struct thread *td;
639         struct mprotect_args *uap;
640 {
641         vm_offset_t addr;
642         vm_size_t size, pageoff;
643         vm_prot_t prot;
644
645         addr = (vm_offset_t) uap->addr;
646         size = uap->len;
647         prot = uap->prot & VM_PROT_ALL;
648
649         pageoff = (addr & PAGE_MASK);
650         addr -= pageoff;
651         size += pageoff;
652         size = (vm_size_t) round_page(size);
653         if (addr + size < addr)
654                 return (EINVAL);
655
656         switch (vm_map_protect(&td->td_proc->p_vmspace->vm_map, addr,
657             addr + size, prot, FALSE)) {
658         case KERN_SUCCESS:
659                 return (0);
660         case KERN_PROTECTION_FAILURE:
661                 return (EACCES);
662         case KERN_RESOURCE_SHORTAGE:
663                 return (ENOMEM);
664         }
665         return (EINVAL);
666 }
667
668 #ifndef _SYS_SYSPROTO_H_
669 struct minherit_args {
670         void *addr;
671         size_t len;
672         int inherit;
673 };
674 #endif
675 /*
676  * MPSAFE
677  */
678 int
679 sys_minherit(td, uap)
680         struct thread *td;
681         struct minherit_args *uap;
682 {
683         vm_offset_t addr;
684         vm_size_t size, pageoff;
685         vm_inherit_t inherit;
686
687         addr = (vm_offset_t)uap->addr;
688         size = uap->len;
689         inherit = uap->inherit;
690
691         pageoff = (addr & PAGE_MASK);
692         addr -= pageoff;
693         size += pageoff;
694         size = (vm_size_t) round_page(size);
695         if (addr + size < addr)
696                 return (EINVAL);
697
698         switch (vm_map_inherit(&td->td_proc->p_vmspace->vm_map, addr,
699             addr + size, inherit)) {
700         case KERN_SUCCESS:
701                 return (0);
702         case KERN_PROTECTION_FAILURE:
703                 return (EACCES);
704         }
705         return (EINVAL);
706 }
707
708 #ifndef _SYS_SYSPROTO_H_
709 struct madvise_args {
710         void *addr;
711         size_t len;
712         int behav;
713 };
714 #endif
715
716 /*
717  * MPSAFE
718  */
719 /* ARGSUSED */
720 int
721 sys_madvise(td, uap)
722         struct thread *td;
723         struct madvise_args *uap;
724 {
725         vm_offset_t start, end;
726         vm_map_t map;
727         struct proc *p;
728         int error;
729
730         /*
731          * Check for our special case, advising the swap pager we are
732          * "immortal."
733          */
734         if (uap->behav == MADV_PROTECT) {
735                 error = priv_check(td, PRIV_VM_MADV_PROTECT);
736                 if (error == 0) {
737                         p = td->td_proc;
738                         PROC_LOCK(p);
739                         p->p_flag |= P_PROTECTED;
740                         PROC_UNLOCK(p);
741                 }
742                 return (error);
743         }
744         /*
745          * Check for illegal behavior
746          */
747         if (uap->behav < 0 || uap->behav > MADV_CORE)
748                 return (EINVAL);
749         /*
750          * Check for illegal addresses.  Watch out for address wrap... Note
751          * that VM_*_ADDRESS are not constants due to casts (argh).
752          */
753         map = &td->td_proc->p_vmspace->vm_map;
754         if ((vm_offset_t)uap->addr < vm_map_min(map) ||
755             (vm_offset_t)uap->addr + uap->len > vm_map_max(map))
756                 return (EINVAL);
757         if (((vm_offset_t) uap->addr + uap->len) < (vm_offset_t) uap->addr)
758                 return (EINVAL);
759
760         /*
761          * Since this routine is only advisory, we default to conservative
762          * behavior.
763          */
764         start = trunc_page((vm_offset_t) uap->addr);
765         end = round_page((vm_offset_t) uap->addr + uap->len);
766
767         if (vm_map_madvise(map, start, end, uap->behav))
768                 return (EINVAL);
769         return (0);
770 }
771
772 #ifndef _SYS_SYSPROTO_H_
773 struct mincore_args {
774         const void *addr;
775         size_t len;
776         char *vec;
777 };
778 #endif
779
780 /*
781  * MPSAFE
782  */
783 /* ARGSUSED */
784 int
785 sys_mincore(td, uap)
786         struct thread *td;
787         struct mincore_args *uap;
788 {
789         vm_offset_t addr, first_addr;
790         vm_offset_t end, cend;
791         pmap_t pmap;
792         vm_map_t map;
793         char *vec;
794         int error = 0;
795         int vecindex, lastvecindex;
796         vm_map_entry_t current;
797         vm_map_entry_t entry;
798         vm_object_t object;
799         vm_paddr_t locked_pa;
800         vm_page_t m;
801         vm_pindex_t pindex;
802         int mincoreinfo;
803         unsigned int timestamp;
804         boolean_t locked;
805
806         /*
807          * Make sure that the addresses presented are valid for user
808          * mode.
809          */
810         first_addr = addr = trunc_page((vm_offset_t) uap->addr);
811         end = addr + (vm_size_t)round_page(uap->len);
812         map = &td->td_proc->p_vmspace->vm_map;
813         if (end > vm_map_max(map) || end < addr)
814                 return (ENOMEM);
815
816         /*
817          * Address of byte vector
818          */
819         vec = uap->vec;
820
821         pmap = vmspace_pmap(td->td_proc->p_vmspace);
822
823         vm_map_lock_read(map);
824 RestartScan:
825         timestamp = map->timestamp;
826
827         if (!vm_map_lookup_entry(map, addr, &entry)) {
828                 vm_map_unlock_read(map);
829                 return (ENOMEM);
830         }
831
832         /*
833          * Do this on a map entry basis so that if the pages are not
834          * in the current processes address space, we can easily look
835          * up the pages elsewhere.
836          */
837         lastvecindex = -1;
838         for (current = entry;
839             (current != &map->header) && (current->start < end);
840             current = current->next) {
841
842                 /*
843                  * check for contiguity
844                  */
845                 if (current->end < end &&
846                     (entry->next == &map->header ||
847                      current->next->start > current->end)) {
848                         vm_map_unlock_read(map);
849                         return (ENOMEM);
850                 }
851
852                 /*
853                  * ignore submaps (for now) or null objects
854                  */
855                 if ((current->eflags & MAP_ENTRY_IS_SUB_MAP) ||
856                         current->object.vm_object == NULL)
857                         continue;
858
859                 /*
860                  * limit this scan to the current map entry and the
861                  * limits for the mincore call
862                  */
863                 if (addr < current->start)
864                         addr = current->start;
865                 cend = current->end;
866                 if (cend > end)
867                         cend = end;
868
869                 /*
870                  * scan this entry one page at a time
871                  */
872                 while (addr < cend) {
873                         /*
874                          * Check pmap first, it is likely faster, also
875                          * it can provide info as to whether we are the
876                          * one referencing or modifying the page.
877                          */
878                         object = NULL;
879                         locked_pa = 0;
880                 retry:
881                         m = NULL;
882                         mincoreinfo = pmap_mincore(pmap, addr, &locked_pa);
883                         if (locked_pa != 0) {
884                                 /*
885                                  * The page is mapped by this process but not
886                                  * both accessed and modified.  It is also
887                                  * managed.  Acquire the object lock so that
888                                  * other mappings might be examined.
889                                  */
890                                 m = PHYS_TO_VM_PAGE(locked_pa);
891                                 if (m->object != object) {
892                                         if (object != NULL)
893                                                 VM_OBJECT_UNLOCK(object);
894                                         object = m->object;
895                                         locked = VM_OBJECT_TRYLOCK(object);
896                                         vm_page_unlock(m);
897                                         if (!locked) {
898                                                 VM_OBJECT_LOCK(object);
899                                                 vm_page_lock(m);
900                                                 goto retry;
901                                         }
902                                 } else
903                                         vm_page_unlock(m);
904                                 KASSERT(m->valid == VM_PAGE_BITS_ALL,
905                                     ("mincore: page %p is mapped but invalid",
906                                     m));
907                         } else if (mincoreinfo == 0) {
908                                 /*
909                                  * The page is not mapped by this process.  If
910                                  * the object implements managed pages, then
911                                  * determine if the page is resident so that
912                                  * the mappings might be examined.
913                                  */
914                                 if (current->object.vm_object != object) {
915                                         if (object != NULL)
916                                                 VM_OBJECT_UNLOCK(object);
917                                         object = current->object.vm_object;
918                                         VM_OBJECT_LOCK(object);
919                                 }
920                                 if (object->type == OBJT_DEFAULT ||
921                                     object->type == OBJT_SWAP ||
922                                     object->type == OBJT_VNODE) {
923                                         pindex = OFF_TO_IDX(current->offset +
924                                             (addr - current->start));
925                                         m = vm_page_lookup(object, pindex);
926                                         if (m == NULL &&
927                                             vm_page_is_cached(object, pindex))
928                                                 mincoreinfo = MINCORE_INCORE;
929                                         if (m != NULL && m->valid == 0)
930                                                 m = NULL;
931                                         if (m != NULL)
932                                                 mincoreinfo = MINCORE_INCORE;
933                                 }
934                         }
935                         if (m != NULL) {
936                                 /* Examine other mappings to the page. */
937                                 if (m->dirty == 0 && pmap_is_modified(m))
938                                         vm_page_dirty(m);
939                                 if (m->dirty != 0)
940                                         mincoreinfo |= MINCORE_MODIFIED_OTHER;
941                                 /*
942                                  * The first test for PGA_REFERENCED is an
943                                  * optimization.  The second test is
944                                  * required because a concurrent pmap
945                                  * operation could clear the last reference
946                                  * and set PGA_REFERENCED before the call to
947                                  * pmap_is_referenced(). 
948                                  */
949                                 if ((m->aflags & PGA_REFERENCED) != 0 ||
950                                     pmap_is_referenced(m) ||
951                                     (m->aflags & PGA_REFERENCED) != 0)
952                                         mincoreinfo |= MINCORE_REFERENCED_OTHER;
953                         }
954                         if (object != NULL)
955                                 VM_OBJECT_UNLOCK(object);
956
957                         /*
958                          * subyte may page fault.  In case it needs to modify
959                          * the map, we release the lock.
960                          */
961                         vm_map_unlock_read(map);
962
963                         /*
964                          * calculate index into user supplied byte vector
965                          */
966                         vecindex = OFF_TO_IDX(addr - first_addr);
967
968                         /*
969                          * If we have skipped map entries, we need to make sure that
970                          * the byte vector is zeroed for those skipped entries.
971                          */
972                         while ((lastvecindex + 1) < vecindex) {
973                                 ++lastvecindex;
974                                 error = subyte(vec + lastvecindex, 0);
975                                 if (error) {
976                                         error = EFAULT;
977                                         goto done2;
978                                 }
979                         }
980
981                         /*
982                          * Pass the page information to the user
983                          */
984                         error = subyte(vec + vecindex, mincoreinfo);
985                         if (error) {
986                                 error = EFAULT;
987                                 goto done2;
988                         }
989
990                         /*
991                          * If the map has changed, due to the subyte, the previous
992                          * output may be invalid.
993                          */
994                         vm_map_lock_read(map);
995                         if (timestamp != map->timestamp)
996                                 goto RestartScan;
997
998                         lastvecindex = vecindex;
999                         addr += PAGE_SIZE;
1000                 }
1001         }
1002
1003         /*
1004          * subyte may page fault.  In case it needs to modify
1005          * the map, we release the lock.
1006          */
1007         vm_map_unlock_read(map);
1008
1009         /*
1010          * Zero the last entries in the byte vector.
1011          */
1012         vecindex = OFF_TO_IDX(end - first_addr);
1013         while ((lastvecindex + 1) < vecindex) {
1014                 ++lastvecindex;
1015                 error = subyte(vec + lastvecindex, 0);
1016                 if (error) {
1017                         error = EFAULT;
1018                         goto done2;
1019                 }
1020         }
1021
1022         /*
1023          * If the map has changed, due to the subyte, the previous
1024          * output may be invalid.
1025          */
1026         vm_map_lock_read(map);
1027         if (timestamp != map->timestamp)
1028                 goto RestartScan;
1029         vm_map_unlock_read(map);
1030 done2:
1031         return (error);
1032 }
1033
1034 #ifndef _SYS_SYSPROTO_H_
1035 struct mlock_args {
1036         const void *addr;
1037         size_t len;
1038 };
1039 #endif
1040 /*
1041  * MPSAFE
1042  */
1043 int
1044 sys_mlock(td, uap)
1045         struct thread *td;
1046         struct mlock_args *uap;
1047 {
1048         struct proc *proc;
1049         vm_offset_t addr, end, last, start;
1050         vm_size_t npages, size;
1051         vm_map_t map;
1052         unsigned long nsize;
1053         int error;
1054
1055         error = priv_check(td, PRIV_VM_MLOCK);
1056         if (error)
1057                 return (error);
1058         addr = (vm_offset_t)uap->addr;
1059         size = uap->len;
1060         last = addr + size;
1061         start = trunc_page(addr);
1062         end = round_page(last);
1063         if (last < addr || end < addr)
1064                 return (EINVAL);
1065         npages = atop(end - start);
1066         if (npages > vm_page_max_wired)
1067                 return (ENOMEM);
1068         proc = td->td_proc;
1069         map = &proc->p_vmspace->vm_map;
1070         PROC_LOCK(proc);
1071         nsize = ptoa(npages + pmap_wired_count(map->pmap));
1072         if (nsize > lim_cur(proc, RLIMIT_MEMLOCK)) {
1073                 PROC_UNLOCK(proc);
1074                 return (ENOMEM);
1075         }
1076         PROC_UNLOCK(proc);
1077         if (npages + cnt.v_wire_count > vm_page_max_wired)
1078                 return (EAGAIN);
1079 #ifdef RACCT
1080         PROC_LOCK(proc);
1081         error = racct_set(proc, RACCT_MEMLOCK, nsize);
1082         PROC_UNLOCK(proc);
1083         if (error != 0)
1084                 return (ENOMEM);
1085 #endif
1086         error = vm_map_wire(map, start, end,
1087             VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
1088 #ifdef RACCT
1089         if (error != KERN_SUCCESS) {
1090                 PROC_LOCK(proc);
1091                 racct_set(proc, RACCT_MEMLOCK,
1092                     ptoa(pmap_wired_count(map->pmap)));
1093                 PROC_UNLOCK(proc);
1094         }
1095 #endif
1096         return (error == KERN_SUCCESS ? 0 : ENOMEM);
1097 }
1098
1099 #ifndef _SYS_SYSPROTO_H_
1100 struct mlockall_args {
1101         int     how;
1102 };
1103 #endif
1104
1105 /*
1106  * MPSAFE
1107  */
1108 int
1109 sys_mlockall(td, uap)
1110         struct thread *td;
1111         struct mlockall_args *uap;
1112 {
1113         vm_map_t map;
1114         int error;
1115
1116         map = &td->td_proc->p_vmspace->vm_map;
1117         error = priv_check(td, PRIV_VM_MLOCK);
1118         if (error)
1119                 return (error);
1120
1121         if ((uap->how == 0) || ((uap->how & ~(MCL_CURRENT|MCL_FUTURE)) != 0))
1122                 return (EINVAL);
1123
1124         /*
1125          * If wiring all pages in the process would cause it to exceed
1126          * a hard resource limit, return ENOMEM.
1127          */
1128         if (!old_mlock && uap->how & MCL_CURRENT) {
1129                 PROC_LOCK(td->td_proc);
1130                 if (map->size > lim_cur(td->td_proc, RLIMIT_MEMLOCK)) {
1131                         PROC_UNLOCK(td->td_proc);
1132                         return (ENOMEM);
1133                 }
1134                 PROC_UNLOCK(td->td_proc);
1135         }
1136 #ifdef RACCT
1137         PROC_LOCK(td->td_proc);
1138         error = racct_set(td->td_proc, RACCT_MEMLOCK, map->size);
1139         PROC_UNLOCK(td->td_proc);
1140         if (error != 0)
1141                 return (ENOMEM);
1142 #endif
1143
1144         if (uap->how & MCL_FUTURE) {
1145                 vm_map_lock(map);
1146                 vm_map_modflags(map, MAP_WIREFUTURE, 0);
1147                 vm_map_unlock(map);
1148                 error = 0;
1149         }
1150
1151         if (uap->how & MCL_CURRENT) {
1152                 /*
1153                  * P1003.1-2001 mandates that all currently mapped pages
1154                  * will be memory resident and locked (wired) upon return
1155                  * from mlockall(). vm_map_wire() will wire pages, by
1156                  * calling vm_fault_wire() for each page in the region.
1157                  */
1158                 error = vm_map_wire(map, vm_map_min(map), vm_map_max(map),
1159                     VM_MAP_WIRE_USER|VM_MAP_WIRE_HOLESOK);
1160                 error = (error == KERN_SUCCESS ? 0 : EAGAIN);
1161         }
1162 #ifdef RACCT
1163         if (error != KERN_SUCCESS) {
1164                 PROC_LOCK(td->td_proc);
1165                 racct_set(td->td_proc, RACCT_MEMLOCK,
1166                     ptoa(pmap_wired_count(map->pmap)));
1167                 PROC_UNLOCK(td->td_proc);
1168         }
1169 #endif
1170
1171         return (error);
1172 }
1173
1174 #ifndef _SYS_SYSPROTO_H_
1175 struct munlockall_args {
1176         register_t dummy;
1177 };
1178 #endif
1179
1180 /*
1181  * MPSAFE
1182  */
1183 int
1184 sys_munlockall(td, uap)
1185         struct thread *td;
1186         struct munlockall_args *uap;
1187 {
1188         vm_map_t map;
1189         int error;
1190
1191         map = &td->td_proc->p_vmspace->vm_map;
1192         error = priv_check(td, PRIV_VM_MUNLOCK);
1193         if (error)
1194                 return (error);
1195
1196         /* Clear the MAP_WIREFUTURE flag from this vm_map. */
1197         vm_map_lock(map);
1198         vm_map_modflags(map, 0, MAP_WIREFUTURE);
1199         vm_map_unlock(map);
1200
1201         /* Forcibly unwire all pages. */
1202         error = vm_map_unwire(map, vm_map_min(map), vm_map_max(map),
1203             VM_MAP_WIRE_USER|VM_MAP_WIRE_HOLESOK);
1204 #ifdef RACCT
1205         if (error == KERN_SUCCESS) {
1206                 PROC_LOCK(td->td_proc);
1207                 racct_set(td->td_proc, RACCT_MEMLOCK, 0);
1208                 PROC_UNLOCK(td->td_proc);
1209         }
1210 #endif
1211
1212         return (error);
1213 }
1214
1215 #ifndef _SYS_SYSPROTO_H_
1216 struct munlock_args {
1217         const void *addr;
1218         size_t len;
1219 };
1220 #endif
1221 /*
1222  * MPSAFE
1223  */
1224 int
1225 sys_munlock(td, uap)
1226         struct thread *td;
1227         struct munlock_args *uap;
1228 {
1229         vm_offset_t addr, end, last, start;
1230         vm_size_t size;
1231 #ifdef RACCT
1232         vm_map_t map;
1233 #endif
1234         int error;
1235
1236         error = priv_check(td, PRIV_VM_MUNLOCK);
1237         if (error)
1238                 return (error);
1239         addr = (vm_offset_t)uap->addr;
1240         size = uap->len;
1241         last = addr + size;
1242         start = trunc_page(addr);
1243         end = round_page(last);
1244         if (last < addr || end < addr)
1245                 return (EINVAL);
1246         error = vm_map_unwire(&td->td_proc->p_vmspace->vm_map, start, end,
1247             VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
1248 #ifdef RACCT
1249         if (error == KERN_SUCCESS) {
1250                 PROC_LOCK(td->td_proc);
1251                 map = &td->td_proc->p_vmspace->vm_map;
1252                 racct_set(td->td_proc, RACCT_MEMLOCK,
1253                     ptoa(pmap_wired_count(map->pmap)));
1254                 PROC_UNLOCK(td->td_proc);
1255         }
1256 #endif
1257         return (error == KERN_SUCCESS ? 0 : ENOMEM);
1258 }
1259
1260 /*
1261  * vm_mmap_vnode()
1262  *
1263  * Helper function for vm_mmap.  Perform sanity check specific for mmap
1264  * operations on vnodes.
1265  *
1266  * For VCHR vnodes, the vnode lock is held over the call to
1267  * vm_mmap_cdev() to keep vp->v_rdev valid.
1268  */
1269 int
1270 vm_mmap_vnode(struct thread *td, vm_size_t objsize,
1271     vm_prot_t prot, vm_prot_t *maxprotp, int *flagsp,
1272     struct vnode *vp, vm_ooffset_t *foffp, vm_object_t *objp,
1273     boolean_t *writecounted)
1274 {
1275         struct vattr va;
1276         vm_object_t obj;
1277         vm_offset_t foff;
1278         struct mount *mp;
1279         struct ucred *cred;
1280         int error, flags, locktype, vfslocked;
1281
1282         mp = vp->v_mount;
1283         cred = td->td_ucred;
1284         if ((*maxprotp & VM_PROT_WRITE) && (*flagsp & MAP_SHARED))
1285                 locktype = LK_EXCLUSIVE;
1286         else
1287                 locktype = LK_SHARED;
1288         vfslocked = VFS_LOCK_GIANT(mp);
1289         if ((error = vget(vp, locktype, td)) != 0) {
1290                 VFS_UNLOCK_GIANT(vfslocked);
1291                 return (error);
1292         }
1293         foff = *foffp;
1294         flags = *flagsp;
1295         obj = vp->v_object;
1296         if (vp->v_type == VREG) {
1297                 /*
1298                  * Get the proper underlying object
1299                  */
1300                 if (obj == NULL) {
1301                         error = EINVAL;
1302                         goto done;
1303                 }
1304                 if (obj->handle != vp) {
1305                         vput(vp);
1306                         vp = (struct vnode *)obj->handle;
1307                         /*
1308                          * Bypass filesystems obey the mpsafety of the
1309                          * underlying fs.
1310                          */
1311                         error = vget(vp, locktype, td);
1312                         if (error != 0) {
1313                                 VFS_UNLOCK_GIANT(vfslocked);
1314                                 return (error);
1315                         }
1316                 }
1317                 if (locktype == LK_EXCLUSIVE) {
1318                         *writecounted = TRUE;
1319                         vnode_pager_update_writecount(obj, 0, objsize);
1320                 }
1321         } else if (vp->v_type == VCHR) {
1322                 error = vm_mmap_cdev(td, objsize, prot, maxprotp, flagsp,
1323                     vp->v_rdev, foffp, objp);
1324                 if (error == 0)
1325                         goto mark_atime;
1326                 goto done;
1327         } else {
1328                 error = EINVAL;
1329                 goto done;
1330         }
1331         if ((error = VOP_GETATTR(vp, &va, cred)))
1332                 goto done;
1333 #ifdef MAC
1334         error = mac_vnode_check_mmap(cred, vp, prot, flags);
1335         if (error != 0)
1336                 goto done;
1337 #endif
1338         if ((flags & MAP_SHARED) != 0) {
1339                 if ((va.va_flags & (SF_SNAPSHOT|IMMUTABLE|APPEND)) != 0) {
1340                         if (prot & PROT_WRITE) {
1341                                 error = EPERM;
1342                                 goto done;
1343                         }
1344                         *maxprotp &= ~VM_PROT_WRITE;
1345                 }
1346         }
1347         /*
1348          * If it is a regular file without any references
1349          * we do not need to sync it.
1350          * Adjust object size to be the size of actual file.
1351          */
1352         objsize = round_page(va.va_size);
1353         if (va.va_nlink == 0)
1354                 flags |= MAP_NOSYNC;
1355         obj = vm_pager_allocate(OBJT_VNODE, vp, objsize, prot, foff, cred);
1356         if (obj == NULL) {
1357                 error = ENOMEM;
1358                 goto done;
1359         }
1360         *objp = obj;
1361         *flagsp = flags;
1362
1363 mark_atime:
1364         vfs_mark_atime(vp, cred);
1365
1366 done:
1367         if (error != 0 && *writecounted) {
1368                 *writecounted = FALSE;
1369                 vnode_pager_update_writecount(obj, objsize, 0);
1370         }
1371         vput(vp);
1372         VFS_UNLOCK_GIANT(vfslocked);
1373         return (error);
1374 }
1375
1376 /*
1377  * vm_mmap_cdev()
1378  *
1379  * MPSAFE
1380  *
1381  * Helper function for vm_mmap.  Perform sanity check specific for mmap
1382  * operations on cdevs.
1383  */
1384 int
1385 vm_mmap_cdev(struct thread *td, vm_size_t objsize,
1386     vm_prot_t prot, vm_prot_t *maxprotp, int *flagsp,
1387     struct cdev *cdev, vm_ooffset_t *foff, vm_object_t *objp)
1388 {
1389         vm_object_t obj;
1390         struct cdevsw *dsw;
1391         int error, flags, ref;
1392
1393         flags = *flagsp;
1394
1395         dsw = dev_refthread(cdev, &ref);
1396         if (dsw == NULL)
1397                 return (ENXIO);
1398         if (dsw->d_flags & D_MMAP_ANON) {
1399                 dev_relthread(cdev, ref);
1400                 *maxprotp = VM_PROT_ALL;
1401                 *flagsp |= MAP_ANON;
1402                 return (0);
1403         }
1404         /*
1405          * cdevs do not provide private mappings of any kind.
1406          */
1407         if ((*maxprotp & VM_PROT_WRITE) == 0 &&
1408             (prot & PROT_WRITE) != 0) {
1409                 dev_relthread(cdev, ref);
1410                 return (EACCES);
1411         }
1412         if (flags & (MAP_PRIVATE|MAP_COPY)) {
1413                 dev_relthread(cdev, ref);
1414                 return (EINVAL);
1415         }
1416         /*
1417          * Force device mappings to be shared.
1418          */
1419         flags |= MAP_SHARED;
1420 #ifdef MAC_XXX
1421         error = mac_cdev_check_mmap(td->td_ucred, cdev, prot);
1422         if (error != 0) {
1423                 dev_relthread(cdev, ref);
1424                 return (error);
1425         }
1426 #endif
1427         /*
1428          * First, try d_mmap_single().  If that is not implemented
1429          * (returns ENODEV), fall back to using the device pager.
1430          * Note that d_mmap_single() must return a reference to the
1431          * object (it needs to bump the reference count of the object
1432          * it returns somehow).
1433          *
1434          * XXX assumes VM_PROT_* == PROT_*
1435          */
1436         error = dsw->d_mmap_single(cdev, foff, objsize, objp, (int)prot);
1437         dev_relthread(cdev, ref);
1438         if (error != ENODEV)
1439                 return (error);
1440         obj = vm_pager_allocate(OBJT_DEVICE, cdev, objsize, prot, *foff,
1441             td->td_ucred);
1442         if (obj == NULL)
1443                 return (EINVAL);
1444         *objp = obj;
1445         *flagsp = flags;
1446         return (0);
1447 }
1448
1449 /*
1450  * vm_mmap_shm()
1451  *
1452  * MPSAFE
1453  *
1454  * Helper function for vm_mmap.  Perform sanity check specific for mmap
1455  * operations on shm file descriptors.
1456  */
1457 int
1458 vm_mmap_shm(struct thread *td, vm_size_t objsize,
1459     vm_prot_t prot, vm_prot_t *maxprotp, int *flagsp,
1460     struct shmfd *shmfd, vm_ooffset_t foff, vm_object_t *objp)
1461 {
1462         int error;
1463
1464         if ((*flagsp & MAP_SHARED) != 0 &&
1465             (*maxprotp & VM_PROT_WRITE) == 0 &&
1466             (prot & PROT_WRITE) != 0)
1467                 return (EACCES);
1468 #ifdef MAC
1469         error = mac_posixshm_check_mmap(td->td_ucred, shmfd, prot, *flagsp);
1470         if (error != 0)
1471                 return (error);
1472 #endif
1473         error = shm_mmap(shmfd, objsize, foff, objp);
1474         if (error)
1475                 return (error);
1476         return (0);
1477 }
1478
1479 /*
1480  * vm_mmap()
1481  *
1482  * MPSAFE
1483  *
1484  * Internal version of mmap.  Currently used by mmap, exec, and sys5
1485  * shared memory.  Handle is either a vnode pointer or NULL for MAP_ANON.
1486  */
1487 int
1488 vm_mmap(vm_map_t map, vm_offset_t *addr, vm_size_t size, vm_prot_t prot,
1489         vm_prot_t maxprot, int flags,
1490         objtype_t handle_type, void *handle,
1491         vm_ooffset_t foff)
1492 {
1493         boolean_t fitit;
1494         vm_object_t object = NULL;
1495         struct thread *td = curthread;
1496         int docow, error, findspace, rv;
1497         boolean_t writecounted;
1498
1499         if (size == 0)
1500                 return (0);
1501
1502         size = round_page(size);
1503
1504         PROC_LOCK(td->td_proc);
1505         if (td->td_proc->p_vmspace->vm_map.size + size >
1506             lim_cur(td->td_proc, RLIMIT_VMEM)) {
1507                 if (!old_mlock && map->flags & MAP_WIREFUTURE) {
1508                         if (ptoa(pmap_wired_count(map->pmap)) + size >
1509                             lim_cur(td->td_proc, RLIMIT_MEMLOCK)) {
1510                                 racct_set_force(td->td_proc, RACCT_VMEM,
1511                                     map->size);
1512                                 PROC_UNLOCK(td->td_proc);
1513                                 return (ENOMEM);
1514                         }
1515                         error = racct_set(td->td_proc, RACCT_MEMLOCK,
1516                             ptoa(pmap_wired_count(map->pmap)) + size);
1517                         if (error != 0) {
1518                                 racct_set_force(td->td_proc, RACCT_VMEM,
1519                                     map->size);
1520                                 PROC_UNLOCK(td->td_proc);
1521                                 return (error);
1522                         }
1523                 }
1524                 PROC_UNLOCK(td->td_proc);
1525                 return (ENOMEM);
1526         }
1527         if (racct_set(td->td_proc, RACCT_VMEM,
1528             td->td_proc->p_vmspace->vm_map.size + size)) {
1529                 PROC_UNLOCK(td->td_proc);
1530                 return (ENOMEM);
1531         }
1532         PROC_UNLOCK(td->td_proc);
1533
1534         /*
1535          * We currently can only deal with page aligned file offsets.
1536          * The check is here rather than in the syscall because the
1537          * kernel calls this function internally for other mmaping
1538          * operations (such as in exec) and non-aligned offsets will
1539          * cause pmap inconsistencies...so we want to be sure to
1540          * disallow this in all cases.
1541          */
1542         if (foff & PAGE_MASK)
1543                 return (EINVAL);
1544
1545         if ((flags & MAP_FIXED) == 0) {
1546                 fitit = TRUE;
1547                 *addr = round_page(*addr);
1548         } else {
1549                 if (*addr != trunc_page(*addr))
1550                         return (EINVAL);
1551                 fitit = FALSE;
1552         }
1553         writecounted = FALSE;
1554
1555         /*
1556          * Lookup/allocate object.
1557          */
1558         switch (handle_type) {
1559         case OBJT_DEVICE:
1560                 error = vm_mmap_cdev(td, size, prot, &maxprot, &flags,
1561                     handle, &foff, &object);
1562                 break;
1563         case OBJT_VNODE:
1564                 error = vm_mmap_vnode(td, size, prot, &maxprot, &flags,
1565                     handle, &foff, &object, &writecounted);
1566                 break;
1567         case OBJT_SWAP:
1568                 error = vm_mmap_shm(td, size, prot, &maxprot, &flags,
1569                     handle, foff, &object);
1570                 break;
1571         case OBJT_DEFAULT:
1572                 if (handle == NULL) {
1573                         error = 0;
1574                         break;
1575                 }
1576                 /* FALLTHROUGH */
1577         default:
1578                 error = EINVAL;
1579                 break;
1580         }
1581         if (error)
1582                 return (error);
1583         if (flags & MAP_ANON) {
1584                 object = NULL;
1585                 docow = 0;
1586                 /*
1587                  * Unnamed anonymous regions always start at 0.
1588                  */
1589                 if (handle == 0)
1590                         foff = 0;
1591         } else if (flags & MAP_PREFAULT_READ)
1592                 docow = MAP_PREFAULT;
1593         else
1594                 docow = MAP_PREFAULT_PARTIAL;
1595
1596         if ((flags & (MAP_ANON|MAP_SHARED)) == 0)
1597                 docow |= MAP_COPY_ON_WRITE;
1598         if (flags & MAP_NOSYNC)
1599                 docow |= MAP_DISABLE_SYNCER;
1600         if (flags & MAP_NOCORE)
1601                 docow |= MAP_DISABLE_COREDUMP;
1602         /* Shared memory is also shared with children. */
1603         if (flags & MAP_SHARED)
1604                 docow |= MAP_INHERIT_SHARE;
1605         if (writecounted)
1606                 docow |= MAP_VN_WRITECOUNT;
1607
1608         if (flags & MAP_STACK)
1609                 rv = vm_map_stack(map, *addr, size, prot, maxprot,
1610                     docow | MAP_STACK_GROWS_DOWN);
1611         else if (fitit) {
1612                 if ((flags & MAP_ALIGNMENT_MASK) == MAP_ALIGNED_SUPER)
1613                         findspace = VMFS_SUPER_SPACE;
1614                 else if ((flags & MAP_ALIGNMENT_MASK) != 0)
1615                         findspace = VMFS_ALIGNED_SPACE(flags >>
1616                             MAP_ALIGNMENT_SHIFT);
1617                 else
1618                         findspace = VMFS_OPTIMAL_SPACE;
1619                 rv = vm_map_find(map, object, foff, addr, size, findspace,
1620                     prot, maxprot, docow);
1621         } else
1622                 rv = vm_map_fixed(map, object, foff, *addr, size,
1623                                  prot, maxprot, docow);
1624
1625         if (rv == KERN_SUCCESS) {
1626                 /*
1627                  * If the process has requested that all future mappings
1628                  * be wired, then heed this.
1629                  */
1630                 if (map->flags & MAP_WIREFUTURE) {
1631                         vm_map_wire(map, *addr, *addr + size,
1632                             VM_MAP_WIRE_USER | ((flags & MAP_STACK) ?
1633                             VM_MAP_WIRE_HOLESOK : VM_MAP_WIRE_NOHOLES));
1634                 }
1635         } else {
1636                 /*
1637                  * If this mapping was accounted for in the vnode's
1638                  * writecount, then undo that now.
1639                  */
1640                 if (writecounted)
1641                         vnode_pager_release_writecount(object, 0, size);
1642                 /*
1643                  * Lose the object reference.  Will destroy the
1644                  * object if it's an unnamed anonymous mapping
1645                  * or named anonymous without other references.
1646                  */
1647                 vm_object_deallocate(object);
1648         }
1649         return (vm_mmap_to_errno(rv));
1650 }
1651
1652 /*
1653  * Translate a Mach VM return code to zero on success or the appropriate errno
1654  * on failure.
1655  */
1656 int
1657 vm_mmap_to_errno(int rv)
1658 {
1659
1660         switch (rv) {
1661         case KERN_SUCCESS:
1662                 return (0);
1663         case KERN_INVALID_ADDRESS:
1664         case KERN_NO_SPACE:
1665                 return (ENOMEM);
1666         case KERN_PROTECTION_FAILURE:
1667                 return (EACCES);
1668         default:
1669                 return (EINVAL);
1670         }
1671 }