hammer2 - Merge Mihai Carabas's VKERNEL/VMM GSOC project into the main tree
[dragonfly.git] / sys / vm / vm_object.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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)vm_object.c   8.5 (Berkeley) 3/22/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
39  *
40  * Permission to use, copy, modify and distribute this software and
41  * its documentation is hereby granted, provided that both the copyright
42  * notice and this permission notice appear in all copies of the
43  * software, derivative works or modified versions, and any portions
44  * thereof, and that both notices appear in supporting documentation.
45  *
46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
49  *
50  * Carnegie Mellon requests users of this software to return to
51  *
52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
53  *  School of Computer Science
54  *  Carnegie Mellon University
55  *  Pittsburgh PA 15213-3890
56  *
57  * any improvements or extensions that they make and grant Carnegie the
58  * rights to redistribute these changes.
59  *
60  * $FreeBSD: src/sys/vm/vm_object.c,v 1.171.2.8 2003/05/26 19:17:56 alc Exp $
61  */
62
63 /*
64  *      Virtual memory object module.
65  */
66
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/proc.h>           /* for curproc, pageproc */
70 #include <sys/thread.h>
71 #include <sys/vnode.h>
72 #include <sys/vmmeter.h>
73 #include <sys/mman.h>
74 #include <sys/mount.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/refcount.h>
78
79 #include <vm/vm.h>
80 #include <vm/vm_param.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_object.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_pageout.h>
86 #include <vm/vm_pager.h>
87 #include <vm/swap_pager.h>
88 #include <vm/vm_kern.h>
89 #include <vm/vm_extern.h>
90 #include <vm/vm_zone.h>
91
92 #include <vm/vm_page2.h>
93
94 #include <machine/specialreg.h>
95
96 #define EASY_SCAN_FACTOR        8
97
98 static void     vm_object_qcollapse(vm_object_t object,
99                                     vm_object_t backing_object);
100 static void     vm_object_page_collect_flush(vm_object_t object, vm_page_t p,
101                                              int pagerflags);
102 static void     vm_object_lock_init(vm_object_t);
103
104
105 /*
106  *      Virtual memory objects maintain the actual data
107  *      associated with allocated virtual memory.  A given
108  *      page of memory exists within exactly one object.
109  *
110  *      An object is only deallocated when all "references"
111  *      are given up.  Only one "reference" to a given
112  *      region of an object should be writeable.
113  *
114  *      Associated with each object is a list of all resident
115  *      memory pages belonging to that object; this list is
116  *      maintained by the "vm_page" module, and locked by the object's
117  *      lock.
118  *
119  *      Each object also records a "pager" routine which is
120  *      used to retrieve (and store) pages to the proper backing
121  *      storage.  In addition, objects may be backed by other
122  *      objects from which they were virtual-copied.
123  *
124  *      The only items within the object structure which are
125  *      modified after time of creation are:
126  *              reference count         locked by object's lock
127  *              pager routine           locked by object's lock
128  *
129  */
130
131 struct object_q vm_object_list;         /* locked by vmobj_token */
132 struct vm_object kernel_object;
133
134 static long vm_object_count;            /* locked by vmobj_token */
135
136 static long object_collapses;
137 static long object_bypasses;
138 static int next_index;
139 static vm_zone_t obj_zone;
140 static struct vm_zone obj_zone_store;
141 #define VM_OBJECTS_INIT 256
142 static struct vm_object vm_objects_init[VM_OBJECTS_INIT];
143
144 /*
145  * Misc low level routines
146  */
147 static void
148 vm_object_lock_init(vm_object_t obj)
149 {
150 #if defined(DEBUG_LOCKS)
151         int i;
152
153         obj->debug_hold_bitmap = 0;
154         obj->debug_hold_ovfl = 0;
155         for (i = 0; i < VMOBJ_DEBUG_ARRAY_SIZE; i++) {
156                 obj->debug_hold_thrs[i] = NULL;
157                 obj->debug_hold_file[i] = NULL;
158                 obj->debug_hold_line[i] = 0;
159         }
160 #endif
161 }
162
163 void
164 vm_object_lock_swap(void)
165 {
166         lwkt_token_swap();
167 }
168
169 void
170 vm_object_lock(vm_object_t obj)
171 {
172         lwkt_gettoken(&obj->token);
173 }
174
175 /*
176  * Returns TRUE on sucesss
177  */
178 static int
179 vm_object_lock_try(vm_object_t obj)
180 {
181         return(lwkt_trytoken(&obj->token));
182 }
183
184 void
185 vm_object_lock_shared(vm_object_t obj)
186 {
187         lwkt_gettoken_shared(&obj->token);
188 }
189
190 void
191 vm_object_unlock(vm_object_t obj)
192 {
193         lwkt_reltoken(&obj->token);
194 }
195
196 static __inline void
197 vm_object_assert_held(vm_object_t obj)
198 {
199         ASSERT_LWKT_TOKEN_HELD(&obj->token);
200 }
201
202 void
203 #ifndef DEBUG_LOCKS
204 vm_object_hold(vm_object_t obj)
205 #else
206 debugvm_object_hold(vm_object_t obj, char *file, int line)
207 #endif
208 {
209         KKASSERT(obj != NULL);
210
211         /*
212          * Object must be held (object allocation is stable due to callers
213          * context, typically already holding the token on a parent object)
214          * prior to potentially blocking on the lock, otherwise the object
215          * can get ripped away from us.
216          */
217         refcount_acquire(&obj->hold_count);
218         vm_object_lock(obj);
219
220 #if defined(DEBUG_LOCKS)
221         int i;
222         u_int mask;
223
224         for (;;) {
225                 mask = ~obj->debug_hold_bitmap;
226                 cpu_ccfence();
227                 if (mask == 0xFFFFFFFFU) {
228                         if (obj->debug_hold_ovfl == 0)
229                                 obj->debug_hold_ovfl = 1;
230                         break;
231                 }
232                 i = ffs(mask) - 1;
233                 if (atomic_cmpset_int(&obj->debug_hold_bitmap, ~mask,
234                                       ~mask | (1 << i))) {
235                         obj->debug_hold_bitmap |= (1 << i);
236                         obj->debug_hold_thrs[i] = curthread;
237                         obj->debug_hold_file[i] = file;
238                         obj->debug_hold_line[i] = line;
239                         break;
240                 }
241         }
242 #endif
243 }
244
245 int
246 #ifndef DEBUG_LOCKS
247 vm_object_hold_try(vm_object_t obj)
248 #else
249 debugvm_object_hold_try(vm_object_t obj, char *file, int line)
250 #endif
251 {
252         KKASSERT(obj != NULL);
253
254         /*
255          * Object must be held (object allocation is stable due to callers
256          * context, typically already holding the token on a parent object)
257          * prior to potentially blocking on the lock, otherwise the object
258          * can get ripped away from us.
259          */
260         refcount_acquire(&obj->hold_count);
261         if (vm_object_lock_try(obj) == 0) {
262                 if (refcount_release(&obj->hold_count)) {
263                         if (obj->ref_count == 0 && (obj->flags & OBJ_DEAD))
264                                 zfree(obj_zone, obj);
265                 }
266                 return(0);
267         }
268
269 #if defined(DEBUG_LOCKS)
270         int i;
271         u_int mask;
272
273         for (;;) {
274                 mask = ~obj->debug_hold_bitmap;
275                 cpu_ccfence();
276                 if (mask == 0xFFFFFFFFU) {
277                         if (obj->debug_hold_ovfl == 0)
278                                 obj->debug_hold_ovfl = 1;
279                         break;
280                 }
281                 i = ffs(mask) - 1;
282                 if (atomic_cmpset_int(&obj->debug_hold_bitmap, ~mask,
283                                       ~mask | (1 << i))) {
284                         obj->debug_hold_bitmap |= (1 << i);
285                         obj->debug_hold_thrs[i] = curthread;
286                         obj->debug_hold_file[i] = file;
287                         obj->debug_hold_line[i] = line;
288                         break;
289                 }
290         }
291 #endif
292         return(1);
293 }
294
295 void
296 #ifndef DEBUG_LOCKS
297 vm_object_hold_shared(vm_object_t obj)
298 #else
299 debugvm_object_hold_shared(vm_object_t obj, char *file, int line)
300 #endif
301 {
302         KKASSERT(obj != NULL);
303
304         /*
305          * Object must be held (object allocation is stable due to callers
306          * context, typically already holding the token on a parent object)
307          * prior to potentially blocking on the lock, otherwise the object
308          * can get ripped away from us.
309          */
310         refcount_acquire(&obj->hold_count);
311         vm_object_lock_shared(obj);
312
313 #if defined(DEBUG_LOCKS)
314         int i;
315         u_int mask;
316
317         for (;;) {
318                 mask = ~obj->debug_hold_bitmap;
319                 cpu_ccfence();
320                 if (mask == 0xFFFFFFFFU) {
321                         if (obj->debug_hold_ovfl == 0)
322                                 obj->debug_hold_ovfl = 1;
323                         break;
324                 }
325                 i = ffs(mask) - 1;
326                 if (atomic_cmpset_int(&obj->debug_hold_bitmap, ~mask,
327                                       ~mask | (1 << i))) {
328                         obj->debug_hold_bitmap |= (1 << i);
329                         obj->debug_hold_thrs[i] = curthread;
330                         obj->debug_hold_file[i] = file;
331                         obj->debug_hold_line[i] = line;
332                         break;
333                 }
334         }
335 #endif
336 }
337
338 /*
339  * Obtain either a shared or exclusive lock on VM object
340  * based on whether this is a terminal vnode object or not.
341  */
342 int
343 #ifndef DEBUG_LOCKS
344 vm_object_hold_maybe_shared(vm_object_t obj)
345 #else
346 debugvm_object_hold_maybe_shared(vm_object_t obj, char *file, int line)
347 #endif
348 {
349         if (vm_shared_fault &&
350             obj->type == OBJT_VNODE &&
351             obj->backing_object == NULL) {
352                 vm_object_hold_shared(obj);
353                 return(1);
354         } else {
355                 vm_object_hold(obj);
356                 return(0);
357         }
358 }
359
360 /*
361  * Drop the token and hold_count on the object.
362  */
363 void
364 vm_object_drop(vm_object_t obj)
365 {
366         if (obj == NULL)
367                 return;
368
369 #if defined(DEBUG_LOCKS)
370         int found = 0;
371         int i;
372
373         for (i = 0; i < VMOBJ_DEBUG_ARRAY_SIZE; i++) {
374                 if ((obj->debug_hold_bitmap & (1 << i)) &&
375                     (obj->debug_hold_thrs[i] == curthread)) {
376                         obj->debug_hold_bitmap &= ~(1 << i);
377                         obj->debug_hold_thrs[i] = NULL;
378                         obj->debug_hold_file[i] = NULL;
379                         obj->debug_hold_line[i] = 0;
380                         found = 1;
381                         break;
382                 }
383         }
384
385         if (found == 0 && obj->debug_hold_ovfl == 0)
386                 panic("vm_object: attempt to drop hold on non-self-held obj");
387 #endif
388
389         /*
390          * No new holders should be possible once we drop hold_count 1->0 as
391          * there is no longer any way to reference the object.
392          */
393         KKASSERT(obj->hold_count > 0);
394         if (refcount_release(&obj->hold_count)) {
395                 if (obj->ref_count == 0 && (obj->flags & OBJ_DEAD)) {
396                         vm_object_unlock(obj);
397                         zfree(obj_zone, obj);
398                 } else {
399                         vm_object_unlock(obj);
400                 }
401         } else {
402                 vm_object_unlock(obj);
403         }
404 }
405
406 /*
407  * Initialize a freshly allocated object, returning a held object.
408  *
409  * Used only by vm_object_allocate() and zinitna().
410  *
411  * No requirements.
412  */
413 void
414 _vm_object_allocate(objtype_t type, vm_pindex_t size, vm_object_t object)
415 {
416         int incr;
417
418         RB_INIT(&object->rb_memq);
419         LIST_INIT(&object->shadow_head);
420         lwkt_token_init(&object->token, "vmobj");
421
422         object->type = type;
423         object->size = size;
424         object->ref_count = 1;
425         object->memattr = VM_MEMATTR_DEFAULT;
426         object->hold_count = 0;
427         object->flags = 0;
428         if ((object->type == OBJT_DEFAULT) || (object->type == OBJT_SWAP))
429                 vm_object_set_flag(object, OBJ_ONEMAPPING);
430         object->paging_in_progress = 0;
431         object->resident_page_count = 0;
432         object->agg_pv_list_count = 0;
433         object->shadow_count = 0;
434         /* cpu localization twist */
435         object->pg_color = (int)(intptr_t)curthread;
436         if ( size > (PQ_L2_SIZE / 3 + PQ_PRIME1))
437                 incr = PQ_L2_SIZE / 3 + PQ_PRIME1;
438         else
439                 incr = size;
440         next_index = (next_index + incr) & PQ_L2_MASK;
441         object->handle = NULL;
442         object->backing_object = NULL;
443         object->backing_object_offset = (vm_ooffset_t)0;
444
445         object->generation++;
446         object->swblock_count = 0;
447         RB_INIT(&object->swblock_root);
448         vm_object_lock_init(object);
449         pmap_object_init(object);
450
451         vm_object_hold(object);
452         lwkt_gettoken(&vmobj_token);
453         TAILQ_INSERT_TAIL(&vm_object_list, object, object_list);
454         vm_object_count++;
455         lwkt_reltoken(&vmobj_token);
456 }
457
458 /*
459  * Initialize the VM objects module.
460  *
461  * Called from the low level boot code only.
462  */
463 void
464 vm_object_init(void)
465 {
466         TAILQ_INIT(&vm_object_list);
467         
468         _vm_object_allocate(OBJT_DEFAULT, OFF_TO_IDX(KvaEnd),
469                             &kernel_object);
470         vm_object_drop(&kernel_object);
471
472         obj_zone = &obj_zone_store;
473         zbootinit(obj_zone, "VM OBJECT", sizeof (struct vm_object),
474                 vm_objects_init, VM_OBJECTS_INIT);
475 }
476
477 void
478 vm_object_init2(void)
479 {
480         zinitna(obj_zone, NULL, NULL, 0, 0, ZONE_PANICFAIL, 1);
481 }
482
483 /*
484  * Allocate and return a new object of the specified type and size.
485  *
486  * No requirements.
487  */
488 vm_object_t
489 vm_object_allocate(objtype_t type, vm_pindex_t size)
490 {
491         vm_object_t result;
492
493         result = (vm_object_t) zalloc(obj_zone);
494
495         _vm_object_allocate(type, size, result);
496         vm_object_drop(result);
497
498         return (result);
499 }
500
501 /*
502  * This version returns a held object, allowing further atomic initialization
503  * of the object.
504  */
505 vm_object_t
506 vm_object_allocate_hold(objtype_t type, vm_pindex_t size)
507 {
508         vm_object_t result;
509
510         result = (vm_object_t) zalloc(obj_zone);
511
512         _vm_object_allocate(type, size, result);
513
514         return (result);
515 }
516
517 /*
518  * Add an additional reference to a vm_object.  The object must already be
519  * held.  The original non-lock version is no longer supported.  The object
520  * must NOT be chain locked by anyone at the time the reference is added.
521  *
522  * Referencing a chain-locked object can blow up the fairly sensitive
523  * ref_count and shadow_count tests in the deallocator.  Most callers
524  * will call vm_object_chain_wait() prior to calling
525  * vm_object_reference_locked() to avoid the case.
526  *
527  * The object must be held, but may be held shared if desired (hence why
528  * we use an atomic op).
529  */
530 void
531 vm_object_reference_locked(vm_object_t object)
532 {
533         KKASSERT(object != NULL);
534         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
535         KKASSERT((object->flags & OBJ_CHAINLOCK) == 0);
536         atomic_add_int(&object->ref_count, 1);
537         if (object->type == OBJT_VNODE) {
538                 vref(object->handle);
539                 /* XXX what if the vnode is being destroyed? */
540         }
541 }
542
543 /*
544  * Object OBJ_CHAINLOCK lock handling.
545  *
546  * The caller can chain-lock backing objects recursively and then
547  * use vm_object_chain_release_all() to undo the whole chain.
548  *
549  * Chain locks are used to prevent collapses and are only applicable
550  * to OBJT_DEFAULT and OBJT_SWAP objects.  Chain locking operations
551  * on other object types are ignored.  This is also important because
552  * it allows e.g. the vnode underlying a memory mapping to take concurrent
553  * faults.
554  *
555  * The object must usually be held on entry, though intermediate
556  * objects need not be held on release.
557  */
558 void
559 vm_object_chain_wait(vm_object_t object)
560 {
561         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
562         while (object->flags & OBJ_CHAINLOCK) {
563                 vm_object_set_flag(object, OBJ_CHAINWANT);
564                 tsleep(object, 0, "objchain", 0);
565         }
566 }
567
568 void
569 vm_object_chain_acquire(vm_object_t object)
570 {
571         if (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP) {
572                 vm_object_chain_wait(object);
573                 vm_object_set_flag(object, OBJ_CHAINLOCK);
574         }
575 }
576
577 void
578 vm_object_chain_release(vm_object_t object)
579 {
580         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
581         if (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP) {
582                 KKASSERT(object->flags & OBJ_CHAINLOCK);
583                 if (object->flags & OBJ_CHAINWANT) {
584                         vm_object_clear_flag(object,
585                                              OBJ_CHAINLOCK | OBJ_CHAINWANT);
586                         wakeup(object);
587                 } else {
588                         vm_object_clear_flag(object, OBJ_CHAINLOCK);
589                 }
590         }
591 }
592
593 /*
594  * This releases the entire chain of objects from first_object to and
595  * including stopobj, flowing through object->backing_object.
596  *
597  * We release stopobj first as an optimization as this object is most
598  * likely to be shared across multiple processes.
599  */
600 void
601 vm_object_chain_release_all(vm_object_t first_object, vm_object_t stopobj)
602 {
603         vm_object_t backing_object;
604         vm_object_t object;
605
606         vm_object_chain_release(stopobj);
607         object = first_object;
608
609         while (object != stopobj) {
610                 KKASSERT(object);
611                 if (object != first_object)
612                         vm_object_hold(object);
613                 backing_object = object->backing_object;
614                 vm_object_chain_release(object);
615                 if (object != first_object)
616                         vm_object_drop(object);
617                 object = backing_object;
618         }
619 }
620
621 /*
622  * Dereference an object and its underlying vnode.
623  *
624  * The object must be held exclusively and will remain held on return.
625  * (We don't need an atomic op due to the exclusivity).
626  */
627 static void
628 vm_object_vndeallocate(vm_object_t object)
629 {
630         struct vnode *vp = (struct vnode *) object->handle;
631
632         KASSERT(object->type == OBJT_VNODE,
633             ("vm_object_vndeallocate: not a vnode object"));
634         KASSERT(vp != NULL, ("vm_object_vndeallocate: missing vp"));
635         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
636 #ifdef INVARIANTS
637         if (object->ref_count == 0) {
638                 vprint("vm_object_vndeallocate", vp);
639                 panic("vm_object_vndeallocate: bad object reference count");
640         }
641 #endif
642         object->ref_count--;
643         if (object->ref_count == 0)
644                 vclrflags(vp, VTEXT);
645         vrele(vp);
646 }
647
648 /*
649  * Release a reference to the specified object, gained either through a
650  * vm_object_allocate or a vm_object_reference call.  When all references
651  * are gone, storage associated with this object may be relinquished.
652  *
653  * The caller does not have to hold the object locked but must have control
654  * over the reference in question in order to guarantee that the object
655  * does not get ripped out from under us.
656  *
657  * XXX Currently all deallocations require an exclusive lock.
658  */
659 void
660 vm_object_deallocate(vm_object_t object)
661 {
662         if (object) {
663                 vm_object_hold(object);
664                 vm_object_deallocate_locked(object);
665                 vm_object_drop(object);
666         }
667 }
668
669 void
670 vm_object_deallocate_locked(vm_object_t object)
671 {
672         struct vm_object_dealloc_list *dlist = NULL;
673         struct vm_object_dealloc_list *dtmp;
674         vm_object_t temp;
675         int must_drop = 0;
676
677         /*
678          * We may chain deallocate object, but additional objects may
679          * collect on the dlist which also have to be deallocated.  We
680          * must avoid a recursion, vm_object chains can get deep.
681          */
682 again:
683         while (object != NULL) {
684                 ASSERT_LWKT_TOKEN_HELD_EXCL(&object->token);
685 #if 0
686                 /*
687                  * Don't rip a ref_count out from under an object undergoing
688                  * collapse, it will confuse the collapse code.
689                  */
690                 vm_object_chain_wait(object);
691 #endif
692                 if (object->type == OBJT_VNODE) {
693                         vm_object_vndeallocate(object);
694                         break;
695                 }
696
697                 if (object->ref_count == 0) {
698                         panic("vm_object_deallocate: object deallocated "
699                               "too many times: %d", object->type);
700                 }
701                 if (object->ref_count > 2) {
702                         object->ref_count--;
703                         break;
704                 }
705
706                 /*
707                  * Here on ref_count of one or two, which are special cases for
708                  * objects.
709                  *
710                  * Nominal ref_count > 1 case if the second ref is not from
711                  * a shadow.
712                  *
713                  * (ONEMAPPING only applies to DEFAULT AND SWAP objects)
714                  */
715                 if (object->ref_count == 2 && object->shadow_count == 0) {
716                         if (object->type == OBJT_DEFAULT ||
717                             object->type == OBJT_SWAP) {
718                                 vm_object_set_flag(object, OBJ_ONEMAPPING);
719                         }
720                         object->ref_count--;
721                         break;
722                 }
723
724                 /*
725                  * If the second ref is from a shadow we chain along it
726                  * upwards if object's handle is exhausted.
727                  *
728                  * We have to decrement object->ref_count before potentially
729                  * collapsing the first shadow object or the collapse code
730                  * will not be able to handle the degenerate case to remove
731                  * object.  However, if we do it too early the object can
732                  * get ripped out from under us.
733                  */
734                 if (object->ref_count == 2 && object->shadow_count == 1 &&
735                     object->handle == NULL && (object->type == OBJT_DEFAULT ||
736                                                object->type == OBJT_SWAP)) {
737                         temp = LIST_FIRST(&object->shadow_head);
738                         KKASSERT(temp != NULL);
739                         vm_object_hold(temp);
740
741                         /*
742                          * Wait for any paging to complete so the collapse
743                          * doesn't (or isn't likely to) qcollapse.  pip
744                          * waiting must occur before we acquire the
745                          * chainlock.
746                          */
747                         while (
748                                 temp->paging_in_progress ||
749                                 object->paging_in_progress
750                         ) {
751                                 vm_object_pip_wait(temp, "objde1");
752                                 vm_object_pip_wait(object, "objde2");
753                         }
754
755                         /*
756                          * If the parent is locked we have to give up, as
757                          * otherwise we would be acquiring locks in the
758                          * wrong order and potentially deadlock.
759                          */
760                         if (temp->flags & OBJ_CHAINLOCK) {
761                                 vm_object_drop(temp);
762                                 goto skip;
763                         }
764                         vm_object_chain_acquire(temp);
765
766                         /*
767                          * Recheck/retry after the hold and the paging
768                          * wait, both of which can block us.
769                          */
770                         if (object->ref_count != 2 ||
771                             object->shadow_count != 1 ||
772                             object->handle ||
773                             LIST_FIRST(&object->shadow_head) != temp ||
774                             (object->type != OBJT_DEFAULT &&
775                              object->type != OBJT_SWAP)) {
776                                 vm_object_chain_release(temp);
777                                 vm_object_drop(temp);
778                                 continue;
779                         }
780
781                         /*
782                          * We can safely drop object's ref_count now.
783                          */
784                         KKASSERT(object->ref_count == 2);
785                         object->ref_count--;
786
787                         /*
788                          * If our single parent is not collapseable just
789                          * decrement ref_count (2->1) and stop.
790                          */
791                         if (temp->handle || (temp->type != OBJT_DEFAULT &&
792                                              temp->type != OBJT_SWAP)) {
793                                 vm_object_chain_release(temp);
794                                 vm_object_drop(temp);
795                                 break;
796                         }
797
798                         /*
799                          * At this point we have already dropped object's
800                          * ref_count so it is possible for a race to
801                          * deallocate obj out from under us.  Any collapse
802                          * will re-check the situation.  We must not block
803                          * until we are able to collapse.
804                          *
805                          * Bump temp's ref_count to avoid an unwanted
806                          * degenerate recursion (can't call
807                          * vm_object_reference_locked() because it asserts
808                          * that CHAINLOCK is not set).
809                          */
810                         temp->ref_count++;
811                         KKASSERT(temp->ref_count > 1);
812
813                         /*
814                          * Collapse temp, then deallocate the extra ref
815                          * formally.
816                          */
817                         vm_object_collapse(temp, &dlist);
818                         vm_object_chain_release(temp);
819                         if (must_drop) {
820                                 vm_object_lock_swap();
821                                 vm_object_drop(object);
822                         }
823                         object = temp;
824                         must_drop = 1;
825                         continue;
826                 }
827
828                 /*
829                  * Drop the ref and handle termination on the 1->0 transition.
830                  * We may have blocked above so we have to recheck.
831                  */
832 skip:
833                 KKASSERT(object->ref_count != 0);
834                 if (object->ref_count >= 2) {
835                         object->ref_count--;
836                         break;
837                 }
838                 KKASSERT(object->ref_count == 1);
839
840                 /*
841                  * 1->0 transition.  Chain through the backing_object.
842                  * Maintain the ref until we've located the backing object,
843                  * then re-check.
844                  */
845                 while ((temp = object->backing_object) != NULL) {
846                         vm_object_hold(temp);
847                         if (temp == object->backing_object)
848                                 break;
849                         vm_object_drop(temp);
850                 }
851
852                 /*
853                  * 1->0 transition verified, retry if ref_count is no longer
854                  * 1.  Otherwise disconnect the backing_object (temp) and
855                  * clean up.
856                  */
857                 if (object->ref_count != 1) {
858                         vm_object_drop(temp);
859                         continue;
860                 }
861
862                 /*
863                  * It shouldn't be possible for the object to be chain locked
864                  * if we're removing the last ref on it.
865                  */
866                 KKASSERT((object->flags & OBJ_CHAINLOCK) == 0);
867
868                 if (temp) {
869                         LIST_REMOVE(object, shadow_list);
870                         temp->shadow_count--;
871                         temp->generation++;
872                         object->backing_object = NULL;
873                 }
874
875                 --object->ref_count;
876                 if ((object->flags & OBJ_DEAD) == 0)
877                         vm_object_terminate(object);
878                 if (must_drop && temp)
879                         vm_object_lock_swap();
880                 if (must_drop)
881                         vm_object_drop(object);
882                 object = temp;
883                 must_drop = 1;
884         }
885         if (must_drop && object)
886                 vm_object_drop(object);
887
888         /*
889          * Additional tail recursion on dlist.  Avoid a recursion.  Objects
890          * on the dlist have a hold count but are not locked.
891          */
892         if ((dtmp = dlist) != NULL) {
893                 dlist = dtmp->next;
894                 object = dtmp->object;
895                 kfree(dtmp, M_TEMP);
896
897                 vm_object_lock(object); /* already held, add lock */
898                 must_drop = 1;          /* and we're responsible for it */
899                 goto again;
900         }
901 }
902
903 /*
904  * Destroy the specified object, freeing up related resources.
905  *
906  * The object must have zero references.
907  *
908  * The object must held.  The caller is responsible for dropping the object
909  * after terminate returns.  Terminate does NOT drop the object.
910  */
911 static int vm_object_terminate_callback(vm_page_t p, void *data);
912
913 void
914 vm_object_terminate(vm_object_t object)
915 {
916         /*
917          * Make sure no one uses us.  Once we set OBJ_DEAD we should be
918          * able to safely block.
919          */
920         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
921         KKASSERT((object->flags & OBJ_DEAD) == 0);
922         vm_object_set_flag(object, OBJ_DEAD);
923
924         /*
925          * Wait for the pageout daemon to be done with the object
926          */
927         vm_object_pip_wait(object, "objtrm1");
928
929         KASSERT(!object->paging_in_progress,
930                 ("vm_object_terminate: pageout in progress"));
931
932         /*
933          * Clean and free the pages, as appropriate. All references to the
934          * object are gone, so we don't need to lock it.
935          */
936         if (object->type == OBJT_VNODE) {
937                 struct vnode *vp;
938
939                 /*
940                  * Clean pages and flush buffers.
941                  *
942                  * NOTE!  TMPFS buffer flushes do not typically flush the
943                  *        actual page to swap as this would be highly
944                  *        inefficient, and normal filesystems usually wrap
945                  *        page flushes with buffer cache buffers.
946                  *
947                  *        To deal with this we have to call vinvalbuf() both
948                  *        before and after the vm_object_page_clean().
949                  */
950                 vp = (struct vnode *) object->handle;
951                 vinvalbuf(vp, V_SAVE, 0, 0);
952                 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
953                 vinvalbuf(vp, V_SAVE, 0, 0);
954         }
955
956         /*
957          * Wait for any I/O to complete, after which there had better not
958          * be any references left on the object.
959          */
960         vm_object_pip_wait(object, "objtrm2");
961
962         if (object->ref_count != 0) {
963                 panic("vm_object_terminate: object with references, "
964                       "ref_count=%d", object->ref_count);
965         }
966
967         /*
968          * Cleanup any shared pmaps associated with this object.
969          */
970         pmap_object_free(object);
971
972         /*
973          * Now free any remaining pages. For internal objects, this also
974          * removes them from paging queues. Don't free wired pages, just
975          * remove them from the object. 
976          */
977         vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
978                                 vm_object_terminate_callback, NULL);
979
980         /*
981          * Let the pager know object is dead.
982          */
983         vm_pager_deallocate(object);
984
985         /*
986          * Wait for the object hold count to hit 1, clean out pages as
987          * we go.  vmobj_token interlocks any race conditions that might
988          * pick the object up from the vm_object_list after we have cleared
989          * rb_memq.
990          */
991         for (;;) {
992                 if (RB_ROOT(&object->rb_memq) == NULL)
993                         break;
994                 kprintf("vm_object_terminate: Warning, object %p "
995                         "still has %d pages\n",
996                         object, object->resident_page_count);
997                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
998                                         vm_object_terminate_callback, NULL);
999         }
1000
1001         /*
1002          * There had better not be any pages left
1003          */
1004         KKASSERT(object->resident_page_count == 0);
1005
1006         /*
1007          * Remove the object from the global object list.
1008          */
1009         lwkt_gettoken(&vmobj_token);
1010         TAILQ_REMOVE(&vm_object_list, object, object_list);
1011         vm_object_count--;
1012         lwkt_reltoken(&vmobj_token);
1013         vm_object_dead_wakeup(object);
1014
1015         if (object->ref_count != 0) {
1016                 panic("vm_object_terminate2: object with references, "
1017                       "ref_count=%d", object->ref_count);
1018         }
1019
1020         /*
1021          * NOTE: The object hold_count is at least 1, so we cannot zfree()
1022          *       the object here.  See vm_object_drop().
1023          */
1024 }
1025
1026 /*
1027  * The caller must hold the object.
1028  */
1029 static int
1030 vm_object_terminate_callback(vm_page_t p, void *data __unused)
1031 {
1032         vm_object_t object;
1033
1034         object = p->object;
1035         vm_page_busy_wait(p, TRUE, "vmpgtrm");
1036         if (object != p->object) {
1037                 kprintf("vm_object_terminate: Warning: Encountered "
1038                         "busied page %p on queue %d\n", p, p->queue);
1039                 vm_page_wakeup(p);
1040         } else if (p->wire_count == 0) {
1041                 /*
1042                  * NOTE: p->dirty and PG_NEED_COMMIT are ignored.
1043                  */
1044                 vm_page_free(p);
1045                 mycpu->gd_cnt.v_pfree++;
1046         } else {
1047                 if (p->queue != PQ_NONE)
1048                         kprintf("vm_object_terminate: Warning: Encountered "
1049                                 "wired page %p on queue %d\n", p, p->queue);
1050                 vm_page_remove(p);
1051                 vm_page_wakeup(p);
1052         }
1053         lwkt_yield();
1054         return(0);
1055 }
1056
1057 /*
1058  * The object is dead but still has an object<->pager association.  Sleep
1059  * and return.  The caller typically retests the association in a loop.
1060  *
1061  * The caller must hold the object.
1062  */
1063 void
1064 vm_object_dead_sleep(vm_object_t object, const char *wmesg)
1065 {
1066         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1067         if (object->handle) {
1068                 vm_object_set_flag(object, OBJ_DEADWNT);
1069                 tsleep(object, 0, wmesg, 0);
1070                 /* object may be invalid after this point */
1071         }
1072 }
1073
1074 /*
1075  * Wakeup anyone waiting for the object<->pager disassociation on
1076  * a dead object.
1077  *
1078  * The caller must hold the object.
1079  */
1080 void
1081 vm_object_dead_wakeup(vm_object_t object)
1082 {
1083         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1084         if (object->flags & OBJ_DEADWNT) {
1085                 vm_object_clear_flag(object, OBJ_DEADWNT);
1086                 wakeup(object);
1087         }
1088 }
1089
1090 /*
1091  * Clean all dirty pages in the specified range of object.  Leaves page
1092  * on whatever queue it is currently on.   If NOSYNC is set then do not
1093  * write out pages with PG_NOSYNC set (originally comes from MAP_NOSYNC),
1094  * leaving the object dirty.
1095  *
1096  * When stuffing pages asynchronously, allow clustering.  XXX we need a
1097  * synchronous clustering mode implementation.
1098  *
1099  * Odd semantics: if start == end, we clean everything.
1100  *
1101  * The object must be locked? XXX
1102  */
1103 static int vm_object_page_clean_pass1(struct vm_page *p, void *data);
1104 static int vm_object_page_clean_pass2(struct vm_page *p, void *data);
1105
1106 void
1107 vm_object_page_clean(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
1108                      int flags)
1109 {
1110         struct rb_vm_page_scan_info info;
1111         struct vnode *vp;
1112         int wholescan;
1113         int pagerflags;
1114         int generation;
1115
1116         vm_object_hold(object);
1117         if (object->type != OBJT_VNODE ||
1118             (object->flags & OBJ_MIGHTBEDIRTY) == 0) {
1119                 vm_object_drop(object);
1120                 return;
1121         }
1122
1123         pagerflags = (flags & (OBJPC_SYNC | OBJPC_INVAL)) ? 
1124                         VM_PAGER_PUT_SYNC : VM_PAGER_CLUSTER_OK;
1125         pagerflags |= (flags & OBJPC_INVAL) ? VM_PAGER_PUT_INVAL : 0;
1126
1127         vp = object->handle;
1128
1129         /*
1130          * Interlock other major object operations.  This allows us to 
1131          * temporarily clear OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY.
1132          */
1133         vm_object_set_flag(object, OBJ_CLEANING);
1134
1135         /*
1136          * Handle 'entire object' case
1137          */
1138         info.start_pindex = start;
1139         if (end == 0) {
1140                 info.end_pindex = object->size - 1;
1141         } else {
1142                 info.end_pindex = end - 1;
1143         }
1144         wholescan = (start == 0 && info.end_pindex == object->size - 1);
1145         info.limit = flags;
1146         info.pagerflags = pagerflags;
1147         info.object = object;
1148
1149         /*
1150          * If cleaning the entire object do a pass to mark the pages read-only.
1151          * If everything worked out ok, clear OBJ_WRITEABLE and
1152          * OBJ_MIGHTBEDIRTY.
1153          */
1154         if (wholescan) {
1155                 info.error = 0;
1156                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1157                                         vm_object_page_clean_pass1, &info);
1158                 if (info.error == 0) {
1159                         vm_object_clear_flag(object,
1160                                              OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
1161                         if (object->type == OBJT_VNODE &&
1162                             (vp = (struct vnode *)object->handle) != NULL) {
1163                                 if (vp->v_flag & VOBJDIRTY) 
1164                                         vclrflags(vp, VOBJDIRTY);
1165                         }
1166                 }
1167         }
1168
1169         /*
1170          * Do a pass to clean all the dirty pages we find.
1171          */
1172         do {
1173                 info.error = 0;
1174                 generation = object->generation;
1175                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1176                                         vm_object_page_clean_pass2, &info);
1177         } while (info.error || generation != object->generation);
1178
1179         vm_object_clear_flag(object, OBJ_CLEANING);
1180         vm_object_drop(object);
1181 }
1182
1183 /*
1184  * The caller must hold the object.
1185  */
1186 static 
1187 int
1188 vm_object_page_clean_pass1(struct vm_page *p, void *data)
1189 {
1190         struct rb_vm_page_scan_info *info = data;
1191
1192         vm_page_flag_set(p, PG_CLEANCHK);
1193         if ((info->limit & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
1194                 info->error = 1;
1195         } else if (vm_page_busy_try(p, FALSE) == 0) {
1196                 vm_page_protect(p, VM_PROT_READ);       /* must not block */
1197                 vm_page_wakeup(p);
1198         } else {
1199                 info->error = 1;
1200         }
1201         lwkt_yield();
1202         return(0);
1203 }
1204
1205 /*
1206  * The caller must hold the object
1207  */
1208 static 
1209 int
1210 vm_object_page_clean_pass2(struct vm_page *p, void *data)
1211 {
1212         struct rb_vm_page_scan_info *info = data;
1213         int generation;
1214
1215         /*
1216          * Do not mess with pages that were inserted after we started
1217          * the cleaning pass.
1218          */
1219         if ((p->flags & PG_CLEANCHK) == 0)
1220                 goto done;
1221
1222         generation = info->object->generation;
1223         vm_page_busy_wait(p, TRUE, "vpcwai");
1224         if (p->object != info->object ||
1225             info->object->generation != generation) {
1226                 info->error = 1;
1227                 vm_page_wakeup(p);
1228                 goto done;
1229         }
1230
1231         /*
1232          * Before wasting time traversing the pmaps, check for trivial
1233          * cases where the page cannot be dirty.
1234          */
1235         if (p->valid == 0 || (p->queue - p->pc) == PQ_CACHE) {
1236                 KKASSERT((p->dirty & p->valid) == 0 &&
1237                          (p->flags & PG_NEED_COMMIT) == 0);
1238                 vm_page_wakeup(p);
1239                 goto done;
1240         }
1241
1242         /*
1243          * Check whether the page is dirty or not.  The page has been set
1244          * to be read-only so the check will not race a user dirtying the
1245          * page.
1246          */
1247         vm_page_test_dirty(p);
1248         if ((p->dirty & p->valid) == 0 && (p->flags & PG_NEED_COMMIT) == 0) {
1249                 vm_page_flag_clear(p, PG_CLEANCHK);
1250                 vm_page_wakeup(p);
1251                 goto done;
1252         }
1253
1254         /*
1255          * If we have been asked to skip nosync pages and this is a
1256          * nosync page, skip it.  Note that the object flags were
1257          * not cleared in this case (because pass1 will have returned an
1258          * error), so we do not have to set them.
1259          */
1260         if ((info->limit & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
1261                 vm_page_flag_clear(p, PG_CLEANCHK);
1262                 vm_page_wakeup(p);
1263                 goto done;
1264         }
1265
1266         /*
1267          * Flush as many pages as we can.  PG_CLEANCHK will be cleared on
1268          * the pages that get successfully flushed.  Set info->error if
1269          * we raced an object modification.
1270          */
1271         vm_object_page_collect_flush(info->object, p, info->pagerflags);
1272         vm_wait_nominal();
1273 done:
1274         lwkt_yield();
1275         return(0);
1276 }
1277
1278 /*
1279  * Collect the specified page and nearby pages and flush them out.
1280  * The number of pages flushed is returned.  The passed page is busied
1281  * by the caller and we are responsible for its disposition.
1282  *
1283  * The caller must hold the object.
1284  */
1285 static void
1286 vm_object_page_collect_flush(vm_object_t object, vm_page_t p, int pagerflags)
1287 {
1288         int error;
1289         int is;
1290         int ib;
1291         int i;
1292         int page_base;
1293         vm_pindex_t pi;
1294         vm_page_t ma[BLIST_MAX_ALLOC];
1295
1296         ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1297
1298         pi = p->pindex;
1299         page_base = pi % BLIST_MAX_ALLOC;
1300         ma[page_base] = p;
1301         ib = page_base - 1;
1302         is = page_base + 1;
1303
1304         while (ib >= 0) {
1305                 vm_page_t tp;
1306
1307                 tp = vm_page_lookup_busy_try(object, pi - page_base + ib,
1308                                              TRUE, &error);
1309                 if (error)
1310                         break;
1311                 if (tp == NULL)
1312                         break;
1313                 if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1314                     (tp->flags & PG_CLEANCHK) == 0) {
1315                         vm_page_wakeup(tp);
1316                         break;
1317                 }
1318                 if ((tp->queue - tp->pc) == PQ_CACHE) {
1319                         vm_page_flag_clear(tp, PG_CLEANCHK);
1320                         vm_page_wakeup(tp);
1321                         break;
1322                 }
1323                 vm_page_test_dirty(tp);
1324                 if ((tp->dirty & tp->valid) == 0 &&
1325                     (tp->flags & PG_NEED_COMMIT) == 0) {
1326                         vm_page_flag_clear(tp, PG_CLEANCHK);
1327                         vm_page_wakeup(tp);
1328                         break;
1329                 }
1330                 ma[ib] = tp;
1331                 --ib;
1332         }
1333         ++ib;   /* fixup */
1334
1335         while (is < BLIST_MAX_ALLOC &&
1336                pi - page_base + is < object->size) {
1337                 vm_page_t tp;
1338
1339                 tp = vm_page_lookup_busy_try(object, pi - page_base + is,
1340                                              TRUE, &error);
1341                 if (error)
1342                         break;
1343                 if (tp == NULL)
1344                         break;
1345                 if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1346                     (tp->flags & PG_CLEANCHK) == 0) {
1347                         vm_page_wakeup(tp);
1348                         break;
1349                 }
1350                 if ((tp->queue - tp->pc) == PQ_CACHE) {
1351                         vm_page_flag_clear(tp, PG_CLEANCHK);
1352                         vm_page_wakeup(tp);
1353                         break;
1354                 }
1355                 vm_page_test_dirty(tp);
1356                 if ((tp->dirty & tp->valid) == 0 &&
1357                     (tp->flags & PG_NEED_COMMIT) == 0) {
1358                         vm_page_flag_clear(tp, PG_CLEANCHK);
1359                         vm_page_wakeup(tp);
1360                         break;
1361                 }
1362                 ma[is] = tp;
1363                 ++is;
1364         }
1365
1366         /*
1367          * All pages in the ma[] array are busied now
1368          */
1369         for (i = ib; i < is; ++i) {
1370                 vm_page_flag_clear(ma[i], PG_CLEANCHK);
1371                 vm_page_hold(ma[i]);    /* XXX need this any more? */
1372         }
1373         vm_pageout_flush(&ma[ib], is - ib, pagerflags);
1374         for (i = ib; i < is; ++i)       /* XXX need this any more? */
1375                 vm_page_unhold(ma[i]);
1376 }
1377
1378 /*
1379  * Same as vm_object_pmap_copy, except range checking really
1380  * works, and is meant for small sections of an object.
1381  *
1382  * This code protects resident pages by making them read-only
1383  * and is typically called on a fork or split when a page
1384  * is converted to copy-on-write.  
1385  *
1386  * NOTE: If the page is already at VM_PROT_NONE, calling
1387  * vm_page_protect will have no effect.
1388  */
1389 void
1390 vm_object_pmap_copy_1(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1391 {
1392         vm_pindex_t idx;
1393         vm_page_t p;
1394
1395         if (object == NULL || (object->flags & OBJ_WRITEABLE) == 0)
1396                 return;
1397
1398         vm_object_hold(object);
1399         for (idx = start; idx < end; idx++) {
1400                 p = vm_page_lookup(object, idx);
1401                 if (p == NULL)
1402                         continue;
1403                 vm_page_protect(p, VM_PROT_READ);
1404         }
1405         vm_object_drop(object);
1406 }
1407
1408 /*
1409  * Removes all physical pages in the specified object range from all
1410  * physical maps.
1411  *
1412  * The object must *not* be locked.
1413  */
1414
1415 static int vm_object_pmap_remove_callback(vm_page_t p, void *data);
1416
1417 void
1418 vm_object_pmap_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1419 {
1420         struct rb_vm_page_scan_info info;
1421
1422         if (object == NULL)
1423                 return;
1424         info.start_pindex = start;
1425         info.end_pindex = end - 1;
1426
1427         vm_object_hold(object);
1428         vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1429                                 vm_object_pmap_remove_callback, &info);
1430         if (start == 0 && end == object->size)
1431                 vm_object_clear_flag(object, OBJ_WRITEABLE);
1432         vm_object_drop(object);
1433 }
1434
1435 /*
1436  * The caller must hold the object
1437  */
1438 static int
1439 vm_object_pmap_remove_callback(vm_page_t p, void *data __unused)
1440 {
1441         vm_page_protect(p, VM_PROT_NONE);
1442         return(0);
1443 }
1444
1445 /*
1446  * Implements the madvise function at the object/page level.
1447  *
1448  * MADV_WILLNEED        (any object)
1449  *
1450  *      Activate the specified pages if they are resident.
1451  *
1452  * MADV_DONTNEED        (any object)
1453  *
1454  *      Deactivate the specified pages if they are resident.
1455  *
1456  * MADV_FREE    (OBJT_DEFAULT/OBJT_SWAP objects, OBJ_ONEMAPPING only)
1457  *
1458  *      Deactivate and clean the specified pages if they are
1459  *      resident.  This permits the process to reuse the pages
1460  *      without faulting or the kernel to reclaim the pages
1461  *      without I/O.
1462  *
1463  * No requirements.
1464  */
1465 void
1466 vm_object_madvise(vm_object_t object, vm_pindex_t pindex, int count, int advise)
1467 {
1468         vm_pindex_t end, tpindex;
1469         vm_object_t tobject;
1470         vm_object_t xobj;
1471         vm_page_t m;
1472         int error;
1473
1474         if (object == NULL)
1475                 return;
1476
1477         end = pindex + count;
1478
1479         vm_object_hold(object);
1480         tobject = object;
1481
1482         /*
1483          * Locate and adjust resident pages
1484          */
1485         for (; pindex < end; pindex += 1) {
1486 relookup:
1487                 if (tobject != object)
1488                         vm_object_drop(tobject);
1489                 tobject = object;
1490                 tpindex = pindex;
1491 shadowlookup:
1492                 /*
1493                  * MADV_FREE only operates on OBJT_DEFAULT or OBJT_SWAP pages
1494                  * and those pages must be OBJ_ONEMAPPING.
1495                  */
1496                 if (advise == MADV_FREE) {
1497                         if ((tobject->type != OBJT_DEFAULT &&
1498                              tobject->type != OBJT_SWAP) ||
1499                             (tobject->flags & OBJ_ONEMAPPING) == 0) {
1500                                 continue;
1501                         }
1502                 }
1503
1504                 m = vm_page_lookup_busy_try(tobject, tpindex, TRUE, &error);
1505
1506                 if (error) {
1507                         vm_page_sleep_busy(m, TRUE, "madvpo");
1508                         goto relookup;
1509                 }
1510                 if (m == NULL) {
1511                         /*
1512                          * There may be swap even if there is no backing page
1513                          */
1514                         if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
1515                                 swap_pager_freespace(tobject, tpindex, 1);
1516
1517                         /*
1518                          * next object
1519                          */
1520                         while ((xobj = tobject->backing_object) != NULL) {
1521                                 KKASSERT(xobj != object);
1522                                 vm_object_hold(xobj);
1523                                 if (xobj == tobject->backing_object)
1524                                         break;
1525                                 vm_object_drop(xobj);
1526                         }
1527                         if (xobj == NULL)
1528                                 continue;
1529                         tpindex += OFF_TO_IDX(tobject->backing_object_offset);
1530                         if (tobject != object) {
1531                                 vm_object_lock_swap();
1532                                 vm_object_drop(tobject);
1533                         }
1534                         tobject = xobj;
1535                         goto shadowlookup;
1536                 }
1537
1538                 /*
1539                  * If the page is not in a normal active state, we skip it.
1540                  * If the page is not managed there are no page queues to
1541                  * mess with.  Things can break if we mess with pages in
1542                  * any of the below states.
1543                  */
1544                 if (m->wire_count ||
1545                     (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
1546                     m->valid != VM_PAGE_BITS_ALL
1547                 ) {
1548                         vm_page_wakeup(m);
1549                         continue;
1550                 }
1551
1552                 /*
1553                  * Theoretically once a page is known not to be busy, an
1554                  * interrupt cannot come along and rip it out from under us.
1555                  */
1556
1557                 if (advise == MADV_WILLNEED) {
1558                         vm_page_activate(m);
1559                 } else if (advise == MADV_DONTNEED) {
1560                         vm_page_dontneed(m);
1561                 } else if (advise == MADV_FREE) {
1562                         /*
1563                          * Mark the page clean.  This will allow the page
1564                          * to be freed up by the system.  However, such pages
1565                          * are often reused quickly by malloc()/free()
1566                          * so we do not do anything that would cause
1567                          * a page fault if we can help it.
1568                          *
1569                          * Specifically, we do not try to actually free
1570                          * the page now nor do we try to put it in the
1571                          * cache (which would cause a page fault on reuse).
1572                          *
1573                          * But we do make the page is freeable as we
1574                          * can without actually taking the step of unmapping
1575                          * it.
1576                          */
1577                         pmap_clear_modify(m);
1578                         m->dirty = 0;
1579                         m->act_count = 0;
1580                         vm_page_dontneed(m);
1581                         if (tobject->type == OBJT_SWAP)
1582                                 swap_pager_freespace(tobject, tpindex, 1);
1583                 }
1584                 vm_page_wakeup(m);
1585         }       
1586         if (tobject != object)
1587                 vm_object_drop(tobject);
1588         vm_object_drop(object);
1589 }
1590
1591 /*
1592  * Create a new object which is backed by the specified existing object
1593  * range.  Replace the pointer and offset that was pointing at the existing
1594  * object with the pointer/offset for the new object.
1595  *
1596  * No other requirements.
1597  */
1598 void
1599 vm_object_shadow(vm_object_t *objectp, vm_ooffset_t *offset, vm_size_t length,
1600                  int addref)
1601 {
1602         vm_object_t source;
1603         vm_object_t result;
1604
1605         source = *objectp;
1606
1607         /*
1608          * Don't create the new object if the old object isn't shared.
1609          * We have to chain wait before adding the reference to avoid
1610          * racing a collapse or deallocation.
1611          *
1612          * Add the additional ref to source here to avoid racing a later
1613          * collapse or deallocation. Clear the ONEMAPPING flag whether
1614          * addref is TRUE or not in this case because the original object
1615          * will be shadowed.
1616          */
1617         if (source) {
1618                 vm_object_hold(source);
1619                 vm_object_chain_wait(source);
1620                 if (source->ref_count == 1 &&
1621                     source->handle == NULL &&
1622                     (source->type == OBJT_DEFAULT ||
1623                      source->type == OBJT_SWAP)) {
1624                         vm_object_drop(source);
1625                         if (addref) {
1626                                 vm_object_reference_locked(source);
1627                                 vm_object_clear_flag(source, OBJ_ONEMAPPING);
1628                         }
1629                         return;
1630                 }
1631                 vm_object_reference_locked(source);
1632                 vm_object_clear_flag(source, OBJ_ONEMAPPING);
1633         }
1634
1635         /*
1636          * Allocate a new object with the given length.  The new object
1637          * is returned referenced but we may have to add another one.
1638          * If we are adding a second reference we must clear OBJ_ONEMAPPING.
1639          * (typically because the caller is about to clone a vm_map_entry).
1640          *
1641          * The source object currently has an extra reference to prevent
1642          * collapses into it while we mess with its shadow list, which
1643          * we will remove later in this routine.
1644          */
1645         if ((result = vm_object_allocate(OBJT_DEFAULT, length)) == NULL)
1646                 panic("vm_object_shadow: no object for shadowing");
1647         vm_object_hold(result);
1648         if (addref) {
1649                 vm_object_reference_locked(result);
1650                 vm_object_clear_flag(result, OBJ_ONEMAPPING);
1651         }
1652
1653         /*
1654          * The new object shadows the source object.  Chain wait before
1655          * adjusting shadow_count or the shadow list to avoid races.
1656          *
1657          * Try to optimize the result object's page color when shadowing
1658          * in order to maintain page coloring consistency in the combined 
1659          * shadowed object.
1660          */
1661         KKASSERT(result->backing_object == NULL);
1662         result->backing_object = source;
1663         if (source) {
1664                 vm_object_chain_wait(source);
1665                 LIST_INSERT_HEAD(&source->shadow_head, result, shadow_list);
1666                 source->shadow_count++;
1667                 source->generation++;
1668                 /* cpu localization twist */
1669                 result->pg_color = (int)(intptr_t)curthread;
1670         }
1671
1672         /*
1673          * Adjust the return storage.  Drop the ref on source before
1674          * returning.
1675          */
1676         result->backing_object_offset = *offset;
1677         vm_object_drop(result);
1678         *offset = 0;
1679         if (source) {
1680                 vm_object_deallocate_locked(source);
1681                 vm_object_drop(source);
1682         }
1683
1684         /*
1685          * Return the new things
1686          */
1687         *objectp = result;
1688 }
1689
1690 #define OBSC_TEST_ALL_SHADOWED  0x0001
1691 #define OBSC_COLLAPSE_NOWAIT    0x0002
1692 #define OBSC_COLLAPSE_WAIT      0x0004
1693
1694 static int vm_object_backing_scan_callback(vm_page_t p, void *data);
1695
1696 /*
1697  * The caller must hold the object.
1698  */
1699 static __inline int
1700 vm_object_backing_scan(vm_object_t object, vm_object_t backing_object, int op)
1701 {
1702         struct rb_vm_page_scan_info info;
1703
1704         vm_object_assert_held(object);
1705         vm_object_assert_held(backing_object);
1706
1707         KKASSERT(backing_object == object->backing_object);
1708         info.backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1709
1710         /*
1711          * Initial conditions
1712          */
1713         if (op & OBSC_TEST_ALL_SHADOWED) {
1714                 /*
1715                  * We do not want to have to test for the existence of
1716                  * swap pages in the backing object.  XXX but with the
1717                  * new swapper this would be pretty easy to do.
1718                  *
1719                  * XXX what about anonymous MAP_SHARED memory that hasn't
1720                  * been ZFOD faulted yet?  If we do not test for this, the
1721                  * shadow test may succeed! XXX
1722                  */
1723                 if (backing_object->type != OBJT_DEFAULT)
1724                         return(0);
1725         }
1726         if (op & OBSC_COLLAPSE_WAIT) {
1727                 KKASSERT((backing_object->flags & OBJ_DEAD) == 0);
1728                 vm_object_set_flag(backing_object, OBJ_DEAD);
1729                 lwkt_gettoken(&vmobj_token);
1730                 TAILQ_REMOVE(&vm_object_list, backing_object, object_list);
1731                 vm_object_count--;
1732                 lwkt_reltoken(&vmobj_token);
1733                 vm_object_dead_wakeup(backing_object);
1734         }
1735
1736         /*
1737          * Our scan.   We have to retry if a negative error code is returned,
1738          * otherwise 0 or 1 will be returned in info.error.  0 Indicates that
1739          * the scan had to be stopped because the parent does not completely
1740          * shadow the child.
1741          */
1742         info.object = object;
1743         info.backing_object = backing_object;
1744         info.limit = op;
1745         do {
1746                 info.error = 1;
1747                 vm_page_rb_tree_RB_SCAN(&backing_object->rb_memq, NULL,
1748                                         vm_object_backing_scan_callback,
1749                                         &info);
1750         } while (info.error < 0);
1751
1752         return(info.error);
1753 }
1754
1755 /*
1756  * The caller must hold the object.
1757  */
1758 static int
1759 vm_object_backing_scan_callback(vm_page_t p, void *data)
1760 {
1761         struct rb_vm_page_scan_info *info = data;
1762         vm_object_t backing_object;
1763         vm_object_t object;
1764         vm_pindex_t pindex;
1765         vm_pindex_t new_pindex;
1766         vm_pindex_t backing_offset_index;
1767         int op;
1768
1769         pindex = p->pindex;
1770         new_pindex = pindex - info->backing_offset_index;
1771         op = info->limit;
1772         object = info->object;
1773         backing_object = info->backing_object;
1774         backing_offset_index = info->backing_offset_index;
1775
1776         if (op & OBSC_TEST_ALL_SHADOWED) {
1777                 vm_page_t pp;
1778
1779                 /*
1780                  * Ignore pages outside the parent object's range
1781                  * and outside the parent object's mapping of the 
1782                  * backing object.
1783                  *
1784                  * note that we do not busy the backing object's
1785                  * page.
1786                  */
1787                 if (pindex < backing_offset_index ||
1788                     new_pindex >= object->size
1789                 ) {
1790                         return(0);
1791                 }
1792
1793                 /*
1794                  * See if the parent has the page or if the parent's
1795                  * object pager has the page.  If the parent has the
1796                  * page but the page is not valid, the parent's
1797                  * object pager must have the page.
1798                  *
1799                  * If this fails, the parent does not completely shadow
1800                  * the object and we might as well give up now.
1801                  */
1802                 pp = vm_page_lookup(object, new_pindex);
1803                 if ((pp == NULL || pp->valid == 0) &&
1804                     !vm_pager_has_page(object, new_pindex)
1805                 ) {
1806                         info->error = 0;        /* problemo */
1807                         return(-1);             /* stop the scan */
1808                 }
1809         }
1810
1811         /*
1812          * Check for busy page.  Note that we may have lost (p) when we
1813          * possibly blocked above.
1814          */
1815         if (op & (OBSC_COLLAPSE_WAIT | OBSC_COLLAPSE_NOWAIT)) {
1816                 vm_page_t pp;
1817
1818                 if (vm_page_busy_try(p, TRUE)) {
1819                         if (op & OBSC_COLLAPSE_NOWAIT) {
1820                                 return(0);
1821                         } else {
1822                                 /*
1823                                  * If we slept, anything could have
1824                                  * happened.   Ask that the scan be restarted.
1825                                  *
1826                                  * Since the object is marked dead, the
1827                                  * backing offset should not have changed.  
1828                                  */
1829                                 vm_page_sleep_busy(p, TRUE, "vmocol");
1830                                 info->error = -1;
1831                                 return(-1);
1832                         }
1833                 }
1834
1835                 /*
1836                  * If (p) is no longer valid restart the scan.
1837                  */
1838                 if (p->object != backing_object || p->pindex != pindex) {
1839                         kprintf("vm_object_backing_scan: Warning: page "
1840                                 "%p ripped out from under us\n", p);
1841                         vm_page_wakeup(p);
1842                         info->error = -1;
1843                         return(-1);
1844                 }
1845
1846                 if (op & OBSC_COLLAPSE_NOWAIT) {
1847                         if (p->valid == 0 ||
1848                             p->wire_count ||
1849                             (p->flags & PG_NEED_COMMIT)) {
1850                                 vm_page_wakeup(p);
1851                                 return(0);
1852                         }
1853                 } else {
1854                         /* XXX what if p->valid == 0 , hold_count, etc? */
1855                 }
1856
1857                 KASSERT(
1858                     p->object == backing_object,
1859                     ("vm_object_qcollapse(): object mismatch")
1860                 );
1861
1862                 /*
1863                  * Destroy any associated swap
1864                  */
1865                 if (backing_object->type == OBJT_SWAP)
1866                         swap_pager_freespace(backing_object, p->pindex, 1);
1867
1868                 if (
1869                     p->pindex < backing_offset_index ||
1870                     new_pindex >= object->size
1871                 ) {
1872                         /*
1873                          * Page is out of the parent object's range, we 
1874                          * can simply destroy it. 
1875                          */
1876                         vm_page_protect(p, VM_PROT_NONE);
1877                         vm_page_free(p);
1878                         return(0);
1879                 }
1880
1881                 pp = vm_page_lookup(object, new_pindex);
1882                 if (pp != NULL || vm_pager_has_page(object, new_pindex)) {
1883                         /*
1884                          * page already exists in parent OR swap exists
1885                          * for this location in the parent.  Destroy 
1886                          * the original page from the backing object.
1887                          *
1888                          * Leave the parent's page alone
1889                          */
1890                         vm_page_protect(p, VM_PROT_NONE);
1891                         vm_page_free(p);
1892                         return(0);
1893                 }
1894
1895                 /*
1896                  * Page does not exist in parent, rename the
1897                  * page from the backing object to the main object. 
1898                  *
1899                  * If the page was mapped to a process, it can remain 
1900                  * mapped through the rename.
1901                  */
1902                 if ((p->queue - p->pc) == PQ_CACHE)
1903                         vm_page_deactivate(p);
1904
1905                 vm_page_rename(p, object, new_pindex);
1906                 vm_page_wakeup(p);
1907                 /* page automatically made dirty by rename */
1908         }
1909         return(0);
1910 }
1911
1912 /*
1913  * This version of collapse allows the operation to occur earlier and
1914  * when paging_in_progress is true for an object...  This is not a complete
1915  * operation, but should plug 99.9% of the rest of the leaks.
1916  *
1917  * The caller must hold the object and backing_object and both must be
1918  * chainlocked.
1919  *
1920  * (only called from vm_object_collapse)
1921  */
1922 static void
1923 vm_object_qcollapse(vm_object_t object, vm_object_t backing_object)
1924 {
1925         if (backing_object->ref_count == 1) {
1926                 backing_object->ref_count += 2;
1927                 vm_object_backing_scan(object, backing_object,
1928                                        OBSC_COLLAPSE_NOWAIT);
1929                 backing_object->ref_count -= 2;
1930         }
1931 }
1932
1933 /*
1934  * Collapse an object with the object backing it.  Pages in the backing
1935  * object are moved into the parent, and the backing object is deallocated.
1936  * Any conflict is resolved in favor of the parent's existing pages.
1937  *
1938  * object must be held and chain-locked on call.
1939  *
1940  * The caller must have an extra ref on object to prevent a race from
1941  * destroying it during the collapse.
1942  */
1943 void
1944 vm_object_collapse(vm_object_t object, struct vm_object_dealloc_list **dlistp)
1945 {
1946         struct vm_object_dealloc_list *dlist = NULL;
1947         vm_object_t backing_object;
1948
1949         /*
1950          * Only one thread is attempting a collapse at any given moment.
1951          * There are few restrictions for (object) that callers of this
1952          * function check so reentrancy is likely.
1953          */
1954         KKASSERT(object != NULL);
1955         vm_object_assert_held(object);
1956         KKASSERT(object->flags & OBJ_CHAINLOCK);
1957
1958         for (;;) {
1959                 vm_object_t bbobj;
1960                 int dodealloc;
1961
1962                 /*
1963                  * We have to hold the backing object, check races.
1964                  */
1965                 while ((backing_object = object->backing_object) != NULL) {
1966                         vm_object_hold(backing_object);
1967                         if (backing_object == object->backing_object)
1968                                 break;
1969                         vm_object_drop(backing_object);
1970                 }
1971
1972                 /*
1973                  * No backing object?  Nothing to collapse then.
1974                  */
1975                 if (backing_object == NULL)
1976                         break;
1977
1978                 /*
1979                  * You can't collapse with a non-default/non-swap object.
1980                  */
1981                 if (backing_object->type != OBJT_DEFAULT &&
1982                     backing_object->type != OBJT_SWAP) {
1983                         vm_object_drop(backing_object);
1984                         backing_object = NULL;
1985                         break;
1986                 }
1987
1988                 /*
1989                  * Chain-lock the backing object too because if we
1990                  * successfully merge its pages into the top object we
1991                  * will collapse backing_object->backing_object as the
1992                  * new backing_object.  Re-check that it is still our
1993                  * backing object.
1994                  */
1995                 vm_object_chain_acquire(backing_object);
1996                 if (backing_object != object->backing_object) {
1997                         vm_object_chain_release(backing_object);
1998                         vm_object_drop(backing_object);
1999                         continue;
2000                 }
2001
2002                 /*
2003                  * we check the backing object first, because it is most likely
2004                  * not collapsable.
2005                  */
2006                 if (backing_object->handle != NULL ||
2007                     (backing_object->type != OBJT_DEFAULT &&
2008                      backing_object->type != OBJT_SWAP) ||
2009                     (backing_object->flags & OBJ_DEAD) ||
2010                     object->handle != NULL ||
2011                     (object->type != OBJT_DEFAULT &&
2012                      object->type != OBJT_SWAP) ||
2013                     (object->flags & OBJ_DEAD)) {
2014                         break;
2015                 }
2016
2017                 /*
2018                  * If paging is in progress we can't do a normal collapse.
2019                  */
2020                 if (
2021                     object->paging_in_progress != 0 ||
2022                     backing_object->paging_in_progress != 0
2023                 ) {
2024                         vm_object_qcollapse(object, backing_object);
2025                         break;
2026                 }
2027
2028                 /*
2029                  * We know that we can either collapse the backing object (if
2030                  * the parent is the only reference to it) or (perhaps) have
2031                  * the parent bypass the object if the parent happens to shadow
2032                  * all the resident pages in the entire backing object.
2033                  *
2034                  * This is ignoring pager-backed pages such as swap pages.
2035                  * vm_object_backing_scan fails the shadowing test in this
2036                  * case.
2037                  */
2038                 if (backing_object->ref_count == 1) {
2039                         /*
2040                          * If there is exactly one reference to the backing
2041                          * object, we can collapse it into the parent.  
2042                          */
2043                         KKASSERT(object->backing_object == backing_object);
2044                         vm_object_backing_scan(object, backing_object,
2045                                                OBSC_COLLAPSE_WAIT);
2046
2047                         /*
2048                          * Move the pager from backing_object to object.
2049                          */
2050                         if (backing_object->type == OBJT_SWAP) {
2051                                 vm_object_pip_add(backing_object, 1);
2052
2053                                 /*
2054                                  * scrap the paging_offset junk and do a 
2055                                  * discrete copy.  This also removes major 
2056                                  * assumptions about how the swap-pager 
2057                                  * works from where it doesn't belong.  The
2058                                  * new swapper is able to optimize the
2059                                  * destroy-source case.
2060                                  */
2061                                 vm_object_pip_add(object, 1);
2062                                 swap_pager_copy(backing_object, object,
2063                                     OFF_TO_IDX(object->backing_object_offset),
2064                                     TRUE);
2065                                 vm_object_pip_wakeup(object);
2066                                 vm_object_pip_wakeup(backing_object);
2067                         }
2068
2069                         /*
2070                          * Object now shadows whatever backing_object did.
2071                          * Remove object from backing_object's shadow_list.
2072                          */
2073                         LIST_REMOVE(object, shadow_list);
2074                         KKASSERT(object->backing_object == backing_object);
2075                         backing_object->shadow_count--;
2076                         backing_object->generation++;
2077
2078                         /*
2079                          * backing_object->backing_object moves from within
2080                          * backing_object to within object.
2081                          */
2082                         while ((bbobj = backing_object->backing_object) != NULL) {
2083                                 vm_object_hold(bbobj);
2084                                 if (bbobj == backing_object->backing_object)
2085                                         break;
2086                                 vm_object_drop(bbobj);
2087                         }
2088                         if (bbobj) {
2089                                 LIST_REMOVE(backing_object, shadow_list);
2090                                 bbobj->shadow_count--;
2091                                 bbobj->generation++;
2092                                 backing_object->backing_object = NULL;
2093                         }
2094                         object->backing_object = bbobj;
2095                         if (bbobj) {
2096                                 LIST_INSERT_HEAD(&bbobj->shadow_head,
2097                                                  object, shadow_list);
2098                                 bbobj->shadow_count++;
2099                                 bbobj->generation++;
2100                         }
2101
2102                         object->backing_object_offset +=
2103                                 backing_object->backing_object_offset;
2104
2105                         vm_object_drop(bbobj);
2106
2107                         /*
2108                          * Discard the old backing_object.  Nothing should be
2109                          * able to ref it, other than a vm_map_split(),
2110                          * and vm_map_split() will stall on our chain lock.
2111                          * And we control the parent so it shouldn't be
2112                          * possible for it to go away either.
2113                          *
2114                          * Since the backing object has no pages, no pager
2115                          * left, and no object references within it, all
2116                          * that is necessary is to dispose of it.
2117                          */
2118                         KASSERT(backing_object->ref_count == 1,
2119                                 ("backing_object %p was somehow "
2120                                  "re-referenced during collapse!",
2121                                  backing_object));
2122                         KASSERT(RB_EMPTY(&backing_object->rb_memq),
2123                                 ("backing_object %p somehow has left "
2124                                  "over pages during collapse!",
2125                                  backing_object));
2126
2127                         /*
2128                          * The object can be destroyed.
2129                          *
2130                          * XXX just fall through and dodealloc instead
2131                          *     of forcing destruction?
2132                          */
2133                         --backing_object->ref_count;
2134                         if ((backing_object->flags & OBJ_DEAD) == 0)
2135                                 vm_object_terminate(backing_object);
2136                         object_collapses++;
2137                         dodealloc = 0;
2138                 } else {
2139                         /*
2140                          * If we do not entirely shadow the backing object,
2141                          * there is nothing we can do so we give up.
2142                          */
2143                         if (vm_object_backing_scan(object, backing_object,
2144                                                 OBSC_TEST_ALL_SHADOWED) == 0) {
2145                                 break;
2146                         }
2147
2148                         /*
2149                          * bbobj is backing_object->backing_object.  Since
2150                          * object completely shadows backing_object we can
2151                          * bypass it and become backed by bbobj instead.
2152                          */
2153                         while ((bbobj = backing_object->backing_object) != NULL) {
2154                                 vm_object_hold(bbobj);
2155                                 if (bbobj == backing_object->backing_object)
2156                                         break;
2157                                 vm_object_drop(bbobj);
2158                         }
2159
2160                         /*
2161                          * Make object shadow bbobj instead of backing_object.
2162                          * Remove object from backing_object's shadow list.
2163                          *
2164                          * Deallocating backing_object will not remove
2165                          * it, since its reference count is at least 2.
2166                          */
2167                         KKASSERT(object->backing_object == backing_object);
2168                         LIST_REMOVE(object, shadow_list);
2169                         backing_object->shadow_count--;
2170                         backing_object->generation++;
2171
2172                         /*
2173                          * Add a ref to bbobj, bbobj now shadows object.
2174                          *
2175                          * NOTE: backing_object->backing_object still points
2176                          *       to bbobj.  That relationship remains intact
2177                          *       because backing_object has > 1 ref, so
2178                          *       someone else is pointing to it (hence why
2179                          *       we can't collapse it into object and can
2180                          *       only handle the all-shadowed bypass case).
2181                          */
2182                         if (bbobj) {
2183                                 vm_object_chain_wait(bbobj);
2184                                 vm_object_reference_locked(bbobj);
2185                                 LIST_INSERT_HEAD(&bbobj->shadow_head,
2186                                                  object, shadow_list);
2187                                 bbobj->shadow_count++;
2188                                 bbobj->generation++;
2189                                 object->backing_object_offset +=
2190                                         backing_object->backing_object_offset;
2191                                 object->backing_object = bbobj;
2192                                 vm_object_drop(bbobj);
2193                         } else {
2194                                 object->backing_object = NULL;
2195                         }
2196
2197                         /*
2198                          * Drop the reference count on backing_object.  To
2199                          * handle ref_count races properly we can't assume
2200                          * that the ref_count is still at least 2 so we
2201                          * have to actually call vm_object_deallocate()
2202                          * (after clearing the chainlock).
2203                          */
2204                         object_bypasses++;
2205                         dodealloc = 1;
2206                 }
2207
2208                 /*
2209                  * Ok, we want to loop on the new object->bbobj association,
2210                  * possibly collapsing it further.  However if dodealloc is
2211                  * non-zero we have to deallocate the backing_object which
2212                  * itself can potentially undergo a collapse, creating a
2213                  * recursion depth issue with the LWKT token subsystem.
2214                  *
2215                  * In the case where we must deallocate the backing_object
2216                  * it is possible now that the backing_object has a single
2217                  * shadow count on some other object (not represented here
2218                  * as yet), since it no longer shadows us.  Thus when we
2219                  * call vm_object_deallocate() it may attempt to collapse
2220                  * itself into its remaining parent.
2221                  */
2222                 if (dodealloc) {
2223                         struct vm_object_dealloc_list *dtmp;
2224
2225                         vm_object_chain_release(backing_object);
2226                         vm_object_unlock(backing_object);
2227                         /* backing_object remains held */
2228
2229                         /*
2230                          * Auto-deallocation list for caller convenience.
2231                          */
2232                         if (dlistp == NULL)
2233                                 dlistp = &dlist;
2234
2235                         dtmp = kmalloc(sizeof(*dtmp), M_TEMP, M_WAITOK);
2236                         dtmp->object = backing_object;
2237                         dtmp->next = *dlistp;
2238                         *dlistp = dtmp;
2239                 } else {
2240                         vm_object_chain_release(backing_object);
2241                         vm_object_drop(backing_object);
2242                 }
2243                 /* backing_object = NULL; not needed */
2244                 /* loop */
2245         }
2246
2247         /*
2248          * Clean up any left over backing_object
2249          */
2250         if (backing_object) {
2251                 vm_object_chain_release(backing_object);
2252                 vm_object_drop(backing_object);
2253         }
2254
2255         /*
2256          * Clean up any auto-deallocation list.  This is a convenience
2257          * for top-level callers so they don't have to pass &dlist.
2258          * Do not clean up any caller-passed dlistp, the caller will
2259          * do that.
2260          */
2261         if (dlist)
2262                 vm_object_deallocate_list(&dlist);
2263
2264 }
2265
2266 /*
2267  * vm_object_collapse() may collect additional objects in need of
2268  * deallocation.  This routine deallocates these objects.  The
2269  * deallocation itself can trigger additional collapses (which the
2270  * deallocate function takes care of).  This procedure is used to
2271  * reduce procedural recursion since these vm_object shadow chains
2272  * can become quite long.
2273  */
2274 void
2275 vm_object_deallocate_list(struct vm_object_dealloc_list **dlistp)
2276 {
2277         struct vm_object_dealloc_list *dlist;
2278
2279         while ((dlist = *dlistp) != NULL) {
2280                 *dlistp = dlist->next;
2281                 vm_object_lock(dlist->object);
2282                 vm_object_deallocate_locked(dlist->object);
2283                 vm_object_drop(dlist->object);
2284                 kfree(dlist, M_TEMP);
2285         }
2286 }
2287
2288 /*
2289  * Removes all physical pages in the specified object range from the
2290  * object's list of pages.
2291  *
2292  * No requirements.
2293  */
2294 static int vm_object_page_remove_callback(vm_page_t p, void *data);
2295
2296 void
2297 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
2298                       boolean_t clean_only)
2299 {
2300         struct rb_vm_page_scan_info info;
2301         int all;
2302
2303         /*
2304          * Degenerate cases and assertions
2305          */
2306         vm_object_hold(object);
2307         if (object == NULL ||
2308             (object->resident_page_count == 0 && object->swblock_count == 0)) {
2309                 vm_object_drop(object);
2310                 return;
2311         }
2312         KASSERT(object->type != OBJT_PHYS, 
2313                 ("attempt to remove pages from a physical object"));
2314
2315         /*
2316          * Indicate that paging is occuring on the object
2317          */
2318         vm_object_pip_add(object, 1);
2319
2320         /*
2321          * Figure out the actual removal range and whether we are removing
2322          * the entire contents of the object or not.  If removing the entire
2323          * contents, be sure to get all pages, even those that might be 
2324          * beyond the end of the object.
2325          */
2326         info.start_pindex = start;
2327         if (end == 0)
2328                 info.end_pindex = (vm_pindex_t)-1;
2329         else
2330                 info.end_pindex = end - 1;
2331         info.limit = clean_only;
2332         all = (start == 0 && info.end_pindex >= object->size - 1);
2333
2334         /*
2335          * Loop until we are sure we have gotten them all.
2336          */
2337         do {
2338                 info.error = 0;
2339                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
2340                                         vm_object_page_remove_callback, &info);
2341         } while (info.error);
2342
2343         /*
2344          * Remove any related swap if throwing away pages, or for
2345          * non-swap objects (the swap is a clean copy in that case).
2346          */
2347         if (object->type != OBJT_SWAP || clean_only == FALSE) {
2348                 if (all)
2349                         swap_pager_freespace_all(object);
2350                 else
2351                         swap_pager_freespace(object, info.start_pindex,
2352                              info.end_pindex - info.start_pindex + 1);
2353         }
2354
2355         /*
2356          * Cleanup
2357          */
2358         vm_object_pip_wakeup(object);
2359         vm_object_drop(object);
2360 }
2361
2362 /*
2363  * The caller must hold the object
2364  */
2365 static int
2366 vm_object_page_remove_callback(vm_page_t p, void *data)
2367 {
2368         struct rb_vm_page_scan_info *info = data;
2369
2370         if (vm_page_busy_try(p, TRUE)) {
2371                 vm_page_sleep_busy(p, TRUE, "vmopar");
2372                 info->error = 1;
2373                 return(0);
2374         }
2375
2376         /*
2377          * Wired pages cannot be destroyed, but they can be invalidated
2378          * and we do so if clean_only (limit) is not set.
2379          *
2380          * WARNING!  The page may be wired due to being part of a buffer
2381          *           cache buffer, and the buffer might be marked B_CACHE.
2382          *           This is fine as part of a truncation but VFSs must be
2383          *           sure to fix the buffer up when re-extending the file.
2384          *
2385          * NOTE!     PG_NEED_COMMIT is ignored.
2386          */
2387         if (p->wire_count != 0) {
2388                 vm_page_protect(p, VM_PROT_NONE);
2389                 if (info->limit == 0)
2390                         p->valid = 0;
2391                 vm_page_wakeup(p);
2392                 return(0);
2393         }
2394
2395         /*
2396          * limit is our clean_only flag.  If set and the page is dirty or
2397          * requires a commit, do not free it.  If set and the page is being
2398          * held by someone, do not free it.
2399          */
2400         if (info->limit && p->valid) {
2401                 vm_page_test_dirty(p);
2402                 if ((p->valid & p->dirty) || (p->flags & PG_NEED_COMMIT)) {
2403                         vm_page_wakeup(p);
2404                         return(0);
2405                 }
2406 #if 0
2407                 if (p->hold_count) {
2408                         vm_page_wakeup(p);
2409                         return(0);
2410                 }
2411 #endif
2412         }
2413
2414         /*
2415          * Destroy the page
2416          */
2417         vm_page_protect(p, VM_PROT_NONE);
2418         vm_page_free(p);
2419         return(0);
2420 }
2421
2422 /*
2423  * Coalesces two objects backing up adjoining regions of memory into a
2424  * single object.
2425  *
2426  * returns TRUE if objects were combined.
2427  *
2428  * NOTE: Only works at the moment if the second object is NULL -
2429  *       if it's not, which object do we lock first?
2430  *
2431  * Parameters:
2432  *      prev_object     First object to coalesce
2433  *      prev_offset     Offset into prev_object
2434  *      next_object     Second object into coalesce
2435  *      next_offset     Offset into next_object
2436  *
2437  *      prev_size       Size of reference to prev_object
2438  *      next_size       Size of reference to next_object
2439  *
2440  * The caller does not need to hold (prev_object) but must have a stable
2441  * pointer to it (typically by holding the vm_map locked).
2442  */
2443 boolean_t
2444 vm_object_coalesce(vm_object_t prev_object, vm_pindex_t prev_pindex,
2445                    vm_size_t prev_size, vm_size_t next_size)
2446 {
2447         vm_pindex_t next_pindex;
2448
2449         if (prev_object == NULL)
2450                 return (TRUE);
2451
2452         vm_object_hold(prev_object);
2453
2454         if (prev_object->type != OBJT_DEFAULT &&
2455             prev_object->type != OBJT_SWAP) {
2456                 vm_object_drop(prev_object);
2457                 return (FALSE);
2458         }
2459
2460         /*
2461          * Try to collapse the object first
2462          */
2463         vm_object_chain_acquire(prev_object);
2464         vm_object_collapse(prev_object, NULL);
2465
2466         /*
2467          * Can't coalesce if: . more than one reference . paged out . shadows
2468          * another object . has a copy elsewhere (any of which mean that the
2469          * pages not mapped to prev_entry may be in use anyway)
2470          */
2471
2472         if (prev_object->backing_object != NULL) {
2473                 vm_object_chain_release(prev_object);
2474                 vm_object_drop(prev_object);
2475                 return (FALSE);
2476         }
2477
2478         prev_size >>= PAGE_SHIFT;
2479         next_size >>= PAGE_SHIFT;
2480         next_pindex = prev_pindex + prev_size;
2481
2482         if ((prev_object->ref_count > 1) &&
2483             (prev_object->size != next_pindex)) {
2484                 vm_object_chain_release(prev_object);
2485                 vm_object_drop(prev_object);
2486                 return (FALSE);
2487         }
2488
2489         /*
2490          * Remove any pages that may still be in the object from a previous
2491          * deallocation.
2492          */
2493         if (next_pindex < prev_object->size) {
2494                 vm_object_page_remove(prev_object,
2495                                       next_pindex,
2496                                       next_pindex + next_size, FALSE);
2497                 if (prev_object->type == OBJT_SWAP)
2498                         swap_pager_freespace(prev_object,
2499                                              next_pindex, next_size);
2500         }
2501
2502         /*
2503          * Extend the object if necessary.
2504          */
2505         if (next_pindex + next_size > prev_object->size)
2506                 prev_object->size = next_pindex + next_size;
2507
2508         vm_object_chain_release(prev_object);
2509         vm_object_drop(prev_object);
2510         return (TRUE);
2511 }
2512
2513 /*
2514  * Make the object writable and flag is being possibly dirty.
2515  *
2516  * The caller must hold the object. XXX called from vm_page_dirty(),
2517  * There is currently no requirement to hold the object.
2518  */
2519 void
2520 vm_object_set_writeable_dirty(vm_object_t object)
2521 {
2522         struct vnode *vp;
2523
2524         /*vm_object_assert_held(object);*/
2525         /*
2526          * Avoid contention in vm fault path by checking the state before
2527          * issuing an atomic op on it.
2528          */
2529         if ((object->flags & (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) !=
2530             (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) {
2531                 vm_object_set_flag(object, OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
2532         }
2533         if (object->type == OBJT_VNODE &&
2534             (vp = (struct vnode *)object->handle) != NULL) {
2535                 if ((vp->v_flag & VOBJDIRTY) == 0) {
2536                         vsetflags(vp, VOBJDIRTY);
2537                 }
2538         }
2539 }
2540
2541 #include "opt_ddb.h"
2542 #ifdef DDB
2543 #include <sys/kernel.h>
2544
2545 #include <sys/cons.h>
2546
2547 #include <ddb/ddb.h>
2548
2549 static int      _vm_object_in_map (vm_map_t map, vm_object_t object,
2550                                        vm_map_entry_t entry);
2551 static int      vm_object_in_map (vm_object_t object);
2552
2553 /*
2554  * The caller must hold the object.
2555  */
2556 static int
2557 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
2558 {
2559         vm_map_t tmpm;
2560         vm_map_entry_t tmpe;
2561         vm_object_t obj, nobj;
2562         int entcount;
2563
2564         if (map == 0)
2565                 return 0;
2566         if (entry == 0) {
2567                 tmpe = map->header.next;
2568                 entcount = map->nentries;
2569                 while (entcount-- && (tmpe != &map->header)) {
2570                         if( _vm_object_in_map(map, object, tmpe)) {
2571                                 return 1;
2572                         }
2573                         tmpe = tmpe->next;
2574                 }
2575                 return (0);
2576         }
2577         switch(entry->maptype) {
2578         case VM_MAPTYPE_SUBMAP:
2579                 tmpm = entry->object.sub_map;
2580                 tmpe = tmpm->header.next;
2581                 entcount = tmpm->nentries;
2582                 while (entcount-- && tmpe != &tmpm->header) {
2583                         if( _vm_object_in_map(tmpm, object, tmpe)) {
2584                                 return 1;
2585                         }
2586                         tmpe = tmpe->next;
2587                 }
2588                 break;
2589         case VM_MAPTYPE_NORMAL:
2590         case VM_MAPTYPE_VPAGETABLE:
2591                 obj = entry->object.vm_object;
2592                 while (obj) {
2593                         if (obj == object) {
2594                                 if (obj != entry->object.vm_object)
2595                                         vm_object_drop(obj);
2596                                 return 1;
2597                         }
2598                         while ((nobj = obj->backing_object) != NULL) {
2599                                 vm_object_hold(nobj);
2600                                 if (nobj == obj->backing_object)
2601                                         break;
2602                                 vm_object_drop(nobj);
2603                         }
2604                         if (obj != entry->object.vm_object) {
2605                                 if (nobj)
2606                                         vm_object_lock_swap();
2607                                 vm_object_drop(obj);
2608                         }
2609                         obj = nobj;
2610                 }
2611                 break;
2612         default:
2613                 break;
2614         }
2615         return 0;
2616 }
2617
2618 static int vm_object_in_map_callback(struct proc *p, void *data);
2619
2620 struct vm_object_in_map_info {
2621         vm_object_t object;
2622         int rv;
2623 };
2624
2625 /*
2626  * Debugging only
2627  */
2628 static int
2629 vm_object_in_map(vm_object_t object)
2630 {
2631         struct vm_object_in_map_info info;
2632
2633         info.rv = 0;
2634         info.object = object;
2635
2636         allproc_scan(vm_object_in_map_callback, &info);
2637         if (info.rv)
2638                 return 1;
2639         if( _vm_object_in_map(&kernel_map, object, 0))
2640                 return 1;
2641         if( _vm_object_in_map(&pager_map, object, 0))
2642                 return 1;
2643         if( _vm_object_in_map(&buffer_map, object, 0))
2644                 return 1;
2645         return 0;
2646 }
2647
2648 /*
2649  * Debugging only
2650  */
2651 static int
2652 vm_object_in_map_callback(struct proc *p, void *data)
2653 {
2654         struct vm_object_in_map_info *info = data;
2655
2656         if (p->p_vmspace) {
2657                 if (_vm_object_in_map(&p->p_vmspace->vm_map, info->object, 0)) {
2658                         info->rv = 1;
2659                         return -1;
2660                 }
2661         }
2662         return (0);
2663 }
2664
2665 DB_SHOW_COMMAND(vmochk, vm_object_check)
2666 {
2667         vm_object_t object;
2668
2669         /*
2670          * make sure that internal objs are in a map somewhere
2671          * and none have zero ref counts.
2672          */
2673         for (object = TAILQ_FIRST(&vm_object_list);
2674                         object != NULL;
2675                         object = TAILQ_NEXT(object, object_list)) {
2676                 if (object->type == OBJT_MARKER)
2677                         continue;
2678                 if (object->handle == NULL &&
2679                     (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2680                         if (object->ref_count == 0) {
2681                                 db_printf("vmochk: internal obj has zero ref count: %ld\n",
2682                                         (long)object->size);
2683                         }
2684                         if (!vm_object_in_map(object)) {
2685                                 db_printf(
2686                         "vmochk: internal obj is not in a map: "
2687                         "ref: %d, size: %lu: 0x%lx, backing_object: %p\n",
2688                                     object->ref_count, (u_long)object->size, 
2689                                     (u_long)object->size,
2690                                     (void *)object->backing_object);
2691                         }
2692                 }
2693         }
2694 }
2695
2696 /*
2697  * Debugging only
2698  */
2699 DB_SHOW_COMMAND(object, vm_object_print_static)
2700 {
2701         /* XXX convert args. */
2702         vm_object_t object = (vm_object_t)addr;
2703         boolean_t full = have_addr;
2704
2705         vm_page_t p;
2706
2707         /* XXX count is an (unused) arg.  Avoid shadowing it. */
2708 #define count   was_count
2709
2710         int count;
2711
2712         if (object == NULL)
2713                 return;
2714
2715         db_iprintf(
2716             "Object %p: type=%d, size=0x%lx, res=%d, ref=%d, flags=0x%x\n",
2717             object, (int)object->type, (u_long)object->size,
2718             object->resident_page_count, object->ref_count, object->flags);
2719         /*
2720          * XXX no %qd in kernel.  Truncate object->backing_object_offset.
2721          */
2722         db_iprintf(" sref=%d, backing_object(%d)=(%p)+0x%lx\n",
2723             object->shadow_count, 
2724             object->backing_object ? object->backing_object->ref_count : 0,
2725             object->backing_object, (long)object->backing_object_offset);
2726
2727         if (!full)
2728                 return;
2729
2730         db_indent += 2;
2731         count = 0;
2732         RB_FOREACH(p, vm_page_rb_tree, &object->rb_memq) {
2733                 if (count == 0)
2734                         db_iprintf("memory:=");
2735                 else if (count == 6) {
2736                         db_printf("\n");
2737                         db_iprintf(" ...");
2738                         count = 0;
2739                 } else
2740                         db_printf(",");
2741                 count++;
2742
2743                 db_printf("(off=0x%lx,page=0x%lx)",
2744                     (u_long) p->pindex, (u_long) VM_PAGE_TO_PHYS(p));
2745         }
2746         if (count != 0)
2747                 db_printf("\n");
2748         db_indent -= 2;
2749 }
2750
2751 /* XXX. */
2752 #undef count
2753
2754 /*
2755  * XXX need this non-static entry for calling from vm_map_print.
2756  *
2757  * Debugging only
2758  */
2759 void
2760 vm_object_print(/* db_expr_t */ long addr,
2761                 boolean_t have_addr,
2762                 /* db_expr_t */ long count,
2763                 char *modif)
2764 {
2765         vm_object_print_static(addr, have_addr, count, modif);
2766 }
2767
2768 /*
2769  * Debugging only
2770  */
2771 DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
2772 {
2773         vm_object_t object;
2774         int nl = 0;
2775         int c;
2776         for (object = TAILQ_FIRST(&vm_object_list);
2777                         object != NULL;
2778                         object = TAILQ_NEXT(object, object_list)) {
2779                 vm_pindex_t idx, fidx;
2780                 vm_pindex_t osize;
2781                 vm_paddr_t pa = -1, padiff;
2782                 int rcount;
2783                 vm_page_t m;
2784
2785                 if (object->type == OBJT_MARKER)
2786                         continue;
2787                 db_printf("new object: %p\n", (void *)object);
2788                 if ( nl > 18) {
2789                         c = cngetc();
2790                         if (c != ' ')
2791                                 return;
2792                         nl = 0;
2793                 }
2794                 nl++;
2795                 rcount = 0;
2796                 fidx = 0;
2797                 osize = object->size;
2798                 if (osize > 128)
2799                         osize = 128;
2800                 for (idx = 0; idx < osize; idx++) {
2801                         m = vm_page_lookup(object, idx);
2802                         if (m == NULL) {
2803                                 if (rcount) {
2804                                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2805                                                 (long)fidx, rcount, (long)pa);
2806                                         if ( nl > 18) {
2807                                                 c = cngetc();
2808                                                 if (c != ' ')
2809                                                         return;
2810                                                 nl = 0;
2811                                         }
2812                                         nl++;
2813                                         rcount = 0;
2814                                 }
2815                                 continue;
2816                         }
2817
2818                                 
2819                         if (rcount &&
2820                                 (VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
2821                                 ++rcount;
2822                                 continue;
2823                         }
2824                         if (rcount) {
2825                                 padiff = pa + rcount * PAGE_SIZE - VM_PAGE_TO_PHYS(m);
2826                                 padiff >>= PAGE_SHIFT;
2827                                 padiff &= PQ_L2_MASK;
2828                                 if (padiff == 0) {
2829                                         pa = VM_PAGE_TO_PHYS(m) - rcount * PAGE_SIZE;
2830                                         ++rcount;
2831                                         continue;
2832                                 }
2833                                 db_printf(" index(%ld)run(%d)pa(0x%lx)",
2834                                         (long)fidx, rcount, (long)pa);
2835                                 db_printf("pd(%ld)\n", (long)padiff);
2836                                 if ( nl > 18) {
2837                                         c = cngetc();
2838                                         if (c != ' ')
2839                                                 return;
2840                                         nl = 0;
2841                                 }
2842                                 nl++;
2843                         }
2844                         fidx = idx;
2845                         pa = VM_PAGE_TO_PHYS(m);
2846                         rcount = 1;
2847                 }
2848                 if (rcount) {
2849                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2850                                 (long)fidx, rcount, (long)pa);
2851                         if ( nl > 18) {
2852                                 c = cngetc();
2853                                 if (c != ' ')
2854                                         return;
2855                                 nl = 0;
2856                         }
2857                         nl++;
2858                 }
2859         }
2860 }
2861 #endif /* DDB */