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