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