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