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