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