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