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