]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_map.c
Remove spurious newline
[FreeBSD/FreeBSD.git] / sys / vm / vm_map.c
1 /*-
2  * SPDX-License-Identifier: (BSD-3-Clause AND MIT-CMU)
3  *
4  * Copyright (c) 1991, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * The Mach Operating System project at Carnegie-Mellon University.
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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      from: @(#)vm_map.c      8.3 (Berkeley) 1/12/94
35  *
36  *
37  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38  * All rights reserved.
39  *
40  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
41  *
42  * Permission to use, copy, modify and distribute this software and
43  * its documentation is hereby granted, provided that both the copyright
44  * notice and this permission notice appear in all copies of the
45  * software, derivative works or modified versions, and any portions
46  * thereof, and that both notices appear in supporting documentation.
47  *
48  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
51  *
52  * Carnegie Mellon requests users of this software to return to
53  *
54  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
55  *  School of Computer Science
56  *  Carnegie Mellon University
57  *  Pittsburgh PA 15213-3890
58  *
59  * any improvements or extensions that they make and grant Carnegie the
60  * rights to redistribute these changes.
61  */
62
63 /*
64  *      Virtual memory mapping module.
65  */
66
67 #include <sys/cdefs.h>
68 __FBSDID("$FreeBSD$");
69
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/ktr.h>
74 #include <sys/lock.h>
75 #include <sys/mutex.h>
76 #include <sys/proc.h>
77 #include <sys/vmmeter.h>
78 #include <sys/mman.h>
79 #include <sys/vnode.h>
80 #include <sys/racct.h>
81 #include <sys/resourcevar.h>
82 #include <sys/rwlock.h>
83 #include <sys/file.h>
84 #include <sys/sysctl.h>
85 #include <sys/sysent.h>
86 #include <sys/shm.h>
87
88 #include <vm/vm.h>
89 #include <vm/vm_param.h>
90 #include <vm/pmap.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_page.h>
93 #include <vm/vm_pageout.h>
94 #include <vm/vm_object.h>
95 #include <vm/vm_pager.h>
96 #include <vm/vm_kern.h>
97 #include <vm/vm_extern.h>
98 #include <vm/vnode_pager.h>
99 #include <vm/swap_pager.h>
100 #include <vm/uma.h>
101
102 /*
103  *      Virtual memory maps provide for the mapping, protection,
104  *      and sharing of virtual memory objects.  In addition,
105  *      this module provides for an efficient virtual copy of
106  *      memory from one map to another.
107  *
108  *      Synchronization is required prior to most operations.
109  *
110  *      Maps consist of an ordered doubly-linked list of simple
111  *      entries; a self-adjusting binary search tree of these
112  *      entries is used to speed up lookups.
113  *
114  *      Since portions of maps are specified by start/end addresses,
115  *      which may not align with existing map entries, all
116  *      routines merely "clip" entries to these start/end values.
117  *      [That is, an entry is split into two, bordering at a
118  *      start or end value.]  Note that these clippings may not
119  *      always be necessary (as the two resulting entries are then
120  *      not changed); however, the clipping is done for convenience.
121  *
122  *      As mentioned above, virtual copy operations are performed
123  *      by copying VM object references from one map to
124  *      another, and then marking both regions as copy-on-write.
125  */
126
127 static struct mtx map_sleep_mtx;
128 static uma_zone_t mapentzone;
129 static uma_zone_t kmapentzone;
130 static uma_zone_t mapzone;
131 static uma_zone_t vmspace_zone;
132 static int vmspace_zinit(void *mem, int size, int flags);
133 static int vm_map_zinit(void *mem, int ize, int flags);
134 static void _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min,
135     vm_offset_t max);
136 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
137 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
138 static void vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry);
139 static int vm_map_growstack(vm_map_t map, vm_offset_t addr,
140     vm_map_entry_t gap_entry);
141 static void vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
142     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags);
143 #ifdef INVARIANTS
144 static void vm_map_zdtor(void *mem, int size, void *arg);
145 static void vmspace_zdtor(void *mem, int size, void *arg);
146 #endif
147 static int vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos,
148     vm_size_t max_ssize, vm_size_t growsize, vm_prot_t prot, vm_prot_t max,
149     int cow);
150 static void vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
151     vm_offset_t failed_addr);
152
153 #define ENTRY_CHARGED(e) ((e)->cred != NULL || \
154     ((e)->object.vm_object != NULL && (e)->object.vm_object->cred != NULL && \
155      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
156
157 /* 
158  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
159  * stable.
160  */
161 #define PROC_VMSPACE_LOCK(p) do { } while (0)
162 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
163
164 /*
165  *      VM_MAP_RANGE_CHECK:     [ internal use only ]
166  *
167  *      Asserts that the starting and ending region
168  *      addresses fall within the valid range of the map.
169  */
170 #define VM_MAP_RANGE_CHECK(map, start, end)             \
171                 {                                       \
172                 if (start < vm_map_min(map))            \
173                         start = vm_map_min(map);        \
174                 if (end > vm_map_max(map))              \
175                         end = vm_map_max(map);          \
176                 if (start > end)                        \
177                         start = end;                    \
178                 }
179
180 /*
181  *      vm_map_startup:
182  *
183  *      Initialize the vm_map module.  Must be called before
184  *      any other vm_map routines.
185  *
186  *      Map and entry structures are allocated from the general
187  *      purpose memory pool with some exceptions:
188  *
189  *      - The kernel map and kmem submap are allocated statically.
190  *      - Kernel map entries are allocated out of a static pool.
191  *
192  *      These restrictions are necessary since malloc() uses the
193  *      maps and requires map entries.
194  */
195
196 void
197 vm_map_startup(void)
198 {
199         mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
200         mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
201 #ifdef INVARIANTS
202             vm_map_zdtor,
203 #else
204             NULL,
205 #endif
206             vm_map_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
207         uma_prealloc(mapzone, MAX_KMAP);
208         kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
209             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
210             UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
211         mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
212             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
213         vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
214 #ifdef INVARIANTS
215             vmspace_zdtor,
216 #else
217             NULL,
218 #endif
219             vmspace_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
220 }
221
222 static int
223 vmspace_zinit(void *mem, int size, int flags)
224 {
225         struct vmspace *vm;
226
227         vm = (struct vmspace *)mem;
228
229         vm->vm_map.pmap = NULL;
230         (void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
231         PMAP_LOCK_INIT(vmspace_pmap(vm));
232         return (0);
233 }
234
235 static int
236 vm_map_zinit(void *mem, int size, int flags)
237 {
238         vm_map_t map;
239
240         map = (vm_map_t)mem;
241         memset(map, 0, sizeof(*map));
242         mtx_init(&map->system_mtx, "vm map (system)", NULL, MTX_DEF | MTX_DUPOK);
243         sx_init(&map->lock, "vm map (user)");
244         return (0);
245 }
246
247 #ifdef INVARIANTS
248 static void
249 vmspace_zdtor(void *mem, int size, void *arg)
250 {
251         struct vmspace *vm;
252
253         vm = (struct vmspace *)mem;
254
255         vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
256 }
257 static void
258 vm_map_zdtor(void *mem, int size, void *arg)
259 {
260         vm_map_t map;
261
262         map = (vm_map_t)mem;
263         KASSERT(map->nentries == 0,
264             ("map %p nentries == %d on free.",
265             map, map->nentries));
266         KASSERT(map->size == 0,
267             ("map %p size == %lu on free.",
268             map, (unsigned long)map->size));
269 }
270 #endif  /* INVARIANTS */
271
272 /*
273  * Allocate a vmspace structure, including a vm_map and pmap,
274  * and initialize those structures.  The refcnt is set to 1.
275  *
276  * If 'pinit' is NULL then the embedded pmap is initialized via pmap_pinit().
277  */
278 struct vmspace *
279 vmspace_alloc(vm_offset_t min, vm_offset_t max, pmap_pinit_t pinit)
280 {
281         struct vmspace *vm;
282
283         vm = uma_zalloc(vmspace_zone, M_WAITOK);
284         KASSERT(vm->vm_map.pmap == NULL, ("vm_map.pmap must be NULL"));
285         if (!pinit(vmspace_pmap(vm))) {
286                 uma_zfree(vmspace_zone, vm);
287                 return (NULL);
288         }
289         CTR1(KTR_VM, "vmspace_alloc: %p", vm);
290         _vm_map_init(&vm->vm_map, vmspace_pmap(vm), min, max);
291         vm->vm_refcnt = 1;
292         vm->vm_shm = NULL;
293         vm->vm_swrss = 0;
294         vm->vm_tsize = 0;
295         vm->vm_dsize = 0;
296         vm->vm_ssize = 0;
297         vm->vm_taddr = 0;
298         vm->vm_daddr = 0;
299         vm->vm_maxsaddr = 0;
300         return (vm);
301 }
302
303 #ifdef RACCT
304 static void
305 vmspace_container_reset(struct proc *p)
306 {
307
308         PROC_LOCK(p);
309         racct_set(p, RACCT_DATA, 0);
310         racct_set(p, RACCT_STACK, 0);
311         racct_set(p, RACCT_RSS, 0);
312         racct_set(p, RACCT_MEMLOCK, 0);
313         racct_set(p, RACCT_VMEM, 0);
314         PROC_UNLOCK(p);
315 }
316 #endif
317
318 static inline void
319 vmspace_dofree(struct vmspace *vm)
320 {
321
322         CTR1(KTR_VM, "vmspace_free: %p", vm);
323
324         /*
325          * Make sure any SysV shm is freed, it might not have been in
326          * exit1().
327          */
328         shmexit(vm);
329
330         /*
331          * Lock the map, to wait out all other references to it.
332          * Delete all of the mappings and pages they hold, then call
333          * the pmap module to reclaim anything left.
334          */
335         (void)vm_map_remove(&vm->vm_map, vm_map_min(&vm->vm_map),
336             vm_map_max(&vm->vm_map));
337
338         pmap_release(vmspace_pmap(vm));
339         vm->vm_map.pmap = NULL;
340         uma_zfree(vmspace_zone, vm);
341 }
342
343 void
344 vmspace_free(struct vmspace *vm)
345 {
346
347         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
348             "vmspace_free() called");
349
350         if (vm->vm_refcnt == 0)
351                 panic("vmspace_free: attempt to free already freed vmspace");
352
353         if (atomic_fetchadd_int(&vm->vm_refcnt, -1) == 1)
354                 vmspace_dofree(vm);
355 }
356
357 void
358 vmspace_exitfree(struct proc *p)
359 {
360         struct vmspace *vm;
361
362         PROC_VMSPACE_LOCK(p);
363         vm = p->p_vmspace;
364         p->p_vmspace = NULL;
365         PROC_VMSPACE_UNLOCK(p);
366         KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
367         vmspace_free(vm);
368 }
369
370 void
371 vmspace_exit(struct thread *td)
372 {
373         int refcnt;
374         struct vmspace *vm;
375         struct proc *p;
376
377         /*
378          * Release user portion of address space.
379          * This releases references to vnodes,
380          * which could cause I/O if the file has been unlinked.
381          * Need to do this early enough that we can still sleep.
382          *
383          * The last exiting process to reach this point releases as
384          * much of the environment as it can. vmspace_dofree() is the
385          * slower fallback in case another process had a temporary
386          * reference to the vmspace.
387          */
388
389         p = td->td_proc;
390         vm = p->p_vmspace;
391         atomic_add_int(&vmspace0.vm_refcnt, 1);
392         refcnt = vm->vm_refcnt;
393         do {
394                 if (refcnt > 1 && p->p_vmspace != &vmspace0) {
395                         /* Switch now since other proc might free vmspace */
396                         PROC_VMSPACE_LOCK(p);
397                         p->p_vmspace = &vmspace0;
398                         PROC_VMSPACE_UNLOCK(p);
399                         pmap_activate(td);
400                 }
401         } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt - 1));
402         if (refcnt == 1) {
403                 if (p->p_vmspace != vm) {
404                         /* vmspace not yet freed, switch back */
405                         PROC_VMSPACE_LOCK(p);
406                         p->p_vmspace = vm;
407                         PROC_VMSPACE_UNLOCK(p);
408                         pmap_activate(td);
409                 }
410                 pmap_remove_pages(vmspace_pmap(vm));
411                 /* Switch now since this proc will free vmspace */
412                 PROC_VMSPACE_LOCK(p);
413                 p->p_vmspace = &vmspace0;
414                 PROC_VMSPACE_UNLOCK(p);
415                 pmap_activate(td);
416                 vmspace_dofree(vm);
417         }
418 #ifdef RACCT
419         if (racct_enable)
420                 vmspace_container_reset(p);
421 #endif
422 }
423
424 /* Acquire reference to vmspace owned by another process. */
425
426 struct vmspace *
427 vmspace_acquire_ref(struct proc *p)
428 {
429         struct vmspace *vm;
430         int refcnt;
431
432         PROC_VMSPACE_LOCK(p);
433         vm = p->p_vmspace;
434         if (vm == NULL) {
435                 PROC_VMSPACE_UNLOCK(p);
436                 return (NULL);
437         }
438         refcnt = vm->vm_refcnt;
439         do {
440                 if (refcnt <= 0) {      /* Avoid 0->1 transition */
441                         PROC_VMSPACE_UNLOCK(p);
442                         return (NULL);
443                 }
444         } while (!atomic_fcmpset_int(&vm->vm_refcnt, &refcnt, refcnt + 1));
445         if (vm != p->p_vmspace) {
446                 PROC_VMSPACE_UNLOCK(p);
447                 vmspace_free(vm);
448                 return (NULL);
449         }
450         PROC_VMSPACE_UNLOCK(p);
451         return (vm);
452 }
453
454 /*
455  * Switch between vmspaces in an AIO kernel process.
456  *
457  * The AIO kernel processes switch to and from a user process's
458  * vmspace while performing an I/O operation on behalf of a user
459  * process.  The new vmspace is either the vmspace of a user process
460  * obtained from an active AIO request or the initial vmspace of the
461  * AIO kernel process (when it is idling).  Because user processes
462  * will block to drain any active AIO requests before proceeding in
463  * exit() or execve(), the vmspace reference count for these vmspaces
464  * can never be 0.  This allows for a much simpler implementation than
465  * the loop in vmspace_acquire_ref() above.  Similarly, AIO kernel
466  * processes hold an extra reference on their initial vmspace for the
467  * life of the process so that this guarantee is true for any vmspace
468  * passed as 'newvm'.
469  */
470 void
471 vmspace_switch_aio(struct vmspace *newvm)
472 {
473         struct vmspace *oldvm;
474
475         /* XXX: Need some way to assert that this is an aio daemon. */
476
477         KASSERT(newvm->vm_refcnt > 0,
478             ("vmspace_switch_aio: newvm unreferenced"));
479
480         oldvm = curproc->p_vmspace;
481         if (oldvm == newvm)
482                 return;
483
484         /*
485          * Point to the new address space and refer to it.
486          */
487         curproc->p_vmspace = newvm;
488         atomic_add_int(&newvm->vm_refcnt, 1);
489
490         /* Activate the new mapping. */
491         pmap_activate(curthread);
492
493         /* Remove the daemon's reference to the old address space. */
494         KASSERT(oldvm->vm_refcnt > 1,
495             ("vmspace_switch_aio: oldvm dropping last reference"));
496         vmspace_free(oldvm);
497 }
498
499 void
500 _vm_map_lock(vm_map_t map, const char *file, int line)
501 {
502
503         if (map->system_map)
504                 mtx_lock_flags_(&map->system_mtx, 0, file, line);
505         else
506                 sx_xlock_(&map->lock, file, line);
507         map->timestamp++;
508 }
509
510 void
511 vm_map_entry_set_vnode_text(vm_map_entry_t entry, bool add)
512 {
513         vm_object_t object, object1;
514         struct vnode *vp;
515
516         if ((entry->eflags & MAP_ENTRY_VN_EXEC) == 0)
517                 return;
518         KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
519             ("Submap with execs"));
520         object = entry->object.vm_object;
521         KASSERT(object != NULL, ("No object for text, entry %p", entry));
522         VM_OBJECT_RLOCK(object);
523         while ((object1 = object->backing_object) != NULL) {
524                 VM_OBJECT_RLOCK(object1);
525                 VM_OBJECT_RUNLOCK(object);
526                 object = object1;
527         }
528
529         /*
530          * For OBJT_DEAD objects, v_writecount was handled in
531          * vnode_pager_dealloc().
532          */
533         if (object->type != OBJT_DEAD) {
534                 KASSERT(((object->flags & OBJ_TMPFS) == 0 &&
535                     object->type == OBJT_VNODE) ||
536                     ((object->flags & OBJ_TMPFS) != 0 &&
537                     object->type == OBJT_SWAP),
538                     ("vm_map_entry_set_vnode_text: wrong object type, "
539                     "entry %p, object %p, add %d", entry, object, add));
540                 vp = (object->flags & OBJ_TMPFS) == 0 ? object->handle :
541                     object->un_pager.swp.swp_tmpfs;
542                 if (add)
543                         VOP_SET_TEXT_CHECKED(vp);
544                 else
545                         VOP_UNSET_TEXT_CHECKED(vp);
546         }
547         VM_OBJECT_RUNLOCK(object);
548 }
549
550 static void
551 vm_map_process_deferred(void)
552 {
553         struct thread *td;
554         vm_map_entry_t entry, next;
555         vm_object_t object;
556
557         td = curthread;
558         entry = td->td_map_def_user;
559         td->td_map_def_user = NULL;
560         while (entry != NULL) {
561                 next = entry->next;
562                 MPASS((entry->eflags & (MAP_ENTRY_VN_WRITECNT |
563                     MAP_ENTRY_VN_EXEC)) != (MAP_ENTRY_VN_WRITECNT |
564                     MAP_ENTRY_VN_EXEC));
565                 if ((entry->eflags & MAP_ENTRY_VN_WRITECNT) != 0) {
566                         /*
567                          * Decrement the object's writemappings and
568                          * possibly the vnode's v_writecount.
569                          */
570                         KASSERT((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0,
571                             ("Submap with writecount"));
572                         object = entry->object.vm_object;
573                         KASSERT(object != NULL, ("No object for writecount"));
574                         vnode_pager_release_writecount(object, entry->start,
575                             entry->end);
576                 }
577                 vm_map_entry_set_vnode_text(entry, false);
578                 vm_map_entry_deallocate(entry, FALSE);
579                 entry = next;
580         }
581 }
582
583 void
584 _vm_map_unlock(vm_map_t map, const char *file, int line)
585 {
586
587         if (map->system_map)
588                 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
589         else {
590                 sx_xunlock_(&map->lock, file, line);
591                 vm_map_process_deferred();
592         }
593 }
594
595 void
596 _vm_map_lock_read(vm_map_t map, const char *file, int line)
597 {
598
599         if (map->system_map)
600                 mtx_lock_flags_(&map->system_mtx, 0, file, line);
601         else
602                 sx_slock_(&map->lock, file, line);
603 }
604
605 void
606 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
607 {
608
609         if (map->system_map)
610                 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
611         else {
612                 sx_sunlock_(&map->lock, file, line);
613                 vm_map_process_deferred();
614         }
615 }
616
617 int
618 _vm_map_trylock(vm_map_t map, const char *file, int line)
619 {
620         int error;
621
622         error = map->system_map ?
623             !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
624             !sx_try_xlock_(&map->lock, file, line);
625         if (error == 0)
626                 map->timestamp++;
627         return (error == 0);
628 }
629
630 int
631 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
632 {
633         int error;
634
635         error = map->system_map ?
636             !mtx_trylock_flags_(&map->system_mtx, 0, file, line) :
637             !sx_try_slock_(&map->lock, file, line);
638         return (error == 0);
639 }
640
641 /*
642  *      _vm_map_lock_upgrade:   [ internal use only ]
643  *
644  *      Tries to upgrade a read (shared) lock on the specified map to a write
645  *      (exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
646  *      non-zero value if the upgrade fails.  If the upgrade fails, the map is
647  *      returned without a read or write lock held.
648  *
649  *      Requires that the map be read locked.
650  */
651 int
652 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
653 {
654         unsigned int last_timestamp;
655
656         if (map->system_map) {
657                 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
658         } else {
659                 if (!sx_try_upgrade_(&map->lock, file, line)) {
660                         last_timestamp = map->timestamp;
661                         sx_sunlock_(&map->lock, file, line);
662                         vm_map_process_deferred();
663                         /*
664                          * If the map's timestamp does not change while the
665                          * map is unlocked, then the upgrade succeeds.
666                          */
667                         sx_xlock_(&map->lock, file, line);
668                         if (last_timestamp != map->timestamp) {
669                                 sx_xunlock_(&map->lock, file, line);
670                                 return (1);
671                         }
672                 }
673         }
674         map->timestamp++;
675         return (0);
676 }
677
678 void
679 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
680 {
681
682         if (map->system_map) {
683                 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
684         } else
685                 sx_downgrade_(&map->lock, file, line);
686 }
687
688 /*
689  *      vm_map_locked:
690  *
691  *      Returns a non-zero value if the caller holds a write (exclusive) lock
692  *      on the specified map and the value "0" otherwise.
693  */
694 int
695 vm_map_locked(vm_map_t map)
696 {
697
698         if (map->system_map)
699                 return (mtx_owned(&map->system_mtx));
700         else
701                 return (sx_xlocked(&map->lock));
702 }
703
704 #ifdef INVARIANTS
705 static void
706 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
707 {
708
709         if (map->system_map)
710                 mtx_assert_(&map->system_mtx, MA_OWNED, file, line);
711         else
712                 sx_assert_(&map->lock, SA_XLOCKED, file, line);
713 }
714
715 #define VM_MAP_ASSERT_LOCKED(map) \
716     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
717
718 #ifdef DIAGNOSTIC
719 static int enable_vmmap_check = 1;
720 #else
721 static int enable_vmmap_check = 0;
722 #endif
723 SYSCTL_INT(_debug, OID_AUTO, vmmap_check, CTLFLAG_RWTUN,
724     &enable_vmmap_check, 0, "Enable vm map consistency checking");
725
726 static void
727 _vm_map_assert_consistent(vm_map_t map)
728 {
729         vm_map_entry_t entry;
730         vm_map_entry_t child;
731         vm_size_t max_left, max_right;
732
733         if (!enable_vmmap_check)
734                 return;
735
736         for (entry = map->header.next; entry != &map->header;
737             entry = entry->next) {
738                 KASSERT(entry->prev->end <= entry->start,
739                     ("map %p prev->end = %jx, start = %jx", map,
740                     (uintmax_t)entry->prev->end, (uintmax_t)entry->start));
741                 KASSERT(entry->start < entry->end,
742                     ("map %p start = %jx, end = %jx", map,
743                     (uintmax_t)entry->start, (uintmax_t)entry->end));
744                 KASSERT(entry->end <= entry->next->start,
745                     ("map %p end = %jx, next->start = %jx", map,
746                     (uintmax_t)entry->end, (uintmax_t)entry->next->start));
747                 KASSERT(entry->left == NULL ||
748                     entry->left->start < entry->start,
749                     ("map %p left->start = %jx, start = %jx", map,
750                     (uintmax_t)entry->left->start, (uintmax_t)entry->start));
751                 KASSERT(entry->right == NULL ||
752                     entry->start < entry->right->start,
753                     ("map %p start = %jx, right->start = %jx", map,
754                     (uintmax_t)entry->start, (uintmax_t)entry->right->start));
755                 child = entry->left;
756                 max_left = (child != NULL) ? child->max_free :
757                         entry->start - entry->prev->end;
758                 child = entry->right;
759                 max_right = (child != NULL) ? child->max_free :
760                         entry->next->start - entry->end;
761                 KASSERT(entry->max_free == MAX(max_left, max_right),
762                     ("map %p max = %jx, max_left = %jx, max_right = %jx", map,
763                      (uintmax_t)entry->max_free,
764                      (uintmax_t)max_left, (uintmax_t)max_right));
765         }       
766 }
767
768 #define VM_MAP_ASSERT_CONSISTENT(map) \
769     _vm_map_assert_consistent(map)
770 #else
771 #define VM_MAP_ASSERT_LOCKED(map)
772 #define VM_MAP_ASSERT_CONSISTENT(map)
773 #endif /* INVARIANTS */
774
775 /*
776  *      _vm_map_unlock_and_wait:
777  *
778  *      Atomically releases the lock on the specified map and puts the calling
779  *      thread to sleep.  The calling thread will remain asleep until either
780  *      vm_map_wakeup() is performed on the map or the specified timeout is
781  *      exceeded.
782  *
783  *      WARNING!  This function does not perform deferred deallocations of
784  *      objects and map entries.  Therefore, the calling thread is expected to
785  *      reacquire the map lock after reawakening and later perform an ordinary
786  *      unlock operation, such as vm_map_unlock(), before completing its
787  *      operation on the map.
788  */
789 int
790 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
791 {
792
793         mtx_lock(&map_sleep_mtx);
794         if (map->system_map)
795                 mtx_unlock_flags_(&map->system_mtx, 0, file, line);
796         else
797                 sx_xunlock_(&map->lock, file, line);
798         return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
799             timo));
800 }
801
802 /*
803  *      vm_map_wakeup:
804  *
805  *      Awaken any threads that have slept on the map using
806  *      vm_map_unlock_and_wait().
807  */
808 void
809 vm_map_wakeup(vm_map_t map)
810 {
811
812         /*
813          * Acquire and release map_sleep_mtx to prevent a wakeup()
814          * from being performed (and lost) between the map unlock
815          * and the msleep() in _vm_map_unlock_and_wait().
816          */
817         mtx_lock(&map_sleep_mtx);
818         mtx_unlock(&map_sleep_mtx);
819         wakeup(&map->root);
820 }
821
822 void
823 vm_map_busy(vm_map_t map)
824 {
825
826         VM_MAP_ASSERT_LOCKED(map);
827         map->busy++;
828 }
829
830 void
831 vm_map_unbusy(vm_map_t map)
832 {
833
834         VM_MAP_ASSERT_LOCKED(map);
835         KASSERT(map->busy, ("vm_map_unbusy: not busy"));
836         if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
837                 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
838                 wakeup(&map->busy);
839         }
840 }
841
842 void 
843 vm_map_wait_busy(vm_map_t map)
844 {
845
846         VM_MAP_ASSERT_LOCKED(map);
847         while (map->busy) {
848                 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
849                 if (map->system_map)
850                         msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
851                 else
852                         sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
853         }
854         map->timestamp++;
855 }
856
857 long
858 vmspace_resident_count(struct vmspace *vmspace)
859 {
860         return pmap_resident_count(vmspace_pmap(vmspace));
861 }
862
863 /*
864  *      vm_map_create:
865  *
866  *      Creates and returns a new empty VM map with
867  *      the given physical map structure, and having
868  *      the given lower and upper address bounds.
869  */
870 vm_map_t
871 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
872 {
873         vm_map_t result;
874
875         result = uma_zalloc(mapzone, M_WAITOK);
876         CTR1(KTR_VM, "vm_map_create: %p", result);
877         _vm_map_init(result, pmap, min, max);
878         return (result);
879 }
880
881 /*
882  * Initialize an existing vm_map structure
883  * such as that in the vmspace structure.
884  */
885 static void
886 _vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
887 {
888
889         map->header.next = map->header.prev = &map->header;
890         map->header.eflags = MAP_ENTRY_HEADER;
891         map->needs_wakeup = FALSE;
892         map->system_map = 0;
893         map->pmap = pmap;
894         map->header.end = min;
895         map->header.start = max;
896         map->flags = 0;
897         map->root = NULL;
898         map->timestamp = 0;
899         map->busy = 0;
900         map->anon_loc = 0;
901 }
902
903 void
904 vm_map_init(vm_map_t map, pmap_t pmap, vm_offset_t min, vm_offset_t max)
905 {
906
907         _vm_map_init(map, pmap, min, max);
908         mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
909         sx_init(&map->lock, "user map");
910 }
911
912 /*
913  *      vm_map_entry_dispose:   [ internal use only ]
914  *
915  *      Inverse of vm_map_entry_create.
916  */
917 static void
918 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
919 {
920         uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
921 }
922
923 /*
924  *      vm_map_entry_create:    [ internal use only ]
925  *
926  *      Allocates a VM map entry for insertion.
927  *      No entry fields are filled in.
928  */
929 static vm_map_entry_t
930 vm_map_entry_create(vm_map_t map)
931 {
932         vm_map_entry_t new_entry;
933
934         if (map->system_map)
935                 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
936         else
937                 new_entry = uma_zalloc(mapentzone, M_WAITOK);
938         if (new_entry == NULL)
939                 panic("vm_map_entry_create: kernel resources exhausted");
940         return (new_entry);
941 }
942
943 /*
944  *      vm_map_entry_set_behavior:
945  *
946  *      Set the expected access behavior, either normal, random, or
947  *      sequential.
948  */
949 static inline void
950 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
951 {
952         entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
953             (behavior & MAP_ENTRY_BEHAV_MASK);
954 }
955
956 /*
957  *      vm_map_entry_set_max_free:
958  *
959  *      Set the max_free field in a vm_map_entry.
960  */
961 static inline void
962 vm_map_entry_set_max_free(vm_map_entry_t entry)
963 {
964         vm_map_entry_t child;
965         vm_size_t max_left, max_right;
966
967         child = entry->left;
968         max_left = (child != NULL) ? child->max_free :
969             entry->start - entry->prev->end;
970         child = entry->right;
971         max_right = (child != NULL) ? child->max_free :
972             entry->next->start - entry->end;
973         entry->max_free = MAX(max_left, max_right);
974 }
975
976 #define SPLAY_LEFT_STEP(root, y, rlist, test) do {      \
977         y = root->left;                                 \
978         if (y != NULL && (test)) {                      \
979                 /* Rotate right and make y root. */     \
980                 root->left = y->right;                  \
981                 y->right = root;                        \
982                 vm_map_entry_set_max_free(root);        \
983                 root = y;                               \
984                 y = root->left;                         \
985         }                                               \
986         /* Put root on rlist. */                        \
987         root->left = rlist;                             \
988         rlist = root;                                   \
989         root = y;                                       \
990 } while (0)
991
992 #define SPLAY_RIGHT_STEP(root, y, llist, test) do {     \
993         y = root->right;                                \
994         if (y != NULL && (test)) {                      \
995                 /* Rotate left and make y root. */      \
996                 root->right = y->left;                  \
997                 y->left = root;                         \
998                 vm_map_entry_set_max_free(root);        \
999                 root = y;                               \
1000                 y = root->right;                        \
1001         }                                               \
1002         /* Put root on llist. */                        \
1003         root->right = llist;                            \
1004         llist = root;                                   \
1005         root = y;                                       \
1006 } while (0)
1007
1008 /*
1009  * Walk down the tree until we find addr or a NULL pointer where addr would go,
1010  * breaking off left and right subtrees of nodes less than, or greater than
1011  * addr.  Treat pointers to nodes with max_free < length as NULL pointers.
1012  * llist and rlist are the two sides in reverse order (bottom-up), with llist
1013  * linked by the right pointer and rlist linked by the left pointer in the
1014  * vm_map_entry.
1015  */
1016 static vm_map_entry_t
1017 vm_map_splay_split(vm_offset_t addr, vm_size_t length,
1018     vm_map_entry_t root, vm_map_entry_t *out_llist, vm_map_entry_t *out_rlist)
1019 {
1020         vm_map_entry_t llist, rlist;
1021         vm_map_entry_t y;
1022
1023         llist = NULL;
1024         rlist = NULL;
1025         while (root != NULL && root->max_free >= length) {
1026                 if (addr < root->start) {
1027                         SPLAY_LEFT_STEP(root, y, rlist,
1028                             y->max_free >= length && addr < y->start);
1029                 } else if (addr >= root->end) {
1030                         SPLAY_RIGHT_STEP(root, y, llist,
1031                             y->max_free >= length && addr >= y->end);
1032                 } else
1033                         break;
1034         }
1035         *out_llist = llist;
1036         *out_rlist = rlist;
1037         return (root);
1038 }
1039
1040 static void
1041 vm_map_splay_findnext(vm_map_entry_t root, vm_map_entry_t *iolist)
1042 {
1043         vm_map_entry_t rlist, y;
1044
1045         root = root->right;
1046         rlist = *iolist;
1047         while (root != NULL)
1048                 SPLAY_LEFT_STEP(root, y, rlist, true);
1049         *iolist = rlist;
1050 }
1051
1052 static void
1053 vm_map_splay_findprev(vm_map_entry_t root, vm_map_entry_t *iolist)
1054 {
1055         vm_map_entry_t llist, y;
1056
1057         root = root->left;
1058         llist = *iolist;
1059         while (root != NULL)
1060                 SPLAY_RIGHT_STEP(root, y, llist, true);
1061         *iolist = llist;
1062 }
1063
1064 /*
1065  * Walk back up the two spines, flip the pointers and set max_free.  The
1066  * subtrees of the root go at the bottom of llist and rlist.
1067  */
1068 static vm_map_entry_t
1069 vm_map_splay_merge(vm_map_entry_t root,
1070     vm_map_entry_t llist, vm_map_entry_t rlist,
1071     vm_map_entry_t ltree, vm_map_entry_t rtree)
1072 {
1073         vm_map_entry_t y;
1074
1075         while (llist != NULL) {
1076                 y = llist->right;
1077                 llist->right = ltree;
1078                 vm_map_entry_set_max_free(llist);
1079                 ltree = llist;
1080                 llist = y;
1081         }
1082         while (rlist != NULL) {
1083                 y = rlist->left;
1084                 rlist->left = rtree;
1085                 vm_map_entry_set_max_free(rlist);
1086                 rtree = rlist;
1087                 rlist = y;
1088         }
1089
1090         /*
1091          * Final assembly: add ltree and rtree as subtrees of root.
1092          */
1093         root->left = ltree;
1094         root->right = rtree;
1095         vm_map_entry_set_max_free(root);
1096
1097         return (root);
1098 }
1099
1100 /*
1101  *      vm_map_entry_splay:
1102  *
1103  *      The Sleator and Tarjan top-down splay algorithm with the
1104  *      following variation.  Max_free must be computed bottom-up, so
1105  *      on the downward pass, maintain the left and right spines in
1106  *      reverse order.  Then, make a second pass up each side to fix
1107  *      the pointers and compute max_free.  The time bound is O(log n)
1108  *      amortized.
1109  *
1110  *      The new root is the vm_map_entry containing "addr", or else an
1111  *      adjacent entry (lower if possible) if addr is not in the tree.
1112  *
1113  *      The map must be locked, and leaves it so.
1114  *
1115  *      Returns: the new root.
1116  */
1117 static vm_map_entry_t
1118 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
1119 {
1120         vm_map_entry_t llist, rlist;
1121
1122         root = vm_map_splay_split(addr, 0, root, &llist, &rlist);
1123         if (root != NULL) {
1124                 /* do nothing */
1125         } else if (llist != NULL) {
1126                 /*
1127                  * Recover the greatest node in the left
1128                  * subtree and make it the root.
1129                  */
1130                 root = llist;
1131                 llist = root->right;
1132                 root->right = NULL;
1133         } else if (rlist != NULL) {
1134                 /*
1135                  * Recover the least node in the right
1136                  * subtree and make it the root.
1137                  */
1138                 root = rlist;
1139                 rlist = root->left;
1140                 root->left = NULL;
1141         } else {
1142                 /* There is no root. */
1143                 return (NULL);
1144         }
1145         return (vm_map_splay_merge(root, llist, rlist,
1146             root->left, root->right));
1147 }
1148
1149 /*
1150  *      vm_map_entry_{un,}link:
1151  *
1152  *      Insert/remove entries from maps.
1153  */
1154 static void
1155 vm_map_entry_link(vm_map_t map,
1156                   vm_map_entry_t entry)
1157 {
1158         vm_map_entry_t llist, rlist, root;
1159
1160         CTR3(KTR_VM,
1161             "vm_map_entry_link: map %p, nentries %d, entry %p", map,
1162             map->nentries, entry);
1163         VM_MAP_ASSERT_LOCKED(map);
1164         map->nentries++;
1165         root = map->root;
1166         root = vm_map_splay_split(entry->start, 0, root, &llist, &rlist);
1167         KASSERT(root == NULL,
1168             ("vm_map_entry_link: link object already mapped"));
1169         entry->prev = (llist == NULL) ? &map->header : llist;
1170         entry->next = (rlist == NULL) ? &map->header : rlist;
1171         entry->prev->next = entry->next->prev = entry;
1172         root = vm_map_splay_merge(entry, llist, rlist, NULL, NULL);
1173         map->root = entry;
1174         VM_MAP_ASSERT_CONSISTENT(map);
1175 }
1176
1177 enum unlink_merge_type {
1178         UNLINK_MERGE_PREV,
1179         UNLINK_MERGE_NONE,
1180         UNLINK_MERGE_NEXT
1181 };
1182
1183 static void
1184 vm_map_entry_unlink(vm_map_t map,
1185                     vm_map_entry_t entry,
1186                     enum unlink_merge_type op)
1187 {
1188         vm_map_entry_t llist, rlist, root, y;
1189
1190         VM_MAP_ASSERT_LOCKED(map);
1191         llist = entry->prev;
1192         rlist = entry->next;
1193         llist->next = rlist;
1194         rlist->prev = llist;
1195         root = map->root;
1196         root = vm_map_splay_split(entry->start, 0, root, &llist, &rlist);
1197         KASSERT(root != NULL,
1198             ("vm_map_entry_unlink: unlink object not mapped"));
1199
1200         switch (op) {
1201         case UNLINK_MERGE_PREV:
1202                 vm_map_splay_findprev(root, &llist);
1203                 llist->end = root->end;
1204                 y = root->right;
1205                 root = llist;
1206                 llist = root->right;
1207                 root->right = y;
1208                 break;
1209         case UNLINK_MERGE_NEXT:
1210                 vm_map_splay_findnext(root, &rlist);
1211                 rlist->start = root->start;
1212                 rlist->offset = root->offset;
1213                 y = root->left;
1214                 root = rlist;
1215                 rlist = root->left;
1216                 root->left = y;
1217                 break;
1218         case UNLINK_MERGE_NONE:
1219                 vm_map_splay_findprev(root, &llist);
1220                 vm_map_splay_findnext(root, &rlist);
1221                 if (llist != NULL) {
1222                         root = llist;
1223                         llist = root->right;
1224                         root->right = NULL;
1225                 } else if (rlist != NULL) {
1226                         root = rlist;
1227                         rlist = root->left;
1228                         root->left = NULL;
1229                 } else
1230                         root = NULL;
1231                 break;
1232         }
1233         if (root != NULL)
1234                 root = vm_map_splay_merge(root, llist, rlist,
1235                     root->left, root->right);
1236         map->root = root;
1237         VM_MAP_ASSERT_CONSISTENT(map);
1238         map->nentries--;
1239         CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1240             map->nentries, entry);
1241 }
1242
1243 /*
1244  *      vm_map_entry_resize_free:
1245  *
1246  *      Recompute the amount of free space following a modified vm_map_entry
1247  *      and propagate those values up the tree.  Call this function after
1248  *      resizing a map entry in-place by changing the end value, without a
1249  *      call to vm_map_entry_link() or _unlink().
1250  *
1251  *      The map must be locked, and leaves it so.
1252  */
1253 static void
1254 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
1255 {
1256         vm_map_entry_t llist, rlist, root;
1257
1258         VM_MAP_ASSERT_LOCKED(map);
1259         root = map->root;
1260         root = vm_map_splay_split(entry->start, 0, root, &llist, &rlist);
1261         KASSERT(root != NULL,
1262             ("vm_map_entry_resize_free: resize_free object not mapped"));
1263         vm_map_splay_findnext(root, &rlist);
1264         root->right = NULL;
1265         map->root = vm_map_splay_merge(root, llist, rlist,
1266             root->left, root->right);
1267         VM_MAP_ASSERT_CONSISTENT(map);
1268         CTR3(KTR_VM, "vm_map_entry_resize_free: map %p, nentries %d, entry %p", map,
1269             map->nentries, entry);
1270 }
1271
1272 /*
1273  *      vm_map_lookup_entry:    [ internal use only ]
1274  *
1275  *      Finds the map entry containing (or
1276  *      immediately preceding) the specified address
1277  *      in the given map; the entry is returned
1278  *      in the "entry" parameter.  The boolean
1279  *      result indicates whether the address is
1280  *      actually contained in the map.
1281  */
1282 boolean_t
1283 vm_map_lookup_entry(
1284         vm_map_t map,
1285         vm_offset_t address,
1286         vm_map_entry_t *entry)  /* OUT */
1287 {
1288         vm_map_entry_t cur, lbound;
1289         boolean_t locked;
1290
1291         /*
1292          * If the map is empty, then the map entry immediately preceding
1293          * "address" is the map's header.
1294          */
1295         cur = map->root;
1296         if (cur == NULL) {
1297                 *entry = &map->header;
1298                 return (FALSE);
1299         }
1300         if (address >= cur->start && cur->end > address) {
1301                 *entry = cur;
1302                 return (TRUE);
1303         }
1304         if ((locked = vm_map_locked(map)) ||
1305             sx_try_upgrade(&map->lock)) {
1306                 /*
1307                  * Splay requires a write lock on the map.  However, it only
1308                  * restructures the binary search tree; it does not otherwise
1309                  * change the map.  Thus, the map's timestamp need not change
1310                  * on a temporary upgrade.
1311                  */
1312                 map->root = cur = vm_map_entry_splay(address, cur);
1313                 VM_MAP_ASSERT_CONSISTENT(map);
1314                 if (!locked)
1315                         sx_downgrade(&map->lock);
1316
1317                 /*
1318                  * If "address" is contained within a map entry, the new root
1319                  * is that map entry.  Otherwise, the new root is a map entry
1320                  * immediately before or after "address".
1321                  */
1322                 if (address < cur->start) {
1323                         *entry = &map->header;
1324                         return (FALSE);
1325                 }
1326                 *entry = cur;
1327                 return (address < cur->end);
1328         }
1329         /*
1330          * Since the map is only locked for read access, perform a
1331          * standard binary search tree lookup for "address".
1332          */
1333         lbound = &map->header;
1334         do {
1335                 if (address < cur->start) {
1336                         cur = cur->left;
1337                 } else if (cur->end <= address) {
1338                         lbound = cur;
1339                         cur = cur->right;
1340                 } else {
1341                         *entry = cur;
1342                         return (TRUE);
1343                 }
1344         } while (cur != NULL);
1345         *entry = lbound;
1346         return (FALSE);
1347 }
1348
1349 /*
1350  *      vm_map_insert:
1351  *
1352  *      Inserts the given whole VM object into the target
1353  *      map at the specified address range.  The object's
1354  *      size should match that of the address range.
1355  *
1356  *      Requires that the map be locked, and leaves it so.
1357  *
1358  *      If object is non-NULL, ref count must be bumped by caller
1359  *      prior to making call to account for the new entry.
1360  */
1361 int
1362 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1363     vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max, int cow)
1364 {
1365         vm_map_entry_t new_entry, prev_entry, temp_entry;
1366         struct ucred *cred;
1367         vm_eflags_t protoeflags;
1368         vm_inherit_t inheritance;
1369
1370         VM_MAP_ASSERT_LOCKED(map);
1371         KASSERT(object != kernel_object ||
1372             (cow & MAP_COPY_ON_WRITE) == 0,
1373             ("vm_map_insert: kernel object and COW"));
1374         KASSERT(object == NULL || (cow & MAP_NOFAULT) == 0,
1375             ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1376         KASSERT((prot & ~max) == 0,
1377             ("prot %#x is not subset of max_prot %#x", prot, max));
1378
1379         /*
1380          * Check that the start and end points are not bogus.
1381          */
1382         if (start < vm_map_min(map) || end > vm_map_max(map) ||
1383             start >= end)
1384                 return (KERN_INVALID_ADDRESS);
1385
1386         /*
1387          * Find the entry prior to the proposed starting address; if it's part
1388          * of an existing entry, this range is bogus.
1389          */
1390         if (vm_map_lookup_entry(map, start, &temp_entry))
1391                 return (KERN_NO_SPACE);
1392
1393         prev_entry = temp_entry;
1394
1395         /*
1396          * Assert that the next entry doesn't overlap the end point.
1397          */
1398         if (prev_entry->next->start < end)
1399                 return (KERN_NO_SPACE);
1400
1401         if ((cow & MAP_CREATE_GUARD) != 0 && (object != NULL ||
1402             max != VM_PROT_NONE))
1403                 return (KERN_INVALID_ARGUMENT);
1404
1405         protoeflags = 0;
1406         if (cow & MAP_COPY_ON_WRITE)
1407                 protoeflags |= MAP_ENTRY_COW | MAP_ENTRY_NEEDS_COPY;
1408         if (cow & MAP_NOFAULT)
1409                 protoeflags |= MAP_ENTRY_NOFAULT;
1410         if (cow & MAP_DISABLE_SYNCER)
1411                 protoeflags |= MAP_ENTRY_NOSYNC;
1412         if (cow & MAP_DISABLE_COREDUMP)
1413                 protoeflags |= MAP_ENTRY_NOCOREDUMP;
1414         if (cow & MAP_STACK_GROWS_DOWN)
1415                 protoeflags |= MAP_ENTRY_GROWS_DOWN;
1416         if (cow & MAP_STACK_GROWS_UP)
1417                 protoeflags |= MAP_ENTRY_GROWS_UP;
1418         if (cow & MAP_VN_WRITECOUNT)
1419                 protoeflags |= MAP_ENTRY_VN_WRITECNT;
1420         if (cow & MAP_VN_EXEC)
1421                 protoeflags |= MAP_ENTRY_VN_EXEC;
1422         if ((cow & MAP_CREATE_GUARD) != 0)
1423                 protoeflags |= MAP_ENTRY_GUARD;
1424         if ((cow & MAP_CREATE_STACK_GAP_DN) != 0)
1425                 protoeflags |= MAP_ENTRY_STACK_GAP_DN;
1426         if ((cow & MAP_CREATE_STACK_GAP_UP) != 0)
1427                 protoeflags |= MAP_ENTRY_STACK_GAP_UP;
1428         if (cow & MAP_INHERIT_SHARE)
1429                 inheritance = VM_INHERIT_SHARE;
1430         else
1431                 inheritance = VM_INHERIT_DEFAULT;
1432
1433         cred = NULL;
1434         if ((cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT | MAP_CREATE_GUARD)) != 0)
1435                 goto charged;
1436         if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1437             ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1438                 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1439                         return (KERN_RESOURCE_SHORTAGE);
1440                 KASSERT(object == NULL ||
1441                     (protoeflags & MAP_ENTRY_NEEDS_COPY) != 0 ||
1442                     object->cred == NULL,
1443                     ("overcommit: vm_map_insert o %p", object));
1444                 cred = curthread->td_ucred;
1445         }
1446
1447 charged:
1448         /* Expand the kernel pmap, if necessary. */
1449         if (map == kernel_map && end > kernel_vm_end)
1450                 pmap_growkernel(end);
1451         if (object != NULL) {
1452                 /*
1453                  * OBJ_ONEMAPPING must be cleared unless this mapping
1454                  * is trivially proven to be the only mapping for any
1455                  * of the object's pages.  (Object granularity
1456                  * reference counting is insufficient to recognize
1457                  * aliases with precision.)
1458                  */
1459                 VM_OBJECT_WLOCK(object);
1460                 if (object->ref_count > 1 || object->shadow_count != 0)
1461                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
1462                 VM_OBJECT_WUNLOCK(object);
1463         } else if ((prev_entry->eflags & ~MAP_ENTRY_USER_WIRED) ==
1464             protoeflags &&
1465             (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP |
1466             MAP_VN_EXEC)) == 0 &&
1467             prev_entry->end == start && (prev_entry->cred == cred ||
1468             (prev_entry->object.vm_object != NULL &&
1469             prev_entry->object.vm_object->cred == cred)) &&
1470             vm_object_coalesce(prev_entry->object.vm_object,
1471             prev_entry->offset,
1472             (vm_size_t)(prev_entry->end - prev_entry->start),
1473             (vm_size_t)(end - prev_entry->end), cred != NULL &&
1474             (protoeflags & MAP_ENTRY_NEEDS_COPY) == 0)) {
1475                 /*
1476                  * We were able to extend the object.  Determine if we
1477                  * can extend the previous map entry to include the
1478                  * new range as well.
1479                  */
1480                 if (prev_entry->inheritance == inheritance &&
1481                     prev_entry->protection == prot &&
1482                     prev_entry->max_protection == max &&
1483                     prev_entry->wired_count == 0) {
1484                         KASSERT((prev_entry->eflags & MAP_ENTRY_USER_WIRED) ==
1485                             0, ("prev_entry %p has incoherent wiring",
1486                             prev_entry));
1487                         if ((prev_entry->eflags & MAP_ENTRY_GUARD) == 0)
1488                                 map->size += end - prev_entry->end;
1489                         prev_entry->end = end;
1490                         vm_map_entry_resize_free(map, prev_entry);
1491                         vm_map_simplify_entry(map, prev_entry);
1492                         return (KERN_SUCCESS);
1493                 }
1494
1495                 /*
1496                  * If we can extend the object but cannot extend the
1497                  * map entry, we have to create a new map entry.  We
1498                  * must bump the ref count on the extended object to
1499                  * account for it.  object may be NULL.
1500                  */
1501                 object = prev_entry->object.vm_object;
1502                 offset = prev_entry->offset +
1503                     (prev_entry->end - prev_entry->start);
1504                 vm_object_reference(object);
1505                 if (cred != NULL && object != NULL && object->cred != NULL &&
1506                     !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1507                         /* Object already accounts for this uid. */
1508                         cred = NULL;
1509                 }
1510         }
1511         if (cred != NULL)
1512                 crhold(cred);
1513
1514         /*
1515          * Create a new entry
1516          */
1517         new_entry = vm_map_entry_create(map);
1518         new_entry->start = start;
1519         new_entry->end = end;
1520         new_entry->cred = NULL;
1521
1522         new_entry->eflags = protoeflags;
1523         new_entry->object.vm_object = object;
1524         new_entry->offset = offset;
1525
1526         new_entry->inheritance = inheritance;
1527         new_entry->protection = prot;
1528         new_entry->max_protection = max;
1529         new_entry->wired_count = 0;
1530         new_entry->wiring_thread = NULL;
1531         new_entry->read_ahead = VM_FAULT_READ_AHEAD_INIT;
1532         new_entry->next_read = start;
1533
1534         KASSERT(cred == NULL || !ENTRY_CHARGED(new_entry),
1535             ("overcommit: vm_map_insert leaks vm_map %p", new_entry));
1536         new_entry->cred = cred;
1537
1538         /*
1539          * Insert the new entry into the list
1540          */
1541         vm_map_entry_link(map, new_entry);
1542         if ((new_entry->eflags & MAP_ENTRY_GUARD) == 0)
1543                 map->size += new_entry->end - new_entry->start;
1544
1545         /*
1546          * Try to coalesce the new entry with both the previous and next
1547          * entries in the list.  Previously, we only attempted to coalesce
1548          * with the previous entry when object is NULL.  Here, we handle the
1549          * other cases, which are less common.
1550          */
1551         vm_map_simplify_entry(map, new_entry);
1552
1553         if ((cow & (MAP_PREFAULT | MAP_PREFAULT_PARTIAL)) != 0) {
1554                 vm_map_pmap_enter(map, start, prot, object, OFF_TO_IDX(offset),
1555                     end - start, cow & MAP_PREFAULT_PARTIAL);
1556         }
1557
1558         return (KERN_SUCCESS);
1559 }
1560
1561 /*
1562  *      vm_map_findspace:
1563  *
1564  *      Find the first fit (lowest VM address) for "length" free bytes
1565  *      beginning at address >= start in the given map.
1566  *
1567  *      In a vm_map_entry, "max_free" is the maximum amount of
1568  *      contiguous free space between an entry in its subtree and a
1569  *      neighbor of that entry.  This allows finding a free region in
1570  *      one path down the tree, so O(log n) amortized with splay
1571  *      trees.
1572  *
1573  *      The map must be locked, and leaves it so.
1574  *
1575  *      Returns: starting address if sufficient space,
1576  *               vm_map_max(map)-length+1 if insufficient space.
1577  */
1578 vm_offset_t
1579 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length)
1580 {
1581         vm_map_entry_t llist, rlist, root, y;
1582         vm_size_t left_length;
1583
1584         /*
1585          * Request must fit within min/max VM address and must avoid
1586          * address wrap.
1587          */
1588         start = MAX(start, vm_map_min(map));
1589         if (start + length > vm_map_max(map) || start + length < start)
1590                 return (vm_map_max(map) - length + 1);
1591
1592         /* Empty tree means wide open address space. */
1593         if (map->root == NULL)
1594                 return (start);
1595
1596         /*
1597          * After splay, if start comes before root node, then there
1598          * must be a gap from start to the root.
1599          */
1600         root = vm_map_splay_split(start, length, map->root,
1601             &llist, &rlist);
1602         if (root != NULL)
1603                 start = root->end;
1604         else if (rlist != NULL) {
1605                 root = rlist;
1606                 rlist = root->left;
1607                 root->left = NULL;
1608         } else {
1609                 root = llist;
1610                 llist = root->right;
1611                 root->right = NULL;
1612         }
1613         map->root = vm_map_splay_merge(root, llist, rlist,
1614             root->left, root->right);
1615         VM_MAP_ASSERT_CONSISTENT(map);
1616         if (start + length <= root->start)
1617                 return (start);
1618
1619         /*
1620          * Root is the last node that might begin its gap before
1621          * start, and this is the last comparison where address
1622          * wrap might be a problem.
1623          */
1624         if (root->right == NULL &&
1625             start + length <= vm_map_max(map))
1626                 return (start);
1627
1628         /* With max_free, can immediately tell if no solution. */
1629         if (root->right == NULL || length > root->right->max_free)
1630                 return (vm_map_max(map) - length + 1);
1631
1632         /*
1633          * Splay for the least large-enough gap in the right subtree.
1634          */
1635         llist = NULL;
1636         rlist = NULL;
1637         for (left_length = 0; ;
1638              left_length = root->left != NULL ?
1639              root->left->max_free : root->start - llist->end) {
1640                 if (length <= left_length)
1641                         SPLAY_LEFT_STEP(root, y, rlist,
1642                             length <= (y->left != NULL ?
1643                             y->left->max_free : y->start - llist->end));
1644                 else
1645                         SPLAY_RIGHT_STEP(root, y, llist,
1646                             length > (y->left != NULL ?
1647                             y->left->max_free : y->start - root->end));
1648                 if (root == NULL)
1649                         break;
1650         }
1651         root = llist;
1652         llist = root->right;
1653         if ((y = rlist) == NULL)
1654                 root->right = NULL;
1655         else {
1656                 rlist = y->left;
1657                 y->left = NULL;
1658                 root->right = y->right;
1659         }
1660         root = vm_map_splay_merge(root, llist, rlist,
1661             root->left, root->right);
1662         if (y != NULL) {
1663                 y->right = root->right;
1664                 vm_map_entry_set_max_free(y);
1665                 root->right = y;
1666                 vm_map_entry_set_max_free(root);
1667         }
1668         map->root = root;
1669         VM_MAP_ASSERT_CONSISTENT(map);
1670         return (root->end);
1671 }
1672
1673 int
1674 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1675     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1676     vm_prot_t max, int cow)
1677 {
1678         vm_offset_t end;
1679         int result;
1680
1681         end = start + length;
1682         KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1683             object == NULL,
1684             ("vm_map_fixed: non-NULL backing object for stack"));
1685         vm_map_lock(map);
1686         VM_MAP_RANGE_CHECK(map, start, end);
1687         if ((cow & MAP_CHECK_EXCL) == 0)
1688                 vm_map_delete(map, start, end);
1689         if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1690                 result = vm_map_stack_locked(map, start, length, sgrowsiz,
1691                     prot, max, cow);
1692         } else {
1693                 result = vm_map_insert(map, object, offset, start, end,
1694                     prot, max, cow);
1695         }
1696         vm_map_unlock(map);
1697         return (result);
1698 }
1699
1700 static const int aslr_pages_rnd_64[2] = {0x1000, 0x10};
1701 static const int aslr_pages_rnd_32[2] = {0x100, 0x4};
1702
1703 static int cluster_anon = 1;
1704 SYSCTL_INT(_vm, OID_AUTO, cluster_anon, CTLFLAG_RW,
1705     &cluster_anon, 0,
1706     "Cluster anonymous mappings: 0 = no, 1 = yes if no hint, 2 = always");
1707
1708 static bool
1709 clustering_anon_allowed(vm_offset_t addr)
1710 {
1711
1712         switch (cluster_anon) {
1713         case 0:
1714                 return (false);
1715         case 1:
1716                 return (addr == 0);
1717         case 2:
1718         default:
1719                 return (true);
1720         }
1721 }
1722
1723 static long aslr_restarts;
1724 SYSCTL_LONG(_vm, OID_AUTO, aslr_restarts, CTLFLAG_RD,
1725     &aslr_restarts, 0,
1726     "Number of aslr failures");
1727
1728 #define MAP_32BIT_MAX_ADDR      ((vm_offset_t)1 << 31)
1729
1730 /*
1731  * Searches for the specified amount of free space in the given map with the
1732  * specified alignment.  Performs an address-ordered, first-fit search from
1733  * the given address "*addr", with an optional upper bound "max_addr".  If the
1734  * parameter "alignment" is zero, then the alignment is computed from the
1735  * given (object, offset) pair so as to enable the greatest possible use of
1736  * superpage mappings.  Returns KERN_SUCCESS and the address of the free space
1737  * in "*addr" if successful.  Otherwise, returns KERN_NO_SPACE.
1738  *
1739  * The map must be locked.  Initially, there must be at least "length" bytes
1740  * of free space at the given address.
1741  */
1742 static int
1743 vm_map_alignspace(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1744     vm_offset_t *addr, vm_size_t length, vm_offset_t max_addr,
1745     vm_offset_t alignment)
1746 {
1747         vm_offset_t aligned_addr, free_addr;
1748
1749         VM_MAP_ASSERT_LOCKED(map);
1750         free_addr = *addr;
1751         KASSERT(free_addr == vm_map_findspace(map, free_addr, length),
1752             ("caller failed to provide space %d at address %p",
1753              (int)length, (void*)free_addr));
1754         for (;;) {
1755                 /*
1756                  * At the start of every iteration, the free space at address
1757                  * "*addr" is at least "length" bytes.
1758                  */
1759                 if (alignment == 0)
1760                         pmap_align_superpage(object, offset, addr, length);
1761                 else if ((*addr & (alignment - 1)) != 0) {
1762                         *addr &= ~(alignment - 1);
1763                         *addr += alignment;
1764                 }
1765                 aligned_addr = *addr;
1766                 if (aligned_addr == free_addr) {
1767                         /*
1768                          * Alignment did not change "*addr", so "*addr" must
1769                          * still provide sufficient free space.
1770                          */
1771                         return (KERN_SUCCESS);
1772                 }
1773
1774                 /*
1775                  * Test for address wrap on "*addr".  A wrapped "*addr" could
1776                  * be a valid address, in which case vm_map_findspace() cannot
1777                  * be relied upon to fail.
1778                  */
1779                 if (aligned_addr < free_addr)
1780                         return (KERN_NO_SPACE);
1781                 *addr = vm_map_findspace(map, aligned_addr, length);
1782                 if (*addr + length > vm_map_max(map) ||
1783                     (max_addr != 0 && *addr + length > max_addr))
1784                         return (KERN_NO_SPACE);
1785                 free_addr = *addr;
1786                 if (free_addr == aligned_addr) {
1787                         /*
1788                          * If a successful call to vm_map_findspace() did not
1789                          * change "*addr", then "*addr" must still be aligned
1790                          * and provide sufficient free space.
1791                          */
1792                         return (KERN_SUCCESS);
1793                 }
1794         }
1795 }
1796
1797 /*
1798  *      vm_map_find finds an unallocated region in the target address
1799  *      map with the given length.  The search is defined to be
1800  *      first-fit from the specified address; the region found is
1801  *      returned in the same parameter.
1802  *
1803  *      If object is non-NULL, ref count must be bumped by caller
1804  *      prior to making call to account for the new entry.
1805  */
1806 int
1807 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1808             vm_offset_t *addr,  /* IN/OUT */
1809             vm_size_t length, vm_offset_t max_addr, int find_space,
1810             vm_prot_t prot, vm_prot_t max, int cow)
1811 {
1812         vm_offset_t alignment, curr_min_addr, min_addr;
1813         int gap, pidx, rv, try;
1814         bool cluster, en_aslr, update_anon;
1815
1816         KASSERT((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0 ||
1817             object == NULL,
1818             ("vm_map_find: non-NULL backing object for stack"));
1819         MPASS((cow & MAP_REMAP) == 0 || (find_space == VMFS_NO_SPACE &&
1820             (cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) == 0));
1821         if (find_space == VMFS_OPTIMAL_SPACE && (object == NULL ||
1822             (object->flags & OBJ_COLORED) == 0))
1823                 find_space = VMFS_ANY_SPACE;
1824         if (find_space >> 8 != 0) {
1825                 KASSERT((find_space & 0xff) == 0, ("bad VMFS flags"));
1826                 alignment = (vm_offset_t)1 << (find_space >> 8);
1827         } else
1828                 alignment = 0;
1829         en_aslr = (map->flags & MAP_ASLR) != 0;
1830         update_anon = cluster = clustering_anon_allowed(*addr) &&
1831             (map->flags & MAP_IS_SUB_MAP) == 0 && max_addr == 0 &&
1832             find_space != VMFS_NO_SPACE && object == NULL &&
1833             (cow & (MAP_INHERIT_SHARE | MAP_STACK_GROWS_UP |
1834             MAP_STACK_GROWS_DOWN)) == 0 && prot != PROT_NONE;
1835         curr_min_addr = min_addr = *addr;
1836         if (en_aslr && min_addr == 0 && !cluster &&
1837             find_space != VMFS_NO_SPACE &&
1838             (map->flags & MAP_ASLR_IGNSTART) != 0)
1839                 curr_min_addr = min_addr = vm_map_min(map);
1840         try = 0;
1841         vm_map_lock(map);
1842         if (cluster) {
1843                 curr_min_addr = map->anon_loc;
1844                 if (curr_min_addr == 0)
1845                         cluster = false;
1846         }
1847         if (find_space != VMFS_NO_SPACE) {
1848                 KASSERT(find_space == VMFS_ANY_SPACE ||
1849                     find_space == VMFS_OPTIMAL_SPACE ||
1850                     find_space == VMFS_SUPER_SPACE ||
1851                     alignment != 0, ("unexpected VMFS flag"));
1852 again:
1853                 /*
1854                  * When creating an anonymous mapping, try clustering
1855                  * with an existing anonymous mapping first.
1856                  *
1857                  * We make up to two attempts to find address space
1858                  * for a given find_space value. The first attempt may
1859                  * apply randomization or may cluster with an existing
1860                  * anonymous mapping. If this first attempt fails,
1861                  * perform a first-fit search of the available address
1862                  * space.
1863                  *
1864                  * If all tries failed, and find_space is
1865                  * VMFS_OPTIMAL_SPACE, fallback to VMFS_ANY_SPACE.
1866                  * Again enable clustering and randomization.
1867                  */
1868                 try++;
1869                 MPASS(try <= 2);
1870
1871                 if (try == 2) {
1872                         /*
1873                          * Second try: we failed either to find a
1874                          * suitable region for randomizing the
1875                          * allocation, or to cluster with an existing
1876                          * mapping.  Retry with free run.
1877                          */
1878                         curr_min_addr = (map->flags & MAP_ASLR_IGNSTART) != 0 ?
1879                             vm_map_min(map) : min_addr;
1880                         atomic_add_long(&aslr_restarts, 1);
1881                 }
1882
1883                 if (try == 1 && en_aslr && !cluster) {
1884                         /*
1885                          * Find space for allocation, including
1886                          * gap needed for later randomization.
1887                          */
1888                         pidx = MAXPAGESIZES > 1 && pagesizes[1] != 0 &&
1889                             (find_space == VMFS_SUPER_SPACE || find_space ==
1890                             VMFS_OPTIMAL_SPACE) ? 1 : 0;
1891                         gap = vm_map_max(map) > MAP_32BIT_MAX_ADDR &&
1892                             (max_addr == 0 || max_addr > MAP_32BIT_MAX_ADDR) ?
1893                             aslr_pages_rnd_64[pidx] : aslr_pages_rnd_32[pidx];
1894                         *addr = vm_map_findspace(map, curr_min_addr,
1895                             length + gap * pagesizes[pidx]);
1896                         if (*addr + length + gap * pagesizes[pidx] >
1897                             vm_map_max(map))
1898                                 goto again;
1899                         /* And randomize the start address. */
1900                         *addr += (arc4random() % gap) * pagesizes[pidx];
1901                         if (max_addr != 0 && *addr + length > max_addr)
1902                                 goto again;
1903                 } else {
1904                         *addr = vm_map_findspace(map, curr_min_addr, length);
1905                         if (*addr + length > vm_map_max(map) ||
1906                             (max_addr != 0 && *addr + length > max_addr)) {
1907                                 if (cluster) {
1908                                         cluster = false;
1909                                         MPASS(try == 1);
1910                                         goto again;
1911                                 }
1912                                 rv = KERN_NO_SPACE;
1913                                 goto done;
1914                         }
1915                 }
1916
1917                 if (find_space != VMFS_ANY_SPACE &&
1918                     (rv = vm_map_alignspace(map, object, offset, addr, length,
1919                     max_addr, alignment)) != KERN_SUCCESS) {
1920                         if (find_space == VMFS_OPTIMAL_SPACE) {
1921                                 find_space = VMFS_ANY_SPACE;
1922                                 curr_min_addr = min_addr;
1923                                 cluster = update_anon;
1924                                 try = 0;
1925                                 goto again;
1926                         }
1927                         goto done;
1928                 }
1929         } else if ((cow & MAP_REMAP) != 0) {
1930                 if (*addr < vm_map_min(map) ||
1931                     *addr + length > vm_map_max(map) ||
1932                     *addr + length <= length) {
1933                         rv = KERN_INVALID_ADDRESS;
1934                         goto done;
1935                 }
1936                 vm_map_delete(map, *addr, *addr + length);
1937         }
1938         if ((cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP)) != 0) {
1939                 rv = vm_map_stack_locked(map, *addr, length, sgrowsiz, prot,
1940                     max, cow);
1941         } else {
1942                 rv = vm_map_insert(map, object, offset, *addr, *addr + length,
1943                     prot, max, cow);
1944         }
1945         if (rv == KERN_SUCCESS && update_anon)
1946                 map->anon_loc = *addr + length;
1947 done:
1948         vm_map_unlock(map);
1949         return (rv);
1950 }
1951
1952 /*
1953  *      vm_map_find_min() is a variant of vm_map_find() that takes an
1954  *      additional parameter (min_addr) and treats the given address
1955  *      (*addr) differently.  Specifically, it treats *addr as a hint
1956  *      and not as the minimum address where the mapping is created.
1957  *
1958  *      This function works in two phases.  First, it tries to
1959  *      allocate above the hint.  If that fails and the hint is
1960  *      greater than min_addr, it performs a second pass, replacing
1961  *      the hint with min_addr as the minimum address for the
1962  *      allocation.
1963  */
1964 int
1965 vm_map_find_min(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1966     vm_offset_t *addr, vm_size_t length, vm_offset_t min_addr,
1967     vm_offset_t max_addr, int find_space, vm_prot_t prot, vm_prot_t max,
1968     int cow)
1969 {
1970         vm_offset_t hint;
1971         int rv;
1972
1973         hint = *addr;
1974         for (;;) {
1975                 rv = vm_map_find(map, object, offset, addr, length, max_addr,
1976                     find_space, prot, max, cow);
1977                 if (rv == KERN_SUCCESS || min_addr >= hint)
1978                         return (rv);
1979                 *addr = hint = min_addr;
1980         }
1981 }
1982
1983 /*
1984  * A map entry with any of the following flags set must not be merged with
1985  * another entry.
1986  */
1987 #define MAP_ENTRY_NOMERGE_MASK  (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP | \
1988             MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP | MAP_ENTRY_VN_EXEC)
1989
1990 static bool
1991 vm_map_mergeable_neighbors(vm_map_entry_t prev, vm_map_entry_t entry)
1992 {
1993
1994         KASSERT((prev->eflags & MAP_ENTRY_NOMERGE_MASK) == 0 ||
1995             (entry->eflags & MAP_ENTRY_NOMERGE_MASK) == 0,
1996             ("vm_map_mergeable_neighbors: neither %p nor %p are mergeable",
1997             prev, entry));
1998         return (prev->end == entry->start &&
1999             prev->object.vm_object == entry->object.vm_object &&
2000             (prev->object.vm_object == NULL ||
2001             prev->offset + (prev->end - prev->start) == entry->offset) &&
2002             prev->eflags == entry->eflags &&
2003             prev->protection == entry->protection &&
2004             prev->max_protection == entry->max_protection &&
2005             prev->inheritance == entry->inheritance &&
2006             prev->wired_count == entry->wired_count &&
2007             prev->cred == entry->cred);
2008 }
2009
2010 static void
2011 vm_map_merged_neighbor_dispose(vm_map_t map, vm_map_entry_t entry)
2012 {
2013
2014         /*
2015          * If the backing object is a vnode object, vm_object_deallocate()
2016          * calls vrele().  However, vrele() does not lock the vnode because
2017          * the vnode has additional references.  Thus, the map lock can be
2018          * kept without causing a lock-order reversal with the vnode lock.
2019          *
2020          * Since we count the number of virtual page mappings in
2021          * object->un_pager.vnp.writemappings, the writemappings value
2022          * should not be adjusted when the entry is disposed of.
2023          */
2024         if (entry->object.vm_object != NULL)
2025                 vm_object_deallocate(entry->object.vm_object);
2026         if (entry->cred != NULL)
2027                 crfree(entry->cred);
2028         vm_map_entry_dispose(map, entry);
2029 }
2030
2031 /*
2032  *      vm_map_simplify_entry:
2033  *
2034  *      Simplify the given map entry by merging with either neighbor.  This
2035  *      routine also has the ability to merge with both neighbors.
2036  *
2037  *      The map must be locked.
2038  *
2039  *      This routine guarantees that the passed entry remains valid (though
2040  *      possibly extended).  When merging, this routine may delete one or
2041  *      both neighbors.
2042  */
2043 void
2044 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
2045 {
2046         vm_map_entry_t next, prev;
2047
2048         if ((entry->eflags & MAP_ENTRY_NOMERGE_MASK) != 0)
2049                 return;
2050         prev = entry->prev;
2051         if (vm_map_mergeable_neighbors(prev, entry)) {
2052                 vm_map_entry_unlink(map, prev, UNLINK_MERGE_NEXT);
2053                 vm_map_merged_neighbor_dispose(map, prev);
2054         }
2055         next = entry->next;
2056         if (vm_map_mergeable_neighbors(entry, next)) {
2057                 vm_map_entry_unlink(map, next, UNLINK_MERGE_PREV);
2058                 vm_map_merged_neighbor_dispose(map, next);
2059         }
2060 }
2061
2062 /*
2063  *      vm_map_clip_start:      [ internal use only ]
2064  *
2065  *      Asserts that the given entry begins at or after
2066  *      the specified address; if necessary,
2067  *      it splits the entry into two.
2068  */
2069 #define vm_map_clip_start(map, entry, startaddr) \
2070 { \
2071         if (startaddr > entry->start) \
2072                 _vm_map_clip_start(map, entry, startaddr); \
2073 }
2074
2075 /*
2076  *      This routine is called only when it is known that
2077  *      the entry must be split.
2078  */
2079 static void
2080 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
2081 {
2082         vm_map_entry_t new_entry;
2083
2084         VM_MAP_ASSERT_LOCKED(map);
2085         KASSERT(entry->end > start && entry->start < start,
2086             ("_vm_map_clip_start: invalid clip of entry %p", entry));
2087
2088         /*
2089          * Split off the front portion -- note that we must insert the new
2090          * entry BEFORE this one, so that this entry has the specified
2091          * starting address.
2092          */
2093         vm_map_simplify_entry(map, entry);
2094
2095         /*
2096          * If there is no object backing this entry, we might as well create
2097          * one now.  If we defer it, an object can get created after the map
2098          * is clipped, and individual objects will be created for the split-up
2099          * map.  This is a bit of a hack, but is also about the best place to
2100          * put this improvement.
2101          */
2102         if (entry->object.vm_object == NULL && !map->system_map &&
2103             (entry->eflags & MAP_ENTRY_GUARD) == 0) {
2104                 vm_object_t object;
2105                 object = vm_object_allocate(OBJT_DEFAULT,
2106                                 atop(entry->end - entry->start));
2107                 entry->object.vm_object = object;
2108                 entry->offset = 0;
2109                 if (entry->cred != NULL) {
2110                         object->cred = entry->cred;
2111                         object->charge = entry->end - entry->start;
2112                         entry->cred = NULL;
2113                 }
2114         } else if (entry->object.vm_object != NULL &&
2115                    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2116                    entry->cred != NULL) {
2117                 VM_OBJECT_WLOCK(entry->object.vm_object);
2118                 KASSERT(entry->object.vm_object->cred == NULL,
2119                     ("OVERCOMMIT: vm_entry_clip_start: both cred e %p", entry));
2120                 entry->object.vm_object->cred = entry->cred;
2121                 entry->object.vm_object->charge = entry->end - entry->start;
2122                 VM_OBJECT_WUNLOCK(entry->object.vm_object);
2123                 entry->cred = NULL;
2124         }
2125
2126         new_entry = vm_map_entry_create(map);
2127         *new_entry = *entry;
2128
2129         new_entry->end = start;
2130         entry->offset += (start - entry->start);
2131         entry->start = start;
2132         if (new_entry->cred != NULL)
2133                 crhold(entry->cred);
2134
2135         vm_map_entry_link(map, new_entry);
2136
2137         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2138                 vm_object_reference(new_entry->object.vm_object);
2139                 vm_map_entry_set_vnode_text(new_entry, true);
2140                 /*
2141                  * The object->un_pager.vnp.writemappings for the
2142                  * object of MAP_ENTRY_VN_WRITECNT type entry shall be
2143                  * kept as is here.  The virtual pages are
2144                  * re-distributed among the clipped entries, so the sum is
2145                  * left the same.
2146                  */
2147         }
2148 }
2149
2150 /*
2151  *      vm_map_clip_end:        [ internal use only ]
2152  *
2153  *      Asserts that the given entry ends at or before
2154  *      the specified address; if necessary,
2155  *      it splits the entry into two.
2156  */
2157 #define vm_map_clip_end(map, entry, endaddr) \
2158 { \
2159         if ((endaddr) < (entry->end)) \
2160                 _vm_map_clip_end((map), (entry), (endaddr)); \
2161 }
2162
2163 /*
2164  *      This routine is called only when it is known that
2165  *      the entry must be split.
2166  */
2167 static void
2168 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
2169 {
2170         vm_map_entry_t new_entry;
2171
2172         VM_MAP_ASSERT_LOCKED(map);
2173         KASSERT(entry->start < end && entry->end > end,
2174             ("_vm_map_clip_end: invalid clip of entry %p", entry));
2175
2176         /*
2177          * If there is no object backing this entry, we might as well create
2178          * one now.  If we defer it, an object can get created after the map
2179          * is clipped, and individual objects will be created for the split-up
2180          * map.  This is a bit of a hack, but is also about the best place to
2181          * put this improvement.
2182          */
2183         if (entry->object.vm_object == NULL && !map->system_map &&
2184             (entry->eflags & MAP_ENTRY_GUARD) == 0) {
2185                 vm_object_t object;
2186                 object = vm_object_allocate(OBJT_DEFAULT,
2187                                 atop(entry->end - entry->start));
2188                 entry->object.vm_object = object;
2189                 entry->offset = 0;
2190                 if (entry->cred != NULL) {
2191                         object->cred = entry->cred;
2192                         object->charge = entry->end - entry->start;
2193                         entry->cred = NULL;
2194                 }
2195         } else if (entry->object.vm_object != NULL &&
2196                    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
2197                    entry->cred != NULL) {
2198                 VM_OBJECT_WLOCK(entry->object.vm_object);
2199                 KASSERT(entry->object.vm_object->cred == NULL,
2200                     ("OVERCOMMIT: vm_entry_clip_end: both cred e %p", entry));
2201                 entry->object.vm_object->cred = entry->cred;
2202                 entry->object.vm_object->charge = entry->end - entry->start;
2203                 VM_OBJECT_WUNLOCK(entry->object.vm_object);
2204                 entry->cred = NULL;
2205         }
2206
2207         /*
2208          * Create a new entry and insert it AFTER the specified entry
2209          */
2210         new_entry = vm_map_entry_create(map);
2211         *new_entry = *entry;
2212
2213         new_entry->start = entry->end = end;
2214         new_entry->offset += (end - entry->start);
2215         if (new_entry->cred != NULL)
2216                 crhold(entry->cred);
2217
2218         vm_map_entry_link(map, new_entry);
2219
2220         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2221                 vm_object_reference(new_entry->object.vm_object);
2222                 vm_map_entry_set_vnode_text(new_entry, true);
2223         }
2224 }
2225
2226 /*
2227  *      vm_map_submap:          [ kernel use only ]
2228  *
2229  *      Mark the given range as handled by a subordinate map.
2230  *
2231  *      This range must have been created with vm_map_find,
2232  *      and no other operations may have been performed on this
2233  *      range prior to calling vm_map_submap.
2234  *
2235  *      Only a limited number of operations can be performed
2236  *      within this rage after calling vm_map_submap:
2237  *              vm_fault
2238  *      [Don't try vm_map_copy!]
2239  *
2240  *      To remove a submapping, one must first remove the
2241  *      range from the superior map, and then destroy the
2242  *      submap (if desired).  [Better yet, don't try it.]
2243  */
2244 int
2245 vm_map_submap(
2246         vm_map_t map,
2247         vm_offset_t start,
2248         vm_offset_t end,
2249         vm_map_t submap)
2250 {
2251         vm_map_entry_t entry;
2252         int result;
2253
2254         result = KERN_INVALID_ARGUMENT;
2255
2256         vm_map_lock(submap);
2257         submap->flags |= MAP_IS_SUB_MAP;
2258         vm_map_unlock(submap);
2259
2260         vm_map_lock(map);
2261
2262         VM_MAP_RANGE_CHECK(map, start, end);
2263
2264         if (vm_map_lookup_entry(map, start, &entry)) {
2265                 vm_map_clip_start(map, entry, start);
2266         } else
2267                 entry = entry->next;
2268
2269         vm_map_clip_end(map, entry, end);
2270
2271         if ((entry->start == start) && (entry->end == end) &&
2272             ((entry->eflags & MAP_ENTRY_COW) == 0) &&
2273             (entry->object.vm_object == NULL)) {
2274                 entry->object.sub_map = submap;
2275                 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
2276                 result = KERN_SUCCESS;
2277         }
2278         vm_map_unlock(map);
2279
2280         if (result != KERN_SUCCESS) {
2281                 vm_map_lock(submap);
2282                 submap->flags &= ~MAP_IS_SUB_MAP;
2283                 vm_map_unlock(submap);
2284         }
2285         return (result);
2286 }
2287
2288 /*
2289  * The maximum number of pages to map if MAP_PREFAULT_PARTIAL is specified
2290  */
2291 #define MAX_INIT_PT     96
2292
2293 /*
2294  *      vm_map_pmap_enter:
2295  *
2296  *      Preload the specified map's pmap with mappings to the specified
2297  *      object's memory-resident pages.  No further physical pages are
2298  *      allocated, and no further virtual pages are retrieved from secondary
2299  *      storage.  If the specified flags include MAP_PREFAULT_PARTIAL, then a
2300  *      limited number of page mappings are created at the low-end of the
2301  *      specified address range.  (For this purpose, a superpage mapping
2302  *      counts as one page mapping.)  Otherwise, all resident pages within
2303  *      the specified address range are mapped.
2304  */
2305 static void
2306 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
2307     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
2308 {
2309         vm_offset_t start;
2310         vm_page_t p, p_start;
2311         vm_pindex_t mask, psize, threshold, tmpidx;
2312
2313         if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
2314                 return;
2315         VM_OBJECT_RLOCK(object);
2316         if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2317                 VM_OBJECT_RUNLOCK(object);
2318                 VM_OBJECT_WLOCK(object);
2319                 if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
2320                         pmap_object_init_pt(map->pmap, addr, object, pindex,
2321                             size);
2322                         VM_OBJECT_WUNLOCK(object);
2323                         return;
2324                 }
2325                 VM_OBJECT_LOCK_DOWNGRADE(object);
2326         }
2327
2328         psize = atop(size);
2329         if (psize + pindex > object->size) {
2330                 if (object->size < pindex) {
2331                         VM_OBJECT_RUNLOCK(object);
2332                         return;
2333                 }
2334                 psize = object->size - pindex;
2335         }
2336
2337         start = 0;
2338         p_start = NULL;
2339         threshold = MAX_INIT_PT;
2340
2341         p = vm_page_find_least(object, pindex);
2342         /*
2343          * Assert: the variable p is either (1) the page with the
2344          * least pindex greater than or equal to the parameter pindex
2345          * or (2) NULL.
2346          */
2347         for (;
2348              p != NULL && (tmpidx = p->pindex - pindex) < psize;
2349              p = TAILQ_NEXT(p, listq)) {
2350                 /*
2351                  * don't allow an madvise to blow away our really
2352                  * free pages allocating pv entries.
2353                  */
2354                 if (((flags & MAP_PREFAULT_MADVISE) != 0 &&
2355                     vm_page_count_severe()) ||
2356                     ((flags & MAP_PREFAULT_PARTIAL) != 0 &&
2357                     tmpidx >= threshold)) {
2358                         psize = tmpidx;
2359                         break;
2360                 }
2361                 if (p->valid == VM_PAGE_BITS_ALL) {
2362                         if (p_start == NULL) {
2363                                 start = addr + ptoa(tmpidx);
2364                                 p_start = p;
2365                         }
2366                         /* Jump ahead if a superpage mapping is possible. */
2367                         if (p->psind > 0 && ((addr + ptoa(tmpidx)) &
2368                             (pagesizes[p->psind] - 1)) == 0) {
2369                                 mask = atop(pagesizes[p->psind]) - 1;
2370                                 if (tmpidx + mask < psize &&
2371                                     vm_page_ps_test(p, PS_ALL_VALID, NULL)) {
2372                                         p += mask;
2373                                         threshold += mask;
2374                                 }
2375                         }
2376                 } else if (p_start != NULL) {
2377                         pmap_enter_object(map->pmap, start, addr +
2378                             ptoa(tmpidx), p_start, prot);
2379                         p_start = NULL;
2380                 }
2381         }
2382         if (p_start != NULL)
2383                 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
2384                     p_start, prot);
2385         VM_OBJECT_RUNLOCK(object);
2386 }
2387
2388 /*
2389  *      vm_map_protect:
2390  *
2391  *      Sets the protection of the specified address
2392  *      region in the target map.  If "set_max" is
2393  *      specified, the maximum protection is to be set;
2394  *      otherwise, only the current protection is affected.
2395  */
2396 int
2397 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
2398                vm_prot_t new_prot, boolean_t set_max)
2399 {
2400         vm_map_entry_t current, entry, in_tran;
2401         vm_object_t obj;
2402         struct ucred *cred;
2403         vm_prot_t old_prot;
2404
2405         if (start == end)
2406                 return (KERN_SUCCESS);
2407
2408 again:
2409         in_tran = NULL;
2410         vm_map_lock(map);
2411
2412         /*
2413          * Ensure that we are not concurrently wiring pages.  vm_map_wire() may
2414          * need to fault pages into the map and will drop the map lock while
2415          * doing so, and the VM object may end up in an inconsistent state if we
2416          * update the protection on the map entry in between faults.
2417          */
2418         vm_map_wait_busy(map);
2419
2420         VM_MAP_RANGE_CHECK(map, start, end);
2421
2422         if (vm_map_lookup_entry(map, start, &entry)) {
2423                 vm_map_clip_start(map, entry, start);
2424         } else {
2425                 entry = entry->next;
2426         }
2427
2428         /*
2429          * Make a first pass to check for protection violations.
2430          */
2431         for (current = entry; current->start < end; current = current->next) {
2432                 if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2433                         continue;
2434                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2435                         vm_map_unlock(map);
2436                         return (KERN_INVALID_ARGUMENT);
2437                 }
2438                 if ((new_prot & current->max_protection) != new_prot) {
2439                         vm_map_unlock(map);
2440                         return (KERN_PROTECTION_FAILURE);
2441                 }
2442                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0)
2443                         in_tran = entry;
2444         }
2445
2446         /*
2447          * Postpone the operation until all in transition map entries
2448          * are stabilized.  In-transition entry might already have its
2449          * pages wired and wired_count incremented, but
2450          * MAP_ENTRY_USER_WIRED flag not yet set, and visible to other
2451          * threads because the map lock is dropped.  In this case we
2452          * would miss our call to vm_fault_copy_entry().
2453          */
2454         if (in_tran != NULL) {
2455                 in_tran->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2456                 vm_map_unlock_and_wait(map, 0);
2457                 goto again;
2458         }
2459
2460         /*
2461          * Do an accounting pass for private read-only mappings that
2462          * now will do cow due to allowed write (e.g. debugger sets
2463          * breakpoint on text segment)
2464          */
2465         for (current = entry; current->start < end; current = current->next) {
2466
2467                 vm_map_clip_end(map, current, end);
2468
2469                 if (set_max ||
2470                     ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
2471                     ENTRY_CHARGED(current) ||
2472                     (current->eflags & MAP_ENTRY_GUARD) != 0) {
2473                         continue;
2474                 }
2475
2476                 cred = curthread->td_ucred;
2477                 obj = current->object.vm_object;
2478
2479                 if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
2480                         if (!swap_reserve(current->end - current->start)) {
2481                                 vm_map_unlock(map);
2482                                 return (KERN_RESOURCE_SHORTAGE);
2483                         }
2484                         crhold(cred);
2485                         current->cred = cred;
2486                         continue;
2487                 }
2488
2489                 VM_OBJECT_WLOCK(obj);
2490                 if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
2491                         VM_OBJECT_WUNLOCK(obj);
2492                         continue;
2493                 }
2494
2495                 /*
2496                  * Charge for the whole object allocation now, since
2497                  * we cannot distinguish between non-charged and
2498                  * charged clipped mapping of the same object later.
2499                  */
2500                 KASSERT(obj->charge == 0,
2501                     ("vm_map_protect: object %p overcharged (entry %p)",
2502                     obj, current));
2503                 if (!swap_reserve(ptoa(obj->size))) {
2504                         VM_OBJECT_WUNLOCK(obj);
2505                         vm_map_unlock(map);
2506                         return (KERN_RESOURCE_SHORTAGE);
2507                 }
2508
2509                 crhold(cred);
2510                 obj->cred = cred;
2511                 obj->charge = ptoa(obj->size);
2512                 VM_OBJECT_WUNLOCK(obj);
2513         }
2514
2515         /*
2516          * Go back and fix up protections. [Note that clipping is not
2517          * necessary the second time.]
2518          */
2519         for (current = entry; current->start < end; current = current->next) {
2520                 if ((current->eflags & MAP_ENTRY_GUARD) != 0)
2521                         continue;
2522
2523                 old_prot = current->protection;
2524
2525                 if (set_max)
2526                         current->protection =
2527                             (current->max_protection = new_prot) &
2528                             old_prot;
2529                 else
2530                         current->protection = new_prot;
2531
2532                 /*
2533                  * For user wired map entries, the normal lazy evaluation of
2534                  * write access upgrades through soft page faults is
2535                  * undesirable.  Instead, immediately copy any pages that are
2536                  * copy-on-write and enable write access in the physical map.
2537                  */
2538                 if ((current->eflags & MAP_ENTRY_USER_WIRED) != 0 &&
2539                     (current->protection & VM_PROT_WRITE) != 0 &&
2540                     (old_prot & VM_PROT_WRITE) == 0)
2541                         vm_fault_copy_entry(map, map, current, current, NULL);
2542
2543                 /*
2544                  * When restricting access, update the physical map.  Worry
2545                  * about copy-on-write here.
2546                  */
2547                 if ((old_prot & ~current->protection) != 0) {
2548 #define MASK(entry)     (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
2549                                                         VM_PROT_ALL)
2550                         pmap_protect(map->pmap, current->start,
2551                             current->end,
2552                             current->protection & MASK(current));
2553 #undef  MASK
2554                 }
2555                 vm_map_simplify_entry(map, current);
2556         }
2557         vm_map_unlock(map);
2558         return (KERN_SUCCESS);
2559 }
2560
2561 /*
2562  *      vm_map_madvise:
2563  *
2564  *      This routine traverses a processes map handling the madvise
2565  *      system call.  Advisories are classified as either those effecting
2566  *      the vm_map_entry structure, or those effecting the underlying
2567  *      objects.
2568  */
2569 int
2570 vm_map_madvise(
2571         vm_map_t map,
2572         vm_offset_t start,
2573         vm_offset_t end,
2574         int behav)
2575 {
2576         vm_map_entry_t current, entry;
2577         bool modify_map;
2578
2579         /*
2580          * Some madvise calls directly modify the vm_map_entry, in which case
2581          * we need to use an exclusive lock on the map and we need to perform
2582          * various clipping operations.  Otherwise we only need a read-lock
2583          * on the map.
2584          */
2585         switch(behav) {
2586         case MADV_NORMAL:
2587         case MADV_SEQUENTIAL:
2588         case MADV_RANDOM:
2589         case MADV_NOSYNC:
2590         case MADV_AUTOSYNC:
2591         case MADV_NOCORE:
2592         case MADV_CORE:
2593                 if (start == end)
2594                         return (0);
2595                 modify_map = true;
2596                 vm_map_lock(map);
2597                 break;
2598         case MADV_WILLNEED:
2599         case MADV_DONTNEED:
2600         case MADV_FREE:
2601                 if (start == end)
2602                         return (0);
2603                 modify_map = false;
2604                 vm_map_lock_read(map);
2605                 break;
2606         default:
2607                 return (EINVAL);
2608         }
2609
2610         /*
2611          * Locate starting entry and clip if necessary.
2612          */
2613         VM_MAP_RANGE_CHECK(map, start, end);
2614
2615         if (vm_map_lookup_entry(map, start, &entry)) {
2616                 if (modify_map)
2617                         vm_map_clip_start(map, entry, start);
2618         } else {
2619                 entry = entry->next;
2620         }
2621
2622         if (modify_map) {
2623                 /*
2624                  * madvise behaviors that are implemented in the vm_map_entry.
2625                  *
2626                  * We clip the vm_map_entry so that behavioral changes are
2627                  * limited to the specified address range.
2628                  */
2629                 for (current = entry; current->start < end;
2630                     current = current->next) {
2631                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2632                                 continue;
2633
2634                         vm_map_clip_end(map, current, end);
2635
2636                         switch (behav) {
2637                         case MADV_NORMAL:
2638                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2639                                 break;
2640                         case MADV_SEQUENTIAL:
2641                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2642                                 break;
2643                         case MADV_RANDOM:
2644                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2645                                 break;
2646                         case MADV_NOSYNC:
2647                                 current->eflags |= MAP_ENTRY_NOSYNC;
2648                                 break;
2649                         case MADV_AUTOSYNC:
2650                                 current->eflags &= ~MAP_ENTRY_NOSYNC;
2651                                 break;
2652                         case MADV_NOCORE:
2653                                 current->eflags |= MAP_ENTRY_NOCOREDUMP;
2654                                 break;
2655                         case MADV_CORE:
2656                                 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2657                                 break;
2658                         default:
2659                                 break;
2660                         }
2661                         vm_map_simplify_entry(map, current);
2662                 }
2663                 vm_map_unlock(map);
2664         } else {
2665                 vm_pindex_t pstart, pend;
2666
2667                 /*
2668                  * madvise behaviors that are implemented in the underlying
2669                  * vm_object.
2670                  *
2671                  * Since we don't clip the vm_map_entry, we have to clip
2672                  * the vm_object pindex and count.
2673                  */
2674                 for (current = entry; current->start < end;
2675                     current = current->next) {
2676                         vm_offset_t useEnd, useStart;
2677
2678                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2679                                 continue;
2680
2681                         pstart = OFF_TO_IDX(current->offset);
2682                         pend = pstart + atop(current->end - current->start);
2683                         useStart = current->start;
2684                         useEnd = current->end;
2685
2686                         if (current->start < start) {
2687                                 pstart += atop(start - current->start);
2688                                 useStart = start;
2689                         }
2690                         if (current->end > end) {
2691                                 pend -= atop(current->end - end);
2692                                 useEnd = end;
2693                         }
2694
2695                         if (pstart >= pend)
2696                                 continue;
2697
2698                         /*
2699                          * Perform the pmap_advise() before clearing
2700                          * PGA_REFERENCED in vm_page_advise().  Otherwise, a
2701                          * concurrent pmap operation, such as pmap_remove(),
2702                          * could clear a reference in the pmap and set
2703                          * PGA_REFERENCED on the page before the pmap_advise()
2704                          * had completed.  Consequently, the page would appear
2705                          * referenced based upon an old reference that
2706                          * occurred before this pmap_advise() ran.
2707                          */
2708                         if (behav == MADV_DONTNEED || behav == MADV_FREE)
2709                                 pmap_advise(map->pmap, useStart, useEnd,
2710                                     behav);
2711
2712                         vm_object_madvise(current->object.vm_object, pstart,
2713                             pend, behav);
2714
2715                         /*
2716                          * Pre-populate paging structures in the
2717                          * WILLNEED case.  For wired entries, the
2718                          * paging structures are already populated.
2719                          */
2720                         if (behav == MADV_WILLNEED &&
2721                             current->wired_count == 0) {
2722                                 vm_map_pmap_enter(map,
2723                                     useStart,
2724                                     current->protection,
2725                                     current->object.vm_object,
2726                                     pstart,
2727                                     ptoa(pend - pstart),
2728                                     MAP_PREFAULT_MADVISE
2729                                 );
2730                         }
2731                 }
2732                 vm_map_unlock_read(map);
2733         }
2734         return (0);
2735 }
2736
2737
2738 /*
2739  *      vm_map_inherit:
2740  *
2741  *      Sets the inheritance of the specified address
2742  *      range in the target map.  Inheritance
2743  *      affects how the map will be shared with
2744  *      child maps at the time of vmspace_fork.
2745  */
2746 int
2747 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2748                vm_inherit_t new_inheritance)
2749 {
2750         vm_map_entry_t entry;
2751         vm_map_entry_t temp_entry;
2752
2753         switch (new_inheritance) {
2754         case VM_INHERIT_NONE:
2755         case VM_INHERIT_COPY:
2756         case VM_INHERIT_SHARE:
2757         case VM_INHERIT_ZERO:
2758                 break;
2759         default:
2760                 return (KERN_INVALID_ARGUMENT);
2761         }
2762         if (start == end)
2763                 return (KERN_SUCCESS);
2764         vm_map_lock(map);
2765         VM_MAP_RANGE_CHECK(map, start, end);
2766         if (vm_map_lookup_entry(map, start, &temp_entry)) {
2767                 entry = temp_entry;
2768                 vm_map_clip_start(map, entry, start);
2769         } else
2770                 entry = temp_entry->next;
2771         while (entry->start < end) {
2772                 vm_map_clip_end(map, entry, end);
2773                 if ((entry->eflags & MAP_ENTRY_GUARD) == 0 ||
2774                     new_inheritance != VM_INHERIT_ZERO)
2775                         entry->inheritance = new_inheritance;
2776                 vm_map_simplify_entry(map, entry);
2777                 entry = entry->next;
2778         }
2779         vm_map_unlock(map);
2780         return (KERN_SUCCESS);
2781 }
2782
2783 /*
2784  *      vm_map_unwire:
2785  *
2786  *      Implements both kernel and user unwiring.
2787  */
2788 int
2789 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2790     int flags)
2791 {
2792         vm_map_entry_t entry, first_entry, tmp_entry;
2793         vm_offset_t saved_start;
2794         unsigned int last_timestamp;
2795         int rv;
2796         boolean_t need_wakeup, result, user_unwire;
2797
2798         if (start == end)
2799                 return (KERN_SUCCESS);
2800         user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2801         vm_map_lock(map);
2802         VM_MAP_RANGE_CHECK(map, start, end);
2803         if (!vm_map_lookup_entry(map, start, &first_entry)) {
2804                 if (flags & VM_MAP_WIRE_HOLESOK)
2805                         first_entry = first_entry->next;
2806                 else {
2807                         vm_map_unlock(map);
2808                         return (KERN_INVALID_ADDRESS);
2809                 }
2810         }
2811         last_timestamp = map->timestamp;
2812         entry = first_entry;
2813         while (entry->start < end) {
2814                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2815                         /*
2816                          * We have not yet clipped the entry.
2817                          */
2818                         saved_start = (start >= entry->start) ? start :
2819                             entry->start;
2820                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2821                         if (vm_map_unlock_and_wait(map, 0)) {
2822                                 /*
2823                                  * Allow interruption of user unwiring?
2824                                  */
2825                         }
2826                         vm_map_lock(map);
2827                         if (last_timestamp+1 != map->timestamp) {
2828                                 /*
2829                                  * Look again for the entry because the map was
2830                                  * modified while it was unlocked.
2831                                  * Specifically, the entry may have been
2832                                  * clipped, merged, or deleted.
2833                                  */
2834                                 if (!vm_map_lookup_entry(map, saved_start,
2835                                     &tmp_entry)) {
2836                                         if (flags & VM_MAP_WIRE_HOLESOK)
2837                                                 tmp_entry = tmp_entry->next;
2838                                         else {
2839                                                 if (saved_start == start) {
2840                                                         /*
2841                                                          * First_entry has been deleted.
2842                                                          */
2843                                                         vm_map_unlock(map);
2844                                                         return (KERN_INVALID_ADDRESS);
2845                                                 }
2846                                                 end = saved_start;
2847                                                 rv = KERN_INVALID_ADDRESS;
2848                                                 goto done;
2849                                         }
2850                                 }
2851                                 if (entry == first_entry)
2852                                         first_entry = tmp_entry;
2853                                 else
2854                                         first_entry = NULL;
2855                                 entry = tmp_entry;
2856                         }
2857                         last_timestamp = map->timestamp;
2858                         continue;
2859                 }
2860                 vm_map_clip_start(map, entry, start);
2861                 vm_map_clip_end(map, entry, end);
2862                 /*
2863                  * Mark the entry in case the map lock is released.  (See
2864                  * above.)
2865                  */
2866                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
2867                     entry->wiring_thread == NULL,
2868                     ("owned map entry %p", entry));
2869                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2870                 entry->wiring_thread = curthread;
2871                 /*
2872                  * Check the map for holes in the specified region.
2873                  * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2874                  */
2875                 if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2876                     (entry->end < end && entry->next->start > entry->end)) {
2877                         end = entry->end;
2878                         rv = KERN_INVALID_ADDRESS;
2879                         goto done;
2880                 }
2881                 /*
2882                  * If system unwiring, require that the entry is system wired.
2883                  */
2884                 if (!user_unwire &&
2885                     vm_map_entry_system_wired_count(entry) == 0) {
2886                         end = entry->end;
2887                         rv = KERN_INVALID_ARGUMENT;
2888                         goto done;
2889                 }
2890                 entry = entry->next;
2891         }
2892         rv = KERN_SUCCESS;
2893 done:
2894         need_wakeup = FALSE;
2895         if (first_entry == NULL) {
2896                 result = vm_map_lookup_entry(map, start, &first_entry);
2897                 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2898                         first_entry = first_entry->next;
2899                 else
2900                         KASSERT(result, ("vm_map_unwire: lookup failed"));
2901         }
2902         for (entry = first_entry; entry->start < end; entry = entry->next) {
2903                 /*
2904                  * If VM_MAP_WIRE_HOLESOK was specified, an empty
2905                  * space in the unwired region could have been mapped
2906                  * while the map lock was dropped for draining
2907                  * MAP_ENTRY_IN_TRANSITION.  Moreover, another thread
2908                  * could be simultaneously wiring this new mapping
2909                  * entry.  Detect these cases and skip any entries
2910                  * marked as in transition by us.
2911                  */
2912                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
2913                     entry->wiring_thread != curthread) {
2914                         KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
2915                             ("vm_map_unwire: !HOLESOK and new/changed entry"));
2916                         continue;
2917                 }
2918
2919                 if (rv == KERN_SUCCESS && (!user_unwire ||
2920                     (entry->eflags & MAP_ENTRY_USER_WIRED))) {
2921                         if (entry->wired_count == 1)
2922                                 vm_map_entry_unwire(map, entry);
2923                         else
2924                                 entry->wired_count--;
2925                         if (user_unwire)
2926                                 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2927                 }
2928                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
2929                     ("vm_map_unwire: in-transition flag missing %p", entry));
2930                 KASSERT(entry->wiring_thread == curthread,
2931                     ("vm_map_unwire: alien wire %p", entry));
2932                 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2933                 entry->wiring_thread = NULL;
2934                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2935                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2936                         need_wakeup = TRUE;
2937                 }
2938                 vm_map_simplify_entry(map, entry);
2939         }
2940         vm_map_unlock(map);
2941         if (need_wakeup)
2942                 vm_map_wakeup(map);
2943         return (rv);
2944 }
2945
2946 static void
2947 vm_map_wire_user_count_sub(u_long npages)
2948 {
2949
2950         atomic_subtract_long(&vm_user_wire_count, npages);
2951 }
2952
2953 static bool
2954 vm_map_wire_user_count_add(u_long npages)
2955 {
2956         u_long wired;
2957
2958         wired = vm_user_wire_count;
2959         do {
2960                 if (npages + wired > vm_page_max_user_wired)
2961                         return (false);
2962         } while (!atomic_fcmpset_long(&vm_user_wire_count, &wired,
2963             npages + wired));
2964
2965         return (true);
2966 }
2967
2968 /*
2969  *      vm_map_wire_entry_failure:
2970  *
2971  *      Handle a wiring failure on the given entry.
2972  *
2973  *      The map should be locked.
2974  */
2975 static void
2976 vm_map_wire_entry_failure(vm_map_t map, vm_map_entry_t entry,
2977     vm_offset_t failed_addr)
2978 {
2979
2980         VM_MAP_ASSERT_LOCKED(map);
2981         KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 &&
2982             entry->wired_count == 1,
2983             ("vm_map_wire_entry_failure: entry %p isn't being wired", entry));
2984         KASSERT(failed_addr < entry->end,
2985             ("vm_map_wire_entry_failure: entry %p was fully wired", entry));
2986
2987         /*
2988          * If any pages at the start of this entry were successfully wired,
2989          * then unwire them.
2990          */
2991         if (failed_addr > entry->start) {
2992                 pmap_unwire(map->pmap, entry->start, failed_addr);
2993                 vm_object_unwire(entry->object.vm_object, entry->offset,
2994                     failed_addr - entry->start, PQ_ACTIVE);
2995         }
2996
2997         /*
2998          * Assign an out-of-range value to represent the failure to wire this
2999          * entry.
3000          */
3001         entry->wired_count = -1;
3002 }
3003
3004 int
3005 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3006 {
3007         int rv;
3008
3009         vm_map_lock(map);
3010         rv = vm_map_wire_locked(map, start, end, flags);
3011         vm_map_unlock(map);
3012         return (rv);
3013 }
3014
3015
3016 /*
3017  *      vm_map_wire_locked:
3018  *
3019  *      Implements both kernel and user wiring.  Returns with the map locked,
3020  *      the map lock may be dropped.
3021  */
3022 int
3023 vm_map_wire_locked(vm_map_t map, vm_offset_t start, vm_offset_t end, int flags)
3024 {
3025         vm_map_entry_t entry, first_entry, tmp_entry;
3026         vm_offset_t faddr, saved_end, saved_start;
3027         u_long npages;
3028         u_int last_timestamp;
3029         int rv;
3030         boolean_t need_wakeup, result, user_wire;
3031         vm_prot_t prot;
3032
3033         VM_MAP_ASSERT_LOCKED(map);
3034
3035         if (start == end)
3036                 return (KERN_SUCCESS);
3037         prot = 0;
3038         if (flags & VM_MAP_WIRE_WRITE)
3039                 prot |= VM_PROT_WRITE;
3040         user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
3041         VM_MAP_RANGE_CHECK(map, start, end);
3042         if (!vm_map_lookup_entry(map, start, &first_entry)) {
3043                 if (flags & VM_MAP_WIRE_HOLESOK)
3044                         first_entry = first_entry->next;
3045                 else
3046                         return (KERN_INVALID_ADDRESS);
3047         }
3048         last_timestamp = map->timestamp;
3049         entry = first_entry;
3050         while (entry->start < end) {
3051                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
3052                         /*
3053                          * We have not yet clipped the entry.
3054                          */
3055                         saved_start = (start >= entry->start) ? start :
3056                             entry->start;
3057                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3058                         if (vm_map_unlock_and_wait(map, 0)) {
3059                                 /*
3060                                  * Allow interruption of user wiring?
3061                                  */
3062                         }
3063                         vm_map_lock(map);
3064                         if (last_timestamp + 1 != map->timestamp) {
3065                                 /*
3066                                  * Look again for the entry because the map was
3067                                  * modified while it was unlocked.
3068                                  * Specifically, the entry may have been
3069                                  * clipped, merged, or deleted.
3070                                  */
3071                                 if (!vm_map_lookup_entry(map, saved_start,
3072                                     &tmp_entry)) {
3073                                         if (flags & VM_MAP_WIRE_HOLESOK)
3074                                                 tmp_entry = tmp_entry->next;
3075                                         else {
3076                                                 if (saved_start == start) {
3077                                                         /*
3078                                                          * first_entry has been deleted.
3079                                                          */
3080                                                         return (KERN_INVALID_ADDRESS);
3081                                                 }
3082                                                 end = saved_start;
3083                                                 rv = KERN_INVALID_ADDRESS;
3084                                                 goto done;
3085                                         }
3086                                 }
3087                                 if (entry == first_entry)
3088                                         first_entry = tmp_entry;
3089                                 else
3090                                         first_entry = NULL;
3091                                 entry = tmp_entry;
3092                         }
3093                         last_timestamp = map->timestamp;
3094                         continue;
3095                 }
3096                 vm_map_clip_start(map, entry, start);
3097                 vm_map_clip_end(map, entry, end);
3098                 /*
3099                  * Mark the entry in case the map lock is released.  (See
3100                  * above.)
3101                  */
3102                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 &&
3103                     entry->wiring_thread == NULL,
3104                     ("owned map entry %p", entry));
3105                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
3106                 entry->wiring_thread = curthread;
3107                 if ((entry->protection & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0
3108                     || (entry->protection & prot) != prot) {
3109                         entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
3110                         if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
3111                                 end = entry->end;
3112                                 rv = KERN_INVALID_ADDRESS;
3113                                 goto done;
3114                         }
3115                         goto next_entry;
3116                 }
3117                 if (entry->wired_count == 0) {
3118                         entry->wired_count++;
3119
3120                         npages = atop(entry->end - entry->start);
3121                         if (user_wire && !vm_map_wire_user_count_add(npages)) {
3122                                 vm_map_wire_entry_failure(map, entry,
3123                                     entry->start);
3124                                 end = entry->end;
3125                                 rv = KERN_RESOURCE_SHORTAGE;
3126                                 goto done;
3127                         }
3128
3129                         /*
3130                          * Release the map lock, relying on the in-transition
3131                          * mark.  Mark the map busy for fork.
3132                          */
3133                         saved_start = entry->start;
3134                         saved_end = entry->end;
3135                         vm_map_busy(map);
3136                         vm_map_unlock(map);
3137
3138                         faddr = saved_start;
3139                         do {
3140                                 /*
3141                                  * Simulate a fault to get the page and enter
3142                                  * it into the physical map.
3143                                  */
3144                                 if ((rv = vm_fault(map, faddr, VM_PROT_NONE,
3145                                     VM_FAULT_WIRE)) != KERN_SUCCESS)
3146                                         break;
3147                         } while ((faddr += PAGE_SIZE) < saved_end);
3148                         vm_map_lock(map);
3149                         vm_map_unbusy(map);
3150                         if (last_timestamp + 1 != map->timestamp) {
3151                                 /*
3152                                  * Look again for the entry because the map was
3153                                  * modified while it was unlocked.  The entry
3154                                  * may have been clipped, but NOT merged or
3155                                  * deleted.
3156                                  */
3157                                 result = vm_map_lookup_entry(map, saved_start,
3158                                     &tmp_entry);
3159                                 KASSERT(result, ("vm_map_wire: lookup failed"));
3160                                 if (entry == first_entry)
3161                                         first_entry = tmp_entry;
3162                                 else
3163                                         first_entry = NULL;
3164                                 entry = tmp_entry;
3165                                 while (entry->end < saved_end) {
3166                                         /*
3167                                          * In case of failure, handle entries
3168                                          * that were not fully wired here;
3169                                          * fully wired entries are handled
3170                                          * later.
3171                                          */
3172                                         if (rv != KERN_SUCCESS &&
3173                                             faddr < entry->end)
3174                                                 vm_map_wire_entry_failure(map,
3175                                                     entry, faddr);
3176                                         entry = entry->next;
3177                                 }
3178                         }
3179                         last_timestamp = map->timestamp;
3180                         if (rv != KERN_SUCCESS) {
3181                                 vm_map_wire_entry_failure(map, entry, faddr);
3182                                 if (user_wire)
3183                                         vm_map_wire_user_count_sub(npages);
3184                                 end = entry->end;
3185                                 goto done;
3186                         }
3187                 } else if (!user_wire ||
3188                            (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3189                         entry->wired_count++;
3190                 }
3191                 /*
3192                  * Check the map for holes in the specified region.
3193                  * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
3194                  */
3195         next_entry:
3196                 if ((flags & VM_MAP_WIRE_HOLESOK) == 0 &&
3197                     entry->end < end && entry->next->start > entry->end) {
3198                         end = entry->end;
3199                         rv = KERN_INVALID_ADDRESS;
3200                         goto done;
3201                 }
3202                 entry = entry->next;
3203         }
3204         rv = KERN_SUCCESS;
3205 done:
3206         need_wakeup = FALSE;
3207         if (first_entry == NULL) {
3208                 result = vm_map_lookup_entry(map, start, &first_entry);
3209                 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
3210                         first_entry = first_entry->next;
3211                 else
3212                         KASSERT(result, ("vm_map_wire: lookup failed"));
3213         }
3214         for (entry = first_entry; entry->start < end; entry = entry->next) {
3215                 /*
3216                  * If VM_MAP_WIRE_HOLESOK was specified, an empty
3217                  * space in the unwired region could have been mapped
3218                  * while the map lock was dropped for faulting in the
3219                  * pages or draining MAP_ENTRY_IN_TRANSITION.
3220                  * Moreover, another thread could be simultaneously
3221                  * wiring this new mapping entry.  Detect these cases
3222                  * and skip any entries marked as in transition not by us.
3223                  */
3224                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) == 0 ||
3225                     entry->wiring_thread != curthread) {
3226                         KASSERT((flags & VM_MAP_WIRE_HOLESOK) != 0,
3227                             ("vm_map_wire: !HOLESOK and new/changed entry"));
3228                         continue;
3229                 }
3230
3231                 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
3232                         goto next_entry_done;
3233
3234                 if (rv == KERN_SUCCESS) {
3235                         if (user_wire)
3236                                 entry->eflags |= MAP_ENTRY_USER_WIRED;
3237                 } else if (entry->wired_count == -1) {
3238                         /*
3239                          * Wiring failed on this entry.  Thus, unwiring is
3240                          * unnecessary.
3241                          */
3242                         entry->wired_count = 0;
3243                 } else if (!user_wire ||
3244                     (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
3245                         /*
3246                          * Undo the wiring.  Wiring succeeded on this entry
3247                          * but failed on a later entry.  
3248                          */
3249                         if (entry->wired_count == 1) {
3250                                 vm_map_entry_unwire(map, entry);
3251                                 if (user_wire)
3252                                         vm_map_wire_user_count_sub(
3253                                             atop(entry->end - entry->start));
3254                         } else
3255                                 entry->wired_count--;
3256                 }
3257         next_entry_done:
3258                 KASSERT((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0,
3259                     ("vm_map_wire: in-transition flag missing %p", entry));
3260                 KASSERT(entry->wiring_thread == curthread,
3261                     ("vm_map_wire: alien wire %p", entry));
3262                 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION |
3263                     MAP_ENTRY_WIRE_SKIPPED);
3264                 entry->wiring_thread = NULL;
3265                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
3266                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
3267                         need_wakeup = TRUE;
3268                 }
3269                 vm_map_simplify_entry(map, entry);
3270         }
3271         if (need_wakeup)
3272                 vm_map_wakeup(map);
3273         return (rv);
3274 }
3275
3276 /*
3277  * vm_map_sync
3278  *
3279  * Push any dirty cached pages in the address range to their pager.
3280  * If syncio is TRUE, dirty pages are written synchronously.
3281  * If invalidate is TRUE, any cached pages are freed as well.
3282  *
3283  * If the size of the region from start to end is zero, we are
3284  * supposed to flush all modified pages within the region containing
3285  * start.  Unfortunately, a region can be split or coalesced with
3286  * neighboring regions, making it difficult to determine what the
3287  * original region was.  Therefore, we approximate this requirement by
3288  * flushing the current region containing start.
3289  *
3290  * Returns an error if any part of the specified range is not mapped.
3291  */
3292 int
3293 vm_map_sync(
3294         vm_map_t map,
3295         vm_offset_t start,
3296         vm_offset_t end,
3297         boolean_t syncio,
3298         boolean_t invalidate)
3299 {
3300         vm_map_entry_t current;
3301         vm_map_entry_t entry;
3302         vm_size_t size;
3303         vm_object_t object;
3304         vm_ooffset_t offset;
3305         unsigned int last_timestamp;
3306         boolean_t failed;
3307
3308         vm_map_lock_read(map);
3309         VM_MAP_RANGE_CHECK(map, start, end);
3310         if (!vm_map_lookup_entry(map, start, &entry)) {
3311                 vm_map_unlock_read(map);
3312                 return (KERN_INVALID_ADDRESS);
3313         } else if (start == end) {
3314                 start = entry->start;
3315                 end = entry->end;
3316         }
3317         /*
3318          * Make a first pass to check for user-wired memory and holes.
3319          */
3320         for (current = entry; current->start < end; current = current->next) {
3321                 if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
3322                         vm_map_unlock_read(map);
3323                         return (KERN_INVALID_ARGUMENT);
3324                 }
3325                 if (end > current->end &&
3326                     current->end != current->next->start) {
3327                         vm_map_unlock_read(map);
3328                         return (KERN_INVALID_ADDRESS);
3329                 }
3330         }
3331
3332         if (invalidate)
3333                 pmap_remove(map->pmap, start, end);
3334         failed = FALSE;
3335
3336         /*
3337          * Make a second pass, cleaning/uncaching pages from the indicated
3338          * objects as we go.
3339          */
3340         for (current = entry; current->start < end;) {
3341                 offset = current->offset + (start - current->start);
3342                 size = (end <= current->end ? end : current->end) - start;
3343                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
3344                         vm_map_t smap;
3345                         vm_map_entry_t tentry;
3346                         vm_size_t tsize;
3347
3348                         smap = current->object.sub_map;
3349                         vm_map_lock_read(smap);
3350                         (void) vm_map_lookup_entry(smap, offset, &tentry);
3351                         tsize = tentry->end - offset;
3352                         if (tsize < size)
3353                                 size = tsize;
3354                         object = tentry->object.vm_object;
3355                         offset = tentry->offset + (offset - tentry->start);
3356                         vm_map_unlock_read(smap);
3357                 } else {
3358                         object = current->object.vm_object;
3359                 }
3360                 vm_object_reference(object);
3361                 last_timestamp = map->timestamp;
3362                 vm_map_unlock_read(map);
3363                 if (!vm_object_sync(object, offset, size, syncio, invalidate))
3364                         failed = TRUE;
3365                 start += size;
3366                 vm_object_deallocate(object);
3367                 vm_map_lock_read(map);
3368                 if (last_timestamp == map->timestamp ||
3369                     !vm_map_lookup_entry(map, start, &current))
3370                         current = current->next;
3371         }
3372
3373         vm_map_unlock_read(map);
3374         return (failed ? KERN_FAILURE : KERN_SUCCESS);
3375 }
3376
3377 /*
3378  *      vm_map_entry_unwire:    [ internal use only ]
3379  *
3380  *      Make the region specified by this entry pageable.
3381  *
3382  *      The map in question should be locked.
3383  *      [This is the reason for this routine's existence.]
3384  */
3385 static void
3386 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
3387 {
3388         vm_size_t size;
3389
3390         VM_MAP_ASSERT_LOCKED(map);
3391         KASSERT(entry->wired_count > 0,
3392             ("vm_map_entry_unwire: entry %p isn't wired", entry));
3393
3394         size = entry->end - entry->start;
3395         if ((entry->eflags & MAP_ENTRY_USER_WIRED) != 0)
3396                 vm_map_wire_user_count_sub(atop(size));
3397         pmap_unwire(map->pmap, entry->start, entry->end);
3398         vm_object_unwire(entry->object.vm_object, entry->offset, size,
3399             PQ_ACTIVE);
3400         entry->wired_count = 0;
3401 }
3402
3403 static void
3404 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
3405 {
3406
3407         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
3408                 vm_object_deallocate(entry->object.vm_object);
3409         uma_zfree(system_map ? kmapentzone : mapentzone, entry);
3410 }
3411
3412 /*
3413  *      vm_map_entry_delete:    [ internal use only ]
3414  *
3415  *      Deallocate the given entry from the target map.
3416  */
3417 static void
3418 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
3419 {
3420         vm_object_t object;
3421         vm_pindex_t offidxstart, offidxend, count, size1;
3422         vm_size_t size;
3423
3424         vm_map_entry_unlink(map, entry, UNLINK_MERGE_NONE);
3425         object = entry->object.vm_object;
3426
3427         if ((entry->eflags & MAP_ENTRY_GUARD) != 0) {
3428                 MPASS(entry->cred == NULL);
3429                 MPASS((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0);
3430                 MPASS(object == NULL);
3431                 vm_map_entry_deallocate(entry, map->system_map);
3432                 return;
3433         }
3434
3435         size = entry->end - entry->start;
3436         map->size -= size;
3437
3438         if (entry->cred != NULL) {
3439                 swap_release_by_cred(size, entry->cred);
3440                 crfree(entry->cred);
3441         }
3442
3443         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
3444             (object != NULL)) {
3445                 KASSERT(entry->cred == NULL || object->cred == NULL ||
3446                     (entry->eflags & MAP_ENTRY_NEEDS_COPY),
3447                     ("OVERCOMMIT vm_map_entry_delete: both cred %p", entry));
3448                 count = atop(size);
3449                 offidxstart = OFF_TO_IDX(entry->offset);
3450                 offidxend = offidxstart + count;
3451                 VM_OBJECT_WLOCK(object);
3452                 if (object->ref_count != 1 && ((object->flags & (OBJ_NOSPLIT |
3453                     OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
3454                     object == kernel_object)) {
3455                         vm_object_collapse(object);
3456
3457                         /*
3458                          * The option OBJPR_NOTMAPPED can be passed here
3459                          * because vm_map_delete() already performed
3460                          * pmap_remove() on the only mapping to this range
3461                          * of pages. 
3462                          */
3463                         vm_object_page_remove(object, offidxstart, offidxend,
3464                             OBJPR_NOTMAPPED);
3465                         if (object->type == OBJT_SWAP)
3466                                 swap_pager_freespace(object, offidxstart,
3467                                     count);
3468                         if (offidxend >= object->size &&
3469                             offidxstart < object->size) {
3470                                 size1 = object->size;
3471                                 object->size = offidxstart;
3472                                 if (object->cred != NULL) {
3473                                         size1 -= object->size;
3474                                         KASSERT(object->charge >= ptoa(size1),
3475                                             ("object %p charge < 0", object));
3476                                         swap_release_by_cred(ptoa(size1),
3477                                             object->cred);
3478                                         object->charge -= ptoa(size1);
3479                                 }
3480                         }
3481                 }
3482                 VM_OBJECT_WUNLOCK(object);
3483         } else
3484                 entry->object.vm_object = NULL;
3485         if (map->system_map)
3486                 vm_map_entry_deallocate(entry, TRUE);
3487         else {
3488                 entry->next = curthread->td_map_def_user;
3489                 curthread->td_map_def_user = entry;
3490         }
3491 }
3492
3493 /*
3494  *      vm_map_delete:  [ internal use only ]
3495  *
3496  *      Deallocates the given address range from the target
3497  *      map.
3498  */
3499 int
3500 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
3501 {
3502         vm_map_entry_t entry;
3503         vm_map_entry_t first_entry;
3504
3505         VM_MAP_ASSERT_LOCKED(map);
3506         if (start == end)
3507                 return (KERN_SUCCESS);
3508
3509         /*
3510          * Find the start of the region, and clip it
3511          */
3512         if (!vm_map_lookup_entry(map, start, &first_entry))
3513                 entry = first_entry->next;
3514         else {
3515                 entry = first_entry;
3516                 vm_map_clip_start(map, entry, start);
3517         }
3518
3519         /*
3520          * Step through all entries in this region
3521          */
3522         while (entry->start < end) {
3523                 vm_map_entry_t next;
3524
3525                 /*
3526                  * Wait for wiring or unwiring of an entry to complete.
3527                  * Also wait for any system wirings to disappear on
3528                  * user maps.
3529                  */
3530                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
3531                     (vm_map_pmap(map) != kernel_pmap &&
3532                     vm_map_entry_system_wired_count(entry) != 0)) {
3533                         unsigned int last_timestamp;
3534                         vm_offset_t saved_start;
3535                         vm_map_entry_t tmp_entry;
3536
3537                         saved_start = entry->start;
3538                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
3539                         last_timestamp = map->timestamp;
3540                         (void) vm_map_unlock_and_wait(map, 0);
3541                         vm_map_lock(map);
3542                         if (last_timestamp + 1 != map->timestamp) {
3543                                 /*
3544                                  * Look again for the entry because the map was
3545                                  * modified while it was unlocked.
3546                                  * Specifically, the entry may have been
3547                                  * clipped, merged, or deleted.
3548                                  */
3549                                 if (!vm_map_lookup_entry(map, saved_start,
3550                                                          &tmp_entry))
3551                                         entry = tmp_entry->next;
3552                                 else {
3553                                         entry = tmp_entry;
3554                                         vm_map_clip_start(map, entry,
3555                                                           saved_start);
3556                                 }
3557                         }
3558                         continue;
3559                 }
3560                 vm_map_clip_end(map, entry, end);
3561
3562                 next = entry->next;
3563
3564                 /*
3565                  * Unwire before removing addresses from the pmap; otherwise,
3566                  * unwiring will put the entries back in the pmap.
3567                  */
3568                 if (entry->wired_count != 0)
3569                         vm_map_entry_unwire(map, entry);
3570
3571                 /*
3572                  * Remove mappings for the pages, but only if the
3573                  * mappings could exist.  For instance, it does not
3574                  * make sense to call pmap_remove() for guard entries.
3575                  */
3576                 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0 ||
3577                     entry->object.vm_object != NULL)
3578                         pmap_remove(map->pmap, entry->start, entry->end);
3579
3580                 if (entry->end == map->anon_loc)
3581                         map->anon_loc = entry->start;
3582
3583                 /*
3584                  * Delete the entry only after removing all pmap
3585                  * entries pointing to its pages.  (Otherwise, its
3586                  * page frames may be reallocated, and any modify bits
3587                  * will be set in the wrong object!)
3588                  */
3589                 vm_map_entry_delete(map, entry);
3590                 entry = next;
3591         }
3592         return (KERN_SUCCESS);
3593 }
3594
3595 /*
3596  *      vm_map_remove:
3597  *
3598  *      Remove the given address range from the target map.
3599  *      This is the exported form of vm_map_delete.
3600  */
3601 int
3602 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
3603 {
3604         int result;
3605
3606         vm_map_lock(map);
3607         VM_MAP_RANGE_CHECK(map, start, end);
3608         result = vm_map_delete(map, start, end);
3609         vm_map_unlock(map);
3610         return (result);
3611 }
3612
3613 /*
3614  *      vm_map_check_protection:
3615  *
3616  *      Assert that the target map allows the specified privilege on the
3617  *      entire address region given.  The entire region must be allocated.
3618  *
3619  *      WARNING!  This code does not and should not check whether the
3620  *      contents of the region is accessible.  For example a smaller file
3621  *      might be mapped into a larger address space.
3622  *
3623  *      NOTE!  This code is also called by munmap().
3624  *
3625  *      The map must be locked.  A read lock is sufficient.
3626  */
3627 boolean_t
3628 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
3629                         vm_prot_t protection)
3630 {
3631         vm_map_entry_t entry;
3632         vm_map_entry_t tmp_entry;
3633
3634         if (!vm_map_lookup_entry(map, start, &tmp_entry))
3635                 return (FALSE);
3636         entry = tmp_entry;
3637
3638         while (start < end) {
3639                 /*
3640                  * No holes allowed!
3641                  */
3642                 if (start < entry->start)
3643                         return (FALSE);
3644                 /*
3645                  * Check protection associated with entry.
3646                  */
3647                 if ((entry->protection & protection) != protection)
3648                         return (FALSE);
3649                 /* go to next entry */
3650                 start = entry->end;
3651                 entry = entry->next;
3652         }
3653         return (TRUE);
3654 }
3655
3656 /*
3657  *      vm_map_copy_entry:
3658  *
3659  *      Copies the contents of the source entry to the destination
3660  *      entry.  The entries *must* be aligned properly.
3661  */
3662 static void
3663 vm_map_copy_entry(
3664         vm_map_t src_map,
3665         vm_map_t dst_map,
3666         vm_map_entry_t src_entry,
3667         vm_map_entry_t dst_entry,
3668         vm_ooffset_t *fork_charge)
3669 {
3670         vm_object_t src_object;
3671         vm_map_entry_t fake_entry;
3672         vm_offset_t size;
3673         struct ucred *cred;
3674         int charged;
3675
3676         VM_MAP_ASSERT_LOCKED(dst_map);
3677
3678         if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
3679                 return;
3680
3681         if (src_entry->wired_count == 0 ||
3682             (src_entry->protection & VM_PROT_WRITE) == 0) {
3683                 /*
3684                  * If the source entry is marked needs_copy, it is already
3685                  * write-protected.
3686                  */
3687                 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0 &&
3688                     (src_entry->protection & VM_PROT_WRITE) != 0) {
3689                         pmap_protect(src_map->pmap,
3690                             src_entry->start,
3691                             src_entry->end,
3692                             src_entry->protection & ~VM_PROT_WRITE);
3693                 }
3694
3695                 /*
3696                  * Make a copy of the object.
3697                  */
3698                 size = src_entry->end - src_entry->start;
3699                 if ((src_object = src_entry->object.vm_object) != NULL) {
3700                         VM_OBJECT_WLOCK(src_object);
3701                         charged = ENTRY_CHARGED(src_entry);
3702                         if (src_object->handle == NULL &&
3703                             (src_object->type == OBJT_DEFAULT ||
3704                             src_object->type == OBJT_SWAP)) {
3705                                 vm_object_collapse(src_object);
3706                                 if ((src_object->flags & (OBJ_NOSPLIT |
3707                                     OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
3708                                         vm_object_split(src_entry);
3709                                         src_object =
3710                                             src_entry->object.vm_object;
3711                                 }
3712                         }
3713                         vm_object_reference_locked(src_object);
3714                         vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
3715                         if (src_entry->cred != NULL &&
3716                             !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
3717                                 KASSERT(src_object->cred == NULL,
3718                                     ("OVERCOMMIT: vm_map_copy_entry: cred %p",
3719                                      src_object));
3720                                 src_object->cred = src_entry->cred;
3721                                 src_object->charge = size;
3722                         }
3723                         VM_OBJECT_WUNLOCK(src_object);
3724                         dst_entry->object.vm_object = src_object;
3725                         if (charged) {
3726                                 cred = curthread->td_ucred;
3727                                 crhold(cred);
3728                                 dst_entry->cred = cred;
3729                                 *fork_charge += size;
3730                                 if (!(src_entry->eflags &
3731                                       MAP_ENTRY_NEEDS_COPY)) {
3732                                         crhold(cred);
3733                                         src_entry->cred = cred;
3734                                         *fork_charge += size;
3735                                 }
3736                         }
3737                         src_entry->eflags |= MAP_ENTRY_COW |
3738                             MAP_ENTRY_NEEDS_COPY;
3739                         dst_entry->eflags |= MAP_ENTRY_COW |
3740                             MAP_ENTRY_NEEDS_COPY;
3741                         dst_entry->offset = src_entry->offset;
3742                         if (src_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3743                                 /*
3744                                  * MAP_ENTRY_VN_WRITECNT cannot
3745                                  * indicate write reference from
3746                                  * src_entry, since the entry is
3747                                  * marked as needs copy.  Allocate a
3748                                  * fake entry that is used to
3749                                  * decrement object->un_pager.vnp.writecount
3750                                  * at the appropriate time.  Attach
3751                                  * fake_entry to the deferred list.
3752                                  */
3753                                 fake_entry = vm_map_entry_create(dst_map);
3754                                 fake_entry->eflags = MAP_ENTRY_VN_WRITECNT;
3755                                 src_entry->eflags &= ~MAP_ENTRY_VN_WRITECNT;
3756                                 vm_object_reference(src_object);
3757                                 fake_entry->object.vm_object = src_object;
3758                                 fake_entry->start = src_entry->start;
3759                                 fake_entry->end = src_entry->end;
3760                                 fake_entry->next = curthread->td_map_def_user;
3761                                 curthread->td_map_def_user = fake_entry;
3762                         }
3763
3764                         pmap_copy(dst_map->pmap, src_map->pmap,
3765                             dst_entry->start, dst_entry->end - dst_entry->start,
3766                             src_entry->start);
3767                 } else {
3768                         dst_entry->object.vm_object = NULL;
3769                         dst_entry->offset = 0;
3770                         if (src_entry->cred != NULL) {
3771                                 dst_entry->cred = curthread->td_ucred;
3772                                 crhold(dst_entry->cred);
3773                                 *fork_charge += size;
3774                         }
3775                 }
3776         } else {
3777                 /*
3778                  * We don't want to make writeable wired pages copy-on-write.
3779                  * Immediately copy these pages into the new map by simulating
3780                  * page faults.  The new pages are pageable.
3781                  */
3782                 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
3783                     fork_charge);
3784         }
3785 }
3786
3787 /*
3788  * vmspace_map_entry_forked:
3789  * Update the newly-forked vmspace each time a map entry is inherited
3790  * or copied.  The values for vm_dsize and vm_tsize are approximate
3791  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3792  */
3793 static void
3794 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3795     vm_map_entry_t entry)
3796 {
3797         vm_size_t entrysize;
3798         vm_offset_t newend;
3799
3800         if ((entry->eflags & MAP_ENTRY_GUARD) != 0)
3801                 return;
3802         entrysize = entry->end - entry->start;
3803         vm2->vm_map.size += entrysize;
3804         if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3805                 vm2->vm_ssize += btoc(entrysize);
3806         } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3807             entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3808                 newend = MIN(entry->end,
3809                     (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3810                 vm2->vm_dsize += btoc(newend - entry->start);
3811         } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3812             entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3813                 newend = MIN(entry->end,
3814                     (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3815                 vm2->vm_tsize += btoc(newend - entry->start);
3816         }
3817 }
3818
3819 /*
3820  * vmspace_fork:
3821  * Create a new process vmspace structure and vm_map
3822  * based on those of an existing process.  The new map
3823  * is based on the old map, according to the inheritance
3824  * values on the regions in that map.
3825  *
3826  * XXX It might be worth coalescing the entries added to the new vmspace.
3827  *
3828  * The source map must not be locked.
3829  */
3830 struct vmspace *
3831 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3832 {
3833         struct vmspace *vm2;
3834         vm_map_t new_map, old_map;
3835         vm_map_entry_t new_entry, old_entry;
3836         vm_object_t object;
3837         int error, locked;
3838         vm_inherit_t inh;
3839
3840         old_map = &vm1->vm_map;
3841         /* Copy immutable fields of vm1 to vm2. */
3842         vm2 = vmspace_alloc(vm_map_min(old_map), vm_map_max(old_map),
3843             pmap_pinit);
3844         if (vm2 == NULL)
3845                 return (NULL);
3846
3847         vm2->vm_taddr = vm1->vm_taddr;
3848         vm2->vm_daddr = vm1->vm_daddr;
3849         vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3850         vm_map_lock(old_map);
3851         if (old_map->busy)
3852                 vm_map_wait_busy(old_map);
3853         new_map = &vm2->vm_map;
3854         locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3855         KASSERT(locked, ("vmspace_fork: lock failed"));
3856
3857         error = pmap_vmspace_copy(new_map->pmap, old_map->pmap);
3858         if (error != 0) {
3859                 sx_xunlock(&old_map->lock);
3860                 sx_xunlock(&new_map->lock);
3861                 vm_map_process_deferred();
3862                 vmspace_free(vm2);
3863                 return (NULL);
3864         }
3865
3866         new_map->anon_loc = old_map->anon_loc;
3867
3868         old_entry = old_map->header.next;
3869
3870         while (old_entry != &old_map->header) {
3871                 if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3872                         panic("vm_map_fork: encountered a submap");
3873
3874                 inh = old_entry->inheritance;
3875                 if ((old_entry->eflags & MAP_ENTRY_GUARD) != 0 &&
3876                     inh != VM_INHERIT_NONE)
3877                         inh = VM_INHERIT_COPY;
3878
3879                 switch (inh) {
3880                 case VM_INHERIT_NONE:
3881                         break;
3882
3883                 case VM_INHERIT_SHARE:
3884                         /*
3885                          * Clone the entry, creating the shared object if necessary.
3886                          */
3887                         object = old_entry->object.vm_object;
3888                         if (object == NULL) {
3889                                 object = vm_object_allocate(OBJT_DEFAULT,
3890                                         atop(old_entry->end - old_entry->start));
3891                                 old_entry->object.vm_object = object;
3892                                 old_entry->offset = 0;
3893                                 if (old_entry->cred != NULL) {
3894                                         object->cred = old_entry->cred;
3895                                         object->charge = old_entry->end -
3896                                             old_entry->start;
3897                                         old_entry->cred = NULL;
3898                                 }
3899                         }
3900
3901                         /*
3902                          * Add the reference before calling vm_object_shadow
3903                          * to insure that a shadow object is created.
3904                          */
3905                         vm_object_reference(object);
3906                         if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3907                                 vm_object_shadow(&old_entry->object.vm_object,
3908                                     &old_entry->offset,
3909                                     old_entry->end - old_entry->start);
3910                                 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3911                                 /* Transfer the second reference too. */
3912                                 vm_object_reference(
3913                                     old_entry->object.vm_object);
3914
3915                                 /*
3916                                  * As in vm_map_simplify_entry(), the
3917                                  * vnode lock will not be acquired in
3918                                  * this call to vm_object_deallocate().
3919                                  */
3920                                 vm_object_deallocate(object);
3921                                 object = old_entry->object.vm_object;
3922                         }
3923                         VM_OBJECT_WLOCK(object);
3924                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
3925                         if (old_entry->cred != NULL) {
3926                                 KASSERT(object->cred == NULL, ("vmspace_fork both cred"));
3927                                 object->cred = old_entry->cred;
3928                                 object->charge = old_entry->end - old_entry->start;
3929                                 old_entry->cred = NULL;
3930                         }
3931
3932                         /*
3933                          * Assert the correct state of the vnode
3934                          * v_writecount while the object is locked, to
3935                          * not relock it later for the assertion
3936                          * correctness.
3937                          */
3938                         if (old_entry->eflags & MAP_ENTRY_VN_WRITECNT &&
3939                             object->type == OBJT_VNODE) {
3940                                 KASSERT(((struct vnode *)object->handle)->
3941                                     v_writecount > 0,
3942                                     ("vmspace_fork: v_writecount %p", object));
3943                                 KASSERT(object->un_pager.vnp.writemappings > 0,
3944                                     ("vmspace_fork: vnp.writecount %p",
3945                                     object));
3946                         }
3947                         VM_OBJECT_WUNLOCK(object);
3948
3949                         /*
3950                          * Clone the entry, referencing the shared object.
3951                          */
3952                         new_entry = vm_map_entry_create(new_map);
3953                         *new_entry = *old_entry;
3954                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3955                             MAP_ENTRY_IN_TRANSITION);
3956                         new_entry->wiring_thread = NULL;
3957                         new_entry->wired_count = 0;
3958                         if (new_entry->eflags & MAP_ENTRY_VN_WRITECNT) {
3959                                 vnode_pager_update_writecount(object,
3960                                     new_entry->start, new_entry->end);
3961                         }
3962                         vm_map_entry_set_vnode_text(new_entry, true);
3963
3964                         /*
3965                          * Insert the entry into the new map -- we know we're
3966                          * inserting at the end of the new map.
3967                          */
3968                         vm_map_entry_link(new_map, new_entry);
3969                         vmspace_map_entry_forked(vm1, vm2, new_entry);
3970
3971                         /*
3972                          * Update the physical map
3973                          */
3974                         pmap_copy(new_map->pmap, old_map->pmap,
3975                             new_entry->start,
3976                             (old_entry->end - old_entry->start),
3977                             old_entry->start);
3978                         break;
3979
3980                 case VM_INHERIT_COPY:
3981                         /*
3982                          * Clone the entry and link into the map.
3983                          */
3984                         new_entry = vm_map_entry_create(new_map);
3985                         *new_entry = *old_entry;
3986                         /*
3987                          * Copied entry is COW over the old object.
3988                          */
3989                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3990                             MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_VN_WRITECNT);
3991                         new_entry->wiring_thread = NULL;
3992                         new_entry->wired_count = 0;
3993                         new_entry->object.vm_object = NULL;
3994                         new_entry->cred = NULL;
3995                         vm_map_entry_link(new_map, new_entry);
3996                         vmspace_map_entry_forked(vm1, vm2, new_entry);
3997                         vm_map_copy_entry(old_map, new_map, old_entry,
3998                             new_entry, fork_charge);
3999                         vm_map_entry_set_vnode_text(new_entry, true);
4000                         break;
4001
4002                 case VM_INHERIT_ZERO:
4003                         /*
4004                          * Create a new anonymous mapping entry modelled from
4005                          * the old one.
4006                          */
4007                         new_entry = vm_map_entry_create(new_map);
4008                         memset(new_entry, 0, sizeof(*new_entry));
4009
4010                         new_entry->start = old_entry->start;
4011                         new_entry->end = old_entry->end;
4012                         new_entry->eflags = old_entry->eflags &
4013                             ~(MAP_ENTRY_USER_WIRED | MAP_ENTRY_IN_TRANSITION |
4014                             MAP_ENTRY_VN_WRITECNT | MAP_ENTRY_VN_EXEC);
4015                         new_entry->protection = old_entry->protection;
4016                         new_entry->max_protection = old_entry->max_protection;
4017                         new_entry->inheritance = VM_INHERIT_ZERO;
4018
4019                         vm_map_entry_link(new_map, new_entry);
4020                         vmspace_map_entry_forked(vm1, vm2, new_entry);
4021
4022                         new_entry->cred = curthread->td_ucred;
4023                         crhold(new_entry->cred);
4024                         *fork_charge += (new_entry->end - new_entry->start);
4025
4026                         break;
4027                 }
4028                 old_entry = old_entry->next;
4029         }
4030         /*
4031          * Use inlined vm_map_unlock() to postpone handling the deferred
4032          * map entries, which cannot be done until both old_map and
4033          * new_map locks are released.
4034          */
4035         sx_xunlock(&old_map->lock);
4036         sx_xunlock(&new_map->lock);
4037         vm_map_process_deferred();
4038
4039         return (vm2);
4040 }
4041
4042 /*
4043  * Create a process's stack for exec_new_vmspace().  This function is never
4044  * asked to wire the newly created stack.
4045  */
4046 int
4047 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4048     vm_prot_t prot, vm_prot_t max, int cow)
4049 {
4050         vm_size_t growsize, init_ssize;
4051         rlim_t vmemlim;
4052         int rv;
4053
4054         MPASS((map->flags & MAP_WIREFUTURE) == 0);
4055         growsize = sgrowsiz;
4056         init_ssize = (max_ssize < growsize) ? max_ssize : growsize;
4057         vm_map_lock(map);
4058         vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4059         /* If we would blow our VMEM resource limit, no go */
4060         if (map->size + init_ssize > vmemlim) {
4061                 rv = KERN_NO_SPACE;
4062                 goto out;
4063         }
4064         rv = vm_map_stack_locked(map, addrbos, max_ssize, growsize, prot,
4065             max, cow);
4066 out:
4067         vm_map_unlock(map);
4068         return (rv);
4069 }
4070
4071 static int stack_guard_page = 1;
4072 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RWTUN,
4073     &stack_guard_page, 0,
4074     "Specifies the number of guard pages for a stack that grows");
4075
4076 static int
4077 vm_map_stack_locked(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
4078     vm_size_t growsize, vm_prot_t prot, vm_prot_t max, int cow)
4079 {
4080         vm_map_entry_t new_entry, prev_entry;
4081         vm_offset_t bot, gap_bot, gap_top, top;
4082         vm_size_t init_ssize, sgp;
4083         int orient, rv;
4084
4085         /*
4086          * The stack orientation is piggybacked with the cow argument.
4087          * Extract it into orient and mask the cow argument so that we
4088          * don't pass it around further.
4089          */
4090         orient = cow & (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP);
4091         KASSERT(orient != 0, ("No stack grow direction"));
4092         KASSERT(orient != (MAP_STACK_GROWS_DOWN | MAP_STACK_GROWS_UP),
4093             ("bi-dir stack"));
4094
4095         if (addrbos < vm_map_min(map) ||
4096             addrbos + max_ssize > vm_map_max(map) ||
4097             addrbos + max_ssize <= addrbos)
4098                 return (KERN_INVALID_ADDRESS);
4099         sgp = (vm_size_t)stack_guard_page * PAGE_SIZE;
4100         if (sgp >= max_ssize)
4101                 return (KERN_INVALID_ARGUMENT);
4102
4103         init_ssize = growsize;
4104         if (max_ssize < init_ssize + sgp)
4105                 init_ssize = max_ssize - sgp;
4106
4107         /* If addr is already mapped, no go */
4108         if (vm_map_lookup_entry(map, addrbos, &prev_entry))
4109                 return (KERN_NO_SPACE);
4110
4111         /*
4112          * If we can't accommodate max_ssize in the current mapping, no go.
4113          */
4114         if (prev_entry->next->start < addrbos + max_ssize)
4115                 return (KERN_NO_SPACE);
4116
4117         /*
4118          * We initially map a stack of only init_ssize.  We will grow as
4119          * needed later.  Depending on the orientation of the stack (i.e.
4120          * the grow direction) we either map at the top of the range, the
4121          * bottom of the range or in the middle.
4122          *
4123          * Note: we would normally expect prot and max to be VM_PROT_ALL,
4124          * and cow to be 0.  Possibly we should eliminate these as input
4125          * parameters, and just pass these values here in the insert call.
4126          */
4127         if (orient == MAP_STACK_GROWS_DOWN) {
4128                 bot = addrbos + max_ssize - init_ssize;
4129                 top = bot + init_ssize;
4130                 gap_bot = addrbos;
4131                 gap_top = bot;
4132         } else /* if (orient == MAP_STACK_GROWS_UP) */ {
4133                 bot = addrbos;
4134                 top = bot + init_ssize;
4135                 gap_bot = top;
4136                 gap_top = addrbos + max_ssize;
4137         }
4138         rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
4139         if (rv != KERN_SUCCESS)
4140                 return (rv);
4141         new_entry = prev_entry->next;
4142         KASSERT(new_entry->end == top || new_entry->start == bot,
4143             ("Bad entry start/end for new stack entry"));
4144         KASSERT((orient & MAP_STACK_GROWS_DOWN) == 0 ||
4145             (new_entry->eflags & MAP_ENTRY_GROWS_DOWN) != 0,
4146             ("new entry lacks MAP_ENTRY_GROWS_DOWN"));
4147         KASSERT((orient & MAP_STACK_GROWS_UP) == 0 ||
4148             (new_entry->eflags & MAP_ENTRY_GROWS_UP) != 0,
4149             ("new entry lacks MAP_ENTRY_GROWS_UP"));
4150         rv = vm_map_insert(map, NULL, 0, gap_bot, gap_top, VM_PROT_NONE,
4151             VM_PROT_NONE, MAP_CREATE_GUARD | (orient == MAP_STACK_GROWS_DOWN ?
4152             MAP_CREATE_STACK_GAP_DN : MAP_CREATE_STACK_GAP_UP));
4153         if (rv != KERN_SUCCESS)
4154                 (void)vm_map_delete(map, bot, top);
4155         return (rv);
4156 }
4157
4158 /*
4159  * Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if we
4160  * successfully grow the stack.
4161  */
4162 static int
4163 vm_map_growstack(vm_map_t map, vm_offset_t addr, vm_map_entry_t gap_entry)
4164 {
4165         vm_map_entry_t stack_entry;
4166         struct proc *p;
4167         struct vmspace *vm;
4168         struct ucred *cred;
4169         vm_offset_t gap_end, gap_start, grow_start;
4170         size_t grow_amount, guard, max_grow;
4171         rlim_t lmemlim, stacklim, vmemlim;
4172         int rv, rv1;
4173         bool gap_deleted, grow_down, is_procstack;
4174 #ifdef notyet
4175         uint64_t limit;
4176 #endif
4177 #ifdef RACCT
4178         int error;
4179 #endif
4180
4181         p = curproc;
4182         vm = p->p_vmspace;
4183
4184         /*
4185          * Disallow stack growth when the access is performed by a
4186          * debugger or AIO daemon.  The reason is that the wrong
4187          * resource limits are applied.
4188          */
4189         if (map != &p->p_vmspace->vm_map || p->p_textvp == NULL)
4190                 return (KERN_FAILURE);
4191
4192         MPASS(!map->system_map);
4193
4194         guard = stack_guard_page * PAGE_SIZE;
4195         lmemlim = lim_cur(curthread, RLIMIT_MEMLOCK);
4196         stacklim = lim_cur(curthread, RLIMIT_STACK);
4197         vmemlim = lim_cur(curthread, RLIMIT_VMEM);
4198 retry:
4199         /* If addr is not in a hole for a stack grow area, no need to grow. */
4200         if (gap_entry == NULL && !vm_map_lookup_entry(map, addr, &gap_entry))
4201                 return (KERN_FAILURE);
4202         if ((gap_entry->eflags & MAP_ENTRY_GUARD) == 0)
4203                 return (KERN_SUCCESS);
4204         if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_DN) != 0) {
4205                 stack_entry = gap_entry->next;
4206                 if ((stack_entry->eflags & MAP_ENTRY_GROWS_DOWN) == 0 ||
4207                     stack_entry->start != gap_entry->end)
4208                         return (KERN_FAILURE);
4209                 grow_amount = round_page(stack_entry->start - addr);
4210                 grow_down = true;
4211         } else if ((gap_entry->eflags & MAP_ENTRY_STACK_GAP_UP) != 0) {
4212                 stack_entry = gap_entry->prev;
4213                 if ((stack_entry->eflags & MAP_ENTRY_GROWS_UP) == 0 ||
4214                     stack_entry->end != gap_entry->start)
4215                         return (KERN_FAILURE);
4216                 grow_amount = round_page(addr + 1 - stack_entry->end);
4217                 grow_down = false;
4218         } else {
4219                 return (KERN_FAILURE);
4220         }
4221         max_grow = gap_entry->end - gap_entry->start;
4222         if (guard > max_grow)
4223                 return (KERN_NO_SPACE);
4224         max_grow -= guard;
4225         if (grow_amount > max_grow)
4226                 return (KERN_NO_SPACE);
4227
4228         /*
4229          * If this is the main process stack, see if we're over the stack
4230          * limit.
4231          */
4232         is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr &&
4233             addr < (vm_offset_t)p->p_sysent->sv_usrstack;
4234         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim))
4235                 return (KERN_NO_SPACE);
4236
4237 #ifdef RACCT
4238         if (racct_enable) {
4239                 PROC_LOCK(p);
4240                 if (is_procstack && racct_set(p, RACCT_STACK,
4241                     ctob(vm->vm_ssize) + grow_amount)) {
4242                         PROC_UNLOCK(p);
4243                         return (KERN_NO_SPACE);
4244                 }
4245                 PROC_UNLOCK(p);
4246         }
4247 #endif
4248
4249         grow_amount = roundup(grow_amount, sgrowsiz);
4250         if (grow_amount > max_grow)
4251                 grow_amount = max_grow;
4252         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
4253                 grow_amount = trunc_page((vm_size_t)stacklim) -
4254                     ctob(vm->vm_ssize);
4255         }
4256
4257 #ifdef notyet
4258         PROC_LOCK(p);
4259         limit = racct_get_available(p, RACCT_STACK);
4260         PROC_UNLOCK(p);
4261         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > limit))
4262                 grow_amount = limit - ctob(vm->vm_ssize);
4263 #endif
4264
4265         if (!old_mlock && (map->flags & MAP_WIREFUTURE) != 0) {
4266                 if (ptoa(pmap_wired_count(map->pmap)) + grow_amount > lmemlim) {
4267                         rv = KERN_NO_SPACE;
4268                         goto out;
4269                 }
4270 #ifdef RACCT
4271                 if (racct_enable) {
4272                         PROC_LOCK(p);
4273                         if (racct_set(p, RACCT_MEMLOCK,
4274                             ptoa(pmap_wired_count(map->pmap)) + grow_amount)) {
4275                                 PROC_UNLOCK(p);
4276                                 rv = KERN_NO_SPACE;
4277                                 goto out;
4278                         }
4279                         PROC_UNLOCK(p);
4280                 }
4281 #endif
4282         }
4283
4284         /* If we would blow our VMEM resource limit, no go */
4285         if (map->size + grow_amount > vmemlim) {
4286                 rv = KERN_NO_SPACE;
4287                 goto out;
4288         }
4289 #ifdef RACCT
4290         if (racct_enable) {
4291                 PROC_LOCK(p);
4292                 if (racct_set(p, RACCT_VMEM, map->size + grow_amount)) {
4293                         PROC_UNLOCK(p);
4294                         rv = KERN_NO_SPACE;
4295                         goto out;
4296                 }
4297                 PROC_UNLOCK(p);
4298         }
4299 #endif
4300
4301         if (vm_map_lock_upgrade(map)) {
4302                 gap_entry = NULL;
4303                 vm_map_lock_read(map);
4304                 goto retry;
4305         }
4306
4307         if (grow_down) {
4308                 grow_start = gap_entry->end - grow_amount;
4309                 if (gap_entry->start + grow_amount == gap_entry->end) {
4310                         gap_start = gap_entry->start;
4311                         gap_end = gap_entry->end;
4312                         vm_map_entry_delete(map, gap_entry);
4313                         gap_deleted = true;
4314                 } else {
4315                         MPASS(gap_entry->start < gap_entry->end - grow_amount);
4316                         gap_entry->end -= grow_amount;
4317                         vm_map_entry_resize_free(map, gap_entry);
4318                         gap_deleted = false;
4319                 }
4320                 rv = vm_map_insert(map, NULL, 0, grow_start,
4321                     grow_start + grow_amount,
4322                     stack_entry->protection, stack_entry->max_protection,
4323                     MAP_STACK_GROWS_DOWN);
4324                 if (rv != KERN_SUCCESS) {
4325                         if (gap_deleted) {
4326                                 rv1 = vm_map_insert(map, NULL, 0, gap_start,
4327                                     gap_end, VM_PROT_NONE, VM_PROT_NONE,
4328                                     MAP_CREATE_GUARD | MAP_CREATE_STACK_GAP_DN);
4329                                 MPASS(rv1 == KERN_SUCCESS);
4330                         } else {
4331                                 gap_entry->end += grow_amount;
4332                                 vm_map_entry_resize_free(map, gap_entry);
4333                         }
4334                 }
4335         } else {
4336                 grow_start = stack_entry->end;
4337                 cred = stack_entry->cred;
4338                 if (cred == NULL && stack_entry->object.vm_object != NULL)
4339                         cred = stack_entry->object.vm_object->cred;
4340                 if (cred != NULL && !swap_reserve_by_cred(grow_amount, cred))
4341                         rv = KERN_NO_SPACE;
4342                 /* Grow the underlying object if applicable. */
4343                 else if (stack_entry->object.vm_object == NULL ||
4344                     vm_object_coalesce(stack_entry->object.vm_object,
4345                     stack_entry->offset,
4346                     (vm_size_t)(stack_entry->end - stack_entry->start),
4347                     (vm_size_t)grow_amount, cred != NULL)) {
4348                         if (gap_entry->start + grow_amount == gap_entry->end)
4349                                 vm_map_entry_delete(map, gap_entry);
4350                         else
4351                                 gap_entry->start += grow_amount;
4352                         stack_entry->end += grow_amount;
4353                         map->size += grow_amount;
4354                         vm_map_entry_resize_free(map, stack_entry);
4355                         rv = KERN_SUCCESS;
4356                 } else
4357                         rv = KERN_FAILURE;
4358         }
4359         if (rv == KERN_SUCCESS && is_procstack)
4360                 vm->vm_ssize += btoc(grow_amount);
4361
4362         /*
4363          * Heed the MAP_WIREFUTURE flag if it was set for this process.
4364          */
4365         if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE) != 0) {
4366                 rv = vm_map_wire_locked(map, grow_start,
4367                     grow_start + grow_amount,
4368                     VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
4369         }
4370         vm_map_lock_downgrade(map);
4371
4372 out:
4373 #ifdef RACCT
4374         if (racct_enable && rv != KERN_SUCCESS) {
4375                 PROC_LOCK(p);
4376                 error = racct_set(p, RACCT_VMEM, map->size);
4377                 KASSERT(error == 0, ("decreasing RACCT_VMEM failed"));
4378                 if (!old_mlock) {
4379                         error = racct_set(p, RACCT_MEMLOCK,
4380                             ptoa(pmap_wired_count(map->pmap)));
4381                         KASSERT(error == 0, ("decreasing RACCT_MEMLOCK failed"));
4382                 }
4383                 error = racct_set(p, RACCT_STACK, ctob(vm->vm_ssize));
4384                 KASSERT(error == 0, ("decreasing RACCT_STACK failed"));
4385                 PROC_UNLOCK(p);
4386         }
4387 #endif
4388
4389         return (rv);
4390 }
4391
4392 /*
4393  * Unshare the specified VM space for exec.  If other processes are
4394  * mapped to it, then create a new one.  The new vmspace is null.
4395  */
4396 int
4397 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
4398 {
4399         struct vmspace *oldvmspace = p->p_vmspace;
4400         struct vmspace *newvmspace;
4401
4402         KASSERT((curthread->td_pflags & TDP_EXECVMSPC) == 0,
4403             ("vmspace_exec recursed"));
4404         newvmspace = vmspace_alloc(minuser, maxuser, pmap_pinit);
4405         if (newvmspace == NULL)
4406                 return (ENOMEM);
4407         newvmspace->vm_swrss = oldvmspace->vm_swrss;
4408         /*
4409          * This code is written like this for prototype purposes.  The
4410          * goal is to avoid running down the vmspace here, but let the
4411          * other process's that are still using the vmspace to finally
4412          * run it down.  Even though there is little or no chance of blocking
4413          * here, it is a good idea to keep this form for future mods.
4414          */
4415         PROC_VMSPACE_LOCK(p);
4416         p->p_vmspace = newvmspace;
4417         PROC_VMSPACE_UNLOCK(p);
4418         if (p == curthread->td_proc)
4419                 pmap_activate(curthread);
4420         curthread->td_pflags |= TDP_EXECVMSPC;
4421         return (0);
4422 }
4423
4424 /*
4425  * Unshare the specified VM space for forcing COW.  This
4426  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
4427  */
4428 int
4429 vmspace_unshare(struct proc *p)
4430 {
4431         struct vmspace *oldvmspace = p->p_vmspace;
4432         struct vmspace *newvmspace;
4433         vm_ooffset_t fork_charge;
4434
4435         if (oldvmspace->vm_refcnt == 1)
4436                 return (0);
4437         fork_charge = 0;
4438         newvmspace = vmspace_fork(oldvmspace, &fork_charge);
4439         if (newvmspace == NULL)
4440                 return (ENOMEM);
4441         if (!swap_reserve_by_cred(fork_charge, p->p_ucred)) {
4442                 vmspace_free(newvmspace);
4443                 return (ENOMEM);
4444         }
4445         PROC_VMSPACE_LOCK(p);
4446         p->p_vmspace = newvmspace;
4447         PROC_VMSPACE_UNLOCK(p);
4448         if (p == curthread->td_proc)
4449                 pmap_activate(curthread);
4450         vmspace_free(oldvmspace);
4451         return (0);
4452 }
4453
4454 /*
4455  *      vm_map_lookup:
4456  *
4457  *      Finds the VM object, offset, and
4458  *      protection for a given virtual address in the
4459  *      specified map, assuming a page fault of the
4460  *      type specified.
4461  *
4462  *      Leaves the map in question locked for read; return
4463  *      values are guaranteed until a vm_map_lookup_done
4464  *      call is performed.  Note that the map argument
4465  *      is in/out; the returned map must be used in
4466  *      the call to vm_map_lookup_done.
4467  *
4468  *      A handle (out_entry) is returned for use in
4469  *      vm_map_lookup_done, to make that fast.
4470  *
4471  *      If a lookup is requested with "write protection"
4472  *      specified, the map may be changed to perform virtual
4473  *      copying operations, although the data referenced will
4474  *      remain the same.
4475  */
4476 int
4477 vm_map_lookup(vm_map_t *var_map,                /* IN/OUT */
4478               vm_offset_t vaddr,
4479               vm_prot_t fault_typea,
4480               vm_map_entry_t *out_entry,        /* OUT */
4481               vm_object_t *object,              /* OUT */
4482               vm_pindex_t *pindex,              /* OUT */
4483               vm_prot_t *out_prot,              /* OUT */
4484               boolean_t *wired)                 /* OUT */
4485 {
4486         vm_map_entry_t entry;
4487         vm_map_t map = *var_map;
4488         vm_prot_t prot;
4489         vm_prot_t fault_type = fault_typea;
4490         vm_object_t eobject;
4491         vm_size_t size;
4492         struct ucred *cred;
4493
4494 RetryLookup:
4495
4496         vm_map_lock_read(map);
4497
4498 RetryLookupLocked:
4499         /*
4500          * Lookup the faulting address.
4501          */
4502         if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
4503                 vm_map_unlock_read(map);
4504                 return (KERN_INVALID_ADDRESS);
4505         }
4506
4507         entry = *out_entry;
4508
4509         /*
4510          * Handle submaps.
4511          */
4512         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4513                 vm_map_t old_map = map;
4514
4515                 *var_map = map = entry->object.sub_map;
4516                 vm_map_unlock_read(old_map);
4517                 goto RetryLookup;
4518         }
4519
4520         /*
4521          * Check whether this task is allowed to have this page.
4522          */
4523         prot = entry->protection;
4524         if ((fault_typea & VM_PROT_FAULT_LOOKUP) != 0) {
4525                 fault_typea &= ~VM_PROT_FAULT_LOOKUP;
4526                 if (prot == VM_PROT_NONE && map != kernel_map &&
4527                     (entry->eflags & MAP_ENTRY_GUARD) != 0 &&
4528                     (entry->eflags & (MAP_ENTRY_STACK_GAP_DN |
4529                     MAP_ENTRY_STACK_GAP_UP)) != 0 &&
4530                     vm_map_growstack(map, vaddr, entry) == KERN_SUCCESS)
4531                         goto RetryLookupLocked;
4532         }
4533         fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4534         if ((fault_type & prot) != fault_type || prot == VM_PROT_NONE) {
4535                 vm_map_unlock_read(map);
4536                 return (KERN_PROTECTION_FAILURE);
4537         }
4538         KASSERT((prot & VM_PROT_WRITE) == 0 || (entry->eflags &
4539             (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY)) !=
4540             (MAP_ENTRY_USER_WIRED | MAP_ENTRY_NEEDS_COPY),
4541             ("entry %p flags %x", entry, entry->eflags));
4542         if ((fault_typea & VM_PROT_COPY) != 0 &&
4543             (entry->max_protection & VM_PROT_WRITE) == 0 &&
4544             (entry->eflags & MAP_ENTRY_COW) == 0) {
4545                 vm_map_unlock_read(map);
4546                 return (KERN_PROTECTION_FAILURE);
4547         }
4548
4549         /*
4550          * If this page is not pageable, we have to get it for all possible
4551          * accesses.
4552          */
4553         *wired = (entry->wired_count != 0);
4554         if (*wired)
4555                 fault_type = entry->protection;
4556         size = entry->end - entry->start;
4557         /*
4558          * If the entry was copy-on-write, we either ...
4559          */
4560         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4561                 /*
4562                  * If we want to write the page, we may as well handle that
4563                  * now since we've got the map locked.
4564                  *
4565                  * If we don't need to write the page, we just demote the
4566                  * permissions allowed.
4567                  */
4568                 if ((fault_type & VM_PROT_WRITE) != 0 ||
4569                     (fault_typea & VM_PROT_COPY) != 0) {
4570                         /*
4571                          * Make a new object, and place it in the object
4572                          * chain.  Note that no new references have appeared
4573                          * -- one just moved from the map to the new
4574                          * object.
4575                          */
4576                         if (vm_map_lock_upgrade(map))
4577                                 goto RetryLookup;
4578
4579                         if (entry->cred == NULL) {
4580                                 /*
4581                                  * The debugger owner is charged for
4582                                  * the memory.
4583                                  */
4584                                 cred = curthread->td_ucred;
4585                                 crhold(cred);
4586                                 if (!swap_reserve_by_cred(size, cred)) {
4587                                         crfree(cred);
4588                                         vm_map_unlock(map);
4589                                         return (KERN_RESOURCE_SHORTAGE);
4590                                 }
4591                                 entry->cred = cred;
4592                         }
4593                         vm_object_shadow(&entry->object.vm_object,
4594                             &entry->offset, size);
4595                         entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
4596                         eobject = entry->object.vm_object;
4597                         if (eobject->cred != NULL) {
4598                                 /*
4599                                  * The object was not shadowed.
4600                                  */
4601                                 swap_release_by_cred(size, entry->cred);
4602                                 crfree(entry->cred);
4603                                 entry->cred = NULL;
4604                         } else if (entry->cred != NULL) {
4605                                 VM_OBJECT_WLOCK(eobject);
4606                                 eobject->cred = entry->cred;
4607                                 eobject->charge = size;
4608                                 VM_OBJECT_WUNLOCK(eobject);
4609                                 entry->cred = NULL;
4610                         }
4611
4612                         vm_map_lock_downgrade(map);
4613                 } else {
4614                         /*
4615                          * We're attempting to read a copy-on-write page --
4616                          * don't allow writes.
4617                          */
4618                         prot &= ~VM_PROT_WRITE;
4619                 }
4620         }
4621
4622         /*
4623          * Create an object if necessary.
4624          */
4625         if (entry->object.vm_object == NULL &&
4626             !map->system_map) {
4627                 if (vm_map_lock_upgrade(map))
4628                         goto RetryLookup;
4629                 entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
4630                     atop(size));
4631                 entry->offset = 0;
4632                 if (entry->cred != NULL) {
4633                         VM_OBJECT_WLOCK(entry->object.vm_object);
4634                         entry->object.vm_object->cred = entry->cred;
4635                         entry->object.vm_object->charge = size;
4636                         VM_OBJECT_WUNLOCK(entry->object.vm_object);
4637                         entry->cred = NULL;
4638                 }
4639                 vm_map_lock_downgrade(map);
4640         }
4641
4642         /*
4643          * Return the object/offset from this entry.  If the entry was
4644          * copy-on-write or empty, it has been fixed up.
4645          */
4646         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4647         *object = entry->object.vm_object;
4648
4649         *out_prot = prot;
4650         return (KERN_SUCCESS);
4651 }
4652
4653 /*
4654  *      vm_map_lookup_locked:
4655  *
4656  *      Lookup the faulting address.  A version of vm_map_lookup that returns 
4657  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
4658  */
4659 int
4660 vm_map_lookup_locked(vm_map_t *var_map,         /* IN/OUT */
4661                      vm_offset_t vaddr,
4662                      vm_prot_t fault_typea,
4663                      vm_map_entry_t *out_entry, /* OUT */
4664                      vm_object_t *object,       /* OUT */
4665                      vm_pindex_t *pindex,       /* OUT */
4666                      vm_prot_t *out_prot,       /* OUT */
4667                      boolean_t *wired)          /* OUT */
4668 {
4669         vm_map_entry_t entry;
4670         vm_map_t map = *var_map;
4671         vm_prot_t prot;
4672         vm_prot_t fault_type = fault_typea;
4673
4674         /*
4675          * Lookup the faulting address.
4676          */
4677         if (!vm_map_lookup_entry(map, vaddr, out_entry))
4678                 return (KERN_INVALID_ADDRESS);
4679
4680         entry = *out_entry;
4681
4682         /*
4683          * Fail if the entry refers to a submap.
4684          */
4685         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
4686                 return (KERN_FAILURE);
4687
4688         /*
4689          * Check whether this task is allowed to have this page.
4690          */
4691         prot = entry->protection;
4692         fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
4693         if ((fault_type & prot) != fault_type)
4694                 return (KERN_PROTECTION_FAILURE);
4695
4696         /*
4697          * If this page is not pageable, we have to get it for all possible
4698          * accesses.
4699          */
4700         *wired = (entry->wired_count != 0);
4701         if (*wired)
4702                 fault_type = entry->protection;
4703
4704         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
4705                 /*
4706                  * Fail if the entry was copy-on-write for a write fault.
4707                  */
4708                 if (fault_type & VM_PROT_WRITE)
4709                         return (KERN_FAILURE);
4710                 /*
4711                  * We're attempting to read a copy-on-write page --
4712                  * don't allow writes.
4713                  */
4714                 prot &= ~VM_PROT_WRITE;
4715         }
4716
4717         /*
4718          * Fail if an object should be created.
4719          */
4720         if (entry->object.vm_object == NULL && !map->system_map)
4721                 return (KERN_FAILURE);
4722
4723         /*
4724          * Return the object/offset from this entry.  If the entry was
4725          * copy-on-write or empty, it has been fixed up.
4726          */
4727         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
4728         *object = entry->object.vm_object;
4729
4730         *out_prot = prot;
4731         return (KERN_SUCCESS);
4732 }
4733
4734 /*
4735  *      vm_map_lookup_done:
4736  *
4737  *      Releases locks acquired by a vm_map_lookup
4738  *      (according to the handle returned by that lookup).
4739  */
4740 void
4741 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
4742 {
4743         /*
4744          * Unlock the main-level map
4745          */
4746         vm_map_unlock_read(map);
4747 }
4748
4749 vm_offset_t
4750 vm_map_max_KBI(const struct vm_map *map)
4751 {
4752
4753         return (vm_map_max(map));
4754 }
4755
4756 vm_offset_t
4757 vm_map_min_KBI(const struct vm_map *map)
4758 {
4759
4760         return (vm_map_min(map));
4761 }
4762
4763 pmap_t
4764 vm_map_pmap_KBI(vm_map_t map)
4765 {
4766
4767         return (map->pmap);
4768 }
4769
4770 #include "opt_ddb.h"
4771 #ifdef DDB
4772 #include <sys/kernel.h>
4773
4774 #include <ddb/ddb.h>
4775
4776 static void
4777 vm_map_print(vm_map_t map)
4778 {
4779         vm_map_entry_t entry;
4780
4781         db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
4782             (void *)map,
4783             (void *)map->pmap, map->nentries, map->timestamp);
4784
4785         db_indent += 2;
4786         for (entry = map->header.next; entry != &map->header;
4787             entry = entry->next) {
4788                 db_iprintf("map entry %p: start=%p, end=%p, eflags=%#x, \n",
4789                     (void *)entry, (void *)entry->start, (void *)entry->end,
4790                     entry->eflags);
4791                 {
4792                         static char *inheritance_name[4] =
4793                         {"share", "copy", "none", "donate_copy"};
4794
4795                         db_iprintf(" prot=%x/%x/%s",
4796                             entry->protection,
4797                             entry->max_protection,
4798                             inheritance_name[(int)(unsigned char)entry->inheritance]);
4799                         if (entry->wired_count != 0)
4800                                 db_printf(", wired");
4801                 }
4802                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
4803                         db_printf(", share=%p, offset=0x%jx\n",
4804                             (void *)entry->object.sub_map,
4805                             (uintmax_t)entry->offset);
4806                         if ((entry->prev == &map->header) ||
4807                             (entry->prev->object.sub_map !=
4808                                 entry->object.sub_map)) {
4809                                 db_indent += 2;
4810                                 vm_map_print((vm_map_t)entry->object.sub_map);
4811                                 db_indent -= 2;
4812                         }
4813                 } else {
4814                         if (entry->cred != NULL)
4815                                 db_printf(", ruid %d", entry->cred->cr_ruid);
4816                         db_printf(", object=%p, offset=0x%jx",
4817                             (void *)entry->object.vm_object,
4818                             (uintmax_t)entry->offset);
4819                         if (entry->object.vm_object && entry->object.vm_object->cred)
4820                                 db_printf(", obj ruid %d charge %jx",
4821                                     entry->object.vm_object->cred->cr_ruid,
4822                                     (uintmax_t)entry->object.vm_object->charge);
4823                         if (entry->eflags & MAP_ENTRY_COW)
4824                                 db_printf(", copy (%s)",
4825                                     (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
4826                         db_printf("\n");
4827
4828                         if ((entry->prev == &map->header) ||
4829                             (entry->prev->object.vm_object !=
4830                                 entry->object.vm_object)) {
4831                                 db_indent += 2;
4832                                 vm_object_print((db_expr_t)(intptr_t)
4833                                                 entry->object.vm_object,
4834                                                 0, 0, (char *)0);
4835                                 db_indent -= 2;
4836                         }
4837                 }
4838         }
4839         db_indent -= 2;
4840 }
4841
4842 DB_SHOW_COMMAND(map, map)
4843 {
4844
4845         if (!have_addr) {
4846                 db_printf("usage: show map <addr>\n");
4847                 return;
4848         }
4849         vm_map_print((vm_map_t)addr);
4850 }
4851
4852 DB_SHOW_COMMAND(procvm, procvm)
4853 {
4854         struct proc *p;
4855
4856         if (have_addr) {
4857                 p = db_lookup_proc(addr);
4858         } else {
4859                 p = curproc;
4860         }
4861
4862         db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
4863             (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
4864             (void *)vmspace_pmap(p->p_vmspace));
4865
4866         vm_map_print((vm_map_t)&p->p_vmspace->vm_map);
4867 }
4868
4869 #endif /* DDB */