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