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