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