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