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