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