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