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