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