]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_map.c
o Remove an unnecessary call to vm_map_wakeup() from vm_map_unwire().
[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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      from: @(#)vm_map.c      8.3 (Berkeley) 1/12/94
37  *
38  *
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
43  *
44  * Permission to use, copy, modify and distribute this software and
45  * its documentation is hereby granted, provided that both the copyright
46  * notice and this permission notice appear in all copies of the
47  * software, derivative works or modified versions, and any portions
48  * thereof, and that both notices appear in supporting documentation.
49  *
50  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
53  *
54  * Carnegie Mellon requests users of this software to return to
55  *
56  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
57  *  School of Computer Science
58  *  Carnegie Mellon University
59  *  Pittsburgh PA 15213-3890
60  *
61  * any improvements or extensions that they make and grant Carnegie the
62  * rights to redistribute these changes.
63  *
64  * $FreeBSD$
65  */
66
67 /*
68  *      Virtual memory mapping module.
69  */
70
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/ktr.h>
74 #include <sys/lock.h>
75 #include <sys/mutex.h>
76 #include <sys/proc.h>
77 #include <sys/vmmeter.h>
78 #include <sys/mman.h>
79 #include <sys/vnode.h>
80 #include <sys/resourcevar.h>
81
82 #include <vm/vm.h>
83 #include <vm/vm_param.h>
84 #include <vm/pmap.h>
85 #include <vm/vm_map.h>
86 #include <vm/vm_page.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_pager.h>
89 #include <vm/vm_kern.h>
90 #include <vm/vm_extern.h>
91 #include <vm/swap_pager.h>
92 #include <vm/uma.h>
93
94 /*
95  *      Virtual memory maps provide for the mapping, protection,
96  *      and sharing of virtual memory objects.  In addition,
97  *      this module provides for an efficient virtual copy of
98  *      memory from one map to another.
99  *
100  *      Synchronization is required prior to most operations.
101  *
102  *      Maps consist of an ordered doubly-linked list of simple
103  *      entries; a single hint is used to speed up lookups.
104  *
105  *      Since portions of maps are specified by start/end addresses,
106  *      which may not align with existing map entries, all
107  *      routines merely "clip" entries to these start/end values.
108  *      [That is, an entry is split into two, bordering at a
109  *      start or end value.]  Note that these clippings may not
110  *      always be necessary (as the two resulting entries are then
111  *      not changed); however, the clipping is done for convenience.
112  *
113  *      As mentioned above, virtual copy operations are performed
114  *      by copying VM object references from one map to
115  *      another, and then marking both regions as copy-on-write.
116  */
117
118 /*
119  *      vm_map_startup:
120  *
121  *      Initialize the vm_map module.  Must be called before
122  *      any other vm_map routines.
123  *
124  *      Map and entry structures are allocated from the general
125  *      purpose memory pool with some exceptions:
126  *
127  *      - The kernel map and kmem submap are allocated statically.
128  *      - Kernel map entries are allocated out of a static pool.
129  *
130  *      These restrictions are necessary since malloc() uses the
131  *      maps and requires map entries.
132  */
133
134 static uma_zone_t mapentzone;
135 static uma_zone_t kmapentzone;
136 static uma_zone_t mapzone;
137 static uma_zone_t vmspace_zone;
138 static struct vm_object kmapentobj;
139 static void vmspace_zinit(void *mem, int size);
140 static void vmspace_zfini(void *mem, int size);
141 static void vm_map_zinit(void *mem, int size);
142 static void vm_map_zfini(void *mem, int size);
143 static void _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max);
144
145 #ifdef INVARIANTS
146 static void vm_map_zdtor(void *mem, int size, void *arg);
147 static void vmspace_zdtor(void *mem, int size, void *arg);
148 #endif
149
150 void
151 vm_map_startup(void)
152 {
153         mapzone = uma_zcreate("MAP", sizeof(struct vm_map), NULL,
154 #ifdef INVARIANTS
155             vm_map_zdtor,
156 #else
157             NULL,
158 #endif
159             vm_map_zinit, vm_map_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
160         uma_prealloc(mapzone, MAX_KMAP);
161         kmapentzone = uma_zcreate("KMAP ENTRY", sizeof(struct vm_map_entry), 
162             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_MTXCLASS);
163         uma_prealloc(kmapentzone, MAX_KMAPENT);
164         mapentzone = uma_zcreate("MAP ENTRY", sizeof(struct vm_map_entry), 
165             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
166         uma_prealloc(mapentzone, MAX_MAPENT);
167 }
168
169 static void
170 vmspace_zfini(void *mem, int size)
171 {
172         struct vmspace *vm;
173
174         vm = (struct vmspace *)mem;
175
176         vm_map_zfini(&vm->vm_map, sizeof(vm->vm_map));
177 }
178
179 static void
180 vmspace_zinit(void *mem, int size)
181 {
182         struct vmspace *vm;
183
184         vm = (struct vmspace *)mem;
185
186         vm_map_zinit(&vm->vm_map, sizeof(vm->vm_map));
187 }
188
189 static void
190 vm_map_zfini(void *mem, int size)
191 {
192         vm_map_t map;
193
194         map = (vm_map_t)mem;
195
196         lockdestroy(&map->lock);
197 }
198
199 static void
200 vm_map_zinit(void *mem, int size)
201 {
202         vm_map_t map;
203
204         map = (vm_map_t)mem;
205         map->nentries = 0;
206         map->size = 0;
207         map->infork = 0;
208         lockinit(&map->lock, PVM, "thrd_sleep", 0, LK_CANRECURSE | LK_NOPAUSE);
209 }
210
211 #ifdef INVARIANTS
212 static void
213 vmspace_zdtor(void *mem, int size, void *arg)
214 {
215         struct vmspace *vm;
216
217         vm = (struct vmspace *)mem;
218
219         vm_map_zdtor(&vm->vm_map, sizeof(vm->vm_map), arg);
220 }
221 static void
222 vm_map_zdtor(void *mem, int size, void *arg)
223 {
224         vm_map_t map;
225
226         map = (vm_map_t)mem;
227         KASSERT(map->nentries == 0,
228             ("map %p nentries == %d on free.", 
229             map, map->nentries));
230         KASSERT(map->size == 0,
231             ("map %p size == %lu on free.",
232             map, (unsigned long)map->size));
233         KASSERT(map->infork == 0,
234             ("map %p infork == %d on free.",
235             map, map->infork));
236 }
237 #endif  /* INVARIANTS */
238
239 /*
240  * Allocate a vmspace structure, including a vm_map and pmap,
241  * and initialize those structures.  The refcnt is set to 1.
242  * The remaining fields must be initialized by the caller.
243  */
244 struct vmspace *
245 vmspace_alloc(min, max)
246         vm_offset_t min, max;
247 {
248         struct vmspace *vm;
249
250         GIANT_REQUIRED;
251         vm = uma_zalloc(vmspace_zone, M_WAITOK);
252         CTR1(KTR_VM, "vmspace_alloc: %p", vm);
253         _vm_map_init(&vm->vm_map, min, max);
254         pmap_pinit(vmspace_pmap(vm));
255         vm->vm_map.pmap = vmspace_pmap(vm);             /* XXX */
256         vm->vm_refcnt = 1;
257         vm->vm_shm = NULL;
258         vm->vm_freer = NULL;
259         return (vm);
260 }
261
262 void
263 vm_init2(void) 
264 {
265         uma_zone_set_obj(kmapentzone, &kmapentobj, cnt.v_page_count / 4);
266         vmspace_zone = uma_zcreate("VMSPACE", sizeof(struct vmspace), NULL,
267 #ifdef INVARIANTS
268             vmspace_zdtor,
269 #else
270             NULL,
271 #endif
272             vmspace_zinit, vmspace_zfini, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
273         pmap_init2();
274         vm_object_init2();
275 }
276
277 static __inline void
278 vmspace_dofree(struct vmspace *vm)
279 {
280         CTR1(KTR_VM, "vmspace_free: %p", vm);
281         /*
282          * Lock the map, to wait out all other references to it.
283          * Delete all of the mappings and pages they hold, then call
284          * the pmap module to reclaim anything left.
285          */
286         vm_map_lock(&vm->vm_map);
287         (void) vm_map_delete(&vm->vm_map, vm->vm_map.min_offset,
288             vm->vm_map.max_offset);
289         vm_map_unlock(&vm->vm_map);
290
291         pmap_release(vmspace_pmap(vm));
292         uma_zfree(vmspace_zone, vm);
293 }
294
295 void
296 vmspace_free(struct vmspace *vm)
297 {
298         GIANT_REQUIRED;
299
300         if (vm->vm_refcnt == 0)
301                 panic("vmspace_free: attempt to free already freed vmspace");
302
303         if (--vm->vm_refcnt == 0)
304                 vmspace_dofree(vm);
305 }
306
307 void
308 vmspace_exitfree(struct proc *p)
309 {
310         struct vmspace *vm;
311
312         GIANT_REQUIRED;
313         if (p == p->p_vmspace->vm_freer) {
314                 vm = p->p_vmspace;
315                 p->p_vmspace = NULL;
316                 vmspace_dofree(vm);
317         }
318 }
319
320 /*
321  * vmspace_swap_count() - count the approximate swap useage in pages for a
322  *                        vmspace.
323  *
324  *      Swap useage is determined by taking the proportional swap used by
325  *      VM objects backing the VM map.  To make up for fractional losses,
326  *      if the VM object has any swap use at all the associated map entries
327  *      count for at least 1 swap page.
328  */
329 int
330 vmspace_swap_count(struct vmspace *vmspace)
331 {
332         vm_map_t map = &vmspace->vm_map;
333         vm_map_entry_t cur;
334         int count = 0;
335
336         vm_map_lock_read(map);
337         for (cur = map->header.next; cur != &map->header; cur = cur->next) {
338                 vm_object_t object;
339
340                 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) == 0 &&
341                     (object = cur->object.vm_object) != NULL &&
342                     object->type == OBJT_SWAP
343                 ) {
344                         int n = (cur->end - cur->start) / PAGE_SIZE;
345
346                         if (object->un_pager.swp.swp_bcount) {
347                                 count += object->un_pager.swp.swp_bcount *
348                                     SWAP_META_PAGES * n / object->size + 1;
349                         }
350                 }
351         }
352         vm_map_unlock_read(map);
353         return (count);
354 }
355
356 void
357 _vm_map_lock(vm_map_t map, const char *file, int line)
358 {
359         int error;
360
361         error = lockmgr(&map->lock, LK_EXCLUSIVE, NULL, curthread);
362         KASSERT(error == 0, ("%s: failed to get lock", __func__));
363         map->timestamp++;
364 }
365
366 void
367 _vm_map_unlock(vm_map_t map, const char *file, int line)
368 {
369
370         lockmgr(&map->lock, LK_RELEASE, NULL, curthread);
371 }
372
373 void
374 _vm_map_lock_read(vm_map_t map, const char *file, int line)
375 {
376         int error;
377
378         error = lockmgr(&map->lock, LK_EXCLUSIVE, NULL, curthread);
379         KASSERT(error == 0, ("%s: failed to get lock", __func__));
380 }
381
382 void
383 _vm_map_unlock_read(vm_map_t map, const char *file, int line)
384 {
385
386         lockmgr(&map->lock, LK_RELEASE, NULL, curthread);
387 }
388
389 int
390 _vm_map_trylock(vm_map_t map, const char *file, int line)
391 {
392         int error;
393
394         error = lockmgr(&map->lock, LK_EXCLUSIVE | LK_NOWAIT, NULL, curthread);
395         return (error == 0);
396 }
397
398 int
399 _vm_map_lock_upgrade(vm_map_t map, const char *file, int line)
400 {
401
402         KASSERT(lockstatus(&map->lock, curthread) == LK_EXCLUSIVE,
403                 ("%s: lock not held", __func__));
404         map->timestamp++;
405         return (0);
406 }
407
408 void
409 _vm_map_lock_downgrade(vm_map_t map, const char *file, int line)
410 {
411
412         KASSERT(lockstatus(&map->lock, curthread) == LK_EXCLUSIVE,
413                 ("%s: lock not held", __func__));
414 }
415
416 void
417 _vm_map_set_recursive(vm_map_t map, const char *file, int line)
418 {
419 }
420
421 void
422 _vm_map_clear_recursive(vm_map_t map, const char *file, int line)
423 {
424 }
425
426 /*
427  *      vm_map_unlock_and_wait:
428  */
429 static __inline int
430 vm_map_unlock_and_wait(vm_map_t map, boolean_t user_wait)
431 {
432
433         GIANT_REQUIRED;
434         vm_map_unlock(map);
435
436         return (tsleep(&map->root, PVM, "vmmapw", 0));
437 }
438
439 /*
440  *      vm_map_wakeup:
441  */
442 static __inline void
443 vm_map_wakeup(vm_map_t map)
444 {
445
446         wakeup(&map->root);
447 }
448
449 long
450 vmspace_resident_count(struct vmspace *vmspace)
451 {
452         return pmap_resident_count(vmspace_pmap(vmspace));
453 }
454
455 /*
456  *      vm_map_create:
457  *
458  *      Creates and returns a new empty VM map with
459  *      the given physical map structure, and having
460  *      the given lower and upper address bounds.
461  */
462 vm_map_t
463 vm_map_create(pmap_t pmap, vm_offset_t min, vm_offset_t max)
464 {
465         vm_map_t result;
466
467         result = uma_zalloc(mapzone, M_WAITOK);
468         CTR1(KTR_VM, "vm_map_create: %p", result);
469         _vm_map_init(result, min, max);
470         result->pmap = pmap;
471         return (result);
472 }
473
474 /*
475  * Initialize an existing vm_map structure
476  * such as that in the vmspace structure.
477  * The pmap is set elsewhere.
478  */
479 static void
480 _vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
481 {
482
483         map->header.next = map->header.prev = &map->header;
484         map->system_map = 0;
485         map->min_offset = min;
486         map->max_offset = max;
487         map->first_free = &map->header;
488         map->root = NULL;
489         map->timestamp = 0;
490 }
491
492 void
493 vm_map_init(vm_map_t map, vm_offset_t min, vm_offset_t max)
494 {
495         _vm_map_init(map, min, max);
496         lockinit(&map->lock, PVM, "thrd_sleep", 0, LK_CANRECURSE | LK_NOPAUSE);
497 }
498
499 /*
500  *      vm_map_entry_dispose:   [ internal use only ]
501  *
502  *      Inverse of vm_map_entry_create.
503  */
504 static void
505 vm_map_entry_dispose(vm_map_t map, vm_map_entry_t entry)
506 {
507         uma_zfree((map->system_map || !mapentzone)
508             ? kmapentzone : mapentzone, entry);
509 }
510
511 /*
512  *      vm_map_entry_create:    [ internal use only ]
513  *
514  *      Allocates a VM map entry for insertion.
515  *      No entry fields are filled in.
516  */
517 static vm_map_entry_t
518 vm_map_entry_create(vm_map_t map)
519 {
520         vm_map_entry_t new_entry;
521
522         new_entry = uma_zalloc((map->system_map || !mapentzone) ? 
523                 kmapentzone : mapentzone, M_WAITOK);
524         if (new_entry == NULL)
525             panic("vm_map_entry_create: kernel resources exhausted");
526         return (new_entry);
527 }
528
529 /*
530  *      vm_map_entry_set_behavior:
531  *
532  *      Set the expected access behavior, either normal, random, or
533  *      sequential.
534  */
535 static __inline void
536 vm_map_entry_set_behavior(vm_map_entry_t entry, u_char behavior)
537 {
538         entry->eflags = (entry->eflags & ~MAP_ENTRY_BEHAV_MASK) |
539             (behavior & MAP_ENTRY_BEHAV_MASK);
540 }
541
542 /*
543  *      vm_map_entry_splay:
544  *
545  *      Implements Sleator and Tarjan's top-down splay algorithm.  Returns
546  *      the vm_map_entry containing the given address.  If, however, that
547  *      address is not found in the vm_map, returns a vm_map_entry that is
548  *      adjacent to the address, coming before or after it.
549  */
550 static vm_map_entry_t
551 vm_map_entry_splay(vm_offset_t address, vm_map_entry_t root)
552 {
553         struct vm_map_entry dummy;
554         vm_map_entry_t lefttreemax, righttreemin, y;
555
556         if (root == NULL)
557                 return (root);
558         lefttreemax = righttreemin = &dummy;
559         for (;; root = y) {
560                 if (address < root->start) {
561                         if ((y = root->left) == NULL)
562                                 break;
563                         if (address < y->start) {
564                                 /* Rotate right. */
565                                 root->left = y->right;
566                                 y->right = root;
567                                 root = y;
568                                 if ((y = root->left) == NULL)
569                                         break;
570                         }
571                         /* Link into the new root's right tree. */
572                         righttreemin->left = root;
573                         righttreemin = root;
574                 } else if (address >= root->end) {
575                         if ((y = root->right) == NULL)
576                                 break;
577                         if (address >= y->end) {
578                                 /* Rotate left. */
579                                 root->right = y->left;
580                                 y->left = root;
581                                 root = y;
582                                 if ((y = root->right) == NULL)
583                                         break;
584                         }
585                         /* Link into the new root's left tree. */
586                         lefttreemax->right = root;
587                         lefttreemax = root;
588                 } else
589                         break;
590         }
591         /* Assemble the new root. */
592         lefttreemax->right = root->left;
593         righttreemin->left = root->right;
594         root->left = dummy.right;
595         root->right = dummy.left;
596         return (root);
597 }
598
599 /*
600  *      vm_map_entry_{un,}link:
601  *
602  *      Insert/remove entries from maps.
603  */
604 static void
605 vm_map_entry_link(vm_map_t map,
606                   vm_map_entry_t after_where,
607                   vm_map_entry_t entry)
608 {
609
610         CTR4(KTR_VM,
611             "vm_map_entry_link: map %p, nentries %d, entry %p, after %p", map,
612             map->nentries, entry, after_where);
613         map->nentries++;
614         entry->prev = after_where;
615         entry->next = after_where->next;
616         entry->next->prev = entry;
617         after_where->next = entry;
618
619         if (after_where != &map->header) {
620                 if (after_where != map->root)
621                         vm_map_entry_splay(after_where->start, map->root);
622                 entry->right = after_where->right;
623                 entry->left = after_where;
624                 after_where->right = NULL;
625         } else {
626                 entry->right = map->root;
627                 entry->left = NULL;
628         }
629         map->root = entry;
630 }
631
632 static void
633 vm_map_entry_unlink(vm_map_t map,
634                     vm_map_entry_t entry)
635 {
636         vm_map_entry_t next, prev, root;
637
638         if (entry != map->root)
639                 vm_map_entry_splay(entry->start, map->root);
640         if (entry->left == NULL)
641                 root = entry->right;
642         else {
643                 root = vm_map_entry_splay(entry->start, entry->left);
644                 root->right = entry->right;
645         }
646         map->root = root;
647
648         prev = entry->prev;
649         next = entry->next;
650         next->prev = prev;
651         prev->next = next;
652         map->nentries--;
653         CTR3(KTR_VM, "vm_map_entry_unlink: map %p, nentries %d, entry %p", map,
654             map->nentries, entry);
655 }
656
657 /*
658  *      vm_map_lookup_entry:    [ internal use only ]
659  *
660  *      Finds the map entry containing (or
661  *      immediately preceding) the specified address
662  *      in the given map; the entry is returned
663  *      in the "entry" parameter.  The boolean
664  *      result indicates whether the address is
665  *      actually contained in the map.
666  */
667 boolean_t
668 vm_map_lookup_entry(
669         vm_map_t map,
670         vm_offset_t address,
671         vm_map_entry_t *entry)  /* OUT */
672 {
673         vm_map_entry_t cur;
674
675         cur = vm_map_entry_splay(address, map->root);
676         if (cur == NULL)
677                 *entry = &map->header;
678         else {
679                 map->root = cur;
680
681                 if (address >= cur->start) {
682                         *entry = cur;
683                         if (cur->end > address)
684                                 return (TRUE);
685                 } else
686                         *entry = cur->prev;
687         }
688         return (FALSE);
689 }
690
691 /*
692  *      vm_map_insert:
693  *
694  *      Inserts the given whole VM object into the target
695  *      map at the specified address range.  The object's
696  *      size should match that of the address range.
697  *
698  *      Requires that the map be locked, and leaves it so.
699  *
700  *      If object is non-NULL, ref count must be bumped by caller
701  *      prior to making call to account for the new entry.
702  */
703 int
704 vm_map_insert(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
705               vm_offset_t start, vm_offset_t end, vm_prot_t prot, vm_prot_t max,
706               int cow)
707 {
708         vm_map_entry_t new_entry;
709         vm_map_entry_t prev_entry;
710         vm_map_entry_t temp_entry;
711         vm_eflags_t protoeflags;
712
713         GIANT_REQUIRED;
714
715         /*
716          * Check that the start and end points are not bogus.
717          */
718         if ((start < map->min_offset) || (end > map->max_offset) ||
719             (start >= end))
720                 return (KERN_INVALID_ADDRESS);
721
722         /*
723          * Find the entry prior to the proposed starting address; if it's part
724          * of an existing entry, this range is bogus.
725          */
726         if (vm_map_lookup_entry(map, start, &temp_entry))
727                 return (KERN_NO_SPACE);
728
729         prev_entry = temp_entry;
730
731         /*
732          * Assert that the next entry doesn't overlap the end point.
733          */
734         if ((prev_entry->next != &map->header) &&
735             (prev_entry->next->start < end))
736                 return (KERN_NO_SPACE);
737
738         protoeflags = 0;
739
740         if (cow & MAP_COPY_ON_WRITE)
741                 protoeflags |= MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY;
742
743         if (cow & MAP_NOFAULT) {
744                 protoeflags |= MAP_ENTRY_NOFAULT;
745
746                 KASSERT(object == NULL,
747                         ("vm_map_insert: paradoxical MAP_NOFAULT request"));
748         }
749         if (cow & MAP_DISABLE_SYNCER)
750                 protoeflags |= MAP_ENTRY_NOSYNC;
751         if (cow & MAP_DISABLE_COREDUMP)
752                 protoeflags |= MAP_ENTRY_NOCOREDUMP;
753
754         if (object) {
755                 /*
756                  * When object is non-NULL, it could be shared with another
757                  * process.  We have to set or clear OBJ_ONEMAPPING 
758                  * appropriately.
759                  */
760                 if ((object->ref_count > 1) || (object->shadow_count != 0)) {
761                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
762                 }
763         }
764         else if ((prev_entry != &map->header) &&
765                  (prev_entry->eflags == protoeflags) &&
766                  (prev_entry->end == start) &&
767                  (prev_entry->wired_count == 0) &&
768                  ((prev_entry->object.vm_object == NULL) ||
769                   vm_object_coalesce(prev_entry->object.vm_object,
770                                      OFF_TO_IDX(prev_entry->offset),
771                                      (vm_size_t)(prev_entry->end - prev_entry->start),
772                                      (vm_size_t)(end - prev_entry->end)))) {
773                 /*
774                  * We were able to extend the object.  Determine if we
775                  * can extend the previous map entry to include the 
776                  * new range as well.
777                  */
778                 if ((prev_entry->inheritance == VM_INHERIT_DEFAULT) &&
779                     (prev_entry->protection == prot) &&
780                     (prev_entry->max_protection == max)) {
781                         map->size += (end - prev_entry->end);
782                         prev_entry->end = end;
783                         vm_map_simplify_entry(map, prev_entry);
784                         return (KERN_SUCCESS);
785                 }
786
787                 /*
788                  * If we can extend the object but cannot extend the
789                  * map entry, we have to create a new map entry.  We
790                  * must bump the ref count on the extended object to
791                  * account for it.  object may be NULL.
792                  */
793                 object = prev_entry->object.vm_object;
794                 offset = prev_entry->offset +
795                         (prev_entry->end - prev_entry->start);
796                 vm_object_reference(object);
797         }
798
799         /*
800          * NOTE: if conditionals fail, object can be NULL here.  This occurs
801          * in things like the buffer map where we manage kva but do not manage
802          * backing objects.
803          */
804
805         /*
806          * Create a new entry
807          */
808         new_entry = vm_map_entry_create(map);
809         new_entry->start = start;
810         new_entry->end = end;
811
812         new_entry->eflags = protoeflags;
813         new_entry->object.vm_object = object;
814         new_entry->offset = offset;
815         new_entry->avail_ssize = 0;
816
817         new_entry->inheritance = VM_INHERIT_DEFAULT;
818         new_entry->protection = prot;
819         new_entry->max_protection = max;
820         new_entry->wired_count = 0;
821
822         /*
823          * Insert the new entry into the list
824          */
825         vm_map_entry_link(map, prev_entry, new_entry);
826         map->size += new_entry->end - new_entry->start;
827
828         /*
829          * Update the free space hint
830          */
831         if ((map->first_free == prev_entry) &&
832             (prev_entry->end >= new_entry->start)) {
833                 map->first_free = new_entry;
834         }
835
836 #if 0
837         /*
838          * Temporarily removed to avoid MAP_STACK panic, due to
839          * MAP_STACK being a huge hack.  Will be added back in
840          * when MAP_STACK (and the user stack mapping) is fixed.
841          */
842         /*
843          * It may be possible to simplify the entry
844          */
845         vm_map_simplify_entry(map, new_entry);
846 #endif
847
848         if (cow & (MAP_PREFAULT|MAP_PREFAULT_PARTIAL)) {
849                 pmap_object_init_pt(map->pmap, start,
850                                     object, OFF_TO_IDX(offset), end - start,
851                                     cow & MAP_PREFAULT_PARTIAL);
852         }
853
854         return (KERN_SUCCESS);
855 }
856
857 /*
858  * Find sufficient space for `length' bytes in the given map, starting at
859  * `start'.  The map must be locked.  Returns 0 on success, 1 on no space.
860  */
861 int
862 vm_map_findspace(
863         vm_map_t map,
864         vm_offset_t start,
865         vm_size_t length,
866         vm_offset_t *addr)
867 {
868         vm_map_entry_t entry, next;
869         vm_offset_t end;
870
871         GIANT_REQUIRED;
872         if (start < map->min_offset)
873                 start = map->min_offset;
874         if (start > map->max_offset)
875                 return (1);
876
877         /*
878          * Look for the first possible address; if there's already something
879          * at this address, we have to start after it.
880          */
881         if (start == map->min_offset) {
882                 if ((entry = map->first_free) != &map->header)
883                         start = entry->end;
884         } else {
885                 vm_map_entry_t tmp;
886
887                 if (vm_map_lookup_entry(map, start, &tmp))
888                         start = tmp->end;
889                 entry = tmp;
890         }
891
892         /*
893          * Look through the rest of the map, trying to fit a new region in the
894          * gap between existing regions, or after the very last region.
895          */
896         for (;; start = (entry = next)->end) {
897                 /*
898                  * Find the end of the proposed new region.  Be sure we didn't
899                  * go beyond the end of the map, or wrap around the address;
900                  * if so, we lose.  Otherwise, if this is the last entry, or
901                  * if the proposed new region fits before the next entry, we
902                  * win.
903                  */
904                 end = start + length;
905                 if (end > map->max_offset || end < start)
906                         return (1);
907                 next = entry->next;
908                 if (next == &map->header || next->start >= end)
909                         break;
910         }
911         *addr = start;
912         if (map == kernel_map) {
913                 vm_offset_t ksize;
914                 if ((ksize = round_page(start + length)) > kernel_vm_end) {
915                         pmap_growkernel(ksize);
916                 }
917         }
918         return (0);
919 }
920
921 /*
922  *      vm_map_find finds an unallocated region in the target address
923  *      map with the given length.  The search is defined to be
924  *      first-fit from the specified address; the region found is
925  *      returned in the same parameter.
926  *
927  *      If object is non-NULL, ref count must be bumped by caller
928  *      prior to making call to account for the new entry.
929  */
930 int
931 vm_map_find(vm_map_t map, vm_object_t object, vm_ooffset_t offset,
932             vm_offset_t *addr,  /* IN/OUT */
933             vm_size_t length, boolean_t find_space, vm_prot_t prot,
934             vm_prot_t max, int cow)
935 {
936         vm_offset_t start;
937         int result, s = 0;
938
939         GIANT_REQUIRED;
940
941         start = *addr;
942
943         if (map == kmem_map)
944                 s = splvm();
945
946         vm_map_lock(map);
947         if (find_space) {
948                 if (vm_map_findspace(map, start, length, addr)) {
949                         vm_map_unlock(map);
950                         if (map == kmem_map)
951                                 splx(s);
952                         return (KERN_NO_SPACE);
953                 }
954                 start = *addr;
955         }
956         result = vm_map_insert(map, object, offset,
957                 start, start + length, prot, max, cow);
958         vm_map_unlock(map);
959
960         if (map == kmem_map)
961                 splx(s);
962
963         return (result);
964 }
965
966 /*
967  *      vm_map_simplify_entry:
968  *
969  *      Simplify the given map entry by merging with either neighbor.  This
970  *      routine also has the ability to merge with both neighbors.
971  *
972  *      The map must be locked.
973  *
974  *      This routine guarentees that the passed entry remains valid (though
975  *      possibly extended).  When merging, this routine may delete one or
976  *      both neighbors.
977  */
978 void
979 vm_map_simplify_entry(vm_map_t map, vm_map_entry_t entry)
980 {
981         vm_map_entry_t next, prev;
982         vm_size_t prevsize, esize;
983
984         if (entry->eflags & (MAP_ENTRY_IN_TRANSITION | MAP_ENTRY_IS_SUB_MAP))
985                 return;
986
987         prev = entry->prev;
988         if (prev != &map->header) {
989                 prevsize = prev->end - prev->start;
990                 if ( (prev->end == entry->start) &&
991                      (prev->object.vm_object == entry->object.vm_object) &&
992                      (!prev->object.vm_object ||
993                         (prev->offset + prevsize == entry->offset)) &&
994                      (prev->eflags == entry->eflags) &&
995                      (prev->protection == entry->protection) &&
996                      (prev->max_protection == entry->max_protection) &&
997                      (prev->inheritance == entry->inheritance) &&
998                      (prev->wired_count == entry->wired_count)) {
999                         if (map->first_free == prev)
1000                                 map->first_free = entry;
1001                         vm_map_entry_unlink(map, prev);
1002                         entry->start = prev->start;
1003                         entry->offset = prev->offset;
1004                         if (prev->object.vm_object)
1005                                 vm_object_deallocate(prev->object.vm_object);
1006                         vm_map_entry_dispose(map, prev);
1007                 }
1008         }
1009
1010         next = entry->next;
1011         if (next != &map->header) {
1012                 esize = entry->end - entry->start;
1013                 if ((entry->end == next->start) &&
1014                     (next->object.vm_object == entry->object.vm_object) &&
1015                      (!entry->object.vm_object ||
1016                         (entry->offset + esize == next->offset)) &&
1017                     (next->eflags == entry->eflags) &&
1018                     (next->protection == entry->protection) &&
1019                     (next->max_protection == entry->max_protection) &&
1020                     (next->inheritance == entry->inheritance) &&
1021                     (next->wired_count == entry->wired_count)) {
1022                         if (map->first_free == next)
1023                                 map->first_free = entry;
1024                         vm_map_entry_unlink(map, next);
1025                         entry->end = next->end;
1026                         if (next->object.vm_object)
1027                                 vm_object_deallocate(next->object.vm_object);
1028                         vm_map_entry_dispose(map, next);
1029                 }
1030         }
1031 }
1032 /*
1033  *      vm_map_clip_start:      [ internal use only ]
1034  *
1035  *      Asserts that the given entry begins at or after
1036  *      the specified address; if necessary,
1037  *      it splits the entry into two.
1038  */
1039 #define vm_map_clip_start(map, entry, startaddr) \
1040 { \
1041         if (startaddr > entry->start) \
1042                 _vm_map_clip_start(map, entry, startaddr); \
1043 }
1044
1045 /*
1046  *      This routine is called only when it is known that
1047  *      the entry must be split.
1048  */
1049 static void
1050 _vm_map_clip_start(vm_map_t map, vm_map_entry_t entry, vm_offset_t start)
1051 {
1052         vm_map_entry_t new_entry;
1053
1054         /*
1055          * Split off the front portion -- note that we must insert the new
1056          * entry BEFORE this one, so that this entry has the specified
1057          * starting address.
1058          */
1059         vm_map_simplify_entry(map, entry);
1060
1061         /*
1062          * If there is no object backing this entry, we might as well create
1063          * one now.  If we defer it, an object can get created after the map
1064          * is clipped, and individual objects will be created for the split-up
1065          * map.  This is a bit of a hack, but is also about the best place to
1066          * put this improvement.
1067          */
1068         if (entry->object.vm_object == NULL && !map->system_map) {
1069                 vm_object_t object;
1070                 object = vm_object_allocate(OBJT_DEFAULT,
1071                                 atop(entry->end - entry->start));
1072                 entry->object.vm_object = object;
1073                 entry->offset = 0;
1074         }
1075
1076         new_entry = vm_map_entry_create(map);
1077         *new_entry = *entry;
1078
1079         new_entry->end = start;
1080         entry->offset += (start - entry->start);
1081         entry->start = start;
1082
1083         vm_map_entry_link(map, entry->prev, new_entry);
1084
1085         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1086                 vm_object_reference(new_entry->object.vm_object);
1087         }
1088 }
1089
1090 /*
1091  *      vm_map_clip_end:        [ internal use only ]
1092  *
1093  *      Asserts that the given entry ends at or before
1094  *      the specified address; if necessary,
1095  *      it splits the entry into two.
1096  */
1097 #define vm_map_clip_end(map, entry, endaddr) \
1098 { \
1099         if (endaddr < entry->end) \
1100                 _vm_map_clip_end(map, entry, endaddr); \
1101 }
1102
1103 /*
1104  *      This routine is called only when it is known that
1105  *      the entry must be split.
1106  */
1107 static void
1108 _vm_map_clip_end(vm_map_t map, vm_map_entry_t entry, vm_offset_t end)
1109 {
1110         vm_map_entry_t new_entry;
1111
1112         /*
1113          * If there is no object backing this entry, we might as well create
1114          * one now.  If we defer it, an object can get created after the map
1115          * is clipped, and individual objects will be created for the split-up
1116          * map.  This is a bit of a hack, but is also about the best place to
1117          * put this improvement.
1118          */
1119         if (entry->object.vm_object == NULL && !map->system_map) {
1120                 vm_object_t object;
1121                 object = vm_object_allocate(OBJT_DEFAULT,
1122                                 atop(entry->end - entry->start));
1123                 entry->object.vm_object = object;
1124                 entry->offset = 0;
1125         }
1126
1127         /*
1128          * Create a new entry and insert it AFTER the specified entry
1129          */
1130         new_entry = vm_map_entry_create(map);
1131         *new_entry = *entry;
1132
1133         new_entry->start = entry->end = end;
1134         new_entry->offset += (end - entry->start);
1135
1136         vm_map_entry_link(map, entry, new_entry);
1137
1138         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1139                 vm_object_reference(new_entry->object.vm_object);
1140         }
1141 }
1142
1143 /*
1144  *      VM_MAP_RANGE_CHECK:     [ internal use only ]
1145  *
1146  *      Asserts that the starting and ending region
1147  *      addresses fall within the valid range of the map.
1148  */
1149 #define VM_MAP_RANGE_CHECK(map, start, end)             \
1150                 {                                       \
1151                 if (start < vm_map_min(map))            \
1152                         start = vm_map_min(map);        \
1153                 if (end > vm_map_max(map))              \
1154                         end = vm_map_max(map);          \
1155                 if (start > end)                        \
1156                         start = end;                    \
1157                 }
1158
1159 /*
1160  *      vm_map_submap:          [ kernel use only ]
1161  *
1162  *      Mark the given range as handled by a subordinate map.
1163  *
1164  *      This range must have been created with vm_map_find,
1165  *      and no other operations may have been performed on this
1166  *      range prior to calling vm_map_submap.
1167  *
1168  *      Only a limited number of operations can be performed
1169  *      within this rage after calling vm_map_submap:
1170  *              vm_fault
1171  *      [Don't try vm_map_copy!]
1172  *
1173  *      To remove a submapping, one must first remove the
1174  *      range from the superior map, and then destroy the
1175  *      submap (if desired).  [Better yet, don't try it.]
1176  */
1177 int
1178 vm_map_submap(
1179         vm_map_t map,
1180         vm_offset_t start,
1181         vm_offset_t end,
1182         vm_map_t submap)
1183 {
1184         vm_map_entry_t entry;
1185         int result = KERN_INVALID_ARGUMENT;
1186
1187         vm_map_lock(map);
1188
1189         VM_MAP_RANGE_CHECK(map, start, end);
1190
1191         if (vm_map_lookup_entry(map, start, &entry)) {
1192                 vm_map_clip_start(map, entry, start);
1193         } else
1194                 entry = entry->next;
1195
1196         vm_map_clip_end(map, entry, end);
1197
1198         if ((entry->start == start) && (entry->end == end) &&
1199             ((entry->eflags & MAP_ENTRY_COW) == 0) &&
1200             (entry->object.vm_object == NULL)) {
1201                 entry->object.sub_map = submap;
1202                 entry->eflags |= MAP_ENTRY_IS_SUB_MAP;
1203                 result = KERN_SUCCESS;
1204         }
1205         vm_map_unlock(map);
1206
1207         return (result);
1208 }
1209
1210 /*
1211  *      vm_map_protect:
1212  *
1213  *      Sets the protection of the specified address
1214  *      region in the target map.  If "set_max" is
1215  *      specified, the maximum protection is to be set;
1216  *      otherwise, only the current protection is affected.
1217  */
1218 int
1219 vm_map_protect(vm_map_t map, vm_offset_t start, vm_offset_t end,
1220                vm_prot_t new_prot, boolean_t set_max)
1221 {
1222         vm_map_entry_t current;
1223         vm_map_entry_t entry;
1224
1225         vm_map_lock(map);
1226
1227         VM_MAP_RANGE_CHECK(map, start, end);
1228
1229         if (vm_map_lookup_entry(map, start, &entry)) {
1230                 vm_map_clip_start(map, entry, start);
1231         } else {
1232                 entry = entry->next;
1233         }
1234
1235         /*
1236          * Make a first pass to check for protection violations.
1237          */
1238         current = entry;
1239         while ((current != &map->header) && (current->start < end)) {
1240                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
1241                         vm_map_unlock(map);
1242                         return (KERN_INVALID_ARGUMENT);
1243                 }
1244                 if ((new_prot & current->max_protection) != new_prot) {
1245                         vm_map_unlock(map);
1246                         return (KERN_PROTECTION_FAILURE);
1247                 }
1248                 current = current->next;
1249         }
1250
1251         /*
1252          * Go back and fix up protections. [Note that clipping is not
1253          * necessary the second time.]
1254          */
1255         current = entry;
1256         while ((current != &map->header) && (current->start < end)) {
1257                 vm_prot_t old_prot;
1258
1259                 vm_map_clip_end(map, current, end);
1260
1261                 old_prot = current->protection;
1262                 if (set_max)
1263                         current->protection =
1264                             (current->max_protection = new_prot) &
1265                             old_prot;
1266                 else
1267                         current->protection = new_prot;
1268
1269                 /*
1270                  * Update physical map if necessary. Worry about copy-on-write
1271                  * here -- CHECK THIS XXX
1272                  */
1273                 if (current->protection != old_prot) {
1274                         mtx_lock(&Giant);
1275 #define MASK(entry)     (((entry)->eflags & MAP_ENTRY_COW) ? ~VM_PROT_WRITE : \
1276                                                         VM_PROT_ALL)
1277                         pmap_protect(map->pmap, current->start,
1278                             current->end,
1279                             current->protection & MASK(current));
1280 #undef  MASK
1281                         mtx_unlock(&Giant);
1282                 }
1283                 vm_map_simplify_entry(map, current);
1284                 current = current->next;
1285         }
1286         vm_map_unlock(map);
1287         return (KERN_SUCCESS);
1288 }
1289
1290 /*
1291  *      vm_map_madvise:
1292  *
1293  *      This routine traverses a processes map handling the madvise
1294  *      system call.  Advisories are classified as either those effecting
1295  *      the vm_map_entry structure, or those effecting the underlying 
1296  *      objects.
1297  */
1298 int
1299 vm_map_madvise(
1300         vm_map_t map,
1301         vm_offset_t start, 
1302         vm_offset_t end,
1303         int behav)
1304 {
1305         vm_map_entry_t current, entry;
1306         int modify_map = 0;
1307
1308         /*
1309          * Some madvise calls directly modify the vm_map_entry, in which case
1310          * we need to use an exclusive lock on the map and we need to perform 
1311          * various clipping operations.  Otherwise we only need a read-lock
1312          * on the map.
1313          */
1314         switch(behav) {
1315         case MADV_NORMAL:
1316         case MADV_SEQUENTIAL:
1317         case MADV_RANDOM:
1318         case MADV_NOSYNC:
1319         case MADV_AUTOSYNC:
1320         case MADV_NOCORE:
1321         case MADV_CORE:
1322                 modify_map = 1;
1323                 vm_map_lock(map);
1324                 break;
1325         case MADV_WILLNEED:
1326         case MADV_DONTNEED:
1327         case MADV_FREE:
1328                 vm_map_lock_read(map);
1329                 break;
1330         default:
1331                 return (KERN_INVALID_ARGUMENT);
1332         }
1333
1334         /*
1335          * Locate starting entry and clip if necessary.
1336          */
1337         VM_MAP_RANGE_CHECK(map, start, end);
1338
1339         if (vm_map_lookup_entry(map, start, &entry)) {
1340                 if (modify_map)
1341                         vm_map_clip_start(map, entry, start);
1342         } else {
1343                 entry = entry->next;
1344         }
1345
1346         if (modify_map) {
1347                 /*
1348                  * madvise behaviors that are implemented in the vm_map_entry.
1349                  *
1350                  * We clip the vm_map_entry so that behavioral changes are
1351                  * limited to the specified address range.
1352                  */
1353                 for (current = entry;
1354                      (current != &map->header) && (current->start < end);
1355                      current = current->next
1356                 ) {
1357                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1358                                 continue;
1359
1360                         vm_map_clip_end(map, current, end);
1361
1362                         switch (behav) {
1363                         case MADV_NORMAL:
1364                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_NORMAL);
1365                                 break;
1366                         case MADV_SEQUENTIAL:
1367                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_SEQUENTIAL);
1368                                 break;
1369                         case MADV_RANDOM:
1370                                 vm_map_entry_set_behavior(current, MAP_ENTRY_BEHAV_RANDOM);
1371                                 break;
1372                         case MADV_NOSYNC:
1373                                 current->eflags |= MAP_ENTRY_NOSYNC;
1374                                 break;
1375                         case MADV_AUTOSYNC:
1376                                 current->eflags &= ~MAP_ENTRY_NOSYNC;
1377                                 break;
1378                         case MADV_NOCORE:
1379                                 current->eflags |= MAP_ENTRY_NOCOREDUMP;
1380                                 break;
1381                         case MADV_CORE:
1382                                 current->eflags &= ~MAP_ENTRY_NOCOREDUMP;
1383                                 break;
1384                         default:
1385                                 break;
1386                         }
1387                         vm_map_simplify_entry(map, current);
1388                 }
1389                 vm_map_unlock(map);
1390         } else {
1391                 vm_pindex_t pindex;
1392                 int count;
1393
1394                 /*
1395                  * madvise behaviors that are implemented in the underlying
1396                  * vm_object.
1397                  *
1398                  * Since we don't clip the vm_map_entry, we have to clip
1399                  * the vm_object pindex and count.
1400                  */
1401                 for (current = entry;
1402                      (current != &map->header) && (current->start < end);
1403                      current = current->next
1404                 ) {
1405                         vm_offset_t useStart;
1406
1407                         if (current->eflags & MAP_ENTRY_IS_SUB_MAP)
1408                                 continue;
1409
1410                         pindex = OFF_TO_IDX(current->offset);
1411                         count = atop(current->end - current->start);
1412                         useStart = current->start;
1413
1414                         if (current->start < start) {
1415                                 pindex += atop(start - current->start);
1416                                 count -= atop(start - current->start);
1417                                 useStart = start;
1418                         }
1419                         if (current->end > end)
1420                                 count -= atop(current->end - end);
1421
1422                         if (count <= 0)
1423                                 continue;
1424
1425                         vm_object_madvise(current->object.vm_object,
1426                                           pindex, count, behav);
1427                         if (behav == MADV_WILLNEED) {
1428                                 mtx_lock(&Giant);
1429                                 pmap_object_init_pt(
1430                                     map->pmap, 
1431                                     useStart,
1432                                     current->object.vm_object,
1433                                     pindex, 
1434                                     (count << PAGE_SHIFT),
1435                                     MAP_PREFAULT_MADVISE
1436                                 );
1437                                 mtx_unlock(&Giant);
1438                         }
1439                 }
1440                 vm_map_unlock_read(map);
1441         }
1442         return (0);
1443 }       
1444
1445
1446 /*
1447  *      vm_map_inherit:
1448  *
1449  *      Sets the inheritance of the specified address
1450  *      range in the target map.  Inheritance
1451  *      affects how the map will be shared with
1452  *      child maps at the time of vm_map_fork.
1453  */
1454 int
1455 vm_map_inherit(vm_map_t map, vm_offset_t start, vm_offset_t end,
1456                vm_inherit_t new_inheritance)
1457 {
1458         vm_map_entry_t entry;
1459         vm_map_entry_t temp_entry;
1460
1461         switch (new_inheritance) {
1462         case VM_INHERIT_NONE:
1463         case VM_INHERIT_COPY:
1464         case VM_INHERIT_SHARE:
1465                 break;
1466         default:
1467                 return (KERN_INVALID_ARGUMENT);
1468         }
1469         vm_map_lock(map);
1470         VM_MAP_RANGE_CHECK(map, start, end);
1471         if (vm_map_lookup_entry(map, start, &temp_entry)) {
1472                 entry = temp_entry;
1473                 vm_map_clip_start(map, entry, start);
1474         } else
1475                 entry = temp_entry->next;
1476         while ((entry != &map->header) && (entry->start < end)) {
1477                 vm_map_clip_end(map, entry, end);
1478                 entry->inheritance = new_inheritance;
1479                 vm_map_simplify_entry(map, entry);
1480                 entry = entry->next;
1481         }
1482         vm_map_unlock(map);
1483         return (KERN_SUCCESS);
1484 }
1485
1486 /*
1487  *      vm_map_unwire:
1488  *
1489  *      Implements both kernel and user unwiring.
1490  */
1491 int
1492 vm_map_unwire(vm_map_t map, vm_offset_t start, vm_offset_t end,
1493         boolean_t user_unwire)
1494 {
1495         vm_map_entry_t entry, first_entry, tmp_entry;
1496         vm_offset_t saved_start;
1497         unsigned int last_timestamp;
1498         int rv;
1499         boolean_t need_wakeup, result;
1500
1501         vm_map_lock(map);
1502         VM_MAP_RANGE_CHECK(map, start, end);
1503         if (!vm_map_lookup_entry(map, start, &first_entry)) {
1504                 vm_map_unlock(map);
1505                 return (KERN_INVALID_ADDRESS);
1506         }
1507         last_timestamp = map->timestamp;
1508         entry = first_entry;
1509         while (entry != &map->header && entry->start < end) {
1510                 if (entry->eflags & MAP_ENTRY_IN_TRANSITION) {
1511                         /*
1512                          * We have not yet clipped the entry.
1513                          */
1514                         saved_start = (start >= entry->start) ? start :
1515                             entry->start;
1516                         entry->eflags |= MAP_ENTRY_NEEDS_WAKEUP;
1517                         if (vm_map_unlock_and_wait(map, user_unwire)) {
1518                                 /*
1519                                  * Allow interruption of user unwiring?
1520                                  */
1521                         }
1522                         vm_map_lock(map);
1523                         if (last_timestamp+1 != map->timestamp) {
1524                                 /*
1525                                  * Look again for the entry because the map was
1526                                  * modified while it was unlocked.
1527                                  * Specifically, the entry may have been
1528                                  * clipped, merged, or deleted.
1529                                  */
1530                                 if (!vm_map_lookup_entry(map, saved_start,
1531                                     &tmp_entry)) {
1532                                         if (saved_start == start) {
1533                                                 /*
1534                                                  * First_entry has been deleted.
1535                                                  */
1536                                                 vm_map_unlock(map);
1537                                                 return (KERN_INVALID_ADDRESS);
1538                                         }
1539                                         end = saved_start;
1540                                         rv = KERN_INVALID_ADDRESS;
1541                                         goto done;
1542                                 }
1543                                 if (entry == first_entry)
1544                                         first_entry = tmp_entry;
1545                                 else
1546                                         first_entry = NULL;
1547                                 entry = tmp_entry;
1548                         }
1549                         last_timestamp = map->timestamp;
1550                         continue;
1551                 }
1552                 vm_map_clip_start(map, entry, start);
1553                 vm_map_clip_end(map, entry, end);
1554                 /*
1555                  * Mark the entry in case the map lock is released.  (See
1556                  * above.)
1557                  */
1558                 entry->eflags |= MAP_ENTRY_IN_TRANSITION;
1559                 /*
1560                  * Check the map for holes in the specified region.
1561                  */
1562                 if (entry->end < end && (entry->next == &map->header ||
1563                     entry->next->start > entry->end)) {
1564                         end = entry->end;
1565                         rv = KERN_INVALID_ADDRESS;
1566                         goto done;
1567                 }
1568                 /*
1569                  * Require that the entry is wired.
1570                  */
1571                 if (entry->wired_count == 0 || (user_unwire &&
1572                     (entry->eflags & MAP_ENTRY_USER_WIRED) == 0)) {
1573                         end = entry->end;
1574                         rv = KERN_INVALID_ARGUMENT;
1575                         goto done;
1576                 }
1577                 entry = entry->next;
1578         }
1579         if (first_entry == NULL) {
1580                 result = vm_map_lookup_entry(map, start, &first_entry);
1581                 KASSERT(result, ("vm_map_unwire: lookup failed"));
1582         }
1583         entry = first_entry;
1584         while (entry != &map->header && entry->start < end) {
1585                 if (user_unwire)
1586                         entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1587                 entry->wired_count--;
1588                 if (entry->wired_count == 0) {
1589                         /*
1590                          * Retain the map lock.
1591                          */
1592                         vm_fault_unwire(map, entry->start, entry->end);
1593                 }
1594                 entry = entry->next;
1595         }
1596         rv = KERN_SUCCESS;
1597 done:
1598         need_wakeup = FALSE;
1599         if (first_entry == NULL) {
1600                 result = vm_map_lookup_entry(map, start, &first_entry);
1601                 KASSERT(result, ("vm_map_unwire: lookup failed"));
1602         }
1603         entry = first_entry;
1604         while (entry != &map->header && entry->start < end) {
1605                 KASSERT(entry->eflags & MAP_ENTRY_IN_TRANSITION,
1606                         ("vm_map_unwire: in-transition flag missing"));
1607                 entry->eflags &= ~MAP_ENTRY_IN_TRANSITION;
1608                 if (entry->eflags & MAP_ENTRY_NEEDS_WAKEUP) {
1609                         entry->eflags &= ~MAP_ENTRY_NEEDS_WAKEUP;
1610                         need_wakeup = TRUE;
1611                 }
1612                 vm_map_simplify_entry(map, entry);
1613                 entry = entry->next;
1614         }
1615         vm_map_unlock(map);
1616         if (need_wakeup)
1617                 vm_map_wakeup(map);
1618         return (rv);
1619 }
1620
1621 /*
1622  *      vm_map_wire:
1623  *
1624  *      Implements both kernel and user wiring.
1625  */
1626 int
1627 vm_map_wire(vm_map_t map, vm_offset_t start, vm_offset_t end,
1628         boolean_t user_wire)
1629 {
1630
1631         return (KERN_FAILURE);
1632 }
1633
1634 /*
1635  * Implement the semantics of mlock
1636  */
1637 int
1638 vm_map_user_pageable(
1639         vm_map_t map,
1640         vm_offset_t start,
1641         vm_offset_t end,
1642         boolean_t new_pageable)
1643 {
1644         vm_map_entry_t entry;
1645         vm_map_entry_t start_entry;
1646         vm_offset_t estart;
1647         vm_offset_t eend;
1648         int rv;
1649
1650         vm_map_lock(map);
1651         VM_MAP_RANGE_CHECK(map, start, end);
1652
1653         if (vm_map_lookup_entry(map, start, &start_entry) == FALSE) {
1654                 vm_map_unlock(map);
1655                 return (KERN_INVALID_ADDRESS);
1656         }
1657
1658         if (new_pageable) {
1659
1660                 entry = start_entry;
1661                 vm_map_clip_start(map, entry, start);
1662
1663                 /*
1664                  * Now decrement the wiring count for each region. If a region
1665                  * becomes completely unwired, unwire its physical pages and
1666                  * mappings.
1667                  */
1668                 while ((entry != &map->header) && (entry->start < end)) {
1669                         if (entry->eflags & MAP_ENTRY_USER_WIRED) {
1670                                 vm_map_clip_end(map, entry, end);
1671                                 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1672                                 entry->wired_count--;
1673                                 if (entry->wired_count == 0)
1674                                         vm_fault_unwire(map, entry->start, entry->end);
1675                         }
1676                         vm_map_simplify_entry(map,entry);
1677                         entry = entry->next;
1678                 }
1679         } else {
1680
1681                 entry = start_entry;
1682
1683                 while ((entry != &map->header) && (entry->start < end)) {
1684
1685                         if (entry->eflags & MAP_ENTRY_USER_WIRED) {
1686                                 entry = entry->next;
1687                                 continue;
1688                         }
1689                         
1690                         if (entry->wired_count != 0) {
1691                                 entry->wired_count++;
1692                                 entry->eflags |= MAP_ENTRY_USER_WIRED;
1693                                 entry = entry->next;
1694                                 continue;
1695                         }
1696
1697                         /* Here on entry being newly wired */
1698
1699                         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1700                                 int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
1701                                 if (copyflag && ((entry->protection & VM_PROT_WRITE) != 0)) {
1702
1703                                         vm_object_shadow(&entry->object.vm_object,
1704                                             &entry->offset,
1705                                             atop(entry->end - entry->start));
1706                                         entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
1707
1708                                 } else if (entry->object.vm_object == NULL &&
1709                                            !map->system_map) {
1710
1711                                         entry->object.vm_object =
1712                                             vm_object_allocate(OBJT_DEFAULT,
1713                                                 atop(entry->end - entry->start));
1714                                         entry->offset = (vm_offset_t) 0;
1715
1716                                 }
1717                         }
1718
1719                         vm_map_clip_start(map, entry, start);
1720                         vm_map_clip_end(map, entry, end);
1721
1722                         entry->wired_count++;
1723                         entry->eflags |= MAP_ENTRY_USER_WIRED;
1724                         estart = entry->start;
1725                         eend = entry->end;
1726
1727                         /* First we need to allow map modifications */
1728                         vm_map_set_recursive(map);
1729                         vm_map_lock_downgrade(map);
1730                         map->timestamp++;
1731
1732                         rv = vm_fault_user_wire(map, entry->start, entry->end);
1733                         if (rv) {
1734
1735                                 entry->wired_count--;
1736                                 entry->eflags &= ~MAP_ENTRY_USER_WIRED;
1737
1738                                 vm_map_clear_recursive(map);
1739                                 vm_map_unlock(map);
1740                         
1741                                 /*
1742                                  * At this point, the map is unlocked, and
1743                                  * entry might no longer be valid.  Use copy
1744                                  * of entry start value obtained while entry
1745                                  * was valid.
1746                                  */
1747                                 (void) vm_map_user_pageable(map, start, estart,
1748                                                             TRUE);
1749                                 return rv;
1750                         }
1751
1752                         vm_map_clear_recursive(map);
1753                         if (vm_map_lock_upgrade(map)) {
1754                                 vm_map_lock(map);
1755                                 if (vm_map_lookup_entry(map, estart, &entry) 
1756                                     == FALSE) {
1757                                         vm_map_unlock(map);
1758                                         /* 
1759                                          * vm_fault_user_wire succeded, thus
1760                                          * the area between start and eend
1761                                          * is wired and has to be unwired
1762                                          * here as part of the cleanup.
1763                                          */
1764                                         (void) vm_map_user_pageable(map,
1765                                                                     start,
1766                                                                     eend,
1767                                                                     TRUE);
1768                                         return (KERN_INVALID_ADDRESS);
1769                                 }
1770                         }
1771                         vm_map_simplify_entry(map,entry);
1772                 }
1773         }
1774         map->timestamp++;
1775         vm_map_unlock(map);
1776         return KERN_SUCCESS;
1777 }
1778
1779 /*
1780  *      vm_map_pageable:
1781  *
1782  *      Sets the pageability of the specified address
1783  *      range in the target map.  Regions specified
1784  *      as not pageable require locked-down physical
1785  *      memory and physical page maps.
1786  *
1787  *      The map must not be locked, but a reference
1788  *      must remain to the map throughout the call.
1789  */
1790 int
1791 vm_map_pageable(
1792         vm_map_t map,
1793         vm_offset_t start,
1794         vm_offset_t end,
1795         boolean_t new_pageable)
1796 {
1797         vm_map_entry_t entry;
1798         vm_map_entry_t start_entry;
1799         vm_offset_t failed = 0;
1800         int rv;
1801
1802         GIANT_REQUIRED;
1803
1804         vm_map_lock(map);
1805
1806         VM_MAP_RANGE_CHECK(map, start, end);
1807
1808         /*
1809          * Only one pageability change may take place at one time, since
1810          * vm_fault assumes it will be called only once for each
1811          * wiring/unwiring.  Therefore, we have to make sure we're actually
1812          * changing the pageability for the entire region.  We do so before
1813          * making any changes.
1814          */
1815         if (vm_map_lookup_entry(map, start, &start_entry) == FALSE) {
1816                 vm_map_unlock(map);
1817                 return (KERN_INVALID_ADDRESS);
1818         }
1819         entry = start_entry;
1820
1821         /*
1822          * Actions are rather different for wiring and unwiring, so we have
1823          * two separate cases.
1824          */
1825         if (new_pageable) {
1826                 vm_map_clip_start(map, entry, start);
1827
1828                 /*
1829                  * Unwiring.  First ensure that the range to be unwired is
1830                  * really wired down and that there are no holes.
1831                  */
1832                 while ((entry != &map->header) && (entry->start < end)) {
1833                         if (entry->wired_count == 0 ||
1834                             (entry->end < end &&
1835                                 (entry->next == &map->header ||
1836                                     entry->next->start > entry->end))) {
1837                                 vm_map_unlock(map);
1838                                 return (KERN_INVALID_ARGUMENT);
1839                         }
1840                         entry = entry->next;
1841                 }
1842
1843                 /*
1844                  * Now decrement the wiring count for each region. If a region
1845                  * becomes completely unwired, unwire its physical pages and
1846                  * mappings.
1847                  */
1848                 entry = start_entry;
1849                 while ((entry != &map->header) && (entry->start < end)) {
1850                         vm_map_clip_end(map, entry, end);
1851
1852                         entry->wired_count--;
1853                         if (entry->wired_count == 0)
1854                                 vm_fault_unwire(map, entry->start, entry->end);
1855
1856                         vm_map_simplify_entry(map, entry);
1857
1858                         entry = entry->next;
1859                 }
1860         } else {
1861                 /*
1862                  * Wiring.  We must do this in two passes:
1863                  *
1864                  * 1.  Holding the write lock, we create any shadow or zero-fill
1865                  * objects that need to be created. Then we clip each map
1866                  * entry to the region to be wired and increment its wiring
1867                  * count.  We create objects before clipping the map entries
1868                  * to avoid object proliferation.
1869                  *
1870                  * 2.  We downgrade to a read lock, and call vm_fault_wire to
1871                  * fault in the pages for any newly wired area (wired_count is
1872                  * 1).
1873                  *
1874                  * Downgrading to a read lock for vm_fault_wire avoids a possible
1875                  * deadlock with another process that may have faulted on one
1876                  * of the pages to be wired (it would mark the page busy,
1877                  * blocking us, then in turn block on the map lock that we
1878                  * hold).  Because of problems in the recursive lock package,
1879                  * we cannot upgrade to a write lock in vm_map_lookup.  Thus,
1880                  * any actions that require the write lock must be done
1881                  * beforehand.  Because we keep the read lock on the map, the
1882                  * copy-on-write status of the entries we modify here cannot
1883                  * change.
1884                  */
1885
1886                 /*
1887                  * Pass 1.
1888                  */
1889                 while ((entry != &map->header) && (entry->start < end)) {
1890                         if (entry->wired_count == 0) {
1891
1892                                 /*
1893                                  * Perform actions of vm_map_lookup that need
1894                                  * the write lock on the map: create a shadow
1895                                  * object for a copy-on-write region, or an
1896                                  * object for a zero-fill region.
1897                                  *
1898                                  * We don't have to do this for entries that
1899                                  * point to sub maps, because we won't
1900                                  * hold the lock on the sub map.
1901                                  */
1902                                 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
1903                                         int copyflag = entry->eflags & MAP_ENTRY_NEEDS_COPY;
1904                                         if (copyflag &&
1905                                             ((entry->protection & VM_PROT_WRITE) != 0)) {
1906
1907                                                 vm_object_shadow(&entry->object.vm_object,
1908                                                     &entry->offset,
1909                                                     atop(entry->end - entry->start));
1910                                                 entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
1911                                         } else if (entry->object.vm_object == NULL &&
1912                                                    !map->system_map) {
1913                                                 entry->object.vm_object =
1914                                                     vm_object_allocate(OBJT_DEFAULT,
1915                                                         atop(entry->end - entry->start));
1916                                                 entry->offset = (vm_offset_t) 0;
1917                                         }
1918                                 }
1919                         }
1920                         vm_map_clip_start(map, entry, start);
1921                         vm_map_clip_end(map, entry, end);
1922                         entry->wired_count++;
1923
1924                         /*
1925                          * Check for holes
1926                          */
1927                         if (entry->end < end &&
1928                             (entry->next == &map->header ||
1929                                 entry->next->start > entry->end)) {
1930                                 /*
1931                                  * Found one.  Object creation actions do not
1932                                  * need to be undone, but the wired counts
1933                                  * need to be restored.
1934                                  */
1935                                 while (entry != &map->header && entry->end > start) {
1936                                         entry->wired_count--;
1937                                         entry = entry->prev;
1938                                 }
1939                                 vm_map_unlock(map);
1940                                 return (KERN_INVALID_ARGUMENT);
1941                         }
1942                         entry = entry->next;
1943                 }
1944
1945                 /*
1946                  * Pass 2.
1947                  */
1948
1949                 /*
1950                  * HACK HACK HACK HACK
1951                  *
1952                  * If we are wiring in the kernel map or a submap of it,
1953                  * unlock the map to avoid deadlocks.  We trust that the
1954                  * kernel is well-behaved, and therefore will not do
1955                  * anything destructive to this region of the map while
1956                  * we have it unlocked.  We cannot trust user processes
1957                  * to do the same.
1958                  *
1959                  * HACK HACK HACK HACK
1960                  */
1961                 if (vm_map_pmap(map) == kernel_pmap) {
1962                         vm_map_unlock(map);     /* trust me ... */
1963                 } else {
1964                         vm_map_lock_downgrade(map);
1965                 }
1966
1967                 rv = 0;
1968                 entry = start_entry;
1969                 while (entry != &map->header && entry->start < end) {
1970                         /*
1971                          * If vm_fault_wire fails for any page we need to undo
1972                          * what has been done.  We decrement the wiring count
1973                          * for those pages which have not yet been wired (now)
1974                          * and unwire those that have (later).
1975                          *
1976                          * XXX this violates the locking protocol on the map,
1977                          * needs to be fixed.
1978                          */
1979                         if (rv)
1980                                 entry->wired_count--;
1981                         else if (entry->wired_count == 1) {
1982                                 rv = vm_fault_wire(map, entry->start, entry->end);
1983                                 if (rv) {
1984                                         failed = entry->start;
1985                                         entry->wired_count--;
1986                                 }
1987                         }
1988                         entry = entry->next;
1989                 }
1990
1991                 if (vm_map_pmap(map) == kernel_pmap) {
1992                         vm_map_lock(map);
1993                 }
1994                 if (rv) {
1995                         vm_map_unlock(map);
1996                         (void) vm_map_pageable(map, start, failed, TRUE);
1997                         return (rv);
1998                 }
1999                 /*
2000                  * An exclusive lock on the map is needed in order to call
2001                  * vm_map_simplify_entry().  If the current lock on the map
2002                  * is only a shared lock, an upgrade is needed.
2003                  */
2004                 if (vm_map_pmap(map) != kernel_pmap &&
2005                     vm_map_lock_upgrade(map)) {
2006                         vm_map_lock(map);
2007                         if (vm_map_lookup_entry(map, start, &start_entry) ==
2008                             FALSE) {
2009                                 vm_map_unlock(map);
2010                                 return KERN_SUCCESS;
2011                         }
2012                 }
2013                 vm_map_simplify_entry(map, start_entry);
2014         }
2015
2016         vm_map_unlock(map);
2017
2018         return (KERN_SUCCESS);
2019 }
2020
2021 /*
2022  * vm_map_clean
2023  *
2024  * Push any dirty cached pages in the address range to their pager.
2025  * If syncio is TRUE, dirty pages are written synchronously.
2026  * If invalidate is TRUE, any cached pages are freed as well.
2027  *
2028  * Returns an error if any part of the specified range is not mapped.
2029  */
2030 int
2031 vm_map_clean(
2032         vm_map_t map,
2033         vm_offset_t start,
2034         vm_offset_t end,
2035         boolean_t syncio,
2036         boolean_t invalidate)
2037 {
2038         vm_map_entry_t current;
2039         vm_map_entry_t entry;
2040         vm_size_t size;
2041         vm_object_t object;
2042         vm_ooffset_t offset;
2043
2044         GIANT_REQUIRED;
2045
2046         vm_map_lock_read(map);
2047         VM_MAP_RANGE_CHECK(map, start, end);
2048         if (!vm_map_lookup_entry(map, start, &entry)) {
2049                 vm_map_unlock_read(map);
2050                 return (KERN_INVALID_ADDRESS);
2051         }
2052         /*
2053          * Make a first pass to check for holes.
2054          */
2055         for (current = entry; current->start < end; current = current->next) {
2056                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2057                         vm_map_unlock_read(map);
2058                         return (KERN_INVALID_ARGUMENT);
2059                 }
2060                 if (end > current->end &&
2061                     (current->next == &map->header ||
2062                         current->end != current->next->start)) {
2063                         vm_map_unlock_read(map);
2064                         return (KERN_INVALID_ADDRESS);
2065                 }
2066         }
2067
2068         if (invalidate)
2069                 pmap_remove(vm_map_pmap(map), start, end);
2070         /*
2071          * Make a second pass, cleaning/uncaching pages from the indicated
2072          * objects as we go.
2073          */
2074         for (current = entry; current->start < end; current = current->next) {
2075                 offset = current->offset + (start - current->start);
2076                 size = (end <= current->end ? end : current->end) - start;
2077                 if (current->eflags & MAP_ENTRY_IS_SUB_MAP) {
2078                         vm_map_t smap;
2079                         vm_map_entry_t tentry;
2080                         vm_size_t tsize;
2081
2082                         smap = current->object.sub_map;
2083                         vm_map_lock_read(smap);
2084                         (void) vm_map_lookup_entry(smap, offset, &tentry);
2085                         tsize = tentry->end - offset;
2086                         if (tsize < size)
2087                                 size = tsize;
2088                         object = tentry->object.vm_object;
2089                         offset = tentry->offset + (offset - tentry->start);
2090                         vm_map_unlock_read(smap);
2091                 } else {
2092                         object = current->object.vm_object;
2093                 }
2094                 /*
2095                  * Note that there is absolutely no sense in writing out
2096                  * anonymous objects, so we track down the vnode object
2097                  * to write out.
2098                  * We invalidate (remove) all pages from the address space
2099                  * anyway, for semantic correctness.
2100                  *
2101                  * note: certain anonymous maps, such as MAP_NOSYNC maps,
2102                  * may start out with a NULL object.
2103                  */
2104                 while (object && object->backing_object) {
2105                         object = object->backing_object;
2106                         offset += object->backing_object_offset;
2107                         if (object->size < OFF_TO_IDX(offset + size))
2108                                 size = IDX_TO_OFF(object->size) - offset;
2109                 }
2110                 if (object && (object->type == OBJT_VNODE) && 
2111                     (current->protection & VM_PROT_WRITE)) {
2112                         /*
2113                          * Flush pages if writing is allowed, invalidate them
2114                          * if invalidation requested.  Pages undergoing I/O
2115                          * will be ignored by vm_object_page_remove().
2116                          *
2117                          * We cannot lock the vnode and then wait for paging
2118                          * to complete without deadlocking against vm_fault.
2119                          * Instead we simply call vm_object_page_remove() and
2120                          * allow it to block internally on a page-by-page 
2121                          * basis when it encounters pages undergoing async 
2122                          * I/O.
2123                          */
2124                         int flags;
2125
2126                         vm_object_reference(object);
2127                         vn_lock(object->handle, LK_EXCLUSIVE | LK_RETRY, curthread);
2128                         flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
2129                         flags |= invalidate ? OBJPC_INVAL : 0;
2130                         vm_object_page_clean(object,
2131                             OFF_TO_IDX(offset),
2132                             OFF_TO_IDX(offset + size + PAGE_MASK),
2133                             flags);
2134                         if (invalidate) {
2135                                 /*vm_object_pip_wait(object, "objmcl");*/
2136                                 vm_object_page_remove(object,
2137                                     OFF_TO_IDX(offset),
2138                                     OFF_TO_IDX(offset + size + PAGE_MASK),
2139                                     FALSE);
2140                         }
2141                         VOP_UNLOCK(object->handle, 0, curthread);
2142                         vm_object_deallocate(object);
2143                 }
2144                 start += size;
2145         }
2146
2147         vm_map_unlock_read(map);
2148         return (KERN_SUCCESS);
2149 }
2150
2151 /*
2152  *      vm_map_entry_unwire:    [ internal use only ]
2153  *
2154  *      Make the region specified by this entry pageable.
2155  *
2156  *      The map in question should be locked.
2157  *      [This is the reason for this routine's existence.]
2158  */
2159 static void 
2160 vm_map_entry_unwire(vm_map_t map, vm_map_entry_t entry)
2161 {
2162         vm_fault_unwire(map, entry->start, entry->end);
2163         entry->wired_count = 0;
2164 }
2165
2166 /*
2167  *      vm_map_entry_delete:    [ internal use only ]
2168  *
2169  *      Deallocate the given entry from the target map.
2170  */
2171 static void
2172 vm_map_entry_delete(vm_map_t map, vm_map_entry_t entry)
2173 {
2174         vm_map_entry_unlink(map, entry);
2175         map->size -= entry->end - entry->start;
2176
2177         if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) {
2178                 vm_object_deallocate(entry->object.vm_object);
2179         }
2180
2181         vm_map_entry_dispose(map, entry);
2182 }
2183
2184 /*
2185  *      vm_map_delete:  [ internal use only ]
2186  *
2187  *      Deallocates the given address range from the target
2188  *      map.
2189  */
2190 int
2191 vm_map_delete(vm_map_t map, vm_offset_t start, vm_offset_t end)
2192 {
2193         vm_object_t object;
2194         vm_map_entry_t entry;
2195         vm_map_entry_t first_entry;
2196
2197         /*
2198          * Find the start of the region, and clip it
2199          */
2200         if (!vm_map_lookup_entry(map, start, &first_entry))
2201                 entry = first_entry->next;
2202         else {
2203                 entry = first_entry;
2204                 vm_map_clip_start(map, entry, start);
2205         }
2206
2207         /*
2208          * Save the free space hint
2209          */
2210         if (entry == &map->header) {
2211                 map->first_free = &map->header;
2212         } else if (map->first_free->start >= start) {
2213                 map->first_free = entry->prev;
2214         }
2215
2216         /*
2217          * Step through all entries in this region
2218          */
2219         while ((entry != &map->header) && (entry->start < end)) {
2220                 vm_map_entry_t next;
2221                 vm_offset_t s, e;
2222                 vm_pindex_t offidxstart, offidxend, count;
2223
2224                 vm_map_clip_end(map, entry, end);
2225
2226                 s = entry->start;
2227                 e = entry->end;
2228                 next = entry->next;
2229
2230                 offidxstart = OFF_TO_IDX(entry->offset);
2231                 count = OFF_TO_IDX(e - s);
2232                 object = entry->object.vm_object;
2233
2234                 /*
2235                  * Unwire before removing addresses from the pmap; otherwise,
2236                  * unwiring will put the entries back in the pmap.
2237                  */
2238                 if (entry->wired_count != 0) {
2239                         vm_map_entry_unwire(map, entry);
2240                 }
2241
2242                 offidxend = offidxstart + count;
2243
2244                 if ((object == kernel_object) || (object == kmem_object)) {
2245                         vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2246                 } else {
2247                         mtx_lock(&Giant);
2248                         pmap_remove(map->pmap, s, e);
2249                         if (object != NULL &&
2250                             object->ref_count != 1 &&
2251                             (object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING &&
2252                             (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2253                                 vm_object_collapse(object);
2254                                 vm_object_page_remove(object, offidxstart, offidxend, FALSE);
2255                                 if (object->type == OBJT_SWAP) {
2256                                         swap_pager_freespace(object, offidxstart, count);
2257                                 }
2258                                 if (offidxend >= object->size &&
2259                                     offidxstart < object->size) {
2260                                         object->size = offidxstart;
2261                                 }
2262                         }
2263                         mtx_unlock(&Giant);
2264                 }
2265
2266                 /*
2267                  * Delete the entry (which may delete the object) only after
2268                  * removing all pmap entries pointing to its pages.
2269                  * (Otherwise, its page frames may be reallocated, and any
2270                  * modify bits will be set in the wrong object!)
2271                  */
2272                 vm_map_entry_delete(map, entry);
2273                 entry = next;
2274         }
2275         return (KERN_SUCCESS);
2276 }
2277
2278 /*
2279  *      vm_map_remove:
2280  *
2281  *      Remove the given address range from the target map.
2282  *      This is the exported form of vm_map_delete.
2283  */
2284 int
2285 vm_map_remove(vm_map_t map, vm_offset_t start, vm_offset_t end)
2286 {
2287         int result, s = 0;
2288
2289         if (map == kmem_map)
2290                 s = splvm();
2291
2292         vm_map_lock(map);
2293         VM_MAP_RANGE_CHECK(map, start, end);
2294         result = vm_map_delete(map, start, end);
2295         vm_map_unlock(map);
2296
2297         if (map == kmem_map)
2298                 splx(s);
2299
2300         return (result);
2301 }
2302
2303 /*
2304  *      vm_map_check_protection:
2305  *
2306  *      Assert that the target map allows the specified
2307  *      privilege on the entire address region given.
2308  *      The entire region must be allocated.
2309  */
2310 boolean_t
2311 vm_map_check_protection(vm_map_t map, vm_offset_t start, vm_offset_t end,
2312                         vm_prot_t protection)
2313 {
2314         vm_map_entry_t entry;
2315         vm_map_entry_t tmp_entry;
2316
2317         vm_map_lock_read(map);
2318         if (!vm_map_lookup_entry(map, start, &tmp_entry)) {
2319                 vm_map_unlock_read(map);
2320                 return (FALSE);
2321         }
2322         entry = tmp_entry;
2323
2324         while (start < end) {
2325                 if (entry == &map->header) {
2326                         vm_map_unlock_read(map);
2327                         return (FALSE);
2328                 }
2329                 /*
2330                  * No holes allowed!
2331                  */
2332                 if (start < entry->start) {
2333                         vm_map_unlock_read(map);
2334                         return (FALSE);
2335                 }
2336                 /*
2337                  * Check protection associated with entry.
2338                  */
2339                 if ((entry->protection & protection) != protection) {
2340                         vm_map_unlock_read(map);
2341                         return (FALSE);
2342                 }
2343                 /* go to next entry */
2344                 start = entry->end;
2345                 entry = entry->next;
2346         }
2347         vm_map_unlock_read(map);
2348         return (TRUE);
2349 }
2350
2351 /*
2352  *      vm_map_copy_entry:
2353  *
2354  *      Copies the contents of the source entry to the destination
2355  *      entry.  The entries *must* be aligned properly.
2356  */
2357 static void
2358 vm_map_copy_entry(
2359         vm_map_t src_map,
2360         vm_map_t dst_map,
2361         vm_map_entry_t src_entry, 
2362         vm_map_entry_t dst_entry)
2363 {
2364         vm_object_t src_object;
2365
2366         if ((dst_entry->eflags|src_entry->eflags) & MAP_ENTRY_IS_SUB_MAP)
2367                 return;
2368
2369         if (src_entry->wired_count == 0) {
2370
2371                 /*
2372                  * If the source entry is marked needs_copy, it is already
2373                  * write-protected.
2374                  */
2375                 if ((src_entry->eflags & MAP_ENTRY_NEEDS_COPY) == 0) {
2376                         pmap_protect(src_map->pmap,
2377                             src_entry->start,
2378                             src_entry->end,
2379                             src_entry->protection & ~VM_PROT_WRITE);
2380                 }
2381
2382                 /*
2383                  * Make a copy of the object.
2384                  */
2385                 if ((src_object = src_entry->object.vm_object) != NULL) {
2386
2387                         if ((src_object->handle == NULL) &&
2388                                 (src_object->type == OBJT_DEFAULT ||
2389                                  src_object->type == OBJT_SWAP)) {
2390                                 vm_object_collapse(src_object);
2391                                 if ((src_object->flags & (OBJ_NOSPLIT|OBJ_ONEMAPPING)) == OBJ_ONEMAPPING) {
2392                                         vm_object_split(src_entry);
2393                                         src_object = src_entry->object.vm_object;
2394                                 }
2395                         }
2396
2397                         vm_object_reference(src_object);
2398                         vm_object_clear_flag(src_object, OBJ_ONEMAPPING);
2399                         dst_entry->object.vm_object = src_object;
2400                         src_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2401                         dst_entry->eflags |= (MAP_ENTRY_COW|MAP_ENTRY_NEEDS_COPY);
2402                         dst_entry->offset = src_entry->offset;
2403                 } else {
2404                         dst_entry->object.vm_object = NULL;
2405                         dst_entry->offset = 0;
2406                 }
2407
2408                 pmap_copy(dst_map->pmap, src_map->pmap, dst_entry->start,
2409                     dst_entry->end - dst_entry->start, src_entry->start);
2410         } else {
2411                 /*
2412                  * Of course, wired down pages can't be set copy-on-write.
2413                  * Cause wired pages to be copied into the new map by
2414                  * simulating faults (the new pages are pageable)
2415                  */
2416                 vm_fault_copy_entry(dst_map, src_map, dst_entry, src_entry);
2417         }
2418 }
2419
2420 /*
2421  * vmspace_fork:
2422  * Create a new process vmspace structure and vm_map
2423  * based on those of an existing process.  The new map
2424  * is based on the old map, according to the inheritance
2425  * values on the regions in that map.
2426  *
2427  * The source map must not be locked.
2428  */
2429 struct vmspace *
2430 vmspace_fork(struct vmspace *vm1)
2431 {
2432         struct vmspace *vm2;
2433         vm_map_t old_map = &vm1->vm_map;
2434         vm_map_t new_map;
2435         vm_map_entry_t old_entry;
2436         vm_map_entry_t new_entry;
2437         vm_object_t object;
2438
2439         GIANT_REQUIRED;
2440
2441         vm_map_lock(old_map);
2442         old_map->infork = 1;
2443
2444         vm2 = vmspace_alloc(old_map->min_offset, old_map->max_offset);
2445         bcopy(&vm1->vm_startcopy, &vm2->vm_startcopy,
2446             (caddr_t) &vm1->vm_endcopy - (caddr_t) &vm1->vm_startcopy);
2447         new_map = &vm2->vm_map; /* XXX */
2448         new_map->timestamp = 1;
2449
2450         old_entry = old_map->header.next;
2451
2452         while (old_entry != &old_map->header) {
2453                 if (old_entry->eflags & MAP_ENTRY_IS_SUB_MAP)
2454                         panic("vm_map_fork: encountered a submap");
2455
2456                 switch (old_entry->inheritance) {
2457                 case VM_INHERIT_NONE:
2458                         break;
2459
2460                 case VM_INHERIT_SHARE:
2461                         /*
2462                          * Clone the entry, creating the shared object if necessary.
2463                          */
2464                         object = old_entry->object.vm_object;
2465                         if (object == NULL) {
2466                                 object = vm_object_allocate(OBJT_DEFAULT,
2467                                         atop(old_entry->end - old_entry->start));
2468                                 old_entry->object.vm_object = object;
2469                                 old_entry->offset = (vm_offset_t) 0;
2470                         }
2471
2472                         /*
2473                          * Add the reference before calling vm_object_shadow
2474                          * to insure that a shadow object is created.
2475                          */
2476                         vm_object_reference(object);
2477                         if (old_entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2478                                 vm_object_shadow(&old_entry->object.vm_object,
2479                                         &old_entry->offset,
2480                                         atop(old_entry->end - old_entry->start));
2481                                 old_entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2482                                 /* Transfer the second reference too. */
2483                                 vm_object_reference(
2484                                     old_entry->object.vm_object);
2485                                 vm_object_deallocate(object);
2486                                 object = old_entry->object.vm_object;
2487                         }
2488                         vm_object_clear_flag(object, OBJ_ONEMAPPING);
2489
2490                         /*
2491                          * Clone the entry, referencing the shared object.
2492                          */
2493                         new_entry = vm_map_entry_create(new_map);
2494                         *new_entry = *old_entry;
2495                         new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2496                         new_entry->wired_count = 0;
2497
2498                         /*
2499                          * Insert the entry into the new map -- we know we're
2500                          * inserting at the end of the new map.
2501                          */
2502                         vm_map_entry_link(new_map, new_map->header.prev,
2503                             new_entry);
2504
2505                         /*
2506                          * Update the physical map
2507                          */
2508                         pmap_copy(new_map->pmap, old_map->pmap,
2509                             new_entry->start,
2510                             (old_entry->end - old_entry->start),
2511                             old_entry->start);
2512                         break;
2513
2514                 case VM_INHERIT_COPY:
2515                         /*
2516                          * Clone the entry and link into the map.
2517                          */
2518                         new_entry = vm_map_entry_create(new_map);
2519                         *new_entry = *old_entry;
2520                         new_entry->eflags &= ~MAP_ENTRY_USER_WIRED;
2521                         new_entry->wired_count = 0;
2522                         new_entry->object.vm_object = NULL;
2523                         vm_map_entry_link(new_map, new_map->header.prev,
2524                             new_entry);
2525                         vm_map_copy_entry(old_map, new_map, old_entry,
2526                             new_entry);
2527                         break;
2528                 }
2529                 old_entry = old_entry->next;
2530         }
2531
2532         new_map->size = old_map->size;
2533         old_map->infork = 0;
2534         vm_map_unlock(old_map);
2535
2536         return (vm2);
2537 }
2538
2539 int
2540 vm_map_stack (vm_map_t map, vm_offset_t addrbos, vm_size_t max_ssize,
2541               vm_prot_t prot, vm_prot_t max, int cow)
2542 {
2543         vm_map_entry_t prev_entry;
2544         vm_map_entry_t new_stack_entry;
2545         vm_size_t      init_ssize;
2546         int            rv;
2547
2548         GIANT_REQUIRED;
2549
2550         if (VM_MIN_ADDRESS > 0 && addrbos < VM_MIN_ADDRESS)
2551                 return (KERN_NO_SPACE);
2552
2553         if (max_ssize < sgrowsiz)
2554                 init_ssize = max_ssize;
2555         else
2556                 init_ssize = sgrowsiz;
2557
2558         vm_map_lock(map);
2559
2560         /* If addr is already mapped, no go */
2561         if (vm_map_lookup_entry(map, addrbos, &prev_entry)) {
2562                 vm_map_unlock(map);
2563                 return (KERN_NO_SPACE);
2564         }
2565
2566         /* If we can't accomodate max_ssize in the current mapping,
2567          * no go.  However, we need to be aware that subsequent user
2568          * mappings might map into the space we have reserved for
2569          * stack, and currently this space is not protected.  
2570          * 
2571          * Hopefully we will at least detect this condition 
2572          * when we try to grow the stack.
2573          */
2574         if ((prev_entry->next != &map->header) &&
2575             (prev_entry->next->start < addrbos + max_ssize)) {
2576                 vm_map_unlock(map);
2577                 return (KERN_NO_SPACE);
2578         }
2579
2580         /* We initially map a stack of only init_ssize.  We will
2581          * grow as needed later.  Since this is to be a grow 
2582          * down stack, we map at the top of the range.
2583          *
2584          * Note: we would normally expect prot and max to be
2585          * VM_PROT_ALL, and cow to be 0.  Possibly we should
2586          * eliminate these as input parameters, and just
2587          * pass these values here in the insert call.
2588          */
2589         rv = vm_map_insert(map, NULL, 0, addrbos + max_ssize - init_ssize,
2590                            addrbos + max_ssize, prot, max, cow);
2591
2592         /* Now set the avail_ssize amount */
2593         if (rv == KERN_SUCCESS){
2594                 if (prev_entry != &map->header)
2595                         vm_map_clip_end(map, prev_entry, addrbos + max_ssize - init_ssize);
2596                 new_stack_entry = prev_entry->next;
2597                 if (new_stack_entry->end   != addrbos + max_ssize ||
2598                     new_stack_entry->start != addrbos + max_ssize - init_ssize)
2599                         panic ("Bad entry start/end for new stack entry");
2600                 else 
2601                         new_stack_entry->avail_ssize = max_ssize - init_ssize;
2602         }
2603
2604         vm_map_unlock(map);
2605         return (rv);
2606 }
2607
2608 /* Attempts to grow a vm stack entry.  Returns KERN_SUCCESS if the
2609  * desired address is already mapped, or if we successfully grow
2610  * the stack.  Also returns KERN_SUCCESS if addr is outside the
2611  * stack range (this is strange, but preserves compatibility with
2612  * the grow function in vm_machdep.c).
2613  */
2614 int
2615 vm_map_growstack (struct proc *p, vm_offset_t addr)
2616 {
2617         vm_map_entry_t prev_entry;
2618         vm_map_entry_t stack_entry;
2619         vm_map_entry_t new_stack_entry;
2620         struct vmspace *vm = p->p_vmspace;
2621         vm_map_t map = &vm->vm_map;
2622         vm_offset_t    end;
2623         int      grow_amount;
2624         int      rv;
2625         int      is_procstack;
2626
2627         GIANT_REQUIRED;
2628         
2629 Retry:
2630         vm_map_lock_read(map);
2631
2632         /* If addr is already in the entry range, no need to grow.*/
2633         if (vm_map_lookup_entry(map, addr, &prev_entry)) {
2634                 vm_map_unlock_read(map);
2635                 return (KERN_SUCCESS);
2636         }
2637
2638         if ((stack_entry = prev_entry->next) == &map->header) {
2639                 vm_map_unlock_read(map);
2640                 return (KERN_SUCCESS);
2641         } 
2642         if (prev_entry == &map->header) 
2643                 end = stack_entry->start - stack_entry->avail_ssize;
2644         else
2645                 end = prev_entry->end;
2646
2647         /* This next test mimics the old grow function in vm_machdep.c.
2648          * It really doesn't quite make sense, but we do it anyway
2649          * for compatibility.
2650          *
2651          * If not growable stack, return success.  This signals the
2652          * caller to proceed as he would normally with normal vm.
2653          */
2654         if (stack_entry->avail_ssize < 1 ||
2655             addr >= stack_entry->start ||
2656             addr <  stack_entry->start - stack_entry->avail_ssize) {
2657                 vm_map_unlock_read(map);
2658                 return (KERN_SUCCESS);
2659         } 
2660         
2661         /* Find the minimum grow amount */
2662         grow_amount = roundup (stack_entry->start - addr, PAGE_SIZE);
2663         if (grow_amount > stack_entry->avail_ssize) {
2664                 vm_map_unlock_read(map);
2665                 return (KERN_NO_SPACE);
2666         }
2667
2668         /* If there is no longer enough space between the entries
2669          * nogo, and adjust the available space.  Note: this 
2670          * should only happen if the user has mapped into the
2671          * stack area after the stack was created, and is
2672          * probably an error.
2673          *
2674          * This also effectively destroys any guard page the user
2675          * might have intended by limiting the stack size.
2676          */
2677         if (grow_amount > stack_entry->start - end) {
2678                 if (vm_map_lock_upgrade(map))
2679                         goto Retry;
2680
2681                 stack_entry->avail_ssize = stack_entry->start - end;
2682
2683                 vm_map_unlock(map);
2684                 return (KERN_NO_SPACE);
2685         }
2686
2687         is_procstack = addr >= (vm_offset_t)vm->vm_maxsaddr;
2688
2689         /* If this is the main process stack, see if we're over the 
2690          * stack limit.
2691          */
2692         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2693                              p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2694                 vm_map_unlock_read(map);
2695                 return (KERN_NO_SPACE);
2696         }
2697
2698         /* Round up the grow amount modulo SGROWSIZ */
2699         grow_amount = roundup (grow_amount, sgrowsiz);
2700         if (grow_amount > stack_entry->avail_ssize) {
2701                 grow_amount = stack_entry->avail_ssize;
2702         }
2703         if (is_procstack && (ctob(vm->vm_ssize) + grow_amount >
2704                              p->p_rlimit[RLIMIT_STACK].rlim_cur)) {
2705                 grow_amount = p->p_rlimit[RLIMIT_STACK].rlim_cur -
2706                               ctob(vm->vm_ssize);
2707         }
2708
2709         if (vm_map_lock_upgrade(map))
2710                 goto Retry;
2711
2712         /* Get the preliminary new entry start value */
2713         addr = stack_entry->start - grow_amount;
2714
2715         /* If this puts us into the previous entry, cut back our growth
2716          * to the available space.  Also, see the note above.
2717          */
2718         if (addr < end) {
2719                 stack_entry->avail_ssize = stack_entry->start - end;
2720                 addr = end;
2721         }
2722
2723         rv = vm_map_insert(map, NULL, 0, addr, stack_entry->start,
2724                            VM_PROT_ALL,
2725                            VM_PROT_ALL,
2726                            0);
2727
2728         /* Adjust the available stack space by the amount we grew. */
2729         if (rv == KERN_SUCCESS) {
2730                 if (prev_entry != &map->header)
2731                         vm_map_clip_end(map, prev_entry, addr);
2732                 new_stack_entry = prev_entry->next;
2733                 if (new_stack_entry->end   != stack_entry->start  ||
2734                     new_stack_entry->start != addr)
2735                         panic ("Bad stack grow start/end in new stack entry");
2736                 else {
2737                         new_stack_entry->avail_ssize = stack_entry->avail_ssize -
2738                                                         (new_stack_entry->end -
2739                                                          new_stack_entry->start);
2740                         if (is_procstack)
2741                                 vm->vm_ssize += btoc(new_stack_entry->end -
2742                                                      new_stack_entry->start);
2743                 }
2744         }
2745
2746         vm_map_unlock(map);
2747         return (rv);
2748 }
2749
2750 /*
2751  * Unshare the specified VM space for exec.  If other processes are
2752  * mapped to it, then create a new one.  The new vmspace is null.
2753  */
2754 void
2755 vmspace_exec(struct proc *p) 
2756 {
2757         struct vmspace *oldvmspace = p->p_vmspace;
2758         struct vmspace *newvmspace;
2759         vm_map_t map = &p->p_vmspace->vm_map;
2760
2761         GIANT_REQUIRED;
2762         newvmspace = vmspace_alloc(map->min_offset, map->max_offset);
2763         bcopy(&oldvmspace->vm_startcopy, &newvmspace->vm_startcopy,
2764             (caddr_t) (newvmspace + 1) - (caddr_t) &newvmspace->vm_startcopy);
2765         /*
2766          * This code is written like this for prototype purposes.  The
2767          * goal is to avoid running down the vmspace here, but let the
2768          * other process's that are still using the vmspace to finally
2769          * run it down.  Even though there is little or no chance of blocking
2770          * here, it is a good idea to keep this form for future mods.
2771          */
2772         p->p_vmspace = newvmspace;
2773         pmap_pinit2(vmspace_pmap(newvmspace));
2774         vmspace_free(oldvmspace);
2775         if (p == curthread->td_proc)            /* XXXKSE ? */
2776                 pmap_activate(curthread);
2777 }
2778
2779 /*
2780  * Unshare the specified VM space for forcing COW.  This
2781  * is called by rfork, for the (RFMEM|RFPROC) == 0 case.
2782  */
2783 void
2784 vmspace_unshare(struct proc *p)
2785 {
2786         struct vmspace *oldvmspace = p->p_vmspace;
2787         struct vmspace *newvmspace;
2788
2789         GIANT_REQUIRED;
2790         if (oldvmspace->vm_refcnt == 1)
2791                 return;
2792         newvmspace = vmspace_fork(oldvmspace);
2793         p->p_vmspace = newvmspace;
2794         pmap_pinit2(vmspace_pmap(newvmspace));
2795         vmspace_free(oldvmspace);
2796         if (p == curthread->td_proc)            /* XXXKSE ? */
2797                 pmap_activate(curthread);
2798 }
2799
2800 /*
2801  *      vm_map_lookup:
2802  *
2803  *      Finds the VM object, offset, and
2804  *      protection for a given virtual address in the
2805  *      specified map, assuming a page fault of the
2806  *      type specified.
2807  *
2808  *      Leaves the map in question locked for read; return
2809  *      values are guaranteed until a vm_map_lookup_done
2810  *      call is performed.  Note that the map argument
2811  *      is in/out; the returned map must be used in
2812  *      the call to vm_map_lookup_done.
2813  *
2814  *      A handle (out_entry) is returned for use in
2815  *      vm_map_lookup_done, to make that fast.
2816  *
2817  *      If a lookup is requested with "write protection"
2818  *      specified, the map may be changed to perform virtual
2819  *      copying operations, although the data referenced will
2820  *      remain the same.
2821  */
2822 int
2823 vm_map_lookup(vm_map_t *var_map,                /* IN/OUT */
2824               vm_offset_t vaddr,
2825               vm_prot_t fault_typea,
2826               vm_map_entry_t *out_entry,        /* OUT */
2827               vm_object_t *object,              /* OUT */
2828               vm_pindex_t *pindex,              /* OUT */
2829               vm_prot_t *out_prot,              /* OUT */
2830               boolean_t *wired)                 /* OUT */
2831 {
2832         vm_map_entry_t entry;
2833         vm_map_t map = *var_map;
2834         vm_prot_t prot;
2835         vm_prot_t fault_type = fault_typea;
2836
2837 RetryLookup:;
2838         /*
2839          * Lookup the faulting address.
2840          */
2841
2842         vm_map_lock_read(map);
2843 #define RETURN(why) \
2844                 { \
2845                 vm_map_unlock_read(map); \
2846                 return (why); \
2847                 }
2848
2849         /*
2850          * If the map has an interesting hint, try it before calling full
2851          * blown lookup routine.
2852          */
2853         entry = map->root;
2854         *out_entry = entry;
2855         if (entry == NULL ||
2856             (vaddr < entry->start) || (vaddr >= entry->end)) {
2857                 /*
2858                  * Entry was either not a valid hint, or the vaddr was not
2859                  * contained in the entry, so do a full lookup.
2860                  */
2861                 if (!vm_map_lookup_entry(map, vaddr, out_entry))
2862                         RETURN(KERN_INVALID_ADDRESS);
2863
2864                 entry = *out_entry;
2865         }
2866         
2867         /*
2868          * Handle submaps.
2869          */
2870         if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
2871                 vm_map_t old_map = map;
2872
2873                 *var_map = map = entry->object.sub_map;
2874                 vm_map_unlock_read(old_map);
2875                 goto RetryLookup;
2876         }
2877
2878         /*
2879          * Check whether this task is allowed to have this page.
2880          * Note the special case for MAP_ENTRY_COW
2881          * pages with an override.  This is to implement a forced
2882          * COW for debuggers.
2883          */
2884         if (fault_type & VM_PROT_OVERRIDE_WRITE)
2885                 prot = entry->max_protection;
2886         else
2887                 prot = entry->protection;
2888         fault_type &= (VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE);
2889         if ((fault_type & prot) != fault_type) {
2890                         RETURN(KERN_PROTECTION_FAILURE);
2891         }
2892         if ((entry->eflags & MAP_ENTRY_USER_WIRED) &&
2893             (entry->eflags & MAP_ENTRY_COW) &&
2894             (fault_type & VM_PROT_WRITE) &&
2895             (fault_typea & VM_PROT_OVERRIDE_WRITE) == 0) {
2896                 RETURN(KERN_PROTECTION_FAILURE);
2897         }
2898
2899         /*
2900          * If this page is not pageable, we have to get it for all possible
2901          * accesses.
2902          */
2903         *wired = (entry->wired_count != 0);
2904         if (*wired)
2905                 prot = fault_type = entry->protection;
2906
2907         /*
2908          * If the entry was copy-on-write, we either ...
2909          */
2910         if (entry->eflags & MAP_ENTRY_NEEDS_COPY) {
2911                 /*
2912                  * If we want to write the page, we may as well handle that
2913                  * now since we've got the map locked.
2914                  *
2915                  * If we don't need to write the page, we just demote the
2916                  * permissions allowed.
2917                  */
2918                 if (fault_type & VM_PROT_WRITE) {
2919                         /*
2920                          * Make a new object, and place it in the object
2921                          * chain.  Note that no new references have appeared
2922                          * -- one just moved from the map to the new
2923                          * object.
2924                          */
2925                         if (vm_map_lock_upgrade(map))
2926                                 goto RetryLookup;
2927
2928                         vm_object_shadow(
2929                             &entry->object.vm_object,
2930                             &entry->offset,
2931                             atop(entry->end - entry->start));
2932                         entry->eflags &= ~MAP_ENTRY_NEEDS_COPY;
2933
2934                         vm_map_lock_downgrade(map);
2935                 } else {
2936                         /*
2937                          * We're attempting to read a copy-on-write page --
2938                          * don't allow writes.
2939                          */
2940                         prot &= ~VM_PROT_WRITE;
2941                 }
2942         }
2943
2944         /*
2945          * Create an object if necessary.
2946          */
2947         if (entry->object.vm_object == NULL &&
2948             !map->system_map) {
2949                 if (vm_map_lock_upgrade(map)) 
2950                         goto RetryLookup;
2951                 entry->object.vm_object = vm_object_allocate(OBJT_DEFAULT,
2952                     atop(entry->end - entry->start));
2953                 entry->offset = 0;
2954                 vm_map_lock_downgrade(map);
2955         }
2956
2957         /*
2958          * Return the object/offset from this entry.  If the entry was
2959          * copy-on-write or empty, it has been fixed up.
2960          */
2961         *pindex = OFF_TO_IDX((vaddr - entry->start) + entry->offset);
2962         *object = entry->object.vm_object;
2963
2964         /*
2965          * Return whether this is the only map sharing this data.
2966          */
2967         *out_prot = prot;
2968         return (KERN_SUCCESS);
2969
2970 #undef  RETURN
2971 }
2972
2973 /*
2974  *      vm_map_lookup_done:
2975  *
2976  *      Releases locks acquired by a vm_map_lookup
2977  *      (according to the handle returned by that lookup).
2978  */
2979 void
2980 vm_map_lookup_done(vm_map_t map, vm_map_entry_t entry)
2981 {
2982         /*
2983          * Unlock the main-level map
2984          */
2985         vm_map_unlock_read(map);
2986 }
2987
2988 #ifdef ENABLE_VFS_IOOPT
2989 /*
2990  * Experimental support for zero-copy I/O
2991  *
2992  * Implement uiomove with VM operations.  This handles (and collateral changes)
2993  * support every combination of source object modification, and COW type
2994  * operations.
2995  */
2996 int
2997 vm_uiomove(
2998         vm_map_t mapa,
2999         vm_object_t srcobject,
3000         off_t cp,
3001         int cnta,
3002         vm_offset_t uaddra,
3003         int *npages)
3004 {
3005         vm_map_t map;
3006         vm_object_t first_object, oldobject, object;
3007         vm_map_entry_t entry;
3008         vm_prot_t prot;
3009         boolean_t wired;
3010         int tcnt, rv;
3011         vm_offset_t uaddr, start, end, tend;
3012         vm_pindex_t first_pindex, osize, oindex;
3013         off_t ooffset;
3014         int cnt;
3015
3016         GIANT_REQUIRED;
3017
3018         if (npages)
3019                 *npages = 0;
3020
3021         cnt = cnta;
3022         uaddr = uaddra;
3023
3024         while (cnt > 0) {
3025                 map = mapa;
3026
3027                 if ((vm_map_lookup(&map, uaddr,
3028                         VM_PROT_READ, &entry, &first_object,
3029                         &first_pindex, &prot, &wired)) != KERN_SUCCESS) {
3030                         return EFAULT;
3031                 }
3032
3033                 vm_map_clip_start(map, entry, uaddr);
3034
3035                 tcnt = cnt;
3036                 tend = uaddr + tcnt;
3037                 if (tend > entry->end) {
3038                         tcnt = entry->end - uaddr;
3039                         tend = entry->end;
3040                 }
3041
3042                 vm_map_clip_end(map, entry, tend);
3043
3044                 start = entry->start;
3045                 end = entry->end;
3046
3047                 osize = atop(tcnt);
3048
3049                 oindex = OFF_TO_IDX(cp);
3050                 if (npages) {
3051                         vm_pindex_t idx;
3052                         for (idx = 0; idx < osize; idx++) {
3053                                 vm_page_t m;
3054                                 if ((m = vm_page_lookup(srcobject, oindex + idx)) == NULL) {
3055                                         vm_map_lookup_done(map, entry);
3056                                         return 0;
3057                                 }
3058                                 /*
3059                                  * disallow busy or invalid pages, but allow
3060                                  * m->busy pages if they are entirely valid.
3061                                  */
3062                                 if ((m->flags & PG_BUSY) ||
3063                                         ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL)) {
3064                                         vm_map_lookup_done(map, entry);
3065                                         return 0;
3066                                 }
3067                         }
3068                 }
3069
3070 /*
3071  * If we are changing an existing map entry, just redirect
3072  * the object, and change mappings.
3073  */
3074                 if ((first_object->type == OBJT_VNODE) &&
3075                         ((oldobject = entry->object.vm_object) == first_object)) {
3076
3077                         if ((entry->offset != cp) || (oldobject != srcobject)) {
3078                                 /*
3079                                 * Remove old window into the file
3080                                 */
3081                                 pmap_remove (map->pmap, uaddr, tend);
3082
3083                                 /*
3084                                 * Force copy on write for mmaped regions
3085                                 */
3086                                 vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
3087
3088                                 /*
3089                                 * Point the object appropriately
3090                                 */
3091                                 if (oldobject != srcobject) {
3092
3093                                 /*
3094                                 * Set the object optimization hint flag
3095                                 */
3096                                         vm_object_set_flag(srcobject, OBJ_OPT);
3097                                         vm_object_reference(srcobject);
3098                                         entry->object.vm_object = srcobject;
3099
3100                                         if (oldobject) {
3101                                                 vm_object_deallocate(oldobject);
3102                                         }
3103                                 }
3104
3105                                 entry->offset = cp;
3106                                 map->timestamp++;
3107                         } else {
3108                                 pmap_remove (map->pmap, uaddr, tend);
3109                         }
3110
3111                 } else if ((first_object->ref_count == 1) &&
3112                         (first_object->size == osize) &&
3113                         ((first_object->type == OBJT_DEFAULT) ||
3114                                 (first_object->type == OBJT_SWAP)) ) {
3115
3116                         oldobject = first_object->backing_object;
3117
3118                         if ((first_object->backing_object_offset != cp) ||
3119                                 (oldobject != srcobject)) {
3120                                 /*
3121                                 * Remove old window into the file
3122                                 */
3123                                 pmap_remove (map->pmap, uaddr, tend);
3124
3125                                 /*
3126                                  * Remove unneeded old pages
3127                                  */
3128                                 vm_object_page_remove(first_object, 0, 0, 0);
3129
3130                                 /*
3131                                  * Invalidate swap space
3132                                  */
3133                                 if (first_object->type == OBJT_SWAP) {
3134                                         swap_pager_freespace(first_object,
3135                                                 0,
3136                                                 first_object->size);
3137                                 }
3138
3139                                 /*
3140                                  * Force copy on write for mmaped regions
3141                                  */
3142                                 vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
3143
3144                                 /*
3145                                  * Point the object appropriately
3146                                  */
3147                                 if (oldobject != srcobject) {
3148                                         /*
3149                                          * Set the object optimization hint flag
3150                                          */
3151                                         vm_object_set_flag(srcobject, OBJ_OPT);
3152                                         vm_object_reference(srcobject);
3153
3154                                         if (oldobject) {
3155                                                 TAILQ_REMOVE(&oldobject->shadow_head,
3156                                                         first_object, shadow_list);
3157                                                 oldobject->shadow_count--;
3158                                                 /* XXX bump generation? */
3159                                                 vm_object_deallocate(oldobject);
3160                                         }
3161
3162                                         TAILQ_INSERT_TAIL(&srcobject->shadow_head,
3163                                                 first_object, shadow_list);
3164                                         srcobject->shadow_count++;
3165                                         /* XXX bump generation? */
3166
3167                                         first_object->backing_object = srcobject;
3168                                 }
3169                                 first_object->backing_object_offset = cp;
3170                                 map->timestamp++;
3171                         } else {
3172                                 pmap_remove (map->pmap, uaddr, tend);
3173                         }
3174 /*
3175  * Otherwise, we have to do a logical mmap.
3176  */
3177                 } else {
3178
3179                         vm_object_set_flag(srcobject, OBJ_OPT);
3180                         vm_object_reference(srcobject);
3181
3182                         pmap_remove (map->pmap, uaddr, tend);
3183
3184                         vm_object_pmap_copy_1 (srcobject, oindex, oindex + osize);
3185                         vm_map_lock_upgrade(map);
3186
3187                         if (entry == &map->header) {
3188                                 map->first_free = &map->header;
3189                         } else if (map->first_free->start >= start) {
3190                                 map->first_free = entry->prev;
3191                         }
3192
3193                         vm_map_entry_delete(map, entry);
3194
3195                         object = srcobject;
3196                         ooffset = cp;
3197
3198                         rv = vm_map_insert(map, object, ooffset, start, tend,
3199                                 VM_PROT_ALL, VM_PROT_ALL, MAP_COPY_ON_WRITE);
3200
3201                         if (rv != KERN_SUCCESS)
3202                                 panic("vm_uiomove: could not insert new entry: %d", rv);
3203                 }
3204
3205 /*
3206  * Map the window directly, if it is already in memory
3207  */
3208                 pmap_object_init_pt(map->pmap, uaddr,
3209                         srcobject, oindex, tcnt, 0);
3210
3211                 map->timestamp++;
3212                 vm_map_unlock(map);
3213
3214                 cnt -= tcnt;
3215                 uaddr += tcnt;
3216                 cp += tcnt;
3217                 if (npages)
3218                         *npages += osize;
3219         }
3220         return 0;
3221 }
3222 #endif
3223
3224 #include "opt_ddb.h"
3225 #ifdef DDB
3226 #include <sys/kernel.h>
3227
3228 #include <ddb/ddb.h>
3229
3230 /*
3231  *      vm_map_print:   [ debug ]
3232  */
3233 DB_SHOW_COMMAND(map, vm_map_print)
3234 {
3235         static int nlines;
3236         /* XXX convert args. */
3237         vm_map_t map = (vm_map_t)addr;
3238         boolean_t full = have_addr;
3239
3240         vm_map_entry_t entry;
3241
3242         db_iprintf("Task map %p: pmap=%p, nentries=%d, version=%u\n",
3243             (void *)map,
3244             (void *)map->pmap, map->nentries, map->timestamp);
3245         nlines++;
3246
3247         if (!full && db_indent)
3248                 return;
3249
3250         db_indent += 2;
3251         for (entry = map->header.next; entry != &map->header;
3252             entry = entry->next) {
3253                 db_iprintf("map entry %p: start=%p, end=%p\n",
3254                     (void *)entry, (void *)entry->start, (void *)entry->end);
3255                 nlines++;
3256                 {
3257                         static char *inheritance_name[4] =
3258                         {"share", "copy", "none", "donate_copy"};
3259
3260                         db_iprintf(" prot=%x/%x/%s",
3261                             entry->protection,
3262                             entry->max_protection,
3263                             inheritance_name[(int)(unsigned char)entry->inheritance]);
3264                         if (entry->wired_count != 0)
3265                                 db_printf(", wired");
3266                 }
3267                 if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
3268                         /* XXX no %qd in kernel.  Truncate entry->offset. */
3269                         db_printf(", share=%p, offset=0x%lx\n",
3270                             (void *)entry->object.sub_map,
3271                             (long)entry->offset);
3272                         nlines++;
3273                         if ((entry->prev == &map->header) ||
3274                             (entry->prev->object.sub_map !=
3275                                 entry->object.sub_map)) {
3276                                 db_indent += 2;
3277                                 vm_map_print((db_expr_t)(intptr_t)
3278                                              entry->object.sub_map,
3279                                              full, 0, (char *)0);
3280                                 db_indent -= 2;
3281                         }
3282                 } else {
3283                         /* XXX no %qd in kernel.  Truncate entry->offset. */
3284                         db_printf(", object=%p, offset=0x%lx",
3285                             (void *)entry->object.vm_object,
3286                             (long)entry->offset);
3287                         if (entry->eflags & MAP_ENTRY_COW)
3288                                 db_printf(", copy (%s)",
3289                                     (entry->eflags & MAP_ENTRY_NEEDS_COPY) ? "needed" : "done");
3290                         db_printf("\n");
3291                         nlines++;
3292
3293                         if ((entry->prev == &map->header) ||
3294                             (entry->prev->object.vm_object !=
3295                                 entry->object.vm_object)) {
3296                                 db_indent += 2;
3297                                 vm_object_print((db_expr_t)(intptr_t)
3298                                                 entry->object.vm_object,
3299                                                 full, 0, (char *)0);
3300                                 nlines += 4;
3301                                 db_indent -= 2;
3302                         }
3303                 }
3304         }
3305         db_indent -= 2;
3306         if (db_indent == 0)
3307                 nlines = 0;
3308 }
3309
3310
3311 DB_SHOW_COMMAND(procvm, procvm)
3312 {
3313         struct proc *p;
3314
3315         if (have_addr) {
3316                 p = (struct proc *) addr;
3317         } else {
3318                 p = curproc;
3319         }
3320
3321         db_printf("p = %p, vmspace = %p, map = %p, pmap = %p\n",
3322             (void *)p, (void *)p->p_vmspace, (void *)&p->p_vmspace->vm_map,
3323             (void *)vmspace_pmap(p->p_vmspace));
3324
3325         vm_map_print((db_expr_t)(intptr_t)&p->p_vmspace->vm_map, 1, 0, NULL);
3326 }
3327
3328 #endif /* DDB */