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