]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - sys/vm/vm_map.c
MFC: 217169
[FreeBSD/releng/8.2.git] / sys / vm / vm_map.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)vm_map.c      8.3 (Berkeley) 1/12/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
39  *
40  * Permission to use, copy, modify and distribute this software and
41  * its documentation is hereby granted, provided that both the copyright
42  * notice and this permission notice appear in all copies of the
43  * software, derivative works or modified versions, and any portions
44  * thereof, and that both notices appear in supporting documentation.
45  *
46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
49  *
50  * Carnegie Mellon requests users of this software to return to
51  *
52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
53  *  School of Computer Science
54  *  Carnegie Mellon University
55  *  Pittsburgh PA 15213-3890
56  *
57  * any improvements or extensions that they make and grant Carnegie the
58  * rights to redistribute these changes.
59  */
60
61 /*
62  *      Virtual memory mapping module.
63  */
64
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67
68 #include <sys/param.h>
69 #include <sys/systm.h>
70 #include <sys/kernel.h>
71 #include <sys/ktr.h>
72 #include <sys/lock.h>
73 #include <sys/mutex.h>
74 #include <sys/proc.h>
75 #include <sys/vmmeter.h>
76 #include <sys/mman.h>
77 #include <sys/vnode.h>
78 #include <sys/resourcevar.h>
79 #include <sys/file.h>
80 #include <sys/sysctl.h>
81 #include <sys/sysent.h>
82 #include <sys/shm.h>
83
84 #include <vm/vm.h>
85 #include <vm/vm_param.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_pager.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_extern.h>
93 #include <vm/swap_pager.h>
94 #include <vm/uma.h>
95
96 /*
97  *      Virtual memory maps provide for the mapping, protection,
98  *      and sharing of virtual memory objects.  In addition,
99  *      this module provides for an efficient virtual copy of
100  *      memory from one map to another.
101  *
102  *      Synchronization is required prior to most operations.
103  *
104  *      Maps consist of an ordered doubly-linked list of simple
105  *      entries; a self-adjusting binary search tree of these
106  *      entries is used to speed up lookups.
107  *
108  *      Since portions of maps are specified by start/end addresses,
109  *      which may not align with existing map entries, all
110  *      routines merely "clip" entries to these start/end values.
111  *      [That is, an entry is split into two, bordering at a
112  *      start or end value.]  Note that these clippings may not
113  *      always be necessary (as the two resulting entries are then
114  *      not changed); however, the clipping is done for convenience.
115  *
116  *      As mentioned above, virtual copy operations are performed
117  *      by copying VM object references from one map to
118  *      another, and then marking both regions as copy-on-write.
119  */
120
121 static struct mtx map_sleep_mtx;
122 static uma_zone_t mapentzone;
123 static uma_zone_t kmapentzone;
124 static uma_zone_t mapzone;
125 static uma_zone_t vmspace_zone;
126 static struct vm_object kmapentobj;
127 static int vmspace_zinit(void *mem, int size, int flags);
128 static void vmspace_zfini(void *mem, int size);
129 static int vm_map_zinit(void *mem, int ize, int flags);
130 static void vm_map_zfini(void *mem, int size);
131 static void _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max);
132 static void vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map);
133 static void vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry);
134 #ifdef INVARIANTS
135 static void vm_map_zdtor(void *mem, int size, void *arg);
136 static void vmspace_zdtor(void *mem, int size, void *arg);
137 #endif
138
139 #define ENTRY_CHARGED(e) ((e)->uip != NULL || \
140     ((e)->object.vm_object != NULL && (e)->object.vm_object->uip != NULL && \
141      !((e)->eflags & MAP_ENTRY_NEEDS_COPY)))
142
143 /* 
144  * PROC_VMSPACE_{UN,}LOCK() can be a noop as long as vmspaces are type
145  * stable.
146  */
147 #define PROC_VMSPACE_LOCK(p) do { } while (0)
148 #define PROC_VMSPACE_UNLOCK(p) do { } while (0)
149
150 /*
151  *      VM_MAP_RANGE_CHECK:     [ internal use only ]
152  *
153  *      Asserts that the starting and ending region
154  *      addresses fall within the valid range of the map.
155  */
156 #define VM_MAP_RANGE_CHECK(map, start, end)             \
157                 {                                       \
158                 if (start < vm_map_min(map))            \
159                         start = vm_map_min(map);        \
160                 if (end > vm_map_max(map))              \
161                         end = vm_map_max(map);          \
162                 if (start > end)                        \
163                         start = end;                    \
164                 }
165
166 /*
167  *      vm_map_startup:
168  *
169  *      Initialize the vm_map module.  Must be called before
170  *      any other vm_map routines.
171  *
172  *      Map and entry structures are allocated from the general
173  *      purpose memory pool with some exceptions:
174  *
175  *      - The kernel map and kmem submap are allocated statically.
176  *      - Kernel map entries are allocated out of a static pool.
177  *
178  *      These restrictions are necessary since malloc() uses the
179  *      maps and requires map entries.
180  */
181
182 void
183 vm_map_startup(void)
184 {
185         mtx_init(&map_sleep_mtx, "vm map sleep mutex", NULL, MTX_DEF);
186         mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
187 #ifdef INVARIANTS
188             vm_map_zdtor,
189 #else
190             NULL,
191 #endif
192             vm_map_zinit, vm_map_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
193         uma_prealloc(mapzone, MAX_KMAP);
194         kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry),
195             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR,
196             UMA_ZONE_MTXCLASS | UMA_ZONE_VM);
197         uma_prealloc(kmapentzone, MAX_KMAPENT);
198         mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry),
199             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
200 }
201
202 static void
203 vmspace_zfini(void *mem, int size)
204 {
205         struct vmspace *vm;
206
207         vm = (struct vmspace *)mem;
208         vm_map_zfini(&vm->vm_map, sizeof(vm->vm_map));
209 }
210
211 static int
212 vmspace_zinit(void *mem, int size, int flags)
213 {
214         struct vmspace *vm;
215
216         vm = (struct vmspace *)mem;
217
218         vm->vm_map.pmap = NULL;
219         (void)vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map), flags);
220         return (0);
221 }
222
223 static void
224 vm_map_zfini(void *mem, int size)
225 {
226         vm_map_t map;
227
228         map = (vm_map_t)mem;
229         mtx_destroy(&map->system_mtx);
230         sx_destroy(&map->lock);
231 }
232
233 static int
234 vm_map_zinit(void *mem, int size, int flags)
235 {
236         vm_map_t map;
237
238         map = (vm_map_t)mem;
239         map->nentries = 0;
240         map->size = 0;
241         mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
242         sx_init(&map->lock, "user map");
243         return (0);
244 }
245
246 #ifdef INVARIANTS
247 static void
248 vmspace_zdtor(void *mem, int size, void *arg)
249 {
250         struct vmspace *vm;
251
252         vm = (struct vmspace *)mem;
253
254         vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
255 }
256 static void
257 vm_map_zdtor(void *mem, int size, void *arg)
258 {
259         vm_map_t map;
260
261         map = (vm_map_t)mem;
262         KASSERT(map->nentries == 0,
263             ("map %p nentries == %d on free.",
264             map, map->nentries));
265         KASSERT(map->size == 0,
266             ("map %p size == %lu on free.",
267             map, (unsigned long)map->size));
268 }
269 #endif  /* INVARIANTS */
270
271 /*
272  * Allocate a vmspace structure, including a vm_map and pmap,
273  * and initialize those structures.  The refcnt is set to 1.
274  */
275 struct vmspace *
276 vmspace_alloc(min, max)
277         vm_offset_t min, max;
278 {
279         struct vmspace *vm;
280
281         vm = uma_zalloc(vmspace_zone, M_WAITOK);
282         if (vm->vm_map.pmap == NULL && !pmap_pinit(vmspace_pmap(vm))) {
283                 uma_zfree(vmspace_zone, vm);
284                 return (NULL);
285         }
286         CTR1(KTR_VM, "vmspace_alloc: %p", vm);
287         _vm_map_init(&vm->vm_map, min, max);
288         vm->vm_map.pmap = vmspace_pmap(vm);             /* XXX */
289         vm->vm_refcnt = 1;
290         vm->vm_shm = NULL;
291         vm->vm_swrss = 0;
292         vm->vm_tsize = 0;
293         vm->vm_dsize = 0;
294         vm->vm_ssize = 0;
295         vm->vm_taddr = 0;
296         vm->vm_daddr = 0;
297         vm->vm_maxsaddr = 0;
298         return (vm);
299 }
300
301 void
302 vm_init2(void)
303 {
304         uma_zone_set_obj(kmapentzone, &kmapentobj, lmin(cnt.v_page_count,
305             (VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS) / PAGE_SIZE) / 8 +
306              maxproc * 2 + maxfiles);
307         vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
308 #ifdef INVARIANTS
309             vmspace_zdtor,
310 #else
311             NULL,
312 #endif
313             vmspace_zinit, vmspace_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
314 }
315
316 static inline void
317 vmspace_dofree(struct vmspace *vm)
318 {
319         CTR1(KTR_VM, "vmspace_free: %p", vm);
320
321         /*
322          * Make sure any SysV shm is freed, it might not have been in
323          * exit1().
324          */
325         shmexit(vm);
326
327         /*
328          * Lock the map, to wait out all other references to it.
329          * Delete all of the mappings and pages they hold, then call
330          * the pmap module to reclaim anything left.
331          */
332         (void)vm_map_remove(&vm->vm_map, vm->vm_map.min_offset,
333             vm->vm_map.max_offset);
334
335         /*
336          * XXX Comment out the pmap_release call for now. The
337          * vmspace_zone is marked as UMA_ZONE_NOFREE, and bugs cause
338          * pmap.resident_count to be != 0 on exit sometimes.
339          */
340 /*      pmap_release(vmspace_pmap(vm)); */
341         uma_zfree(vmspace_zone, vm);
342 }
343
344 void
345 vmspace_free(struct vmspace *vm)
346 {
347         int refcnt;
348
349         if (vm->vm_refcnt == 0)
350                 panic("vmspace_free: attempt to free already freed vmspace");
351
352         do
353                 refcnt = vm->vm_refcnt;
354         while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
355         if (refcnt == 1)
356                 vmspace_dofree(vm);
357 }
358
359 void
360 vmspace_exitfree(struct proc *p)
361 {
362         struct vmspace *vm;
363
364         PROC_VMSPACE_LOCK(p);
365         vm = p->p_vmspace;
366         p->p_vmspace = NULL;
367         PROC_VMSPACE_UNLOCK(p);
368         KASSERT(vm == &vmspace0, ("vmspace_exitfree: wrong vmspace"));
369         vmspace_free(vm);
370 }
371
372 void
373 vmspace_exit(struct thread *td)
374 {
375         int refcnt;
376         struct vmspace *vm;
377         struct proc *p;
378
379         /*
380          * Release user portion of address space.
381          * This releases references to vnodes,
382          * which could cause I/O if the file has been unlinked.
383          * Need to do this early enough that we can still sleep.
384          *
385          * The last exiting process to reach this point releases as
386          * much of the environment as it can. vmspace_dofree() is the
387          * slower fallback in case another process had a temporary
388          * reference to the vmspace.
389          */
390
391         p = td->td_proc;
392         vm = p->p_vmspace;
393         atomic_add_int(&vmspace0.vm_refcnt, 1);
394         do {
395                 refcnt = vm->vm_refcnt;
396                 if (refcnt > 1 && p->p_vmspace != &vmspace0) {
397                         /* Switch now since other proc might free vmspace */
398                         PROC_VMSPACE_LOCK(p);
399                         p->p_vmspace = &vmspace0;
400                         PROC_VMSPACE_UNLOCK(p);
401                         pmap_activate(td);
402                 }
403         } while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt - 1));
404         if (refcnt == 1) {
405                 if (p->p_vmspace != vm) {
406                         /* vmspace not yet freed, switch back */
407                         PROC_VMSPACE_LOCK(p);
408                         p->p_vmspace = vm;
409                         PROC_VMSPACE_UNLOCK(p);
410                         pmap_activate(td);
411                 }
412                 pmap_remove_pages(vmspace_pmap(vm));
413                 /* Switch now since this proc will free vmspace */
414                 PROC_VMSPACE_LOCK(p);
415                 p->p_vmspace = &vmspace0;
416                 PROC_VMSPACE_UNLOCK(p);
417                 pmap_activate(td);
418                 vmspace_dofree(vm);
419         }
420 }
421
422 /* Acquire reference to vmspace owned by another process. */
423
424 struct vmspace *
425 vmspace_acquire_ref(struct proc *p)
426 {
427         struct vmspace *vm;
428         int refcnt;
429
430         PROC_VMSPACE_LOCK(p);
431         vm = p->p_vmspace;
432         if (vm == NULL) {
433                 PROC_VMSPACE_UNLOCK(p);
434                 return (NULL);
435         }
436         do {
437                 refcnt = vm->vm_refcnt;
438                 if (refcnt <= 0) {      /* Avoid 0->1 transition */
439                         PROC_VMSPACE_UNLOCK(p);
440                         return (NULL);
441                 }
442         } while (!atomic_cmpset_int(&vm->vm_refcnt, refcnt, refcnt + 1));
443         if (vm != p->p_vmspace) {
444                 PROC_VMSPACE_UNLOCK(p);
445                 vmspace_free(vm);
446                 return (NULL);
447         }
448         PROC_VMSPACE_UNLOCK(p);
449         return (vm);
450 }
451
452 void
453 _vm_map_lock(vm_map_t map, const char *file, int line)
454 {
455
456         if (map->system_map)
457                 _mtx_lock_flags(&map->system_mtx, 0, file, line);
458         else
459                 (void)_sx_xlock(&map->lock, 0, file, line);
460         map->timestamp++;
461 }
462
463 static void
464 vm_map_process_deferred(void)
465 {
466         struct thread *td;
467         vm_map_entry_t entry;
468
469         td = curthread;
470
471         while ((entry = td->td_map_def_user) != NULL) {
472                 td->td_map_def_user = entry->next;
473                 vm_map_entry_deallocate(entry, FALSE);
474         }
475 }
476
477 void
478 _vm_map_unlock(vm_map_t map, const char *file, int line)
479 {
480
481         if (map->system_map)
482                 _mtx_unlock_flags(&map->system_mtx, 0, file, line);
483         else {
484                 _sx_xunlock(&map->lock, file, line);
485                 vm_map_process_deferred();
486         }
487 }
488
489 void
490 _vm_map_lock_read(vm_map_t map, const char *file, int line)
491 {
492
493         if (map->system_map)
494                 _mtx_lock_flags(&map->system_mtx, 0, file, line);
495         else
496                 (void)_sx_slock(&map->lock, 0, file, line);
497 }
498
499 void
500 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
501 {
502
503         if (map->system_map)
504                 _mtx_unlock_flags(&map->system_mtx, 0, file, line);
505         else {
506                 _sx_sunlock(&map->lock, file, line);
507                 vm_map_process_deferred();
508         }
509 }
510
511 int
512 _vm_map_trylock(vm_map_t map, const char *file, int line)
513 {
514         int error;
515
516         error = map->system_map ?
517             !_mtx_trylock(&map->system_mtx, 0, file, line) :
518             !_sx_try_xlock(&map->lock, file, line);
519         if (error == 0)
520                 map->timestamp++;
521         return (error == 0);
522 }
523
524 int
525 _vm_map_trylock_read(vm_map_t map, const char *file, int line)
526 {
527         int error;
528
529         error = map->system_map ?
530             !_mtx_trylock(&map->system_mtx, 0, file, line) :
531             !_sx_try_slock(&map->lock, file, line);
532         return (error == 0);
533 }
534
535 /*
536  *      _vm_map_lock_upgrade:   [ internal use only ]
537  *
538  *      Tries to upgrade a read (shared) lock on the specified map to a write
539  *      (exclusive) lock.  Returns the value "0" if the upgrade succeeds and a
540  *      non-zero value if the upgrade fails.  If the upgrade fails, the map is
541  *      returned without a read or write lock held.
542  *
543  *      Requires that the map be read locked.
544  */
545 int
546 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
547 {
548         unsigned int last_timestamp;
549
550         if (map->system_map) {
551 #ifdef INVARIANTS
552                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
553 #endif
554         } else {
555                 if (!_sx_try_upgrade(&map->lock, file, line)) {
556                         last_timestamp = map->timestamp;
557                         _sx_sunlock(&map->lock, file, line);
558                         vm_map_process_deferred();
559                         /*
560                          * If the map's timestamp does not change while the
561                          * map is unlocked, then the upgrade succeeds.
562                          */
563                         (void)_sx_xlock(&map->lock, 0, file, line);
564                         if (last_timestamp != map->timestamp) {
565                                 _sx_xunlock(&map->lock, file, line);
566                                 return (1);
567                         }
568                 }
569         }
570         map->timestamp++;
571         return (0);
572 }
573
574 void
575 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
576 {
577
578         if (map->system_map) {
579 #ifdef INVARIANTS
580                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
581 #endif
582         } else
583                 _sx_downgrade(&map->lock, file, line);
584 }
585
586 /*
587  *      vm_map_locked:
588  *
589  *      Returns a non-zero value if the caller holds a write (exclusive) lock
590  *      on the specified map and the value "0" otherwise.
591  */
592 int
593 vm_map_locked(vm_map_t map)
594 {
595
596         if (map->system_map)
597                 return (mtx_owned(&map->system_mtx));
598         else
599                 return (sx_xlocked(&map->lock));
600 }
601
602 #ifdef INVARIANTS
603 static void
604 _vm_map_assert_locked(vm_map_t map, const char *file, int line)
605 {
606
607         if (map->system_map)
608                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
609         else
610                 _sx_assert(&map->lock, SA_XLOCKED, file, line);
611 }
612
613 #if 0
614 static void
615 _vm_map_assert_locked_read(vm_map_t map, const char *file, int line)
616 {
617
618         if (map->system_map)
619                 _mtx_assert(&map->system_mtx, MA_OWNED, file, line);
620         else
621                 _sx_assert(&map->lock, SA_SLOCKED, file, line);
622 }
623 #endif
624
625 #define VM_MAP_ASSERT_LOCKED(map) \
626     _vm_map_assert_locked(map, LOCK_FILE, LOCK_LINE)
627 #define VM_MAP_ASSERT_LOCKED_READ(map) \
628     _vm_map_assert_locked_read(map, LOCK_FILE, LOCK_LINE)
629 #else
630 #define VM_MAP_ASSERT_LOCKED(map)
631 #define VM_MAP_ASSERT_LOCKED_READ(map)
632 #endif
633
634 /*
635  *      _vm_map_unlock_and_wait:
636  *
637  *      Atomically releases the lock on the specified map and puts the calling
638  *      thread to sleep.  The calling thread will remain asleep until either
639  *      vm_map_wakeup() is performed on the map or the specified timeout is
640  *      exceeded.
641  *
642  *      WARNING!  This function does not perform deferred deallocations of
643  *      objects and map entries.  Therefore, the calling thread is expected to
644  *      reacquire the map lock after reawakening and later perform an ordinary
645  *      unlock operation, such as vm_map_unlock(), before completing its
646  *      operation on the map.
647  */
648 int
649 _vm_map_unlock_and_wait(vm_map_t map, int timo, const char *file, int line)
650 {
651
652         mtx_lock(&map_sleep_mtx);
653         if (map->system_map)
654                 _mtx_unlock_flags(&map->system_mtx, 0, file, line);
655         else
656                 _sx_xunlock(&map->lock, file, line);
657         return (msleep(&map->root, &map_sleep_mtx, PDROP | PVM, "vmmaps",
658             timo));
659 }
660
661 /*
662  *      vm_map_wakeup:
663  *
664  *      Awaken any threads that have slept on the map using
665  *      vm_map_unlock_and_wait().
666  */
667 void
668 vm_map_wakeup(vm_map_t map)
669 {
670
671         /*
672          * Acquire and release map_sleep_mtx to prevent a wakeup()
673          * from being performed (and lost) between the map unlock
674          * and the msleep() in _vm_map_unlock_and_wait().
675          */
676         mtx_lock(&map_sleep_mtx);
677         mtx_unlock(&map_sleep_mtx);
678         wakeup(&map->root);
679 }
680
681 void
682 vm_map_busy(vm_map_t map)
683 {
684
685         VM_MAP_ASSERT_LOCKED(map);
686         map->busy++;
687 }
688
689 void
690 vm_map_unbusy(vm_map_t map)
691 {
692
693         VM_MAP_ASSERT_LOCKED(map);
694         KASSERT(map->busy, ("vm_map_unbusy: not busy"));
695         if (--map->busy == 0 && (map->flags & MAP_BUSY_WAKEUP)) {
696                 vm_map_modflags(map, 0, MAP_BUSY_WAKEUP);
697                 wakeup(&map->busy);
698         }
699 }
700
701 void 
702 vm_map_wait_busy(vm_map_t map)
703 {
704
705         VM_MAP_ASSERT_LOCKED(map);
706         while (map->busy) {
707                 vm_map_modflags(map, MAP_BUSY_WAKEUP, 0);
708                 if (map->system_map)
709                         msleep(&map->busy, &map->system_mtx, 0, "mbusy", 0);
710                 else
711                         sx_sleep(&map->busy, &map->lock, 0, "mbusy", 0);
712         }
713         map->timestamp++;
714 }
715
716 long
717 vmspace_resident_count(struct vmspace *vmspace)
718 {
719         return pmap_resident_count(vmspace_pmap(vmspace));
720 }
721
722 long
723 vmspace_wired_count(struct vmspace *vmspace)
724 {
725         return pmap_wired_count(vmspace_pmap(vmspace));
726 }
727
728 /*
729  *      vm_map_create:
730  *
731  *      Creates and returns a new empty VM map with
732  *      the given physical map structure, and having
733  *      the given lower and upper address bounds.
734  */
735 vm_map_t
736 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
737 {
738         vm_map_t result;
739
740         result = uma_zalloc(mapzone, M_WAITOK);
741         CTR1(KTR_VM, "vm_map_create: %p", result);
742         _vm_map_init(result, min, max);
743         result->pmap = pmap;
744         return (result);
745 }
746
747 /*
748  * Initialize an existing vm_map structure
749  * such as that in the vmspace structure.
750  * The pmap is set elsewhere.
751  */
752 static void
753 _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
754 {
755
756         map->header.next = map->header.prev = &map->header;
757         map->needs_wakeup = FALSE;
758         map->system_map = 0;
759         map->min_offset = min;
760         map->max_offset = max;
761         map->flags = 0;
762         map->root = NULL;
763         map->timestamp = 0;
764         map->busy = 0;
765 }
766
767 void
768 vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
769 {
770         _vm_map_init(map, min, max);
771         mtx_init(&map->system_mtx, "system map", NULL, MTX_DEF | MTX_DUPOK);
772         sx_init(&map->lock, "user map");
773 }
774
775 /*
776  *      vm_map_entry_dispose:   [ internal use only ]
777  *
778  *      Inverse of vm_map_entry_create.
779  */
780 static void
781 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
782 {
783         uma_zfree(map->system_map ? kmapentzone : mapentzone, entry);
784 }
785
786 /*
787  *      vm_map_entry_create:    [ internal use only ]
788  *
789  *      Allocates a VM map entry for insertion.
790  *      No entry fields are filled in.
791  */
792 static vm_map_entry_t
793 vm_map_entry_create(vm_map_t map)
794 {
795         vm_map_entry_t new_entry;
796
797         if (map->system_map)
798                 new_entry = uma_zalloc(kmapentzone, M_NOWAIT);
799         else
800                 new_entry = uma_zalloc(mapentzone, M_WAITOK);
801         if (new_entry == NULL)
802                 panic("vm_map_entry_create: kernel resources exhausted");
803         return (new_entry);
804 }
805
806 /*
807  *      vm_map_entry_set_behavior:
808  *
809  *      Set the expected access behavior, either normal, random, or
810  *      sequential.
811  */
812 static inline void
813 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
814 {
815         entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
816             (behavior & MAP_ENTRY_BEHAV_MASK);
817 }
818
819 /*
820  *      vm_map_entry_set_max_free:
821  *
822  *      Set the max_free field in a vm_map_entry.
823  */
824 static inline void
825 vm_map_entry_set_max_free(vm_map_entry_t entry)
826 {
827
828         entry->max_free = entry->adj_free;
829         if (entry->left != NULL && entry->left->max_free > entry->max_free)
830                 entry->max_free = entry->left->max_free;
831         if (entry->right != NULL && entry->right->max_free > entry->max_free)
832                 entry->max_free = entry->right->max_free;
833 }
834
835 /*
836  *      vm_map_entry_splay:
837  *
838  *      The Sleator and Tarjan top-down splay algorithm with the
839  *      following variation.  Max_free must be computed bottom-up, so
840  *      on the downward pass, maintain the left and right spines in
841  *      reverse order.  Then, make a second pass up each side to fix
842  *      the pointers and compute max_free.  The time bound is O(log n)
843  *      amortized.
844  *
845  *      The new root is the vm_map_entry containing "addr", or else an
846  *      adjacent entry (lower or higher) if addr is not in the tree.
847  *
848  *      The map must be locked, and leaves it so.
849  *
850  *      Returns: the new root.
851  */
852 static vm_map_entry_t
853 vm_map_entry_splay(vm_offset_t addr, vm_map_entry_t root)
854 {
855         vm_map_entry_t llist, rlist;
856         vm_map_entry_t ltree, rtree;
857         vm_map_entry_t y;
858
859         /* Special case of empty tree. */
860         if (root == NULL)
861                 return (root);
862
863         /*
864          * Pass One: Splay down the tree until we find addr or a NULL
865          * pointer where addr would go.  llist and rlist are the two
866          * sides in reverse order (bottom-up), with llist linked by
867          * the right pointer and rlist linked by the left pointer in
868          * the vm_map_entry.  Wait until Pass Two to set max_free on
869          * the two spines.
870          */
871         llist = NULL;
872         rlist = NULL;
873         for (;;) {
874                 /* root is never NULL in here. */
875                 if (addr < root->start) {
876                         y = root->left;
877                         if (y == NULL)
878                                 break;
879                         if (addr < y->start && y->left != NULL) {
880                                 /* Rotate right and put y on rlist. */
881                                 root->left = y->right;
882                                 y->right = root;
883                                 vm_map_entry_set_max_free(root);
884                                 root = y->left;
885                                 y->left = rlist;
886                                 rlist = y;
887                         } else {
888                                 /* Put root on rlist. */
889                                 root->left = rlist;
890                                 rlist = root;
891                                 root = y;
892                         }
893                 } else if (addr >= root->end) {
894                         y = root->right;
895                         if (y == NULL)
896                                 break;
897                         if (addr >= y->end && y->right != NULL) {
898                                 /* Rotate left and put y on llist. */
899                                 root->right = y->left;
900                                 y->left = root;
901                                 vm_map_entry_set_max_free(root);
902                                 root = y->right;
903                                 y->right = llist;
904                                 llist = y;
905                         } else {
906                                 /* Put root on llist. */
907                                 root->right = llist;
908                                 llist = root;
909                                 root = y;
910                         }
911                 } else
912                         break;
913         }
914
915         /*
916          * Pass Two: Walk back up the two spines, flip the pointers
917          * and set max_free.  The subtrees of the root go at the
918          * bottom of llist and rlist.
919          */
920         ltree = root->left;
921         while (llist != NULL) {
922                 y = llist->right;
923                 llist->right = ltree;
924                 vm_map_entry_set_max_free(llist);
925                 ltree = llist;
926                 llist = y;
927         }
928         rtree = root->right;
929         while (rlist != NULL) {
930                 y = rlist->left;
931                 rlist->left = rtree;
932                 vm_map_entry_set_max_free(rlist);
933                 rtree = rlist;
934                 rlist = y;
935         }
936
937         /*
938          * Final assembly: add ltree and rtree as subtrees of root.
939          */
940         root->left = ltree;
941         root->right = rtree;
942         vm_map_entry_set_max_free(root);
943
944         return (root);
945 }
946
947 /*
948  *      vm_map_entry_{un,}link:
949  *
950  *      Insert/remove entries from maps.
951  */
952 static void
953 vm_map_entry_link(vm_map_t map,
954                   vm_map_entry_t after_where,
955                   vm_map_entry_t entry)
956 {
957
958         CTR4(KTR_VM,
959             "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
960             map->nentries, entry, after_where);
961         VM_MAP_ASSERT_LOCKED(map);
962         map->nentries++;
963         entry->prev = after_where;
964         entry->next = after_where->next;
965         entry->next->prev = entry;
966         after_where->next = entry;
967
968         if (after_where != &map->header) {
969                 if (after_where != map->root)
970                         vm_map_entry_splay(after_where->start, map->root);
971                 entry->right = after_where->right;
972                 entry->left = after_where;
973                 after_where->right = NULL;
974                 after_where->adj_free = entry->start - after_where->end;
975                 vm_map_entry_set_max_free(after_where);
976         } else {
977                 entry->right = map->root;
978                 entry->left = NULL;
979         }
980         entry->adj_free = (entry->next == &map->header ? map->max_offset :
981             entry->next->start) - entry->end;
982         vm_map_entry_set_max_free(entry);
983         map->root = entry;
984 }
985
986 static void
987 vm_map_entry_unlink(vm_map_t map,
988                     vm_map_entry_t entry)
989 {
990         vm_map_entry_t next, prev, root;
991
992         VM_MAP_ASSERT_LOCKED(map);
993         if (entry != map->root)
994                 vm_map_entry_splay(entry->start, map->root);
995         if (entry->left == NULL)
996                 root = entry->right;
997         else {
998                 root = vm_map_entry_splay(entry->start, entry->left);
999                 root->right = entry->right;
1000                 root->adj_free = (entry->next == &map->header ? map->max_offset :
1001                     entry->next->start) - root->end;
1002                 vm_map_entry_set_max_free(root);
1003         }
1004         map->root = root;
1005
1006         prev = entry->prev;
1007         next = entry->next;
1008         next->prev = prev;
1009         prev->next = next;
1010         map->nentries--;
1011         CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
1012             map->nentries, entry);
1013 }
1014
1015 /*
1016  *      vm_map_entry_resize_free:
1017  *
1018  *      Recompute the amount of free space following a vm_map_entry
1019  *      and propagate that value up the tree.  Call this function after
1020  *      resizing a map entry in-place, that is, without a call to
1021  *      vm_map_entry_link() or _unlink().
1022  *
1023  *      The map must be locked, and leaves it so.
1024  */
1025 static void
1026 vm_map_entry_resize_free(vm_map_t map, vm_map_entry_t entry)
1027 {
1028
1029         /*
1030          * Using splay trees without parent pointers, propagating
1031          * max_free up the tree is done by moving the entry to the
1032          * root and making the change there.
1033          */
1034         if (entry != map->root)
1035                 map->root = vm_map_entry_splay(entry->start, map->root);
1036
1037         entry->adj_free = (entry->next == &map->header ? map->max_offset :
1038             entry->next->start) - entry->end;
1039         vm_map_entry_set_max_free(entry);
1040 }
1041
1042 /*
1043  *      vm_map_lookup_entry:    [ internal use only ]
1044  *
1045  *      Finds the map entry containing (or
1046  *      immediately preceding) the specified address
1047  *      in the given map; the entry is returned
1048  *      in the "entry" parameter.  The boolean
1049  *      result indicates whether the address is
1050  *      actually contained in the map.
1051  */
1052 boolean_t
1053 vm_map_lookup_entry(
1054         vm_map_t map,
1055         vm_offset_t address,
1056         vm_map_entry_t *entry)  /* OUT */
1057 {
1058         vm_map_entry_t cur;
1059         boolean_t locked;
1060
1061         /*
1062          * If the map is empty, then the map entry immediately preceding
1063          * "address" is the map's header.
1064          */
1065         cur = map->root;
1066         if (cur == NULL)
1067                 *entry = &map->header;
1068         else if (address >= cur->start && cur->end > address) {
1069                 *entry = cur;
1070                 return (TRUE);
1071         } else if ((locked = vm_map_locked(map)) ||
1072             sx_try_upgrade(&map->lock)) {
1073                 /*
1074                  * Splay requires a write lock on the map.  However, it only
1075                  * restructures the binary search tree; it does not otherwise
1076                  * change the map.  Thus, the map's timestamp need not change
1077                  * on a temporary upgrade.
1078                  */
1079                 map->root = cur = vm_map_entry_splay(address, cur);
1080                 if (!locked)
1081                         sx_downgrade(&map->lock);
1082
1083                 /*
1084                  * If "address" is contained within a map entry, the new root
1085                  * is that map entry.  Otherwise, the new root is a map entry
1086                  * immediately before or after "address".
1087                  */
1088                 if (address >= cur->start) {
1089                         *entry = cur;
1090                         if (cur->end > address)
1091                                 return (TRUE);
1092                 } else
1093                         *entry = cur->prev;
1094         } else
1095                 /*
1096                  * Since the map is only locked for read access, perform a
1097                  * standard binary search tree lookup for "address".
1098                  */
1099                 for (;;) {
1100                         if (address < cur->start) {
1101                                 if (cur->left == NULL) {
1102                                         *entry = cur->prev;
1103                                         break;
1104                                 }
1105                                 cur = cur->left;
1106                         } else if (cur->end > address) {
1107                                 *entry = cur;
1108                                 return (TRUE);
1109                         } else {
1110                                 if (cur->right == NULL) {
1111                                         *entry = cur;
1112                                         break;
1113                                 }
1114                                 cur = cur->right;
1115                         }
1116                 }
1117         return (FALSE);
1118 }
1119
1120 /*
1121  *      vm_map_insert:
1122  *
1123  *      Inserts the given whole VM object into the target
1124  *      map at the specified address range.  The object's
1125  *      size should match that of the address range.
1126  *
1127  *      Requires that the map be locked, and leaves it so.
1128  *
1129  *      If object is non-NULL, ref count must be bumped by caller
1130  *      prior to making call to account for the new entry.
1131  */
1132 int
1133 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1134               vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max,
1135               int cow)
1136 {
1137         vm_map_entry_t new_entry;
1138         vm_map_entry_t prev_entry;
1139         vm_map_entry_t temp_entry;
1140         vm_eflags_t protoeflags;
1141         struct uidinfo *uip;
1142         boolean_t charge_prev_obj;
1143
1144         VM_MAP_ASSERT_LOCKED(map);
1145
1146         /*
1147          * Check that the start and end points are not bogus.
1148          */
1149         if ((start < map->min_offset) || (end > map->max_offset) ||
1150             (start >= end))
1151                 return (KERN_INVALID_ADDRESS);
1152
1153         /*
1154          * Find the entry prior to the proposed starting address; if it's part
1155          * of an existing entry, this range is bogus.
1156          */
1157         if (vm_map_lookup_entry(map, start, &temp_entry))
1158                 return (KERN_NO_SPACE);
1159
1160         prev_entry = temp_entry;
1161
1162         /*
1163          * Assert that the next entry doesn't overlap the end point.
1164          */
1165         if ((prev_entry->next != &map->header) &&
1166             (prev_entry->next->start < end))
1167                 return (KERN_NO_SPACE);
1168
1169         protoeflags = 0;
1170         charge_prev_obj = FALSE;
1171
1172         if (cow & MAP_COPY_ON_WRITE)
1173                 protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
1174
1175         if (cow & MAP_NOFAULT) {
1176                 protoeflags |= MAP_ENTRY_NOFAULT;
1177
1178                 KASSERT(object == NULL,
1179                         ("vm_map_insert: paradoxical MAP_NOFAULT request"));
1180         }
1181         if (cow & MAP_DISABLE_SYNCER)
1182                 protoeflags |= MAP_ENTRY_NOSYNC;
1183         if (cow & MAP_DISABLE_COREDUMP)
1184                 protoeflags |= MAP_ENTRY_NOCOREDUMP;
1185
1186         uip = NULL;
1187         KASSERT((object != kmem_object && object != kernel_object) ||
1188             ((object == kmem_object || object == kernel_object) &&
1189                 !(protoeflags & MAP_ENTRY_NEEDS_COPY)),
1190             ("kmem or kernel object and cow"));
1191         if (cow & (MAP_ACC_NO_CHARGE | MAP_NOFAULT))
1192                 goto charged;
1193         if ((cow & MAP_ACC_CHARGED) || ((prot & VM_PROT_WRITE) &&
1194             ((protoeflags & MAP_ENTRY_NEEDS_COPY) || object == NULL))) {
1195                 if (!(cow & MAP_ACC_CHARGED) && !swap_reserve(end - start))
1196                         return (KERN_RESOURCE_SHORTAGE);
1197                 KASSERT(object == NULL || (protoeflags & MAP_ENTRY_NEEDS_COPY) ||
1198                     object->uip == NULL,
1199                     ("OVERCOMMIT: vm_map_insert o %p", object));
1200                 uip = curthread->td_ucred->cr_ruidinfo;
1201                 uihold(uip);
1202                 if (object == NULL && !(protoeflags & MAP_ENTRY_NEEDS_COPY))
1203                         charge_prev_obj = TRUE;
1204         }
1205
1206 charged:
1207         /* Expand the kernel pmap, if necessary. */
1208         if (map == kernel_map && end > kernel_vm_end)
1209                 pmap_growkernel(end);
1210         if (object != NULL) {
1211                 /*
1212                  * OBJ_ONEMAPPING must be cleared unless this mapping
1213                  * is trivially proven to be the only mapping for any
1214                  * of the object's pages.  (Object granularity
1215                  * reference counting is insufficient to recognize
1216                  * aliases with precision.)
1217                  */
1218                 VM_OBJECT_LOCK(object);
1219                 if (object->ref_count > 1 || object->shadow_count != 0)
1220                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
1221                 VM_OBJECT_UNLOCK(object);
1222         }
1223         else if ((prev_entry != &map->header) &&
1224                  (prev_entry->eflags == protoeflags) &&
1225                  (prev_entry->end == start) &&
1226                  (prev_entry->wired_count == 0) &&
1227                  (prev_entry->uip == uip ||
1228                   (prev_entry->object.vm_object != NULL &&
1229                    (prev_entry->object.vm_object->uip == uip))) &&
1230                    vm_object_coalesce(prev_entry->object.vm_object,
1231                        prev_entry->offset,
1232                        (vm_size_t)(prev_entry->end - prev_entry->start),
1233                        (vm_size_t)(end - prev_entry->end), charge_prev_obj)) {
1234                 /*
1235                  * We were able to extend the object.  Determine if we
1236                  * can extend the previous map entry to include the
1237                  * new range as well.
1238                  */
1239                 if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
1240                     (prev_entry->protection == prot) &&
1241                     (prev_entry->max_protection == max)) {
1242                         map->size += (end - prev_entry->end);
1243                         prev_entry->end = end;
1244                         vm_map_entry_resize_free(map, prev_entry);
1245                         vm_map_simplify_entry(map, prev_entry);
1246                         if (uip != NULL)
1247                                 uifree(uip);
1248                         return (KERN_SUCCESS);
1249                 }
1250
1251                 /*
1252                  * If we can extend the object but cannot extend the
1253                  * map entry, we have to create a new map entry.  We
1254                  * must bump the ref count on the extended object to
1255                  * account for it.  object may be NULL.
1256                  */
1257                 object = prev_entry->object.vm_object;
1258                 offset = prev_entry->offset +
1259                         (prev_entry->end - prev_entry->start);
1260                 vm_object_reference(object);
1261                 if (uip != NULL && object != NULL && object->uip != NULL &&
1262                     !(prev_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
1263                         /* Object already accounts for this uid. */
1264                         uifree(uip);
1265                         uip = NULL;
1266                 }
1267         }
1268
1269         /*
1270          * NOTE: if conditionals fail, object can be NULL here.  This occurs
1271          * in things like the buffer map where we manage kva but do not manage
1272          * backing objects.
1273          */
1274
1275         /*
1276          * Create a new entry
1277          */
1278         new_entry = vm_map_entry_create(map);
1279         new_entry->start = start;
1280         new_entry->end = end;
1281         new_entry->uip = NULL;
1282
1283         new_entry->eflags = protoeflags;
1284         new_entry->object.vm_object = object;
1285         new_entry->offset = offset;
1286         new_entry->avail_ssize = 0;
1287
1288         new_entry->inheritance = VM_INHERIT_DEFAULT;
1289         new_entry->protection = prot;
1290         new_entry->max_protection = max;
1291         new_entry->wired_count = 0;
1292
1293         KASSERT(uip == NULL || !ENTRY_CHARGED(new_entry),
1294             ("OVERCOMMIT: vm_map_insert leaks vm_map %p", new_entry));
1295         new_entry->uip = uip;
1296
1297         /*
1298          * Insert the new entry into the list
1299          */
1300         vm_map_entry_link(map, prev_entry, new_entry);
1301         map->size += new_entry->end - new_entry->start;
1302
1303 #if 0
1304         /*
1305          * Temporarily removed to avoid MAP_STACK panic, due to
1306          * MAP_STACK being a huge hack.  Will be added back in
1307          * when MAP_STACK (and the user stack mapping) is fixed.
1308          */
1309         /*
1310          * It may be possible to simplify the entry
1311          */
1312         vm_map_simplify_entry(map, new_entry);
1313 #endif
1314
1315         if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
1316                 vm_map_pmap_enter(map, start, prot,
1317                                     object, OFF_TO_IDX(offset), end - start,
1318                                     cow & MAP_PREFAULT_PARTIAL);
1319         }
1320
1321         return (KERN_SUCCESS);
1322 }
1323
1324 /*
1325  *      vm_map_findspace:
1326  *
1327  *      Find the first fit (lowest VM address) for "length" free bytes
1328  *      beginning at address >= start in the given map.
1329  *
1330  *      In a vm_map_entry, "adj_free" is the amount of free space
1331  *      adjacent (higher address) to this entry, and "max_free" is the
1332  *      maximum amount of contiguous free space in its subtree.  This
1333  *      allows finding a free region in one path down the tree, so
1334  *      O(log n) amortized with splay trees.
1335  *
1336  *      The map must be locked, and leaves it so.
1337  *
1338  *      Returns: 0 on success, and starting address in *addr,
1339  *               1 if insufficient space.
1340  */
1341 int
1342 vm_map_findspace(vm_map_t map, vm_offset_t start, vm_size_t length,
1343     vm_offset_t *addr)  /* OUT */
1344 {
1345         vm_map_entry_t entry;
1346         vm_offset_t st;
1347
1348         /*
1349          * Request must fit within min/max VM address and must avoid
1350          * address wrap.
1351          */
1352         if (start < map->min_offset)
1353                 start = map->min_offset;
1354         if (start + length > map->max_offset || start + length < start)
1355                 return (1);
1356
1357         /* Empty tree means wide open address space. */
1358         if (map->root == NULL) {
1359                 *addr = start;
1360                 return (0);
1361         }
1362
1363         /*
1364          * After splay, if start comes before root node, then there
1365          * must be a gap from start to the root.
1366          */
1367         map->root = vm_map_entry_splay(start, map->root);
1368         if (start + length <= map->root->start) {
1369                 *addr = start;
1370                 return (0);
1371         }
1372
1373         /*
1374          * Root is the last node that might begin its gap before
1375          * start, and this is the last comparison where address
1376          * wrap might be a problem.
1377          */
1378         st = (start > map->root->end) ? start : map->root->end;
1379         if (length <= map->root->end + map->root->adj_free - st) {
1380                 *addr = st;
1381                 return (0);
1382         }
1383
1384         /* With max_free, can immediately tell if no solution. */
1385         entry = map->root->right;
1386         if (entry == NULL || length > entry->max_free)
1387                 return (1);
1388
1389         /*
1390          * Search the right subtree in the order: left subtree, root,
1391          * right subtree (first fit).  The previous splay implies that
1392          * all regions in the right subtree have addresses > start.
1393          */
1394         while (entry != NULL) {
1395                 if (entry->left != NULL && entry->left->max_free >= length)
1396                         entry = entry->left;
1397                 else if (entry->adj_free >= length) {
1398                         *addr = entry->end;
1399                         return (0);
1400                 } else
1401                         entry = entry->right;
1402         }
1403
1404         /* Can't get here, so panic if we do. */
1405         panic("vm_map_findspace: max_free corrupt");
1406 }
1407
1408 int
1409 vm_map_fixed(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1410     vm_offset_t start, vm_size_t length, vm_prot_t prot,
1411     vm_prot_t max, int cow)
1412 {
1413         vm_offset_t end;
1414         int result;
1415
1416         end = start + length;
1417         vm_map_lock(map);
1418         VM_MAP_RANGE_CHECK(map, start, end);
1419         (void) vm_map_delete(map, start, end);
1420         result = vm_map_insert(map, object, offset, start, end, prot,
1421             max, cow);
1422         vm_map_unlock(map);
1423         return (result);
1424 }
1425
1426 /*
1427  *      vm_map_find finds an unallocated region in the target address
1428  *      map with the given length.  The search is defined to be
1429  *      first-fit from the specified address; the region found is
1430  *      returned in the same parameter.
1431  *
1432  *      If object is non-NULL, ref count must be bumped by caller
1433  *      prior to making call to account for the new entry.
1434  */
1435 int
1436 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
1437             vm_offset_t *addr,  /* IN/OUT */
1438             vm_size_t length, int find_space, vm_prot_t prot,
1439             vm_prot_t max, int cow)
1440 {
1441         vm_offset_t start;
1442         int result;
1443
1444         start = *addr;
1445         vm_map_lock(map);
1446         do {
1447                 if (find_space != VMFS_NO_SPACE) {
1448                         if (vm_map_findspace(map, start, length, addr)) {
1449                                 vm_map_unlock(map);
1450                                 return (KERN_NO_SPACE);
1451                         }
1452                         switch (find_space) {
1453                         case VMFS_ALIGNED_SPACE:
1454                                 pmap_align_superpage(object, offset, addr,
1455                                     length);
1456                                 break;
1457 #ifdef VMFS_TLB_ALIGNED_SPACE
1458                         case VMFS_TLB_ALIGNED_SPACE:
1459                                 pmap_align_tlb(addr);
1460                                 break;
1461 #endif
1462                         default:
1463                                 break;
1464                         }
1465
1466                         start = *addr;
1467                 }
1468                 result = vm_map_insert(map, object, offset, start, start +
1469                     length, prot, max, cow);
1470         } while (result == KERN_NO_SPACE && find_space == VMFS_ALIGNED_SPACE);
1471         vm_map_unlock(map);
1472         return (result);
1473 }
1474
1475 /*
1476  *      vm_map_simplify_entry:
1477  *
1478  *      Simplify the given map entry by merging with either neighbor.  This
1479  *      routine also has the ability to merge with both neighbors.
1480  *
1481  *      The map must be locked.
1482  *
1483  *      This routine guarentees that the passed entry remains valid (though
1484  *      possibly extended).  When merging, this routine may delete one or
1485  *      both neighbors.
1486  */
1487 void
1488 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
1489 {
1490         vm_map_entry_t next, prev;
1491         vm_size_t prevsize, esize;
1492
1493         if (entry->eflags & (MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP))
1494                 return;
1495
1496         prev = entry->prev;
1497         if (prev != &map->header) {
1498                 prevsize = prev->end - prev->start;
1499                 if ( (prev->end == entry->start) &&
1500                      (prev->object.vm_object == entry->object.vm_object) &&
1501                      (!prev->object.vm_object ||
1502                         (prev->offset + prevsize == entry->offset)) &&
1503                      (prev->eflags == entry->eflags) &&
1504                      (prev->protection == entry->protection) &&
1505                      (prev->max_protection == entry->max_protection) &&
1506                      (prev->inheritance == entry->inheritance) &&
1507                      (prev->wired_count == entry->wired_count) &&
1508                      (prev->uip == entry->uip)) {
1509                         vm_map_entry_unlink(map, prev);
1510                         entry->start = prev->start;
1511                         entry->offset = prev->offset;
1512                         if (entry->prev != &map->header)
1513                                 vm_map_entry_resize_free(map, entry->prev);
1514
1515                         /*
1516                          * If the backing object is a vnode object,
1517                          * vm_object_deallocate() calls vrele().
1518                          * However, vrele() does not lock the vnode
1519                          * because the vnode has additional
1520                          * references.  Thus, the map lock can be kept
1521                          * without causing a lock-order reversal with
1522                          * the vnode lock.
1523                          */
1524                         if (prev->object.vm_object)
1525                                 vm_object_deallocate(prev->object.vm_object);
1526                         if (prev->uip != NULL)
1527                                 uifree(prev->uip);
1528                         vm_map_entry_dispose(map, prev);
1529                 }
1530         }
1531
1532         next = entry->next;
1533         if (next != &map->header) {
1534                 esize = entry->end - entry->start;
1535                 if ((entry->end == next->start) &&
1536                     (next->object.vm_object == entry->object.vm_object) &&
1537                      (!entry->object.vm_object ||
1538                         (entry->offset + esize == next->offset)) &&
1539                     (next->eflags == entry->eflags) &&
1540                     (next->protection == entry->protection) &&
1541                     (next->max_protection == entry->max_protection) &&
1542                     (next->inheritance == entry->inheritance) &&
1543                     (next->wired_count == entry->wired_count) &&
1544                     (next->uip == entry->uip)) {
1545                         vm_map_entry_unlink(map, next);
1546                         entry->end = next->end;
1547                         vm_map_entry_resize_free(map, entry);
1548
1549                         /*
1550                          * See comment above.
1551                          */
1552                         if (next->object.vm_object)
1553                                 vm_object_deallocate(next->object.vm_object);
1554                         if (next->uip != NULL)
1555                                 uifree(next->uip);
1556                         vm_map_entry_dispose(map, next);
1557                 }
1558         }
1559 }
1560 /*
1561  *      vm_map_clip_start:      [ internal use only ]
1562  *
1563  *      Asserts that the given entry begins at or after
1564  *      the specified address; if necessary,
1565  *      it splits the entry into two.
1566  */
1567 #define vm_map_clip_start(map, entry, startaddr) \
1568 { \
1569         if (startaddr > entry->start) \
1570                 _vm_map_clip_start(map, entry, startaddr); \
1571 }
1572
1573 /*
1574  *      This routine is called only when it is known that
1575  *      the entry must be split.
1576  */
1577 static void
1578 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
1579 {
1580         vm_map_entry_t new_entry;
1581
1582         VM_MAP_ASSERT_LOCKED(map);
1583
1584         /*
1585          * Split off the front portion -- note that we must insert the new
1586          * entry BEFORE this one, so that this entry has the specified
1587          * starting address.
1588          */
1589         vm_map_simplify_entry(map, entry);
1590
1591         /*
1592          * If there is no object backing this entry, we might as well create
1593          * one now.  If we defer it, an object can get created after the map
1594          * is clipped, and individual objects will be created for the split-up
1595          * map.  This is a bit of a hack, but is also about the best place to
1596          * put this improvement.
1597          */
1598         if (entry->object.vm_object == NULL && !map->system_map) {
1599                 vm_object_t object;
1600                 object = vm_object_allocate(OBJT_DEFAULT,
1601                                 atop(entry->end - entry->start));
1602                 entry->object.vm_object = object;
1603                 entry->offset = 0;
1604                 if (entry->uip != NULL) {
1605                         object->uip = entry->uip;
1606                         object->charge = entry->end - entry->start;
1607                         entry->uip = NULL;
1608                 }
1609         } else if (entry->object.vm_object != NULL &&
1610                    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1611                    entry->uip != NULL) {
1612                 VM_OBJECT_LOCK(entry->object.vm_object);
1613                 KASSERT(entry->object.vm_object->uip == NULL,
1614                     ("OVERCOMMIT: vm_entry_clip_start: both uip e %p", entry));
1615                 entry->object.vm_object->uip = entry->uip;
1616                 entry->object.vm_object->charge = entry->end - entry->start;
1617                 VM_OBJECT_UNLOCK(entry->object.vm_object);
1618                 entry->uip = NULL;
1619         }
1620
1621         new_entry = vm_map_entry_create(map);
1622         *new_entry = *entry;
1623
1624         new_entry->end = start;
1625         entry->offset += (start - entry->start);
1626         entry->start = start;
1627         if (new_entry->uip != NULL)
1628                 uihold(entry->uip);
1629
1630         vm_map_entry_link(map, entry->prev, new_entry);
1631
1632         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1633                 vm_object_reference(new_entry->object.vm_object);
1634         }
1635 }
1636
1637 /*
1638  *      vm_map_clip_end:        [ internal use only ]
1639  *
1640  *      Asserts that the given entry ends at or before
1641  *      the specified address; if necessary,
1642  *      it splits the entry into two.
1643  */
1644 #define vm_map_clip_end(map, entry, endaddr) \
1645 { \
1646         if ((endaddr) < (entry->end)) \
1647                 _vm_map_clip_end((map), (entry), (endaddr)); \
1648 }
1649
1650 /*
1651  *      This routine is called only when it is known that
1652  *      the entry must be split.
1653  */
1654 static void
1655 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
1656 {
1657         vm_map_entry_t new_entry;
1658
1659         VM_MAP_ASSERT_LOCKED(map);
1660
1661         /*
1662          * If there is no object backing this entry, we might as well create
1663          * one now.  If we defer it, an object can get created after the map
1664          * is clipped, and individual objects will be created for the split-up
1665          * map.  This is a bit of a hack, but is also about the best place to
1666          * put this improvement.
1667          */
1668         if (entry->object.vm_object == NULL && !map->system_map) {
1669                 vm_object_t object;
1670                 object = vm_object_allocate(OBJT_DEFAULT,
1671                                 atop(entry->end - entry->start));
1672                 entry->object.vm_object = object;
1673                 entry->offset = 0;
1674                 if (entry->uip != NULL) {
1675                         object->uip = entry->uip;
1676                         object->charge = entry->end - entry->start;
1677                         entry->uip = NULL;
1678                 }
1679         } else if (entry->object.vm_object != NULL &&
1680                    ((entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) &&
1681                    entry->uip != NULL) {
1682                 VM_OBJECT_LOCK(entry->object.vm_object);
1683                 KASSERT(entry->object.vm_object->uip == NULL,
1684                     ("OVERCOMMIT: vm_entry_clip_end: both uip e %p", entry));
1685                 entry->object.vm_object->uip = entry->uip;
1686                 entry->object.vm_object->charge = entry->end - entry->start;
1687                 VM_OBJECT_UNLOCK(entry->object.vm_object);
1688                 entry->uip = NULL;
1689         }
1690
1691         /*
1692          * Create a new entry and insert it AFTER the specified entry
1693          */
1694         new_entry = vm_map_entry_create(map);
1695         *new_entry = *entry;
1696
1697         new_entry->start = entry->end = end;
1698         new_entry->offset += (end - entry->start);
1699         if (new_entry->uip != NULL)
1700                 uihold(entry->uip);
1701
1702         vm_map_entry_link(map, entry, new_entry);
1703
1704         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1705                 vm_object_reference(new_entry->object.vm_object);
1706         }
1707 }
1708
1709 /*
1710  *      vm_map_submap:          [ kernel use only ]
1711  *
1712  *      Mark the given range as handled by a subordinate map.
1713  *
1714  *      This range must have been created with vm_map_find,
1715  *      and no other operations may have been performed on this
1716  *      range prior to calling vm_map_submap.
1717  *
1718  *      Only a limited number of operations can be performed
1719  *      within this rage after calling vm_map_submap:
1720  *              vm_fault
1721  *      [Don't try vm_map_copy!]
1722  *
1723  *      To remove a submapping, one must first remove the
1724  *      range from the superior map, and then destroy the
1725  *      submap (if desired).  [Better yet, don't try it.]
1726  */
1727 int
1728 vm_map_submap(
1729         vm_map_t map,
1730         vm_offset_t start,
1731         vm_offset_t end,
1732         vm_map_t submap)
1733 {
1734         vm_map_entry_t entry;
1735         int result = KERN_INVALID_ARGUMENT;
1736
1737         vm_map_lock(map);
1738
1739         VM_MAP_RANGE_CHECK(map, start, end);
1740
1741         if (vm_map_lookup_entry(map, start, &entry)) {
1742                 vm_map_clip_start(map, entry, start);
1743         } else
1744                 entry = entry->next;
1745
1746         vm_map_clip_end(map, entry, end);
1747
1748         if ((entry->start == start) && (entry->end == end) &&
1749             ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1750             (entry->object.vm_object == NULL)) {
1751                 entry->object.sub_map = submap;
1752                 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
1753                 result = KERN_SUCCESS;
1754         }
1755         vm_map_unlock(map);
1756
1757         return (result);
1758 }
1759
1760 /*
1761  * The maximum number of pages to map
1762  */
1763 #define MAX_INIT_PT     96
1764
1765 /*
1766  *      vm_map_pmap_enter:
1767  *
1768  *      Preload read-only mappings for the given object's resident pages into
1769  *      the given map.  This eliminates the soft faults on process startup and
1770  *      immediately after an mmap(2).  Because these are speculative mappings,
1771  *      cached pages are not reactivated and mapped.
1772  */
1773 void
1774 vm_map_pmap_enter(vm_map_t map, vm_offset_t addr, vm_prot_t prot,
1775     vm_object_t object, vm_pindex_t pindex, vm_size_t size, int flags)
1776 {
1777         vm_offset_t start;
1778         vm_page_t p, p_start;
1779         vm_pindex_t psize, tmpidx;
1780         boolean_t are_queues_locked;
1781
1782         if ((prot & (VM_PROT_READ | VM_PROT_EXECUTE)) == 0 || object == NULL)
1783                 return;
1784         VM_OBJECT_LOCK(object);
1785         if (object->type == OBJT_DEVICE || object->type == OBJT_SG) {
1786                 pmap_object_init_pt(map->pmap, addr, object, pindex, size);
1787                 goto unlock_return;
1788         }
1789
1790         psize = atop(size);
1791
1792         if ((flags & MAP_PREFAULT_PARTIAL) && psize > MAX_INIT_PT &&
1793             object->resident_page_count > MAX_INIT_PT)
1794                 goto unlock_return;
1795
1796         if (psize + pindex > object->size) {
1797                 if (object->size < pindex)
1798                         goto unlock_return;
1799                 psize = object->size - pindex;
1800         }
1801
1802         are_queues_locked = FALSE;
1803         start = 0;
1804         p_start = NULL;
1805
1806         p = vm_page_find_least(object, pindex);
1807         /*
1808          * Assert: the variable p is either (1) the page with the
1809          * least pindex greater than or equal to the parameter pindex
1810          * or (2) NULL.
1811          */
1812         for (;
1813              p != NULL && (tmpidx = p->pindex - pindex) < psize;
1814              p = TAILQ_NEXT(p, listq)) {
1815                 /*
1816                  * don't allow an madvise to blow away our really
1817                  * free pages allocating pv entries.
1818                  */
1819                 if ((flags & MAP_PREFAULT_MADVISE) &&
1820                     cnt.v_free_count < cnt.v_free_reserved) {
1821                         psize = tmpidx;
1822                         break;
1823                 }
1824                 if (p->valid == VM_PAGE_BITS_ALL) {
1825                         if (p_start == NULL) {
1826                                 start = addr + ptoa(tmpidx);
1827                                 p_start = p;
1828                         }
1829                 } else if (p_start != NULL) {
1830                         if (!are_queues_locked) {
1831                                 are_queues_locked = TRUE;
1832                                 vm_page_lock_queues();
1833                         }
1834                         pmap_enter_object(map->pmap, start, addr +
1835                             ptoa(tmpidx), p_start, prot);
1836                         p_start = NULL;
1837                 }
1838         }
1839         if (p_start != NULL) {
1840                 if (!are_queues_locked) {
1841                         are_queues_locked = TRUE;
1842                         vm_page_lock_queues();
1843                 }
1844                 pmap_enter_object(map->pmap, start, addr + ptoa(psize),
1845                     p_start, prot);
1846         }
1847         if (are_queues_locked)
1848                 vm_page_unlock_queues();
1849 unlock_return:
1850         VM_OBJECT_UNLOCK(object);
1851 }
1852
1853 /*
1854  *      vm_map_protect:
1855  *
1856  *      Sets the protection of the specified address
1857  *      region in the target map.  If "set_max" is
1858  *      specified, the maximum protection is to be set;
1859  *      otherwise, only the current protection is affected.
1860  */
1861 int
1862 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1863                vm_prot_t new_prot, boolean_t set_max)
1864 {
1865         vm_map_entry_t current, entry;
1866         vm_object_t obj;
1867         struct uidinfo *uip;
1868         vm_prot_t old_prot;
1869
1870         vm_map_lock(map);
1871
1872         VM_MAP_RANGE_CHECK(map, start, end);
1873
1874         if (vm_map_lookup_entry(map, start, &entry)) {
1875                 vm_map_clip_start(map, entry, start);
1876         } else {
1877                 entry = entry->next;
1878         }
1879
1880         /*
1881          * Make a first pass to check for protection violations.
1882          */
1883         current = entry;
1884         while ((current != &map->header) && (current->start < end)) {
1885                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1886                         vm_map_unlock(map);
1887                         return (KERN_INVALID_ARGUMENT);
1888                 }
1889                 if ((new_prot & current->max_protection) != new_prot) {
1890                         vm_map_unlock(map);
1891                         return (KERN_PROTECTION_FAILURE);
1892                 }
1893                 current = current->next;
1894         }
1895
1896
1897         /*
1898          * Do an accounting pass for private read-only mappings that
1899          * now will do cow due to allowed write (e.g. debugger sets
1900          * breakpoint on text segment)
1901          */
1902         for (current = entry; (current != &map->header) &&
1903              (current->start < end); current = current->next) {
1904
1905                 vm_map_clip_end(map, current, end);
1906
1907                 if (set_max ||
1908                     ((new_prot & ~(current->protection)) & VM_PROT_WRITE) == 0 ||
1909                     ENTRY_CHARGED(current)) {
1910                         continue;
1911                 }
1912
1913                 uip = curthread->td_ucred->cr_ruidinfo;
1914                 obj = current->object.vm_object;
1915
1916                 if (obj == NULL || (current->eflags & MAP_ENTRY_NEEDS_COPY)) {
1917                         if (!swap_reserve(current->end - current->start)) {
1918                                 vm_map_unlock(map);
1919                                 return (KERN_RESOURCE_SHORTAGE);
1920                         }
1921                         uihold(uip);
1922                         current->uip = uip;
1923                         continue;
1924                 }
1925
1926                 VM_OBJECT_LOCK(obj);
1927                 if (obj->type != OBJT_DEFAULT && obj->type != OBJT_SWAP) {
1928                         VM_OBJECT_UNLOCK(obj);
1929                         continue;
1930                 }
1931
1932                 /*
1933                  * Charge for the whole object allocation now, since
1934                  * we cannot distinguish between non-charged and
1935                  * charged clipped mapping of the same object later.
1936                  */
1937                 KASSERT(obj->charge == 0,
1938                     ("vm_map_protect: object %p overcharged\n", obj));
1939                 if (!swap_reserve(ptoa(obj->size))) {
1940                         VM_OBJECT_UNLOCK(obj);
1941                         vm_map_unlock(map);
1942                         return (KERN_RESOURCE_SHORTAGE);
1943                 }
1944
1945                 uihold(uip);
1946                 obj->uip = uip;
1947                 obj->charge = ptoa(obj->size);
1948                 VM_OBJECT_UNLOCK(obj);
1949         }
1950
1951         /*
1952          * Go back and fix up protections. [Note that clipping is not
1953          * necessary the second time.]
1954          */
1955         current = entry;
1956         while ((current != &map->header) && (current->start < end)) {
1957                 old_prot = current->protection;
1958
1959                 if (set_max)
1960                         current->protection =
1961                             (current->max_protection = new_prot) &
1962                             old_prot;
1963                 else
1964                         current->protection = new_prot;
1965
1966                 if ((current->eflags & (MAP_ENTRY_COW | MAP_ENTRY_USER_WIRED))
1967                      == (MAP_ENTRY_COW | MAP_ENTRY_USER_WIRED) &&
1968                     (current->protection & VM_PROT_WRITE) != 0 &&
1969                     (old_prot & VM_PROT_WRITE) == 0) {
1970                         vm_fault_copy_entry(map, map, current, current, NULL);
1971                 }
1972
1973                 /*
1974                  * Update physical map if necessary. Worry about copy-on-write
1975                  * here.
1976                  */
1977                 if (current->protection != old_prot) {
1978 #define MASK(entry)     (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1979                                                         VM_PROT_ALL)
1980                         pmap_protect(map->pmap, current->start,
1981                             current->end,
1982                             current->protection & MASK(current));
1983 #undef  MASK
1984                 }
1985                 vm_map_simplify_entry(map, current);
1986                 current = current->next;
1987         }
1988         vm_map_unlock(map);
1989         return (KERN_SUCCESS);
1990 }
1991
1992 /*
1993  *      vm_map_madvise:
1994  *
1995  *      This routine traverses a processes map handling the madvise
1996  *      system call.  Advisories are classified as either those effecting
1997  *      the vm_map_entry structure, or those effecting the underlying
1998  *      objects.
1999  */
2000 int
2001 vm_map_madvise(
2002         vm_map_t map,
2003         vm_offset_t start,
2004         vm_offset_t end,
2005         int behav)
2006 {
2007         vm_map_entry_t current, entry;
2008         int modify_map = 0;
2009
2010         /*
2011          * Some madvise calls directly modify the vm_map_entry, in which case
2012          * we need to use an exclusive lock on the map and we need to perform
2013          * various clipping operations.  Otherwise we only need a read-lock
2014          * on the map.
2015          */
2016         switch(behav) {
2017         case MADV_NORMAL:
2018         case MADV_SEQUENTIAL:
2019         case MADV_RANDOM:
2020         case MADV_NOSYNC:
2021         case MADV_AUTOSYNC:
2022         case MADV_NOCORE:
2023         case MADV_CORE:
2024                 modify_map = 1;
2025                 vm_map_lock(map);
2026                 break;
2027         case MADV_WILLNEED:
2028         case MADV_DONTNEED:
2029         case MADV_FREE:
2030                 vm_map_lock_read(map);
2031                 break;
2032         default:
2033                 return (KERN_INVALID_ARGUMENT);
2034         }
2035
2036         /*
2037          * Locate starting entry and clip if necessary.
2038          */
2039         VM_MAP_RANGE_CHECK(map, start, end);
2040
2041         if (vm_map_lookup_entry(map, start, &entry)) {
2042                 if (modify_map)
2043                         vm_map_clip_start(map, entry, start);
2044         } else {
2045                 entry = entry->next;
2046         }
2047
2048         if (modify_map) {
2049                 /*
2050                  * madvise behaviors that are implemented in the vm_map_entry.
2051                  *
2052                  * We clip the vm_map_entry so that behavioral changes are
2053                  * limited to the specified address range.
2054                  */
2055                 for (current = entry;
2056                      (current != &map->header) && (current->start < end);
2057                      current = current->next
2058                 ) {
2059                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2060                                 continue;
2061
2062                         vm_map_clip_end(map, current, end);
2063
2064                         switch (behav) {
2065                         case MADV_NORMAL:
2066                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
2067                                 break;
2068                         case MADV_SEQUENTIAL:
2069                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
2070                                 break;
2071                         case MADV_RANDOM:
2072                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
2073                                 break;
2074                         case MADV_NOSYNC:
2075                                 current->eflags |= MAP_ENTRY_NOSYNC;
2076                                 break;
2077                         case MADV_AUTOSYNC:
2078                                 current->eflags &= ~MAP_ENTRY_NOSYNC;
2079                                 break;
2080                         case MADV_NOCORE:
2081                                 current->eflags |= MAP_ENTRY_NOCOREDUMP;
2082                                 break;
2083                         case MADV_CORE:
2084                                 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
2085                                 break;
2086                         default:
2087                                 break;
2088                         }
2089                         vm_map_simplify_entry(map, current);
2090                 }
2091                 vm_map_unlock(map);
2092         } else {
2093                 vm_pindex_t pindex;
2094                 int count;
2095
2096                 /*
2097                  * madvise behaviors that are implemented in the underlying
2098                  * vm_object.
2099                  *
2100                  * Since we don't clip the vm_map_entry, we have to clip
2101                  * the vm_object pindex and count.
2102                  */
2103                 for (current = entry;
2104                      (current != &map->header) && (current->start < end);
2105                      current = current->next
2106                 ) {
2107                         vm_offset_t useStart;
2108
2109                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
2110                                 continue;
2111
2112                         pindex = OFF_TO_IDX(current->offset);
2113                         count = atop(current->end - current->start);
2114                         useStart = current->start;
2115
2116                         if (current->start < start) {
2117                                 pindex += atop(start - current->start);
2118                                 count -= atop(start - current->start);
2119                                 useStart = start;
2120                         }
2121                         if (current->end > end)
2122                                 count -= atop(current->end - end);
2123
2124                         if (count <= 0)
2125                                 continue;
2126
2127                         vm_object_madvise(current->object.vm_object,
2128                                           pindex, count, behav);
2129                         if (behav == MADV_WILLNEED) {
2130                                 vm_map_pmap_enter(map,
2131                                     useStart,
2132                                     current->protection,
2133                                     current->object.vm_object,
2134                                     pindex,
2135                                     (count << PAGE_SHIFT),
2136                                     MAP_PREFAULT_MADVISE
2137                                 );
2138                         }
2139                 }
2140                 vm_map_unlock_read(map);
2141         }
2142         return (0);
2143 }
2144
2145
2146 /*
2147  *      vm_map_inherit:
2148  *
2149  *      Sets the inheritance of the specified address
2150  *      range in the target map.  Inheritance
2151  *      affects how the map will be shared with
2152  *      child maps at the time of vmspace_fork.
2153  */
2154 int
2155 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
2156                vm_inherit_t new_inheritance)
2157 {
2158         vm_map_entry_t entry;
2159         vm_map_entry_t temp_entry;
2160
2161         switch (new_inheritance) {
2162         case VM_INHERIT_NONE:
2163         case VM_INHERIT_COPY:
2164         case VM_INHERIT_SHARE:
2165                 break;
2166         default:
2167                 return (KERN_INVALID_ARGUMENT);
2168         }
2169         vm_map_lock(map);
2170         VM_MAP_RANGE_CHECK(map, start, end);
2171         if (vm_map_lookup_entry(map, start, &temp_entry)) {
2172                 entry = temp_entry;
2173                 vm_map_clip_start(map, entry, start);
2174         } else
2175                 entry = temp_entry->next;
2176         while ((entry != &map->header) && (entry->start < end)) {
2177                 vm_map_clip_end(map, entry, end);
2178                 entry->inheritance = new_inheritance;
2179                 vm_map_simplify_entry(map, entry);
2180                 entry = entry->next;
2181         }
2182         vm_map_unlock(map);
2183         return (KERN_SUCCESS);
2184 }
2185
2186 /*
2187  *      vm_map_unwire:
2188  *
2189  *      Implements both kernel and user unwiring.
2190  */
2191 int
2192 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2193     int flags)
2194 {
2195         vm_map_entry_t entry, first_entry, tmp_entry;
2196         vm_offset_t saved_start;
2197         unsigned int last_timestamp;
2198         int rv;
2199         boolean_t need_wakeup, result, user_unwire;
2200
2201         user_unwire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2202         vm_map_lock(map);
2203         VM_MAP_RANGE_CHECK(map, start, end);
2204         if (!vm_map_lookup_entry(map, start, &first_entry)) {
2205                 if (flags & VM_MAP_WIRE_HOLESOK)
2206                         first_entry = first_entry->next;
2207                 else {
2208                         vm_map_unlock(map);
2209                         return (KERN_INVALID_ADDRESS);
2210                 }
2211         }
2212         last_timestamp = map->timestamp;
2213         entry = first_entry;
2214         while (entry != &map->header && entry->start < end) {
2215                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2216                         /*
2217                          * We have not yet clipped the entry.
2218                          */
2219                         saved_start = (start >= entry->start) ? start :
2220                             entry->start;
2221                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2222                         if (vm_map_unlock_and_wait(map, 0)) {
2223                                 /*
2224                                  * Allow interruption of user unwiring?
2225                                  */
2226                         }
2227                         vm_map_lock(map);
2228                         if (last_timestamp+1 != map->timestamp) {
2229                                 /*
2230                                  * Look again for the entry because the map was
2231                                  * modified while it was unlocked.
2232                                  * Specifically, the entry may have been
2233                                  * clipped, merged, or deleted.
2234                                  */
2235                                 if (!vm_map_lookup_entry(map, saved_start,
2236                                     &tmp_entry)) {
2237                                         if (flags & VM_MAP_WIRE_HOLESOK)
2238                                                 tmp_entry = tmp_entry->next;
2239                                         else {
2240                                                 if (saved_start == start) {
2241                                                         /*
2242                                                          * First_entry has been deleted.
2243                                                          */
2244                                                         vm_map_unlock(map);
2245                                                         return (KERN_INVALID_ADDRESS);
2246                                                 }
2247                                                 end = saved_start;
2248                                                 rv = KERN_INVALID_ADDRESS;
2249                                                 goto done;
2250                                         }
2251                                 }
2252                                 if (entry == first_entry)
2253                                         first_entry = tmp_entry;
2254                                 else
2255                                         first_entry = NULL;
2256                                 entry = tmp_entry;
2257                         }
2258                         last_timestamp = map->timestamp;
2259                         continue;
2260                 }
2261                 vm_map_clip_start(map, entry, start);
2262                 vm_map_clip_end(map, entry, end);
2263                 /*
2264                  * Mark the entry in case the map lock is released.  (See
2265                  * above.)
2266                  */
2267                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2268                 /*
2269                  * Check the map for holes in the specified region.
2270                  * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2271                  */
2272                 if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2273                     (entry->end < end && (entry->next == &map->header ||
2274                     entry->next->start > entry->end))) {
2275                         end = entry->end;
2276                         rv = KERN_INVALID_ADDRESS;
2277                         goto done;
2278                 }
2279                 /*
2280                  * If system unwiring, require that the entry is system wired.
2281                  */
2282                 if (!user_unwire &&
2283                     vm_map_entry_system_wired_count(entry) == 0) {
2284                         end = entry->end;
2285                         rv = KERN_INVALID_ARGUMENT;
2286                         goto done;
2287                 }
2288                 entry = entry->next;
2289         }
2290         rv = KERN_SUCCESS;
2291 done:
2292         need_wakeup = FALSE;
2293         if (first_entry == NULL) {
2294                 result = vm_map_lookup_entry(map, start, &first_entry);
2295                 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2296                         first_entry = first_entry->next;
2297                 else
2298                         KASSERT(result, ("vm_map_unwire: lookup failed"));
2299         }
2300         entry = first_entry;
2301         while (entry != &map->header && entry->start < end) {
2302                 if (rv == KERN_SUCCESS && (!user_unwire ||
2303                     (entry->eflags & MAP_ENTRY_USER_WIRED))) {
2304                         if (user_unwire)
2305                                 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2306                         entry->wired_count--;
2307                         if (entry->wired_count == 0) {
2308                                 /*
2309                                  * Retain the map lock.
2310                                  */
2311                                 vm_fault_unwire(map, entry->start, entry->end,
2312                                     entry->object.vm_object != NULL &&
2313                                     (entry->object.vm_object->type == OBJT_DEVICE ||
2314                                     entry->object.vm_object->type == OBJT_SG));
2315                         }
2316                 }
2317                 KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
2318                         ("vm_map_unwire: in-transition flag missing"));
2319                 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
2320                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2321                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2322                         need_wakeup = TRUE;
2323                 }
2324                 vm_map_simplify_entry(map, entry);
2325                 entry = entry->next;
2326         }
2327         vm_map_unlock(map);
2328         if (need_wakeup)
2329                 vm_map_wakeup(map);
2330         return (rv);
2331 }
2332
2333 /*
2334  *      vm_map_wire:
2335  *
2336  *      Implements both kernel and user wiring.
2337  */
2338 int
2339 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
2340     int flags)
2341 {
2342         vm_map_entry_t entry, first_entry, tmp_entry;
2343         vm_offset_t saved_end, saved_start;
2344         unsigned int last_timestamp;
2345         int rv;
2346         boolean_t fictitious, need_wakeup, result, user_wire;
2347
2348         user_wire = (flags & VM_MAP_WIRE_USER) ? TRUE : FALSE;
2349         vm_map_lock(map);
2350         VM_MAP_RANGE_CHECK(map, start, end);
2351         if (!vm_map_lookup_entry(map, start, &first_entry)) {
2352                 if (flags & VM_MAP_WIRE_HOLESOK)
2353                         first_entry = first_entry->next;
2354                 else {
2355                         vm_map_unlock(map);
2356                         return (KERN_INVALID_ADDRESS);
2357                 }
2358         }
2359         last_timestamp = map->timestamp;
2360         entry = first_entry;
2361         while (entry != &map->header && entry->start < end) {
2362                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
2363                         /*
2364                          * We have not yet clipped the entry.
2365                          */
2366                         saved_start = (start >= entry->start) ? start :
2367                             entry->start;
2368                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2369                         if (vm_map_unlock_and_wait(map, 0)) {
2370                                 /*
2371                                  * Allow interruption of user wiring?
2372                                  */
2373                         }
2374                         vm_map_lock(map);
2375                         if (last_timestamp + 1 != map->timestamp) {
2376                                 /*
2377                                  * Look again for the entry because the map was
2378                                  * modified while it was unlocked.
2379                                  * Specifically, the entry may have been
2380                                  * clipped, merged, or deleted.
2381                                  */
2382                                 if (!vm_map_lookup_entry(map, saved_start,
2383                                     &tmp_entry)) {
2384                                         if (flags & VM_MAP_WIRE_HOLESOK)
2385                                                 tmp_entry = tmp_entry->next;
2386                                         else {
2387                                                 if (saved_start == start) {
2388                                                         /*
2389                                                          * first_entry has been deleted.
2390                                                          */
2391                                                         vm_map_unlock(map);
2392                                                         return (KERN_INVALID_ADDRESS);
2393                                                 }
2394                                                 end = saved_start;
2395                                                 rv = KERN_INVALID_ADDRESS;
2396                                                 goto done;
2397                                         }
2398                                 }
2399                                 if (entry == first_entry)
2400                                         first_entry = tmp_entry;
2401                                 else
2402                                         first_entry = NULL;
2403                                 entry = tmp_entry;
2404                         }
2405                         last_timestamp = map->timestamp;
2406                         continue;
2407                 }
2408                 vm_map_clip_start(map, entry, start);
2409                 vm_map_clip_end(map, entry, end);
2410                 /*
2411                  * Mark the entry in case the map lock is released.  (See
2412                  * above.)
2413                  */
2414                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
2415                 /*
2416                  *
2417                  */
2418                 if (entry->wired_count == 0) {
2419                         if ((entry->protection & (VM_PROT_READ|VM_PROT_EXECUTE))
2420                             == 0) {
2421                                 entry->eflags |= MAP_ENTRY_WIRE_SKIPPED;
2422                                 if ((flags & VM_MAP_WIRE_HOLESOK) == 0) {
2423                                         end = entry->end;
2424                                         rv = KERN_INVALID_ADDRESS;
2425                                         goto done;
2426                                 }
2427                                 goto next_entry;
2428                         }
2429                         entry->wired_count++;
2430                         saved_start = entry->start;
2431                         saved_end = entry->end;
2432                         fictitious = entry->object.vm_object != NULL &&
2433                             (entry->object.vm_object->type == OBJT_DEVICE ||
2434                             entry->object.vm_object->type == OBJT_SG);
2435                         /*
2436                          * Release the map lock, relying on the in-transition
2437                          * mark.  Mark the map busy for fork.
2438                          */
2439                         vm_map_busy(map);
2440                         vm_map_unlock(map);
2441                         rv = vm_fault_wire(map, saved_start, saved_end,
2442                             user_wire, fictitious);
2443                         vm_map_lock(map);
2444                         vm_map_unbusy(map);
2445                         if (last_timestamp + 1 != map->timestamp) {
2446                                 /*
2447                                  * Look again for the entry because the map was
2448                                  * modified while it was unlocked.  The entry
2449                                  * may have been clipped, but NOT merged or
2450                                  * deleted.
2451                                  */
2452                                 result = vm_map_lookup_entry(map, saved_start,
2453                                     &tmp_entry);
2454                                 KASSERT(result, ("vm_map_wire: lookup failed"));
2455                                 if (entry == first_entry)
2456                                         first_entry = tmp_entry;
2457                                 else
2458                                         first_entry = NULL;
2459                                 entry = tmp_entry;
2460                                 while (entry->end < saved_end) {
2461                                         if (rv != KERN_SUCCESS) {
2462                                                 KASSERT(entry->wired_count == 1,
2463                                                     ("vm_map_wire: bad count"));
2464                                                 entry->wired_count = -1;
2465                                         }
2466                                         entry = entry->next;
2467                                 }
2468                         }
2469                         last_timestamp = map->timestamp;
2470                         if (rv != KERN_SUCCESS) {
2471                                 KASSERT(entry->wired_count == 1,
2472                                     ("vm_map_wire: bad count"));
2473                                 /*
2474                                  * Assign an out-of-range value to represent
2475                                  * the failure to wire this entry.
2476                                  */
2477                                 entry->wired_count = -1;
2478                                 end = entry->end;
2479                                 goto done;
2480                         }
2481                 } else if (!user_wire ||
2482                            (entry->eflags & MAP_ENTRY_USER_WIRED) == 0) {
2483                         entry->wired_count++;
2484                 }
2485                 /*
2486                  * Check the map for holes in the specified region.
2487                  * If VM_MAP_WIRE_HOLESOK was specified, skip this check.
2488                  */
2489         next_entry:
2490                 if (((flags & VM_MAP_WIRE_HOLESOK) == 0) &&
2491                     (entry->end < end && (entry->next == &map->header ||
2492                     entry->next->start > entry->end))) {
2493                         end = entry->end;
2494                         rv = KERN_INVALID_ADDRESS;
2495                         goto done;
2496                 }
2497                 entry = entry->next;
2498         }
2499         rv = KERN_SUCCESS;
2500 done:
2501         need_wakeup = FALSE;
2502         if (first_entry == NULL) {
2503                 result = vm_map_lookup_entry(map, start, &first_entry);
2504                 if (!result && (flags & VM_MAP_WIRE_HOLESOK))
2505                         first_entry = first_entry->next;
2506                 else
2507                         KASSERT(result, ("vm_map_wire: lookup failed"));
2508         }
2509         entry = first_entry;
2510         while (entry != &map->header && entry->start < end) {
2511                 if ((entry->eflags & MAP_ENTRY_WIRE_SKIPPED) != 0)
2512                         goto next_entry_done;
2513                 if (rv == KERN_SUCCESS) {
2514                         if (user_wire)
2515                                 entry->eflags |= MAP_ENTRY_USER_WIRED;
2516                 } else if (entry->wired_count == -1) {
2517                         /*
2518                          * Wiring failed on this entry.  Thus, unwiring is
2519                          * unnecessary.
2520                          */
2521                         entry->wired_count = 0;
2522                 } else {
2523                         if (!user_wire ||
2524                             (entry->eflags & MAP_ENTRY_USER_WIRED) == 0)
2525                                 entry->wired_count--;
2526                         if (entry->wired_count == 0) {
2527                                 /*
2528                                  * Retain the map lock.
2529                                  */
2530                                 vm_fault_unwire(map, entry->start, entry->end,
2531                                     entry->object.vm_object != NULL &&
2532                                     (entry->object.vm_object->type == OBJT_DEVICE ||
2533                                     entry->object.vm_object->type == OBJT_SG));
2534                         }
2535                 }
2536         next_entry_done:
2537                 KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
2538                         ("vm_map_wire: in-transition flag missing"));
2539                 entry->eflags &= ~(MAP_ENTRY_IN_TRANSITION|MAP_ENTRY_WIRE_SKIPPED);
2540                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
2541                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
2542                         need_wakeup = TRUE;
2543                 }
2544                 vm_map_simplify_entry(map, entry);
2545                 entry = entry->next;
2546         }
2547         vm_map_unlock(map);
2548         if (need_wakeup)
2549                 vm_map_wakeup(map);
2550         return (rv);
2551 }
2552
2553 /*
2554  * vm_map_sync
2555  *
2556  * Push any dirty cached pages in the address range to their pager.
2557  * If syncio is TRUE, dirty pages are written synchronously.
2558  * If invalidate is TRUE, any cached pages are freed as well.
2559  *
2560  * If the size of the region from start to end is zero, we are
2561  * supposed to flush all modified pages within the region containing
2562  * start.  Unfortunately, a region can be split or coalesced with
2563  * neighboring regions, making it difficult to determine what the
2564  * original region was.  Therefore, we approximate this requirement by
2565  * flushing the current region containing start.
2566  *
2567  * Returns an error if any part of the specified range is not mapped.
2568  */
2569 int
2570 vm_map_sync(
2571         vm_map_t map,
2572         vm_offset_t start,
2573         vm_offset_t end,
2574         boolean_t syncio,
2575         boolean_t invalidate)
2576 {
2577         vm_map_entry_t current;
2578         vm_map_entry_t entry;
2579         vm_size_t size;
2580         vm_object_t object;
2581         vm_ooffset_t offset;
2582         unsigned int last_timestamp;
2583
2584         vm_map_lock_read(map);
2585         VM_MAP_RANGE_CHECK(map, start, end);
2586         if (!vm_map_lookup_entry(map, start, &entry)) {
2587                 vm_map_unlock_read(map);
2588                 return (KERN_INVALID_ADDRESS);
2589         } else if (start == end) {
2590                 start = entry->start;
2591                 end = entry->end;
2592         }
2593         /*
2594          * Make a first pass to check for user-wired memory and holes.
2595          */
2596         for (current = entry; current != &map->header && current->start < end;
2597             current = current->next) {
2598                 if (invalidate && (current->eflags & MAP_ENTRY_USER_WIRED)) {
2599                         vm_map_unlock_read(map);
2600                         return (KERN_INVALID_ARGUMENT);
2601                 }
2602                 if (end > current->end &&
2603                     (current->next == &map->header ||
2604                         current->end != current->next->start)) {
2605                         vm_map_unlock_read(map);
2606                         return (KERN_INVALID_ADDRESS);
2607                 }
2608         }
2609
2610         if (invalidate)
2611                 pmap_remove(map->pmap, start, end);
2612
2613         /*
2614          * Make a second pass, cleaning/uncaching pages from the indicated
2615          * objects as we go.
2616          */
2617         for (current = entry; current != &map->header && current->start < end;) {
2618                 offset = current->offset + (start - current->start);
2619                 size = (end <= current->end ? end : current->end) - start;
2620                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2621                         vm_map_t smap;
2622                         vm_map_entry_t tentry;
2623                         vm_size_t tsize;
2624
2625                         smap = current->object.sub_map;
2626                         vm_map_lock_read(smap);
2627                         (void) vm_map_lookup_entry(smap, offset, &tentry);
2628                         tsize = tentry->end - offset;
2629                         if (tsize < size)
2630                                 size = tsize;
2631                         object = tentry->object.vm_object;
2632                         offset = tentry->offset + (offset - tentry->start);
2633                         vm_map_unlock_read(smap);
2634                 } else {
2635                         object = current->object.vm_object;
2636                 }
2637                 vm_object_reference(object);
2638                 last_timestamp = map->timestamp;
2639                 vm_map_unlock_read(map);
2640                 vm_object_sync(object, offset, size, syncio, invalidate);
2641                 start += size;
2642                 vm_object_deallocate(object);
2643                 vm_map_lock_read(map);
2644                 if (last_timestamp == map->timestamp ||
2645                     !vm_map_lookup_entry(map, start, &current))
2646                         current = current->next;
2647         }
2648
2649         vm_map_unlock_read(map);
2650         return (KERN_SUCCESS);
2651 }
2652
2653 /*
2654  *      vm_map_entry_unwire:    [ internal use only ]
2655  *
2656  *      Make the region specified by this entry pageable.
2657  *
2658  *      The map in question should be locked.
2659  *      [This is the reason for this routine's existence.]
2660  */
2661 static void
2662 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2663 {
2664         vm_fault_unwire(map, entry->start, entry->end,
2665             entry->object.vm_object != NULL &&
2666             (entry->object.vm_object->type == OBJT_DEVICE ||
2667             entry->object.vm_object->type == OBJT_SG));
2668         entry->wired_count = 0;
2669 }
2670
2671 static void
2672 vm_map_entry_deallocate(vm_map_entry_t entry, boolean_t system_map)
2673 {
2674
2675         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0)
2676                 vm_object_deallocate(entry->object.vm_object);
2677         uma_zfree(system_map ? kmapentzone : mapentzone, entry);
2678 }
2679
2680 /*
2681  *      vm_map_entry_delete:    [ internal use only ]
2682  *
2683  *      Deallocate the given entry from the target map.
2684  */
2685 static void
2686 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
2687 {
2688         vm_object_t object;
2689         vm_pindex_t offidxstart, offidxend, count, size1;
2690         vm_ooffset_t size;
2691
2692         vm_map_entry_unlink(map, entry);
2693         object = entry->object.vm_object;
2694         size = entry->end - entry->start;
2695         map->size -= size;
2696
2697         if (entry->uip != NULL) {
2698                 swap_release_by_uid(size, entry->uip);
2699                 uifree(entry->uip);
2700         }
2701
2702         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
2703             (object != NULL)) {
2704                 KASSERT(entry->uip == NULL || object->uip == NULL ||
2705                     (entry->eflags & MAP_ENTRY_NEEDS_COPY),
2706                     ("OVERCOMMIT vm_map_entry_delete: both uip %p", entry));
2707                 count = OFF_TO_IDX(size);
2708                 offidxstart = OFF_TO_IDX(entry->offset);
2709                 offidxend = offidxstart + count;
2710                 VM_OBJECT_LOCK(object);
2711                 if (object->ref_count != 1 &&
2712                     ((object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING ||
2713                     object == kernel_object || object == kmem_object)) {
2714                         vm_object_collapse(object);
2715                         vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2716                         if (object->type == OBJT_SWAP)
2717                                 swap_pager_freespace(object, offidxstart, count);
2718                         if (offidxend >= object->size &&
2719                             offidxstart < object->size) {
2720                                 size1 = object->size;
2721                                 object->size = offidxstart;
2722                                 if (object->uip != NULL) {
2723                                         size1 -= object->size;
2724                                         KASSERT(object->charge >= ptoa(size1),
2725                                             ("vm_map_entry_delete: object->charge < 0"));
2726                                         swap_release_by_uid(ptoa(size1), object->uip);
2727                                         object->charge -= ptoa(size1);
2728                                 }
2729                         }
2730                 }
2731                 VM_OBJECT_UNLOCK(object);
2732         } else
2733                 entry->object.vm_object = NULL;
2734         if (map->system_map)
2735                 vm_map_entry_deallocate(entry, TRUE);
2736         else {
2737                 entry->next = curthread->td_map_def_user;
2738                 curthread->td_map_def_user = entry;
2739         }
2740 }
2741
2742 /*
2743  *      vm_map_delete:  [ internal use only ]
2744  *
2745  *      Deallocates the given address range from the target
2746  *      map.
2747  */
2748 int
2749 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
2750 {
2751         vm_map_entry_t entry;
2752         vm_map_entry_t first_entry;
2753
2754         VM_MAP_ASSERT_LOCKED(map);
2755
2756         /*
2757          * Find the start of the region, and clip it
2758          */
2759         if (!vm_map_lookup_entry(map, start, &first_entry))
2760                 entry = first_entry->next;
2761         else {
2762                 entry = first_entry;
2763                 vm_map_clip_start(map, entry, start);
2764         }
2765
2766         /*
2767          * Step through all entries in this region
2768          */
2769         while ((entry != &map->header) && (entry->start < end)) {
2770                 vm_map_entry_t next;
2771
2772                 /*
2773                  * Wait for wiring or unwiring of an entry to complete.
2774                  * Also wait for any system wirings to disappear on
2775                  * user maps.
2776                  */
2777                 if ((entry->eflags & MAP_ENTRY_IN_TRANSITION) != 0 ||
2778                     (vm_map_pmap(map) != kernel_pmap &&
2779                     vm_map_entry_system_wired_count(entry) != 0)) {
2780                         unsigned int last_timestamp;
2781                         vm_offset_t saved_start;
2782                         vm_map_entry_t tmp_entry;
2783
2784                         saved_start = entry->start;
2785                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
2786                         last_timestamp = map->timestamp;
2787                         (void) vm_map_unlock_and_wait(map, 0);
2788                         vm_map_lock(map);
2789                         if (last_timestamp + 1 != map->timestamp) {
2790                                 /*
2791                                  * Look again for the entry because the map was
2792                                  * modified while it was unlocked.
2793                                  * Specifically, the entry may have been
2794                                  * clipped, merged, or deleted.
2795                                  */
2796                                 if (!vm_map_lookup_entry(map, saved_start,
2797                                                          &tmp_entry))
2798                                         entry = tmp_entry->next;
2799                                 else {
2800                                         entry = tmp_entry;
2801                                         vm_map_clip_start(map, entry,
2802                                                           saved_start);
2803                                 }
2804                         }
2805                         continue;
2806                 }
2807                 vm_map_clip_end(map, entry, end);
2808
2809                 next = entry->next;
2810
2811                 /*
2812                  * Unwire before removing addresses from the pmap; otherwise,
2813                  * unwiring will put the entries back in the pmap.
2814                  */
2815                 if (entry->wired_count != 0) {
2816                         vm_map_entry_unwire(map, entry);
2817                 }
2818
2819                 pmap_remove(map->pmap, entry->start, entry->end);
2820
2821                 /*
2822                  * Delete the entry only after removing all pmap
2823                  * entries pointing to its pages.  (Otherwise, its
2824                  * page frames may be reallocated, and any modify bits
2825                  * will be set in the wrong object!)
2826                  */
2827                 vm_map_entry_delete(map, entry);
2828                 entry = next;
2829         }
2830         return (KERN_SUCCESS);
2831 }
2832
2833 /*
2834  *      vm_map_remove:
2835  *
2836  *      Remove the given address range from the target map.
2837  *      This is the exported form of vm_map_delete.
2838  */
2839 int
2840 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2841 {
2842         int result;
2843
2844         vm_map_lock(map);
2845         VM_MAP_RANGE_CHECK(map, start, end);
2846         result = vm_map_delete(map, start, end);
2847         vm_map_unlock(map);
2848         return (result);
2849 }
2850
2851 /*
2852  *      vm_map_check_protection:
2853  *
2854  *      Assert that the target map allows the specified privilege on the
2855  *      entire address region given.  The entire region must be allocated.
2856  *
2857  *      WARNING!  This code does not and should not check whether the
2858  *      contents of the region is accessible.  For example a smaller file
2859  *      might be mapped into a larger address space.
2860  *
2861  *      NOTE!  This code is also called by munmap().
2862  *
2863  *      The map must be locked.  A read lock is sufficient.
2864  */
2865 boolean_t
2866 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2867                         vm_prot_t protection)
2868 {
2869         vm_map_entry_t entry;
2870         vm_map_entry_t tmp_entry;
2871
2872         if (!vm_map_lookup_entry(map, start, &tmp_entry))
2873                 return (FALSE);
2874         entry = tmp_entry;
2875
2876         while (start < end) {
2877                 if (entry == &map->header)
2878                         return (FALSE);
2879                 /*
2880                  * No holes allowed!
2881                  */
2882                 if (start < entry->start)
2883                         return (FALSE);
2884                 /*
2885                  * Check protection associated with entry.
2886                  */
2887                 if ((entry->protection & protection) != protection)
2888                         return (FALSE);
2889                 /* go to next entry */
2890                 start = entry->end;
2891                 entry = entry->next;
2892         }
2893         return (TRUE);
2894 }
2895
2896 /*
2897  *      vm_map_copy_entry:
2898  *
2899  *      Copies the contents of the source entry to the destination
2900  *      entry.  The entries *must* be aligned properly.
2901  */
2902 static void
2903 vm_map_copy_entry(
2904         vm_map_t src_map,
2905         vm_map_t dst_map,
2906         vm_map_entry_t src_entry,
2907         vm_map_entry_t dst_entry,
2908         vm_ooffset_t *fork_charge)
2909 {
2910         vm_object_t src_object;
2911         vm_offset_t size;
2912         struct uidinfo *uip;
2913         int charged;
2914
2915         VM_MAP_ASSERT_LOCKED(dst_map);
2916
2917         if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
2918                 return;
2919
2920         if (src_entry->wired_count == 0) {
2921
2922                 /*
2923                  * If the source entry is marked needs_copy, it is already
2924                  * write-protected.
2925                  */
2926                 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2927                         pmap_protect(src_map->pmap,
2928                             src_entry->start,
2929                             src_entry->end,
2930                             src_entry->protection & ~VM_PROT_WRITE);
2931                 }
2932
2933                 /*
2934                  * Make a copy of the object.
2935                  */
2936                 size = src_entry->end - src_entry->start;
2937                 if ((src_object = src_entry->object.vm_object) != NULL) {
2938                         VM_OBJECT_LOCK(src_object);
2939                         charged = ENTRY_CHARGED(src_entry);
2940                         if ((src_object->handle == NULL) &&
2941                                 (src_object->type == OBJT_DEFAULT ||
2942                                  src_object->type == OBJT_SWAP)) {
2943                                 vm_object_collapse(src_object);
2944                                 if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
2945                                         vm_object_split(src_entry);
2946                                         src_object = src_entry->object.vm_object;
2947                                 }
2948                         }
2949                         vm_object_reference_locked(src_object);
2950                         vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2951                         if (src_entry->uip != NULL &&
2952                             !(src_entry->eflags & MAP_ENTRY_NEEDS_COPY)) {
2953                                 KASSERT(src_object->uip == NULL,
2954                                     ("OVERCOMMIT: vm_map_copy_entry: uip %p",
2955                                      src_object));
2956                                 src_object->uip = src_entry->uip;
2957                                 src_object->charge = size;
2958                         }
2959                         VM_OBJECT_UNLOCK(src_object);
2960                         dst_entry->object.vm_object = src_object;
2961                         if (charged) {
2962                                 uip = curthread->td_ucred->cr_ruidinfo;
2963                                 uihold(uip);
2964                                 dst_entry->uip = uip;
2965                                 *fork_charge += size;
2966                                 if (!(src_entry->eflags &
2967                                       MAP_ENTRY_NEEDS_COPY)) {
2968                                         uihold(uip);
2969                                         src_entry->uip = uip;
2970                                         *fork_charge += size;
2971                                 }
2972                         }
2973                         src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2974                         dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2975                         dst_entry->offset = src_entry->offset;
2976                 } else {
2977                         dst_entry->object.vm_object = NULL;
2978                         dst_entry->offset = 0;
2979                         if (src_entry->uip != NULL) {
2980                                 dst_entry->uip = curthread->td_ucred->cr_ruidinfo;
2981                                 uihold(dst_entry->uip);
2982                                 *fork_charge += size;
2983                         }
2984                 }
2985
2986                 pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
2987                     dst_entry->end - dst_entry->start, src_entry->start);
2988         } else {
2989                 /*
2990                  * Of course, wired down pages can't be set copy-on-write.
2991                  * Cause wired pages to be copied into the new map by
2992                  * simulating faults (the new pages are pageable)
2993                  */
2994                 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry,
2995                     fork_charge);
2996         }
2997 }
2998
2999 /*
3000  * vmspace_map_entry_forked:
3001  * Update the newly-forked vmspace each time a map entry is inherited
3002  * or copied.  The values for vm_dsize and vm_tsize are approximate
3003  * (and mostly-obsolete ideas in the face of mmap(2) et al.)
3004  */
3005 static void
3006 vmspace_map_entry_forked(const struct vmspace *vm1, struct vmspace *vm2,
3007     vm_map_entry_t entry)
3008 {
3009         vm_size_t entrysize;
3010         vm_offset_t newend;
3011
3012         entrysize = entry->end - entry->start;
3013         vm2->vm_map.size += entrysize;
3014         if (entry->eflags & (MAP_ENTRY_GROWS_DOWN | MAP_ENTRY_GROWS_UP)) {
3015                 vm2->vm_ssize += btoc(entrysize);
3016         } else if (entry->start >= (vm_offset_t)vm1->vm_daddr &&
3017             entry->start < (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize)) {
3018                 newend = MIN(entry->end,
3019                     (vm_offset_t)vm1->vm_daddr + ctob(vm1->vm_dsize));
3020                 vm2->vm_dsize += btoc(newend - entry->start);
3021         } else if (entry->start >= (vm_offset_t)vm1->vm_taddr &&
3022             entry->start < (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize)) {
3023                 newend = MIN(entry->end,
3024                     (vm_offset_t)vm1->vm_taddr + ctob(vm1->vm_tsize));
3025                 vm2->vm_tsize += btoc(newend - entry->start);
3026         }
3027 }
3028
3029 /*
3030  * vmspace_fork:
3031  * Create a new process vmspace structure and vm_map
3032  * based on those of an existing process.  The new map
3033  * is based on the old map, according to the inheritance
3034  * values on the regions in that map.
3035  *
3036  * XXX It might be worth coalescing the entries added to the new vmspace.
3037  *
3038  * The source map must not be locked.
3039  */
3040 struct vmspace *
3041 vmspace_fork(struct vmspace *vm1, vm_ooffset_t *fork_charge)
3042 {
3043         struct vmspace *vm2;
3044         vm_map_t old_map = &vm1->vm_map;
3045         vm_map_t new_map;
3046         vm_map_entry_t old_entry;
3047         vm_map_entry_t new_entry;
3048         vm_object_t object;
3049         int locked;
3050
3051         vm_map_lock(old_map);
3052         if (old_map->busy)
3053                 vm_map_wait_busy(old_map);
3054         vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
3055         if (vm2 == NULL)
3056                 goto unlock_and_return;
3057         vm2->vm_taddr = vm1->vm_taddr;
3058         vm2->vm_daddr = vm1->vm_daddr;
3059         vm2->vm_maxsaddr = vm1->vm_maxsaddr;
3060         new_map = &vm2->vm_map; /* XXX */
3061         locked = vm_map_trylock(new_map); /* trylock to silence WITNESS */
3062         KASSERT(locked, ("vmspace_fork: lock failed"));
3063         new_map->timestamp = 1;
3064
3065         old_entry = old_map->header.next;
3066
3067         while (old_entry != &old_map->header) {
3068                 if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3069                         panic("vm_map_fork: encountered a submap");
3070
3071                 switch (old_entry->inheritance) {
3072                 case VM_INHERIT_NONE:
3073                         break;
3074
3075                 case VM_INHERIT_SHARE:
3076                         /*
3077                          * Clone the entry, creating the shared object if necessary.
3078                          */
3079                         object = old_entry->object.vm_object;
3080                         if (object == NULL) {
3081                                 object = vm_object_allocate(OBJT_DEFAULT,
3082                                         atop(old_entry->end - old_entry->start));
3083                                 old_entry->object.vm_object = object;
3084                                 old_entry->offset = 0;
3085                                 if (old_entry->uip != NULL) {
3086                                         object->uip = old_entry->uip;
3087                                         object->charge = old_entry->end -
3088                                             old_entry->start;
3089                                         old_entry->uip = NULL;
3090                                 }
3091                         }
3092
3093                         /*
3094                          * Add the reference before calling vm_object_shadow
3095                          * to insure that a shadow object is created.
3096                          */
3097                         vm_object_reference(object);
3098                         if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3099                                 vm_object_shadow(&old_entry->object.vm_object,
3100                                         &old_entry->offset,
3101                                         atop(old_entry->end - old_entry->start));
3102                                 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3103                                 /* Transfer the second reference too. */
3104                                 vm_object_reference(
3105                                     old_entry->object.vm_object);
3106
3107                                 /*
3108                                  * As in vm_map_simplify_entry(), the
3109                                  * vnode lock will not be acquired in
3110                                  * this call to vm_object_deallocate().
3111                                  */
3112                                 vm_object_deallocate(object);
3113                                 object = old_entry->object.vm_object;
3114                         }
3115                         VM_OBJECT_LOCK(object);
3116                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
3117                         if (old_entry->uip != NULL) {
3118                                 KASSERT(object->uip == NULL, ("vmspace_fork both uip"));
3119                                 object->uip = old_entry->uip;
3120                                 object->charge = old_entry->end - old_entry->start;
3121                                 old_entry->uip = NULL;
3122                         }
3123                         VM_OBJECT_UNLOCK(object);
3124
3125                         /*
3126                          * Clone the entry, referencing the shared object.
3127                          */
3128                         new_entry = vm_map_entry_create(new_map);
3129                         *new_entry = *old_entry;
3130                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3131                             MAP_ENTRY_IN_TRANSITION);
3132                         new_entry->wired_count = 0;
3133
3134                         /*
3135                          * Insert the entry into the new map -- we know we're
3136                          * inserting at the end of the new map.
3137                          */
3138                         vm_map_entry_link(new_map, new_map->header.prev,
3139                             new_entry);
3140                         vmspace_map_entry_forked(vm1, vm2, new_entry);
3141
3142                         /*
3143                          * Update the physical map
3144                          */
3145                         pmap_copy(new_map->pmap, old_map->pmap,
3146                             new_entry->start,
3147                             (old_entry->end - old_entry->start),
3148                             old_entry->start);
3149                         break;
3150
3151                 case VM_INHERIT_COPY:
3152                         /*
3153                          * Clone the entry and link into the map.
3154                          */
3155                         new_entry = vm_map_entry_create(new_map);
3156                         *new_entry = *old_entry;
3157                         new_entry->eflags &= ~(MAP_ENTRY_USER_WIRED |
3158                             MAP_ENTRY_IN_TRANSITION);
3159                         new_entry->wired_count = 0;
3160                         new_entry->object.vm_object = NULL;
3161                         new_entry->uip = NULL;
3162                         vm_map_entry_link(new_map, new_map->header.prev,
3163                             new_entry);
3164                         vmspace_map_entry_forked(vm1, vm2, new_entry);
3165                         vm_map_copy_entry(old_map, new_map, old_entry,
3166                             new_entry, fork_charge);
3167                         break;
3168                 }
3169                 old_entry = old_entry->next;
3170         }
3171 unlock_and_return:
3172         vm_map_unlock(old_map);
3173         if (vm2 != NULL)
3174                 vm_map_unlock(new_map);
3175
3176         return (vm2);
3177 }
3178
3179 int
3180 vm_map_stack(vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
3181     vm_prot_t prot, vm_prot_t max, int cow)
3182 {
3183         vm_map_entry_t new_entry, prev_entry;
3184         vm_offset_t bot, top;
3185         vm_size_t init_ssize;
3186         int orient, rv;
3187         rlim_t vmemlim;
3188
3189         /*
3190          * The stack orientation is piggybacked with the cow argument.
3191          * Extract it into orient and mask the cow argument so that we
3192          * don't pass it around further.
3193          * NOTE: We explicitly allow bi-directional stacks.
3194          */
3195         orient = cow & (MAP_STACK_GROWS_DOWN|MAP_STACK_GROWS_UP);
3196         cow &= ~orient;
3197         KASSERT(orient != 0, ("No stack grow direction"));
3198
3199         if (addrbos < vm_map_min(map) ||
3200             addrbos > vm_map_max(map) ||
3201             addrbos + max_ssize < addrbos)
3202                 return (KERN_NO_SPACE);
3203
3204         init_ssize = (max_ssize < sgrowsiz) ? max_ssize : sgrowsiz;
3205
3206         PROC_LOCK(curthread->td_proc);
3207         vmemlim = lim_cur(curthread->td_proc, RLIMIT_VMEM);
3208         PROC_UNLOCK(curthread->td_proc);
3209
3210         vm_map_lock(map);
3211
3212         /* If addr is already mapped, no go */
3213         if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
3214                 vm_map_unlock(map);
3215                 return (KERN_NO_SPACE);
3216         }
3217
3218         /* If we would blow our VMEM resource limit, no go */
3219         if (map->size + init_ssize > vmemlim) {
3220                 vm_map_unlock(map);
3221                 return (KERN_NO_SPACE);
3222         }
3223
3224         /*
3225          * If we can't accomodate max_ssize in the current mapping, no go.
3226          * However, we need to be aware that subsequent user mappings might
3227          * map into the space we have reserved for stack, and currently this
3228          * space is not protected.
3229          *
3230          * Hopefully we will at least detect this condition when we try to
3231          * grow the stack.
3232          */
3233         if ((prev_entry->next != &map->header) &&
3234             (prev_entry->next->start < addrbos + max_ssize)) {
3235                 vm_map_unlock(map);
3236                 return (KERN_NO_SPACE);
3237         }
3238
3239         /*
3240          * We initially map a stack of only init_ssize.  We will grow as
3241          * needed later.  Depending on the orientation of the stack (i.e.
3242          * the grow direction) we either map at the top of the range, the
3243          * bottom of the range or in the middle.
3244          *
3245          * Note: we would normally expect prot and max to be VM_PROT_ALL,
3246          * and cow to be 0.  Possibly we should eliminate these as input
3247          * parameters, and just pass these values here in the insert call.
3248          */
3249         if (orient == MAP_STACK_GROWS_DOWN)
3250                 bot = addrbos + max_ssize - init_ssize;
3251         else if (orient == MAP_STACK_GROWS_UP)
3252                 bot = addrbos;
3253         else
3254                 bot = round_page(addrbos + max_ssize/2 - init_ssize/2);
3255         top = bot + init_ssize;
3256         rv = vm_map_insert(map, NULL, 0, bot, top, prot, max, cow);
3257
3258         /* Now set the avail_ssize amount. */
3259         if (rv == KERN_SUCCESS) {
3260                 if (prev_entry != &map->header)
3261                         vm_map_clip_end(map, prev_entry, bot);
3262                 new_entry = prev_entry->next;
3263                 if (new_entry->end != top || new_entry->start != bot)
3264                         panic("Bad entry start/end for new stack entry");
3265
3266                 new_entry->avail_ssize = max_ssize - init_ssize;
3267                 if (orient & MAP_STACK_GROWS_DOWN)
3268                         new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
3269                 if (orient & MAP_STACK_GROWS_UP)
3270                         new_entry->eflags |= MAP_ENTRY_GROWS_UP;
3271         }
3272
3273         vm_map_unlock(map);
3274         return (rv);
3275 }
3276
3277 static int stack_guard_page = 0;
3278 TUNABLE_INT("security.bsd.stack_guard_page", &stack_guard_page);
3279 SYSCTL_INT(_security_bsd, OID_AUTO, stack_guard_page, CTLFLAG_RW,
3280     &stack_guard_page, 0,
3281     "Insert stack guard page ahead of the growable segments.");
3282
3283 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
3284  * desired address is already mapped, or if we successfully grow
3285  * the stack.  Also returns KERN_SUCCESS if addr is outside the
3286  * stack range (this is strange, but preserves compatibility with
3287  * the grow function in vm_machdep.c).
3288  */
3289 int
3290 vm_map_growstack(struct proc *p, vm_offset_t addr)
3291 {
3292         vm_map_entry_t next_entry, prev_entry;
3293         vm_map_entry_t new_entry, stack_entry;
3294         struct vmspace *vm = p->p_vmspace;
3295         vm_map_t map = &vm->vm_map;
3296         vm_offset_t end;
3297         size_t grow_amount, max_grow;
3298         rlim_t stacklim, vmemlim;
3299         int is_procstack, rv;
3300         struct uidinfo *uip;
3301
3302 Retry:
3303         PROC_LOCK(p);
3304         stacklim = lim_cur(p, RLIMIT_STACK);
3305         vmemlim = lim_cur(p, RLIMIT_VMEM);
3306         PROC_UNLOCK(p);
3307
3308         vm_map_lock_read(map);
3309
3310         /* If addr is already in the entry range, no need to grow.*/
3311         if (vm_map_lookup_entry(map, addr, &prev_entry)) {
3312                 vm_map_unlock_read(map);
3313                 return (KERN_SUCCESS);
3314         }
3315
3316         next_entry = prev_entry->next;
3317         if (!(prev_entry->eflags & MAP_ENTRY_GROWS_UP)) {
3318                 /*
3319                  * This entry does not grow upwards. Since the address lies
3320                  * beyond this entry, the next entry (if one exists) has to
3321                  * be a downward growable entry. The entry list header is
3322                  * never a growable entry, so it suffices to check the flags.
3323                  */
3324                 if (!(next_entry->eflags & MAP_ENTRY_GROWS_DOWN)) {
3325                         vm_map_unlock_read(map);
3326                         return (KERN_SUCCESS);
3327                 }
3328                 stack_entry = next_entry;
3329         } else {
3330                 /*
3331                  * This entry grows upward. If the next entry does not at
3332                  * least grow downwards, this is the entry we need to grow.
3333                  * otherwise we have two possible choices and we have to
3334                  * select one.
3335                  */
3336                 if (next_entry->eflags & MAP_ENTRY_GROWS_DOWN) {
3337                         /*
3338                          * We have two choices; grow the entry closest to
3339                          * the address to minimize the amount of growth.
3340                          */
3341                         if (addr - prev_entry->end <= next_entry->start - addr)
3342                                 stack_entry = prev_entry;
3343                         else
3344                                 stack_entry = next_entry;
3345                 } else
3346                         stack_entry = prev_entry;
3347         }
3348
3349         if (stack_entry == next_entry) {
3350                 KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_DOWN, ("foo"));
3351                 KASSERT(addr < stack_entry->start, ("foo"));
3352                 end = (prev_entry != &map->header) ? prev_entry->end :
3353                     stack_entry->start - stack_entry->avail_ssize;
3354                 grow_amount = roundup(stack_entry->start - addr, PAGE_SIZE);
3355                 max_grow = stack_entry->start - end;
3356         } else {
3357                 KASSERT(stack_entry->eflags & MAP_ENTRY_GROWS_UP, ("foo"));
3358                 KASSERT(addr >= stack_entry->end, ("foo"));
3359                 end = (next_entry != &map->header) ? next_entry->start :
3360                     stack_entry->end + stack_entry->avail_ssize;
3361                 grow_amount = roundup(addr + 1 - stack_entry->end, PAGE_SIZE);
3362                 max_grow = end - stack_entry->end;
3363         }
3364
3365         if (grow_amount > stack_entry->avail_ssize) {
3366                 vm_map_unlock_read(map);
3367                 return (KERN_NO_SPACE);
3368         }
3369
3370         /*
3371          * If there is no longer enough space between the entries nogo, and
3372          * adjust the available space.  Note: this  should only happen if the
3373          * user has mapped into the stack area after the stack was created,
3374          * and is probably an error.
3375          *
3376          * This also effectively destroys any guard page the user might have
3377          * intended by limiting the stack size.
3378          */
3379         if (grow_amount + (stack_guard_page ? PAGE_SIZE : 0) > max_grow) {
3380                 if (vm_map_lock_upgrade(map))
3381                         goto Retry;
3382
3383                 stack_entry->avail_ssize = max_grow;
3384
3385                 vm_map_unlock(map);
3386                 return (KERN_NO_SPACE);
3387         }
3388
3389         is_procstack = (addr >= (vm_offset_t)vm->vm_maxsaddr) ? 1 : 0;
3390
3391         /*
3392          * If this is the main process stack, see if we're over the stack
3393          * limit.
3394          */
3395         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3396                 vm_map_unlock_read(map);
3397                 return (KERN_NO_SPACE);
3398         }
3399
3400         /* Round up the grow amount modulo SGROWSIZ */
3401         grow_amount = roundup (grow_amount, sgrowsiz);
3402         if (grow_amount > stack_entry->avail_ssize)
3403                 grow_amount = stack_entry->avail_ssize;
3404         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount > stacklim)) {
3405                 grow_amount = trunc_page((vm_size_t)stacklim) -
3406                     ctob(vm->vm_ssize);
3407         }
3408
3409         /* If we would blow our VMEM resource limit, no go */
3410         if (map->size + grow_amount > vmemlim) {
3411                 vm_map_unlock_read(map);
3412                 return (KERN_NO_SPACE);
3413         }
3414
3415         if (vm_map_lock_upgrade(map))
3416                 goto Retry;
3417
3418         if (stack_entry == next_entry) {
3419                 /*
3420                  * Growing downward.
3421                  */
3422                 /* Get the preliminary new entry start value */
3423                 addr = stack_entry->start - grow_amount;
3424
3425                 /*
3426                  * If this puts us into the previous entry, cut back our
3427                  * growth to the available space. Also, see the note above.
3428                  */
3429                 if (addr < end) {
3430                         stack_entry->avail_ssize = max_grow;
3431                         addr = end;
3432                         if (stack_guard_page)
3433                                 addr += PAGE_SIZE;
3434                 }
3435
3436                 rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
3437                     p->p_sysent->sv_stackprot, VM_PROT_ALL, 0);
3438
3439                 /* Adjust the available stack space by the amount we grew. */
3440                 if (rv == KERN_SUCCESS) {
3441                         if (prev_entry != &map->header)
3442                                 vm_map_clip_end(map, prev_entry, addr);
3443                         new_entry = prev_entry->next;
3444                         KASSERT(new_entry == stack_entry->prev, ("foo"));
3445                         KASSERT(new_entry->end == stack_entry->start, ("foo"));
3446                         KASSERT(new_entry->start == addr, ("foo"));
3447                         grow_amount = new_entry->end - new_entry->start;
3448                         new_entry->avail_ssize = stack_entry->avail_ssize -
3449                             grow_amount;
3450                         stack_entry->eflags &= ~MAP_ENTRY_GROWS_DOWN;
3451                         new_entry->eflags |= MAP_ENTRY_GROWS_DOWN;
3452                 }
3453         } else {
3454                 /*
3455                  * Growing upward.
3456                  */
3457                 addr = stack_entry->end + grow_amount;
3458
3459                 /*
3460                  * If this puts us into the next entry, cut back our growth
3461                  * to the available space. Also, see the note above.
3462                  */
3463                 if (addr > end) {
3464                         stack_entry->avail_ssize = end - stack_entry->end;
3465                         addr = end;
3466                         if (stack_guard_page)
3467                                 addr -= PAGE_SIZE;
3468                 }
3469
3470                 grow_amount = addr - stack_entry->end;
3471                 uip = stack_entry->uip;
3472                 if (uip == NULL && stack_entry->object.vm_object != NULL)
3473                         uip = stack_entry->object.vm_object->uip;
3474                 if (uip != NULL && !swap_reserve_by_uid(grow_amount, uip))
3475                         rv = KERN_NO_SPACE;
3476                 /* Grow the underlying object if applicable. */
3477                 else if (stack_entry->object.vm_object == NULL ||
3478                          vm_object_coalesce(stack_entry->object.vm_object,
3479                          stack_entry->offset,
3480                          (vm_size_t)(stack_entry->end - stack_entry->start),
3481                          (vm_size_t)grow_amount, uip != NULL)) {
3482                         map->size += (addr - stack_entry->end);
3483                         /* Update the current entry. */
3484                         stack_entry->end = addr;
3485                         stack_entry->avail_ssize -= grow_amount;
3486                         vm_map_entry_resize_free(map, stack_entry);
3487                         rv = KERN_SUCCESS;
3488
3489                         if (next_entry != &map->header)
3490                                 vm_map_clip_start(map, next_entry, addr);
3491                 } else
3492                         rv = KERN_FAILURE;
3493         }
3494
3495         if (rv == KERN_SUCCESS && is_procstack)
3496                 vm->vm_ssize += btoc(grow_amount);
3497
3498         vm_map_unlock(map);
3499
3500         /*
3501          * Heed the MAP_WIREFUTURE flag if it was set for this process.
3502          */
3503         if (rv == KERN_SUCCESS && (map->flags & MAP_WIREFUTURE)) {
3504                 vm_map_wire(map,
3505                     (stack_entry == next_entry) ? addr : addr - grow_amount,
3506                     (stack_entry == next_entry) ? stack_entry->start : addr,
3507                     (p->p_flag & P_SYSTEM)
3508                     ? VM_MAP_WIRE_SYSTEM|VM_MAP_WIRE_NOHOLES
3509                     : VM_MAP_WIRE_USER|VM_MAP_WIRE_NOHOLES);
3510         }
3511
3512         return (rv);
3513 }
3514
3515 /*
3516  * Unshare the specified VM space for exec.  If other processes are
3517  * mapped to it, then create a new one.  The new vmspace is null.
3518  */
3519 int
3520 vmspace_exec(struct proc *p, vm_offset_t minuser, vm_offset_t maxuser)
3521 {
3522         struct vmspace *oldvmspace = p->p_vmspace;
3523         struct vmspace *newvmspace;
3524
3525         newvmspace = vmspace_alloc(minuser, maxuser);
3526         if (newvmspace == NULL)
3527                 return (ENOMEM);
3528         newvmspace->vm_swrss = oldvmspace->vm_swrss;
3529         /*
3530          * This code is written like this for prototype purposes.  The
3531          * goal is to avoid running down the vmspace here, but let the
3532          * other process's that are still using the vmspace to finally
3533          * run it down.  Even though there is little or no chance of blocking
3534          * here, it is a good idea to keep this form for future mods.
3535          */
3536         PROC_VMSPACE_LOCK(p);
3537         p->p_vmspace = newvmspace;
3538         PROC_VMSPACE_UNLOCK(p);
3539         if (p == curthread->td_proc)
3540                 pmap_activate(curthread);
3541         vmspace_free(oldvmspace);
3542         return (0);
3543 }
3544
3545 /*
3546  * Unshare the specified VM space for forcing COW.  This
3547  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
3548  */
3549 int
3550 vmspace_unshare(struct proc *p)
3551 {
3552         struct vmspace *oldvmspace = p->p_vmspace;
3553         struct vmspace *newvmspace;
3554         vm_ooffset_t fork_charge;
3555
3556         if (oldvmspace->vm_refcnt == 1)
3557                 return (0);
3558         fork_charge = 0;
3559         newvmspace = vmspace_fork(oldvmspace, &fork_charge);
3560         if (newvmspace == NULL)
3561                 return (ENOMEM);
3562         if (!swap_reserve_by_uid(fork_charge, p->p_ucred->cr_ruidinfo)) {
3563                 vmspace_free(newvmspace);
3564                 return (ENOMEM);
3565         }
3566         PROC_VMSPACE_LOCK(p);
3567         p->p_vmspace = newvmspace;
3568         PROC_VMSPACE_UNLOCK(p);
3569         if (p == curthread->td_proc)
3570                 pmap_activate(curthread);
3571         vmspace_free(oldvmspace);
3572         return (0);
3573 }
3574
3575 /*
3576  *      vm_map_lookup:
3577  *
3578  *      Finds the VM object, offset, and
3579  *      protection for a given virtual address in the
3580  *      specified map, assuming a page fault of the
3581  *      type specified.
3582  *
3583  *      Leaves the map in question locked for read; return
3584  *      values are guaranteed until a vm_map_lookup_done
3585  *      call is performed.  Note that the map argument
3586  *      is in/out; the returned map must be used in
3587  *      the call to vm_map_lookup_done.
3588  *
3589  *      A handle (out_entry) is returned for use in
3590  *      vm_map_lookup_done, to make that fast.
3591  *
3592  *      If a lookup is requested with "write protection"
3593  *      specified, the map may be changed to perform virtual
3594  *      copying operations, although the data referenced will
3595  *      remain the same.
3596  */
3597 int
3598 vm_map_lookup(vm_map_t *var_map,                /* IN/OUT */
3599               vm_offset_t vaddr,
3600               vm_prot_t fault_typea,
3601               vm_map_entry_t *out_entry,        /* OUT */
3602               vm_object_t *object,              /* OUT */
3603               vm_pindex_t *pindex,              /* OUT */
3604               vm_prot_t *out_prot,              /* OUT */
3605               boolean_t *wired)                 /* OUT */
3606 {
3607         vm_map_entry_t entry;
3608         vm_map_t map = *var_map;
3609         vm_prot_t prot;
3610         vm_prot_t fault_type = fault_typea;
3611         vm_object_t eobject;
3612         struct uidinfo *uip;
3613         vm_ooffset_t size;
3614
3615 RetryLookup:;
3616
3617         vm_map_lock_read(map);
3618
3619         /*
3620          * Lookup the faulting address.
3621          */
3622         if (!vm_map_lookup_entry(map, vaddr, out_entry)) {
3623                 vm_map_unlock_read(map);
3624                 return (KERN_INVALID_ADDRESS);
3625         }
3626
3627         entry = *out_entry;
3628
3629         /*
3630          * Handle submaps.
3631          */
3632         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3633                 vm_map_t old_map = map;
3634
3635                 *var_map = map = entry->object.sub_map;
3636                 vm_map_unlock_read(old_map);
3637                 goto RetryLookup;
3638         }
3639
3640         /*
3641          * Check whether this task is allowed to have this page.
3642          * Note the special case for MAP_ENTRY_COW
3643          * pages with an override.  This is to implement a forced
3644          * COW for debuggers.
3645          */
3646         if (fault_type & VM_PROT_OVERRIDE_WRITE)
3647                 prot = entry->max_protection;
3648         else
3649                 prot = entry->protection;
3650         fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
3651         if ((fault_type & prot) != fault_type) {
3652                 vm_map_unlock_read(map);
3653                 return (KERN_PROTECTION_FAILURE);
3654         }
3655         if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3656             (entry->eflags & MAP_ENTRY_COW) &&
3657             (fault_type & VM_PROT_WRITE) &&
3658             (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
3659                 vm_map_unlock_read(map);
3660                 return (KERN_PROTECTION_FAILURE);
3661         }
3662
3663         /*
3664          * If this page is not pageable, we have to get it for all possible
3665          * accesses.
3666          */
3667         *wired = (entry->wired_count != 0);
3668         if (*wired)
3669                 prot = fault_type = entry->protection;
3670         size = entry->end - entry->start;
3671         /*
3672          * If the entry was copy-on-write, we either ...
3673          */
3674         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3675                 /*
3676                  * If we want to write the page, we may as well handle that
3677                  * now since we've got the map locked.
3678                  *
3679                  * If we don't need to write the page, we just demote the
3680                  * permissions allowed.
3681                  */
3682                 if (fault_type & VM_PROT_WRITE) {
3683                         /*
3684                          * Make a new object, and place it in the object
3685                          * chain.  Note that no new references have appeared
3686                          * -- one just moved from the map to the new
3687                          * object.
3688                          */
3689                         if (vm_map_lock_upgrade(map))
3690                                 goto RetryLookup;
3691
3692                         if (entry->uip == NULL) {
3693                                 /*
3694                                  * The debugger owner is charged for
3695                                  * the memory.
3696                                  */
3697                                 uip = curthread->td_ucred->cr_ruidinfo;
3698                                 uihold(uip);
3699                                 if (!swap_reserve_by_uid(size, uip)) {
3700                                         uifree(uip);
3701                                         vm_map_unlock(map);
3702                                         return (KERN_RESOURCE_SHORTAGE);
3703                                 }
3704                                 entry->uip = uip;
3705                         }
3706                         vm_object_shadow(
3707                             &entry->object.vm_object,
3708                             &entry->offset,
3709                             atop(size));
3710                         entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
3711                         eobject = entry->object.vm_object;
3712                         if (eobject->uip != NULL) {
3713                                 /*
3714                                  * The object was not shadowed.
3715                                  */
3716                                 swap_release_by_uid(size, entry->uip);
3717                                 uifree(entry->uip);
3718                                 entry->uip = NULL;
3719                         } else if (entry->uip != NULL) {
3720                                 VM_OBJECT_LOCK(eobject);
3721                                 eobject->uip = entry->uip;
3722                                 eobject->charge = size;
3723                                 VM_OBJECT_UNLOCK(eobject);
3724                                 entry->uip = NULL;
3725                         }
3726
3727                         vm_map_lock_downgrade(map);
3728                 } else {
3729                         /*
3730                          * We're attempting to read a copy-on-write page --
3731                          * don't allow writes.
3732                          */
3733                         prot &= ~VM_PROT_WRITE;
3734                 }
3735         }
3736
3737         /*
3738          * Create an object if necessary.
3739          */
3740         if (entry->object.vm_object == NULL &&
3741             !map->system_map) {
3742                 if (vm_map_lock_upgrade(map))
3743                         goto RetryLookup;
3744                 entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
3745                     atop(size));
3746                 entry->offset = 0;
3747                 if (entry->uip != NULL) {
3748                         VM_OBJECT_LOCK(entry->object.vm_object);
3749                         entry->object.vm_object->uip = entry->uip;
3750                         entry->object.vm_object->charge = size;
3751                         VM_OBJECT_UNLOCK(entry->object.vm_object);
3752                         entry->uip = NULL;
3753                 }
3754                 vm_map_lock_downgrade(map);
3755         }
3756
3757         /*
3758          * Return the object/offset from this entry.  If the entry was
3759          * copy-on-write or empty, it has been fixed up.
3760          */
3761         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3762         *object = entry->object.vm_object;
3763
3764         *out_prot = prot;
3765         return (KERN_SUCCESS);
3766 }
3767
3768 /*
3769  *      vm_map_lookup_locked:
3770  *
3771  *      Lookup the faulting address.  A version of vm_map_lookup that returns 
3772  *      KERN_FAILURE instead of blocking on map lock or memory allocation.
3773  */
3774 int
3775 vm_map_lookup_locked(vm_map_t *var_map,         /* IN/OUT */
3776                      vm_offset_t vaddr,
3777                      vm_prot_t fault_typea,
3778                      vm_map_entry_t *out_entry, /* OUT */
3779                      vm_object_t *object,       /* OUT */
3780                      vm_pindex_t *pindex,       /* OUT */
3781                      vm_prot_t *out_prot,       /* OUT */
3782                      boolean_t *wired)          /* OUT */
3783 {
3784         vm_map_entry_t entry;
3785         vm_map_t map = *var_map;
3786         vm_prot_t prot;
3787         vm_prot_t fault_type = fault_typea;
3788
3789         /*
3790          * Lookup the faulting address.
3791          */
3792         if (!vm_map_lookup_entry(map, vaddr, out_entry))
3793                 return (KERN_INVALID_ADDRESS);
3794
3795         entry = *out_entry;
3796
3797         /*
3798          * Fail if the entry refers to a submap.
3799          */
3800         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP)
3801                 return (KERN_FAILURE);
3802
3803         /*
3804          * Check whether this task is allowed to have this page.
3805          * Note the special case for MAP_ENTRY_COW
3806          * pages with an override.  This is to implement a forced
3807          * COW for debuggers.
3808          */
3809         if (fault_type & VM_PROT_OVERRIDE_WRITE)
3810                 prot = entry->max_protection;
3811         else
3812                 prot = entry->protection;
3813         fault_type &= VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;
3814         if ((fault_type & prot) != fault_type)
3815                 return (KERN_PROTECTION_FAILURE);
3816         if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
3817             (entry->eflags & MAP_ENTRY_COW) &&
3818             (fault_type & VM_PROT_WRITE) &&
3819             (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0)
3820                 return (KERN_PROTECTION_FAILURE);
3821
3822         /*
3823          * If this page is not pageable, we have to get it for all possible
3824          * accesses.
3825          */
3826         *wired = (entry->wired_count != 0);
3827         if (*wired)
3828                 prot = fault_type = entry->protection;
3829
3830         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
3831                 /*
3832                  * Fail if the entry was copy-on-write for a write fault.
3833                  */
3834                 if (fault_type & VM_PROT_WRITE)
3835                         return (KERN_FAILURE);
3836                 /*
3837                  * We're attempting to read a copy-on-write page --
3838                  * don't allow writes.
3839                  */
3840                 prot &= ~VM_PROT_WRITE;
3841         }
3842
3843         /*
3844          * Fail if an object should be created.
3845          */
3846         if (entry->object.vm_object == NULL && !map->system_map)
3847                 return (KERN_FAILURE);
3848
3849         /*
3850          * Return the object/offset from this entry.  If the entry was
3851          * copy-on-write or empty, it has been fixed up.
3852          */
3853         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
3854         *object = entry->object.vm_object;
3855
3856         *out_prot = prot;
3857         return (KERN_SUCCESS);
3858 }
3859
3860 /*
3861  *      vm_map_lookup_done:
3862  *
3863  *      Releases locks acquired by a vm_map_lookup
3864  *      (according to the handle returned by that lookup).
3865  */
3866 void
3867 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
3868 {
3869         /*
3870          * Unlock the main-level map
3871          */
3872         vm_map_unlock_read(map);
3873 }
3874
3875 #include "opt_ddb.h"
3876 #ifdef DDB
3877 #include <sys/kernel.h>
3878
3879 #include <ddb/ddb.h>
3880
3881 /*
3882  *      vm_map_print:   [ debug ]
3883  */
3884 DB_SHOW_COMMAND(map, vm_map_print)
3885 {
3886         static int nlines;
3887         /* XXX convert args. */
3888         vm_map_t map = (vm_map_t)addr;
3889         boolean_t full = have_addr;
3890
3891         vm_map_entry_t entry;
3892
3893         db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
3894             (void *)map,
3895             (void *)map->pmap, map->nentries, map->timestamp);
3896         nlines++;
3897
3898         if (!full && db_indent)
3899                 return;
3900
3901         db_indent += 2;
3902         for (entry = map->header.next; entry != &map->header;
3903             entry = entry->next) {
3904                 db_iprintf("map entry %p: start=%p, end=%p\n",
3905                     (void *)entry, (void *)entry->start, (void *)entry->end);
3906                 nlines++;
3907                 {
3908                         static char *inheritance_name[4] =
3909                         {"share", "copy", "none", "donate_copy"};
3910
3911                         db_iprintf(" prot=%x/%x/%s",
3912                             entry->protection,
3913                             entry->max_protection,
3914                             inheritance_name[(int)(unsigned char)entry->inheritance]);
3915                         if (entry->wired_count != 0)
3916                                 db_printf(", wired");
3917                 }
3918                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3919                         db_printf(", share=%p, offset=0x%jx\n",
3920                             (void *)entry->object.sub_map,
3921                             (uintmax_t)entry->offset);
3922                         nlines++;
3923                         if ((entry->prev == &map->header) ||
3924                             (entry->prev->object.sub_map !=
3925                                 entry->object.sub_map)) {
3926                                 db_indent += 2;
3927                                 vm_map_print((db_expr_t)(intptr_t)
3928                                              entry->object.sub_map,
3929                                              full, 0, (char *)0);
3930                                 db_indent -= 2;
3931                         }
3932                 } else {
3933                         if (entry->uip != NULL)
3934                                 db_printf(", uip %d", entry->uip->ui_uid);
3935                         db_printf(", object=%p, offset=0x%jx",
3936                             (void *)entry->object.vm_object,
3937                             (uintmax_t)entry->offset);
3938                         if (entry->object.vm_object && entry->object.vm_object->uip)
3939                                 db_printf(", obj uip %d charge %jx",
3940                                     entry->object.vm_object->uip->ui_uid,
3941                                     (uintmax_t)entry->object.vm_object->charge);
3942                         if (entry->eflags & MAP_ENTRY_COW)
3943                                 db_printf(", copy (%s)",
3944                                     (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
3945                         db_printf("\n");
3946                         nlines++;
3947
3948                         if ((entry->prev == &map->header) ||
3949                             (entry->prev->object.vm_object !=
3950                                 entry->object.vm_object)) {
3951                                 db_indent += 2;
3952                                 vm_object_print((db_expr_t)(intptr_t)
3953                                                 entry->object.vm_object,
3954                                                 full, 0, (char *)0);
3955                                 nlines += 4;
3956                                 db_indent -= 2;
3957                         }
3958                 }
3959         }
3960         db_indent -= 2;
3961         if (db_indent == 0)
3962                 nlines = 0;
3963 }
3964
3965
3966 DB_SHOW_COMMAND(procvm, procvm)
3967 {
3968         struct proc *p;
3969
3970         if (have_addr) {
3971                 p = (struct proc *) addr;
3972         } else {
3973                 p = curproc;
3974         }
3975
3976         db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3977             (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3978             (void *)vmspace_pmap(p->p_vmspace));
3979
3980         vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3981 }
3982
3983 #endif /* DDB */