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