xref: /freebsd/sys/vm/vm_mmap.c (revision 3ff369fed2a08f32dda232c10470b949bef9489f)
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. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  * from: Utah $Hdr: vm_mmap.c 1.6 91/10/21$
39  *
40  *	@(#)vm_mmap.c	8.4 (Berkeley) 1/12/94
41  * $FreeBSD$
42  */
43 
44 /*
45  * Mapped file (mmap) interface to VM
46  */
47 
48 #include "opt_compat.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/lock.h>
54 #include <sys/mutex.h>
55 #include <sys/sysproto.h>
56 #include <sys/filedesc.h>
57 #include <sys/proc.h>
58 #include <sys/vnode.h>
59 #include <sys/fcntl.h>
60 #include <sys/file.h>
61 #include <sys/mman.h>
62 #include <sys/conf.h>
63 #include <sys/stat.h>
64 #include <sys/vmmeter.h>
65 #include <sys/sysctl.h>
66 
67 #include <vm/vm.h>
68 #include <vm/vm_param.h>
69 #include <vm/pmap.h>
70 #include <vm/vm_map.h>
71 #include <vm/vm_object.h>
72 #include <vm/vm_page.h>
73 #include <vm/vm_pager.h>
74 #include <vm/vm_pageout.h>
75 #include <vm/vm_extern.h>
76 #include <vm/vm_page.h>
77 #include <vm/vm_kern.h>
78 
79 #ifndef _SYS_SYSPROTO_H_
80 struct sbrk_args {
81 	int incr;
82 };
83 #endif
84 
85 static int max_proc_mmap;
86 SYSCTL_INT(_vm, OID_AUTO, max_proc_mmap, CTLFLAG_RW, &max_proc_mmap, 0, "");
87 
88 /*
89  * Set the maximum number of vm_map_entry structures per process.  Roughly
90  * speaking vm_map_entry structures are tiny, so allowing them to eat 1/100
91  * of our KVM malloc space still results in generous limits.  We want a
92  * default that is good enough to prevent the kernel running out of resources
93  * if attacked from compromised user account but generous enough such that
94  * multi-threaded processes are not unduly inconvenienced.
95  */
96 static void vmmapentry_rsrc_init(void *);
97 SYSINIT(vmmersrc, SI_SUB_KVM_RSRC, SI_ORDER_FIRST, vmmapentry_rsrc_init, NULL)
98 
99 static void
100 vmmapentry_rsrc_init(dummy)
101         void *dummy;
102 {
103     max_proc_mmap = vm_kmem_size / sizeof(struct vm_map_entry);
104     max_proc_mmap /= 100;
105 }
106 
107 /*
108  * MPSAFE
109  */
110 /* ARGSUSED */
111 int
112 sbrk(td, uap)
113 	struct thread *td;
114 	struct sbrk_args *uap;
115 {
116 	/* Not yet implemented */
117 	/* mtx_lock(&Giant); */
118 	/* mtx_unlock(&Giant); */
119 	return (EOPNOTSUPP);
120 }
121 
122 #ifndef _SYS_SYSPROTO_H_
123 struct sstk_args {
124 	int incr;
125 };
126 #endif
127 
128 /*
129  * MPSAFE
130  */
131 /* ARGSUSED */
132 int
133 sstk(td, uap)
134 	struct thread *td;
135 	struct sstk_args *uap;
136 {
137 	/* Not yet implemented */
138 	/* mtx_lock(&Giant); */
139 	/* mtx_unlock(&Giant); */
140 	return (EOPNOTSUPP);
141 }
142 
143 #if defined(COMPAT_43) || defined(COMPAT_SUNOS)
144 #ifndef _SYS_SYSPROTO_H_
145 struct getpagesize_args {
146 	int dummy;
147 };
148 #endif
149 
150 /* ARGSUSED */
151 int
152 ogetpagesize(td, uap)
153 	struct thread *td;
154 	struct getpagesize_args *uap;
155 {
156 	/* MP SAFE */
157 	td->td_retval[0] = PAGE_SIZE;
158 	return (0);
159 }
160 #endif				/* COMPAT_43 || COMPAT_SUNOS */
161 
162 
163 /*
164  * Memory Map (mmap) system call.  Note that the file offset
165  * and address are allowed to be NOT page aligned, though if
166  * the MAP_FIXED flag it set, both must have the same remainder
167  * modulo the PAGE_SIZE (POSIX 1003.1b).  If the address is not
168  * page-aligned, the actual mapping starts at trunc_page(addr)
169  * and the return value is adjusted up by the page offset.
170  *
171  * Generally speaking, only character devices which are themselves
172  * memory-based, such as a video framebuffer, can be mmap'd.  Otherwise
173  * there would be no cache coherency between a descriptor and a VM mapping
174  * both to the same character device.
175  *
176  * Block devices can be mmap'd no matter what they represent.  Cache coherency
177  * is maintained as long as you do not write directly to the underlying
178  * character device.
179  */
180 #ifndef _SYS_SYSPROTO_H_
181 struct mmap_args {
182 	void *addr;
183 	size_t len;
184 	int prot;
185 	int flags;
186 	int fd;
187 	long pad;
188 	off_t pos;
189 };
190 #endif
191 
192 /*
193  * MPSAFE
194  */
195 int
196 mmap(td, uap)
197 	struct thread *td;
198 	struct mmap_args *uap;
199 {
200 	struct file *fp = NULL;
201 	struct vnode *vp;
202 	vm_offset_t addr;
203 	vm_size_t size, pageoff;
204 	vm_prot_t prot, maxprot;
205 	void *handle;
206 	int flags, error;
207 	int disablexworkaround;
208 	off_t pos;
209 	struct vmspace *vms = td->td_proc->p_vmspace;
210 	vm_object_t obj;
211 
212 	addr = (vm_offset_t) uap->addr;
213 	size = uap->len;
214 	prot = uap->prot & VM_PROT_ALL;
215 	flags = uap->flags;
216 	pos = uap->pos;
217 
218 	fp = NULL;
219 	/* make sure mapping fits into numeric range etc */
220 	if ((ssize_t) uap->len < 0 ||
221 	    ((flags & MAP_ANON) && uap->fd != -1))
222 		return (EINVAL);
223 
224 	if (flags & MAP_STACK) {
225 		if ((uap->fd != -1) ||
226 		    ((prot & (PROT_READ | PROT_WRITE)) != (PROT_READ | PROT_WRITE)))
227 			return (EINVAL);
228 		flags |= MAP_ANON;
229 		pos = 0;
230 	}
231 
232 	/*
233 	 * Align the file position to a page boundary,
234 	 * and save its page offset component.
235 	 */
236 	pageoff = (pos & PAGE_MASK);
237 	pos -= pageoff;
238 
239 	/* Adjust size for rounding (on both ends). */
240 	size += pageoff;			/* low end... */
241 	size = (vm_size_t) round_page(size);	/* hi end */
242 
243 	/*
244 	 * Check for illegal addresses.  Watch out for address wrap... Note
245 	 * that VM_*_ADDRESS are not constants due to casts (argh).
246 	 */
247 	if (flags & MAP_FIXED) {
248 		/*
249 		 * The specified address must have the same remainder
250 		 * as the file offset taken modulo PAGE_SIZE, so it
251 		 * should be aligned after adjustment by pageoff.
252 		 */
253 		addr -= pageoff;
254 		if (addr & PAGE_MASK)
255 			return (EINVAL);
256 		/* Address range must be all in user VM space. */
257 		if (VM_MAXUSER_ADDRESS > 0 && addr + size > VM_MAXUSER_ADDRESS)
258 			return (EINVAL);
259 #ifndef __i386__
260 		if (VM_MIN_ADDRESS > 0 && addr < VM_MIN_ADDRESS)
261 			return (EINVAL);
262 #endif
263 		if (addr + size < addr)
264 			return (EINVAL);
265 	}
266 	/*
267 	 * XXX for non-fixed mappings where no hint is provided or
268 	 * the hint would fall in the potential heap space,
269 	 * place it after the end of the largest possible heap.
270 	 *
271 	 * There should really be a pmap call to determine a reasonable
272 	 * location.
273 	 */
274 	else if (addr == 0 ||
275 	    (addr >= round_page((vm_offset_t)vms->vm_taddr) &&
276 	     addr < round_page((vm_offset_t)vms->vm_daddr + maxdsiz)))
277 		addr = round_page((vm_offset_t)vms->vm_daddr + maxdsiz);
278 
279 	mtx_lock(&Giant);	/* syscall marked mp-safe but isn't */
280 	if (flags & MAP_ANON) {
281 		/*
282 		 * Mapping blank space is trivial.
283 		 */
284 		handle = NULL;
285 		maxprot = VM_PROT_ALL;
286 		pos = 0;
287 	} else {
288 		/*
289 		 * Mapping file, get fp for validation. Obtain vnode and make
290 		 * sure it is of appropriate type.
291 		 * don't let the descriptor disappear on us if we block
292 		 */
293 		if ((error = fget(td, uap->fd, &fp)) != 0)
294 			goto done;
295 		if (fp->f_type != DTYPE_VNODE) {
296 			error = EINVAL;
297 			goto done;
298 		}
299 
300 		/*
301 		 * POSIX shared-memory objects are defined to have
302 		 * kernel persistence, and are not defined to support
303 		 * read(2)/write(2) -- or even open(2).  Thus, we can
304 		 * use MAP_ASYNC to trade on-disk coherence for speed.
305 		 * The shm_open(3) library routine turns on the FPOSIXSHM
306 		 * flag to request this behavior.
307 		 */
308 		if (fp->f_flag & FPOSIXSHM)
309 			flags |= MAP_NOSYNC;
310 		vp = (struct vnode *) fp->f_data;
311 		if (vp->v_type != VREG && vp->v_type != VCHR) {
312 			error = EINVAL;
313 			goto done;
314 		}
315 		if (vp->v_type == VREG) {
316 			/*
317 			 * Get the proper underlying object
318 			 */
319 			if (VOP_GETVOBJECT(vp, &obj) != 0) {
320 				error = EINVAL;
321 				goto done;
322 			}
323 			vp = (struct vnode*)obj->handle;
324 		}
325 		/*
326 		 * XXX hack to handle use of /dev/zero to map anon memory (ala
327 		 * SunOS).
328 		 */
329 		if ((vp->v_type == VCHR) &&
330 		    (vp->v_rdev->si_devsw->d_flags & D_MMAP_ANON)) {
331 			handle = NULL;
332 			maxprot = VM_PROT_ALL;
333 			flags |= MAP_ANON;
334 			pos = 0;
335 		} else {
336 			/*
337 			 * cdevs does not provide private mappings of any kind.
338 			 */
339 			/*
340 			 * However, for XIG X server to continue to work,
341 			 * we should allow the superuser to do it anyway.
342 			 * We only allow it at securelevel < 1.
343 			 * (Because the XIG X server writes directly to video
344 			 * memory via /dev/mem, it should never work at any
345 			 * other securelevel.
346 			 * XXX this will have to go
347 			 */
348 			if (securelevel_ge(td->td_ucred, 1))
349 				disablexworkaround = 1;
350 			else
351 				disablexworkaround = suser(td);
352 			if (vp->v_type == VCHR && disablexworkaround &&
353 			    (flags & (MAP_PRIVATE|MAP_COPY))) {
354 				error = EINVAL;
355 				goto done;
356 			}
357 			/*
358 			 * Ensure that file and memory protections are
359 			 * compatible.  Note that we only worry about
360 			 * writability if mapping is shared; in this case,
361 			 * current and max prot are dictated by the open file.
362 			 * XXX use the vnode instead?  Problem is: what
363 			 * credentials do we use for determination? What if
364 			 * proc does a setuid?
365 			 */
366 			maxprot = VM_PROT_EXECUTE;	/* ??? */
367 			if (fp->f_flag & FREAD) {
368 				maxprot |= VM_PROT_READ;
369 			} else if (prot & PROT_READ) {
370 				error = EACCES;
371 				goto done;
372 			}
373 			/*
374 			 * If we are sharing potential changes (either via
375 			 * MAP_SHARED or via the implicit sharing of character
376 			 * device mappings), and we are trying to get write
377 			 * permission although we opened it without asking
378 			 * for it, bail out.  Check for superuser, only if
379 			 * we're at securelevel < 1, to allow the XIG X server
380 			 * to continue to work.
381 			 */
382 			if ((flags & MAP_SHARED) != 0 ||
383 			    (vp->v_type == VCHR && disablexworkaround)) {
384 				if ((fp->f_flag & FWRITE) != 0) {
385 					struct vattr va;
386 					if ((error =
387 					    VOP_GETATTR(vp, &va,
388 						        td->td_ucred, td))) {
389 						goto done;
390 					}
391 					if ((va.va_flags &
392 					   (SF_SNAPSHOT|IMMUTABLE|APPEND)) == 0) {
393 						maxprot |= VM_PROT_WRITE;
394 					} else if (prot & PROT_WRITE) {
395 						error = EPERM;
396 						goto done;
397 					}
398 				} else if ((prot & PROT_WRITE) != 0) {
399 					error = EACCES;
400 					goto done;
401 				}
402 			} else {
403 				maxprot |= VM_PROT_WRITE;
404 			}
405 
406 			handle = (void *)vp;
407 		}
408 	}
409 
410 	/*
411 	 * Do not allow more then a certain number of vm_map_entry structures
412 	 * per process.  Scale with the number of rforks sharing the map
413 	 * to make the limit reasonable for threads.
414 	 */
415 	if (max_proc_mmap &&
416 	    vms->vm_map.nentries >= max_proc_mmap * vms->vm_refcnt) {
417 		error = ENOMEM;
418 		goto done;
419 	}
420 
421 	mtx_unlock(&Giant);
422 	error = vm_mmap(&vms->vm_map, &addr, size, prot, maxprot,
423 	    flags, handle, pos);
424 	if (error == 0)
425 		td->td_retval[0] = (register_t) (addr + pageoff);
426 	mtx_lock(&Giant);
427 done:
428 	if (fp)
429 		fdrop(fp, td);
430 	mtx_unlock(&Giant);
431 	return (error);
432 }
433 
434 #ifdef COMPAT_43
435 #ifndef _SYS_SYSPROTO_H_
436 struct ommap_args {
437 	caddr_t addr;
438 	int len;
439 	int prot;
440 	int flags;
441 	int fd;
442 	long pos;
443 };
444 #endif
445 int
446 ommap(td, uap)
447 	struct thread *td;
448 	struct ommap_args *uap;
449 {
450 	struct mmap_args nargs;
451 	static const char cvtbsdprot[8] = {
452 		0,
453 		PROT_EXEC,
454 		PROT_WRITE,
455 		PROT_EXEC | PROT_WRITE,
456 		PROT_READ,
457 		PROT_EXEC | PROT_READ,
458 		PROT_WRITE | PROT_READ,
459 		PROT_EXEC | PROT_WRITE | PROT_READ,
460 	};
461 
462 #define	OMAP_ANON	0x0002
463 #define	OMAP_COPY	0x0020
464 #define	OMAP_SHARED	0x0010
465 #define	OMAP_FIXED	0x0100
466 
467 	nargs.addr = uap->addr;
468 	nargs.len = uap->len;
469 	nargs.prot = cvtbsdprot[uap->prot & 0x7];
470 	nargs.flags = 0;
471 	if (uap->flags & OMAP_ANON)
472 		nargs.flags |= MAP_ANON;
473 	if (uap->flags & OMAP_COPY)
474 		nargs.flags |= MAP_COPY;
475 	if (uap->flags & OMAP_SHARED)
476 		nargs.flags |= MAP_SHARED;
477 	else
478 		nargs.flags |= MAP_PRIVATE;
479 	if (uap->flags & OMAP_FIXED)
480 		nargs.flags |= MAP_FIXED;
481 	nargs.fd = uap->fd;
482 	nargs.pos = uap->pos;
483 	return (mmap(td, &nargs));
484 }
485 #endif				/* COMPAT_43 */
486 
487 
488 #ifndef _SYS_SYSPROTO_H_
489 struct msync_args {
490 	void *addr;
491 	int len;
492 	int flags;
493 };
494 #endif
495 /*
496  * MPSAFE
497  */
498 int
499 msync(td, uap)
500 	struct thread *td;
501 	struct msync_args *uap;
502 {
503 	vm_offset_t addr;
504 	vm_size_t size, pageoff;
505 	int flags;
506 	vm_map_t map;
507 	int rv;
508 
509 	addr = (vm_offset_t) uap->addr;
510 	size = uap->len;
511 	flags = uap->flags;
512 
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 	if ((flags & (MS_ASYNC|MS_INVALIDATE)) == (MS_ASYNC|MS_INVALIDATE))
521 		return (EINVAL);
522 
523 	mtx_lock(&Giant);
524 
525 	map = &td->td_proc->p_vmspace->vm_map;
526 
527 	/*
528 	 * XXX Gak!  If size is zero we are supposed to sync "all modified
529 	 * pages with the region containing addr".  Unfortunately, we don't
530 	 * really keep track of individual mmaps so we approximate by flushing
531 	 * the range of the map entry containing addr. This can be incorrect
532 	 * if the region splits or is coalesced with a neighbor.
533 	 */
534 	if (size == 0) {
535 		vm_map_entry_t entry;
536 
537 		vm_map_lock_read(map);
538 		rv = vm_map_lookup_entry(map, addr, &entry);
539 		vm_map_unlock_read(map);
540 		if (rv == FALSE) {
541 			rv = -1;
542 			goto done2;
543 		}
544 		addr = entry->start;
545 		size = entry->end - entry->start;
546 	}
547 
548 	/*
549 	 * Clean the pages and interpret the return value.
550 	 */
551 	rv = vm_map_clean(map, addr, addr + size, (flags & MS_ASYNC) == 0,
552 	    (flags & MS_INVALIDATE) != 0);
553 
554 done2:
555 	mtx_unlock(&Giant);
556 
557 	switch (rv) {
558 	case KERN_SUCCESS:
559 		return (0);
560 	case KERN_INVALID_ADDRESS:
561 		return (EINVAL);	/* Sun returns ENOMEM? */
562 	case KERN_FAILURE:
563 		return (EIO);
564 	default:
565 		return (EINVAL);
566 	}
567 }
568 
569 #ifndef _SYS_SYSPROTO_H_
570 struct munmap_args {
571 	void *addr;
572 	size_t len;
573 };
574 #endif
575 /*
576  * MPSAFE
577  */
578 int
579 munmap(td, uap)
580 	struct thread *td;
581 	struct munmap_args *uap;
582 {
583 	vm_offset_t addr;
584 	vm_size_t size, pageoff;
585 	vm_map_t map;
586 
587 	addr = (vm_offset_t) uap->addr;
588 	size = uap->len;
589 
590 	pageoff = (addr & PAGE_MASK);
591 	addr -= pageoff;
592 	size += pageoff;
593 	size = (vm_size_t) round_page(size);
594 	if (addr + size < addr)
595 		return (EINVAL);
596 
597 	if (size == 0)
598 		return (0);
599 
600 	/*
601 	 * Check for illegal addresses.  Watch out for address wrap... Note
602 	 * that VM_*_ADDRESS are not constants due to casts (argh).
603 	 */
604 	if (VM_MAXUSER_ADDRESS > 0 && addr + size > VM_MAXUSER_ADDRESS)
605 		return (EINVAL);
606 #ifndef __i386__
607 	if (VM_MIN_ADDRESS > 0 && addr < VM_MIN_ADDRESS)
608 		return (EINVAL);
609 #endif
610 	map = &td->td_proc->p_vmspace->vm_map;
611 	/*
612 	 * Make sure entire range is allocated.
613 	 */
614 	if (!vm_map_check_protection(map, addr, addr + size, VM_PROT_NONE))
615 		return (EINVAL);
616 
617 	/* returns nothing but KERN_SUCCESS anyway */
618 	(void) vm_map_remove(map, addr, addr + size);
619 	return (0);
620 }
621 
622 #if 0
623 void
624 munmapfd(td, fd)
625 	struct thread *td;
626 	int fd;
627 {
628 	/*
629 	 * XXX should unmap any regions mapped to this file
630 	 */
631 	FILEDESC_LOCK(p->p_fd);
632 	td->td_proc->p_fd->fd_ofileflags[fd] &= ~UF_MAPPED;
633 	FILEDESC_UNLOCK(p->p_fd);
634 }
635 #endif
636 
637 #ifndef _SYS_SYSPROTO_H_
638 struct mprotect_args {
639 	const void *addr;
640 	size_t len;
641 	int prot;
642 };
643 #endif
644 /*
645  * MPSAFE
646  */
647 int
648 mprotect(td, uap)
649 	struct thread *td;
650 	struct mprotect_args *uap;
651 {
652 	vm_offset_t addr;
653 	vm_size_t size, pageoff;
654 	vm_prot_t prot;
655 
656 	addr = (vm_offset_t) uap->addr;
657 	size = uap->len;
658 	prot = uap->prot & VM_PROT_ALL;
659 #if defined(VM_PROT_READ_IS_EXEC)
660 	if (prot & VM_PROT_READ)
661 		prot |= VM_PROT_EXECUTE;
662 #endif
663 
664 	pageoff = (addr & PAGE_MASK);
665 	addr -= pageoff;
666 	size += pageoff;
667 	size = (vm_size_t) round_page(size);
668 	if (addr + size < addr)
669 		return (EINVAL);
670 
671 	switch (vm_map_protect(&td->td_proc->p_vmspace->vm_map, addr,
672 	    addr + size, prot, FALSE)) {
673 	case KERN_SUCCESS:
674 		return (0);
675 	case KERN_PROTECTION_FAILURE:
676 		return (EACCES);
677 	}
678 	return (EINVAL);
679 }
680 
681 #ifndef _SYS_SYSPROTO_H_
682 struct minherit_args {
683 	void *addr;
684 	size_t len;
685 	int inherit;
686 };
687 #endif
688 /*
689  * MPSAFE
690  */
691 int
692 minherit(td, uap)
693 	struct thread *td;
694 	struct minherit_args *uap;
695 {
696 	vm_offset_t addr;
697 	vm_size_t size, pageoff;
698 	vm_inherit_t inherit;
699 
700 	addr = (vm_offset_t)uap->addr;
701 	size = uap->len;
702 	inherit = uap->inherit;
703 
704 	pageoff = (addr & PAGE_MASK);
705 	addr -= pageoff;
706 	size += pageoff;
707 	size = (vm_size_t) round_page(size);
708 	if (addr + size < addr)
709 		return (EINVAL);
710 
711 	switch (vm_map_inherit(&td->td_proc->p_vmspace->vm_map, addr,
712 	    addr + size, inherit)) {
713 	case KERN_SUCCESS:
714 		return (0);
715 	case KERN_PROTECTION_FAILURE:
716 		return (EACCES);
717 	}
718 	return (EINVAL);
719 }
720 
721 #ifndef _SYS_SYSPROTO_H_
722 struct madvise_args {
723 	void *addr;
724 	size_t len;
725 	int behav;
726 };
727 #endif
728 
729 /*
730  * MPSAFE
731  */
732 /* ARGSUSED */
733 int
734 madvise(td, uap)
735 	struct thread *td;
736 	struct madvise_args *uap;
737 {
738 	vm_offset_t start, end;
739 
740 	/*
741 	 * Check for illegal behavior
742 	 */
743 	if (uap->behav < 0 || uap->behav > MADV_CORE)
744 		return (EINVAL);
745 	/*
746 	 * Check for illegal addresses.  Watch out for address wrap... Note
747 	 * that VM_*_ADDRESS are not constants due to casts (argh).
748 	 */
749 	if (VM_MAXUSER_ADDRESS > 0 &&
750 		((vm_offset_t) uap->addr + uap->len) > VM_MAXUSER_ADDRESS)
751 		return (EINVAL);
752 #ifndef __i386__
753 	if (VM_MIN_ADDRESS > 0 && uap->addr < VM_MIN_ADDRESS)
754 		return (EINVAL);
755 #endif
756 	if (((vm_offset_t) uap->addr + uap->len) < (vm_offset_t) uap->addr)
757 		return (EINVAL);
758 
759 	/*
760 	 * Since this routine is only advisory, we default to conservative
761 	 * behavior.
762 	 */
763 	start = trunc_page((vm_offset_t) uap->addr);
764 	end = round_page((vm_offset_t) uap->addr + uap->len);
765 
766 	if (vm_map_madvise(&td->td_proc->p_vmspace->vm_map, start, end,
767 	    uap->behav))
768 		return (EINVAL);
769 	return (0);
770 }
771 
772 #ifndef _SYS_SYSPROTO_H_
773 struct mincore_args {
774 	const void *addr;
775 	size_t len;
776 	char *vec;
777 };
778 #endif
779 
780 /*
781  * MPSAFE
782  */
783 /* ARGSUSED */
784 int
785 mincore(td, uap)
786 	struct thread *td;
787 	struct mincore_args *uap;
788 {
789 	vm_offset_t addr, first_addr;
790 	vm_offset_t end, cend;
791 	pmap_t pmap;
792 	vm_map_t map;
793 	char *vec;
794 	int error = 0;
795 	int vecindex, lastvecindex;
796 	vm_map_entry_t current;
797 	vm_map_entry_t entry;
798 	int mincoreinfo;
799 	unsigned int timestamp;
800 
801 	/*
802 	 * Make sure that the addresses presented are valid for user
803 	 * mode.
804 	 */
805 	first_addr = addr = trunc_page((vm_offset_t) uap->addr);
806 	end = addr + (vm_size_t)round_page(uap->len);
807 	if (VM_MAXUSER_ADDRESS > 0 && end > VM_MAXUSER_ADDRESS)
808 		return (EINVAL);
809 	if (end < addr)
810 		return (EINVAL);
811 
812 	/*
813 	 * Address of byte vector
814 	 */
815 	vec = uap->vec;
816 
817 	mtx_lock(&Giant);
818 	map = &td->td_proc->p_vmspace->vm_map;
819 	pmap = vmspace_pmap(td->td_proc->p_vmspace);
820 
821 	vm_map_lock_read(map);
822 RestartScan:
823 	timestamp = map->timestamp;
824 
825 	if (!vm_map_lookup_entry(map, addr, &entry))
826 		entry = entry->next;
827 
828 	/*
829 	 * Do this on a map entry basis so that if the pages are not
830 	 * in the current processes address space, we can easily look
831 	 * up the pages elsewhere.
832 	 */
833 	lastvecindex = -1;
834 	for (current = entry;
835 	    (current != &map->header) && (current->start < end);
836 	    current = current->next) {
837 
838 		/*
839 		 * ignore submaps (for now) or null objects
840 		 */
841 		if ((current->eflags & MAP_ENTRY_IS_SUB_MAP) ||
842 			current->object.vm_object == NULL)
843 			continue;
844 
845 		/*
846 		 * limit this scan to the current map entry and the
847 		 * limits for the mincore call
848 		 */
849 		if (addr < current->start)
850 			addr = current->start;
851 		cend = current->end;
852 		if (cend > end)
853 			cend = end;
854 
855 		/*
856 		 * scan this entry one page at a time
857 		 */
858 		while (addr < cend) {
859 			/*
860 			 * Check pmap first, it is likely faster, also
861 			 * it can provide info as to whether we are the
862 			 * one referencing or modifying the page.
863 			 */
864 			mincoreinfo = pmap_mincore(pmap, addr);
865 			if (!mincoreinfo) {
866 				vm_pindex_t pindex;
867 				vm_ooffset_t offset;
868 				vm_page_t m;
869 				/*
870 				 * calculate the page index into the object
871 				 */
872 				offset = current->offset + (addr - current->start);
873 				pindex = OFF_TO_IDX(offset);
874 				m = vm_page_lookup(current->object.vm_object,
875 					pindex);
876 				/*
877 				 * if the page is resident, then gather information about
878 				 * it.
879 				 */
880 				if (m) {
881 					mincoreinfo = MINCORE_INCORE;
882 					if (m->dirty ||
883 						pmap_is_modified(m))
884 						mincoreinfo |= MINCORE_MODIFIED_OTHER;
885 					if ((m->flags & PG_REFERENCED) ||
886 						pmap_ts_referenced(m)) {
887 						vm_page_flag_set(m, PG_REFERENCED);
888 						mincoreinfo |= MINCORE_REFERENCED_OTHER;
889 					}
890 				}
891 			}
892 
893 			/*
894 			 * subyte may page fault.  In case it needs to modify
895 			 * the map, we release the lock.
896 			 */
897 			vm_map_unlock_read(map);
898 
899 			/*
900 			 * calculate index into user supplied byte vector
901 			 */
902 			vecindex = OFF_TO_IDX(addr - first_addr);
903 
904 			/*
905 			 * If we have skipped map entries, we need to make sure that
906 			 * the byte vector is zeroed for those skipped entries.
907 			 */
908 			while ((lastvecindex + 1) < vecindex) {
909 				error = subyte(vec + lastvecindex, 0);
910 				if (error) {
911 					error = EFAULT;
912 					goto done2;
913 				}
914 				++lastvecindex;
915 			}
916 
917 			/*
918 			 * Pass the page information to the user
919 			 */
920 			error = subyte(vec + vecindex, mincoreinfo);
921 			if (error) {
922 				error = EFAULT;
923 				goto done2;
924 			}
925 
926 			/*
927 			 * If the map has changed, due to the subyte, the previous
928 			 * output may be invalid.
929 			 */
930 			vm_map_lock_read(map);
931 			if (timestamp != map->timestamp)
932 				goto RestartScan;
933 
934 			lastvecindex = vecindex;
935 			addr += PAGE_SIZE;
936 		}
937 	}
938 
939 	/*
940 	 * subyte may page fault.  In case it needs to modify
941 	 * the map, we release the lock.
942 	 */
943 	vm_map_unlock_read(map);
944 
945 	/*
946 	 * Zero the last entries in the byte vector.
947 	 */
948 	vecindex = OFF_TO_IDX(end - first_addr);
949 	while ((lastvecindex + 1) < vecindex) {
950 		error = subyte(vec + lastvecindex, 0);
951 		if (error) {
952 			error = EFAULT;
953 			goto done2;
954 		}
955 		++lastvecindex;
956 	}
957 
958 	/*
959 	 * If the map has changed, due to the subyte, the previous
960 	 * output may be invalid.
961 	 */
962 	vm_map_lock_read(map);
963 	if (timestamp != map->timestamp)
964 		goto RestartScan;
965 	vm_map_unlock_read(map);
966 done2:
967 	mtx_unlock(&Giant);
968 	return (error);
969 }
970 
971 #ifndef _SYS_SYSPROTO_H_
972 struct mlock_args {
973 	const void *addr;
974 	size_t len;
975 };
976 #endif
977 /*
978  * MPSAFE
979  */
980 int
981 mlock(td, uap)
982 	struct thread *td;
983 	struct mlock_args *uap;
984 {
985 	vm_offset_t addr;
986 	vm_size_t size, pageoff;
987 	int error;
988 
989 	addr = (vm_offset_t) uap->addr;
990 	size = uap->len;
991 
992 	pageoff = (addr & PAGE_MASK);
993 	addr -= pageoff;
994 	size += pageoff;
995 	size = (vm_size_t) round_page(size);
996 
997 	/* disable wrap around */
998 	if (addr + size < addr)
999 		return (EINVAL);
1000 
1001 	if (atop(size) + cnt.v_wire_count > vm_page_max_wired)
1002 		return (EAGAIN);
1003 
1004 #ifdef pmap_wired_count
1005 	if (size + ptoa(pmap_wired_count(vm_map_pmap(&td->td_proc->p_vmspace->vm_map))) >
1006 	    td->td_proc->p_rlimit[RLIMIT_MEMLOCK].rlim_cur)
1007 		return (ENOMEM);
1008 #else
1009 	error = suser(td);
1010 	if (error)
1011 		return (error);
1012 #endif
1013 
1014 	error = vm_map_wire(&td->td_proc->p_vmspace->vm_map, addr,
1015 		     addr + size, TRUE);
1016 	return (error == KERN_SUCCESS ? 0 : ENOMEM);
1017 }
1018 
1019 #ifndef _SYS_SYSPROTO_H_
1020 struct mlockall_args {
1021 	int	how;
1022 };
1023 #endif
1024 
1025 /*
1026  * MPSAFE
1027  */
1028 int
1029 mlockall(td, uap)
1030 	struct thread *td;
1031 	struct mlockall_args *uap;
1032 {
1033 	/* mtx_lock(&Giant); */
1034 	/* mtx_unlock(&Giant); */
1035 	return 0;
1036 }
1037 
1038 #ifndef _SYS_SYSPROTO_H_
1039 struct munlockall_args {
1040 	int	how;
1041 };
1042 #endif
1043 
1044 /*
1045  * MPSAFE
1046  */
1047 int
1048 munlockall(td, uap)
1049 	struct thread *td;
1050 	struct munlockall_args *uap;
1051 {
1052 	/* mtx_lock(&Giant); */
1053 	/* mtx_unlock(&Giant); */
1054 	return 0;
1055 }
1056 
1057 #ifndef _SYS_SYSPROTO_H_
1058 struct munlock_args {
1059 	const void *addr;
1060 	size_t len;
1061 };
1062 #endif
1063 /*
1064  * MPSAFE
1065  */
1066 int
1067 munlock(td, uap)
1068 	struct thread *td;
1069 	struct munlock_args *uap;
1070 {
1071 	vm_offset_t addr;
1072 	vm_size_t size, pageoff;
1073 	int error;
1074 
1075 	addr = (vm_offset_t) uap->addr;
1076 	size = uap->len;
1077 
1078 	pageoff = (addr & PAGE_MASK);
1079 	addr -= pageoff;
1080 	size += pageoff;
1081 	size = (vm_size_t) round_page(size);
1082 
1083 	/* disable wrap around */
1084 	if (addr + size < addr)
1085 		return (EINVAL);
1086 
1087 #ifndef pmap_wired_count
1088 	error = suser(td);
1089 	if (error)
1090 		return (error);
1091 #endif
1092 
1093 	error = vm_map_unwire(&td->td_proc->p_vmspace->vm_map, addr,
1094 		     addr + size, TRUE);
1095 	return (error == KERN_SUCCESS ? 0 : ENOMEM);
1096 }
1097 
1098 /*
1099  * vm_mmap()
1100  *
1101  * MPSAFE
1102  *
1103  * Internal version of mmap.  Currently used by mmap, exec, and sys5
1104  * shared memory.  Handle is either a vnode pointer or NULL for MAP_ANON.
1105  */
1106 int
1107 vm_mmap(vm_map_t map, vm_offset_t *addr, vm_size_t size, vm_prot_t prot,
1108 	vm_prot_t maxprot, int flags,
1109 	void *handle,
1110 	vm_ooffset_t foff)
1111 {
1112 	boolean_t fitit;
1113 	vm_object_t object;
1114 	struct vnode *vp = NULL;
1115 	objtype_t type;
1116 	int rv = KERN_SUCCESS;
1117 	vm_ooffset_t objsize;
1118 	int docow;
1119 	struct thread *td = curthread;
1120 
1121 	if (size == 0)
1122 		return (0);
1123 
1124 	objsize = size = round_page(size);
1125 
1126 	/*
1127 	 * We currently can only deal with page aligned file offsets.
1128 	 * The check is here rather than in the syscall because the
1129 	 * kernel calls this function internally for other mmaping
1130 	 * operations (such as in exec) and non-aligned offsets will
1131 	 * cause pmap inconsistencies...so we want to be sure to
1132 	 * disallow this in all cases.
1133 	 */
1134 	if (foff & PAGE_MASK)
1135 		return (EINVAL);
1136 
1137 	if ((flags & MAP_FIXED) == 0) {
1138 		fitit = TRUE;
1139 		*addr = round_page(*addr);
1140 		mtx_lock(&Giant);
1141 	} else {
1142 		if (*addr != trunc_page(*addr))
1143 			return (EINVAL);
1144 		fitit = FALSE;
1145 		mtx_lock(&Giant);
1146 		(void) vm_map_remove(map, *addr, *addr + size);
1147 	}
1148 
1149 	/*
1150 	 * Lookup/allocate object.
1151 	 */
1152 	if (flags & MAP_ANON) {
1153 		type = OBJT_DEFAULT;
1154 		/*
1155 		 * Unnamed anonymous regions always start at 0.
1156 		 */
1157 		if (handle == 0)
1158 			foff = 0;
1159 	} else {
1160 		vp = (struct vnode *) handle;
1161 		if (vp->v_type == VCHR) {
1162 			type = OBJT_DEVICE;
1163 			handle = (void *)(intptr_t)vp->v_rdev;
1164 		} else {
1165 			struct vattr vat;
1166 			int error;
1167 
1168 			error = VOP_GETATTR(vp, &vat, td->td_ucred, td);
1169 			if (error) {
1170 				mtx_unlock(&Giant);
1171 				return (error);
1172 			}
1173 			objsize = round_page(vat.va_size);
1174 			type = OBJT_VNODE;
1175 			/*
1176 			 * if it is a regular file without any references
1177 			 * we do not need to sync it.
1178 			 */
1179 			if (vp->v_type == VREG && vat.va_nlink == 0) {
1180 				flags |= MAP_NOSYNC;
1181 			}
1182 		}
1183 	}
1184 
1185 	if (handle == NULL) {
1186 		object = NULL;
1187 		docow = 0;
1188 	} else {
1189 		object = vm_pager_allocate(type,
1190 			handle, objsize, prot, foff);
1191 		if (object == NULL) {
1192 			mtx_unlock(&Giant);
1193 			return (type == OBJT_DEVICE ? EINVAL : ENOMEM);
1194 		}
1195 		docow = MAP_PREFAULT_PARTIAL;
1196 	}
1197 
1198 	/*
1199 	 * Force device mappings to be shared.
1200 	 */
1201 	if (type == OBJT_DEVICE || type == OBJT_PHYS) {
1202 		flags &= ~(MAP_PRIVATE|MAP_COPY);
1203 		flags |= MAP_SHARED;
1204 	}
1205 
1206 	if ((flags & (MAP_ANON|MAP_SHARED)) == 0)
1207 		docow |= MAP_COPY_ON_WRITE;
1208 	if (flags & MAP_NOSYNC)
1209 		docow |= MAP_DISABLE_SYNCER;
1210 	if (flags & MAP_NOCORE)
1211 		docow |= MAP_DISABLE_COREDUMP;
1212 
1213 #if defined(VM_PROT_READ_IS_EXEC)
1214 	if (prot & VM_PROT_READ)
1215 		prot |= VM_PROT_EXECUTE;
1216 
1217 	if (maxprot & VM_PROT_READ)
1218 		maxprot |= VM_PROT_EXECUTE;
1219 #endif
1220 
1221 	if (fitit)
1222 		*addr = pmap_addr_hint(object, *addr, size);
1223 
1224 	if (flags & MAP_STACK)
1225 		rv = vm_map_stack (map, *addr, size, prot,
1226 				   maxprot, docow);
1227 	else
1228 		rv = vm_map_find(map, object, foff, addr, size, fitit,
1229 				 prot, maxprot, docow);
1230 
1231 	if (rv != KERN_SUCCESS) {
1232 		/*
1233 		 * Lose the object reference. Will destroy the
1234 		 * object if it's an unnamed anonymous mapping
1235 		 * or named anonymous without other references.
1236 		 */
1237 		vm_object_deallocate(object);
1238 	} else if (flags & MAP_SHARED) {
1239 		/*
1240 		 * Shared memory is also shared with children.
1241 		 */
1242 		rv = vm_map_inherit(map, *addr, *addr + size, VM_INHERIT_SHARE);
1243 		if (rv != KERN_SUCCESS)
1244 			(void) vm_map_remove(map, *addr, *addr + size);
1245 	}
1246 	mtx_unlock(&Giant);
1247 	switch (rv) {
1248 	case KERN_SUCCESS:
1249 		return (0);
1250 	case KERN_INVALID_ADDRESS:
1251 	case KERN_NO_SPACE:
1252 		return (ENOMEM);
1253 	case KERN_PROTECTION_FAILURE:
1254 		return (EACCES);
1255 	default:
1256 		return (EINVAL);
1257 	}
1258 }
1259