kernel - Improve pageout daemon for tmpfs write load
[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         ib = page_base - 1;
1296         is = page_base + 1;
1297
1298         while (ib >= 0) {
1299                 vm_page_t tp;
1300
1301                 tp = vm_page_lookup_busy_try(object, pi - page_base + ib,
1302                                              TRUE, &error);
1303                 if (error)
1304                         break;
1305                 if (tp == NULL)
1306                         break;
1307                 if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1308                     (tp->flags & PG_CLEANCHK) == 0) {
1309                         vm_page_wakeup(tp);
1310                         break;
1311                 }
1312                 if ((tp->queue - tp->pc) == PQ_CACHE) {
1313                         vm_page_flag_clear(tp, PG_CLEANCHK);
1314                         vm_page_wakeup(tp);
1315                         break;
1316                 }
1317                 vm_page_test_dirty(tp);
1318                 if ((tp->dirty & tp->valid) == 0 &&
1319                     (tp->flags & PG_NEED_COMMIT) == 0) {
1320                         vm_page_flag_clear(tp, PG_CLEANCHK);
1321                         vm_page_wakeup(tp);
1322                         break;
1323                 }
1324                 ma[ib] = tp;
1325                 --ib;
1326         }
1327         ++ib;   /* fixup */
1328
1329         while (is < BLIST_MAX_ALLOC &&
1330                pi - page_base + is < object->size) {
1331                 vm_page_t tp;
1332
1333                 tp = vm_page_lookup_busy_try(object, pi - page_base + is,
1334                                              TRUE, &error);
1335                 if (error)
1336                         break;
1337                 if (tp == NULL)
1338                         break;
1339                 if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1340                     (tp->flags & PG_CLEANCHK) == 0) {
1341                         vm_page_wakeup(tp);
1342                         break;
1343                 }
1344                 if ((tp->queue - tp->pc) == PQ_CACHE) {
1345                         vm_page_flag_clear(tp, PG_CLEANCHK);
1346                         vm_page_wakeup(tp);
1347                         break;
1348                 }
1349                 vm_page_test_dirty(tp);
1350                 if ((tp->dirty & tp->valid) == 0 &&
1351                     (tp->flags & PG_NEED_COMMIT) == 0) {
1352                         vm_page_flag_clear(tp, PG_CLEANCHK);
1353                         vm_page_wakeup(tp);
1354                         break;
1355                 }
1356                 ma[is] = tp;
1357                 ++is;
1358         }
1359
1360         /*
1361          * All pages in the ma[] array are busied now
1362          */
1363         for (i = ib; i < is; ++i) {
1364                 vm_page_flag_clear(ma[i], PG_CLEANCHK);
1365                 vm_page_hold(ma[i]);    /* XXX need this any more? */
1366         }
1367         vm_pageout_flush(&ma[ib], is - ib, pagerflags);
1368         for (i = ib; i < is; ++i)       /* XXX need this any more? */
1369                 vm_page_unhold(ma[i]);
1370 }
1371
1372 /*
1373  * Same as vm_object_pmap_copy, except range checking really
1374  * works, and is meant for small sections of an object.
1375  *
1376  * This code protects resident pages by making them read-only
1377  * and is typically called on a fork or split when a page
1378  * is converted to copy-on-write.  
1379  *
1380  * NOTE: If the page is already at VM_PROT_NONE, calling
1381  * vm_page_protect will have no effect.
1382  */
1383 void
1384 vm_object_pmap_copy_1(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1385 {
1386         vm_pindex_t idx;
1387         vm_page_t p;
1388
1389         if (object == NULL || (object->flags & OBJ_WRITEABLE) == 0)
1390                 return;
1391
1392         vm_object_hold(object);
1393         for (idx = start; idx < end; idx++) {
1394                 p = vm_page_lookup(object, idx);
1395                 if (p == NULL)
1396                         continue;
1397                 vm_page_protect(p, VM_PROT_READ);
1398         }
1399         vm_object_drop(object);
1400 }
1401
1402 /*
1403  * Removes all physical pages in the specified object range from all
1404  * physical maps.
1405  *
1406  * The object must *not* be locked.
1407  */
1408
1409 static int vm_object_pmap_remove_callback(vm_page_t p, void *data);
1410
1411 void
1412 vm_object_pmap_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1413 {
1414         struct rb_vm_page_scan_info info;
1415
1416         if (object == NULL)
1417                 return;
1418         info.start_pindex = start;
1419         info.end_pindex = end - 1;
1420
1421         vm_object_hold(object);
1422         vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1423                                 vm_object_pmap_remove_callback, &info);
1424         if (start == 0 && end == object->size)
1425                 vm_object_clear_flag(object, OBJ_WRITEABLE);
1426         vm_object_drop(object);
1427 }
1428
1429 /*
1430  * The caller must hold the object
1431  */
1432 static int
1433 vm_object_pmap_remove_callback(vm_page_t p, void *data __unused)
1434 {
1435         vm_page_protect(p, VM_PROT_NONE);
1436         return(0);
1437 }
1438
1439 /*
1440  * Implements the madvise function at the object/page level.
1441  *
1442  * MADV_WILLNEED        (any object)
1443  *
1444  *      Activate the specified pages if they are resident.
1445  *
1446  * MADV_DONTNEED        (any object)
1447  *
1448  *      Deactivate the specified pages if they are resident.
1449  *
1450  * MADV_FREE    (OBJT_DEFAULT/OBJT_SWAP objects, OBJ_ONEMAPPING only)
1451  *
1452  *      Deactivate and clean the specified pages if they are
1453  *      resident.  This permits the process to reuse the pages
1454  *      without faulting or the kernel to reclaim the pages
1455  *      without I/O.
1456  *
1457  * No requirements.
1458  */
1459 void
1460 vm_object_madvise(vm_object_t object, vm_pindex_t pindex, int count, int advise)
1461 {
1462         vm_pindex_t end, tpindex;
1463         vm_object_t tobject;
1464         vm_object_t xobj;
1465         vm_page_t m;
1466         int error;
1467
1468         if (object == NULL)
1469                 return;
1470
1471         end = pindex + count;
1472
1473         vm_object_hold(object);
1474         tobject = object;
1475
1476         /*
1477          * Locate and adjust resident pages
1478          */
1479         for (; pindex < end; pindex += 1) {
1480 relookup:
1481                 if (tobject != object)
1482                         vm_object_drop(tobject);
1483                 tobject = object;
1484                 tpindex = pindex;
1485 shadowlookup:
1486                 /*
1487                  * MADV_FREE only operates on OBJT_DEFAULT or OBJT_SWAP pages
1488                  * and those pages must be OBJ_ONEMAPPING.
1489                  */
1490                 if (advise == MADV_FREE) {
1491                         if ((tobject->type != OBJT_DEFAULT &&
1492                              tobject->type != OBJT_SWAP) ||
1493                             (tobject->flags & OBJ_ONEMAPPING) == 0) {
1494                                 continue;
1495                         }
1496                 }
1497
1498                 m = vm_page_lookup_busy_try(tobject, tpindex, TRUE, &error);
1499
1500                 if (error) {
1501                         vm_page_sleep_busy(m, TRUE, "madvpo");
1502                         goto relookup;
1503                 }
1504                 if (m == NULL) {
1505                         /*
1506                          * There may be swap even if there is no backing page
1507                          */
1508                         if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
1509                                 swap_pager_freespace(tobject, tpindex, 1);
1510
1511                         /*
1512                          * next object
1513                          */
1514                         while ((xobj = tobject->backing_object) != NULL) {
1515                                 KKASSERT(xobj != object);
1516                                 vm_object_hold(xobj);
1517                                 if (xobj == tobject->backing_object)
1518                                         break;
1519                                 vm_object_drop(xobj);
1520                         }
1521                         if (xobj == NULL)
1522                                 continue;
1523                         tpindex += OFF_TO_IDX(tobject->backing_object_offset);
1524                         if (tobject != object) {
1525                                 vm_object_lock_swap();
1526                                 vm_object_drop(tobject);
1527                         }
1528                         tobject = xobj;
1529                         goto shadowlookup;
1530                 }
1531
1532                 /*
1533                  * If the page is not in a normal active state, we skip it.
1534                  * If the page is not managed there are no page queues to
1535                  * mess with.  Things can break if we mess with pages in
1536                  * any of the below states.
1537                  */
1538                 if (m->wire_count ||
1539                     (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
1540                     m->valid != VM_PAGE_BITS_ALL
1541                 ) {
1542                         vm_page_wakeup(m);
1543                         continue;
1544                 }
1545
1546                 /*
1547                  * Theoretically once a page is known not to be busy, an
1548                  * interrupt cannot come along and rip it out from under us.
1549                  */
1550
1551                 if (advise == MADV_WILLNEED) {
1552                         vm_page_activate(m);
1553                 } else if (advise == MADV_DONTNEED) {
1554                         vm_page_dontneed(m);
1555                 } else if (advise == MADV_FREE) {
1556                         /*
1557                          * Mark the page clean.  This will allow the page
1558                          * to be freed up by the system.  However, such pages
1559                          * are often reused quickly by malloc()/free()
1560                          * so we do not do anything that would cause
1561                          * a page fault if we can help it.
1562                          *
1563                          * Specifically, we do not try to actually free
1564                          * the page now nor do we try to put it in the
1565                          * cache (which would cause a page fault on reuse).
1566                          *
1567                          * But we do make the page is freeable as we
1568                          * can without actually taking the step of unmapping
1569                          * it.
1570                          */
1571                         pmap_clear_modify(m);
1572                         m->dirty = 0;
1573                         m->act_count = 0;
1574                         vm_page_dontneed(m);
1575                         if (tobject->type == OBJT_SWAP)
1576                                 swap_pager_freespace(tobject, tpindex, 1);
1577                 }
1578                 vm_page_wakeup(m);
1579         }       
1580         if (tobject != object)
1581                 vm_object_drop(tobject);
1582         vm_object_drop(object);
1583 }
1584
1585 /*
1586  * Create a new object which is backed by the specified existing object
1587  * range.  Replace the pointer and offset that was pointing at the existing
1588  * object with the pointer/offset for the new object.
1589  *
1590  * No other requirements.
1591  */
1592 void
1593 vm_object_shadow(vm_object_t *objectp, vm_ooffset_t *offset, vm_size_t length,
1594                  int addref)
1595 {
1596         vm_object_t source;
1597         vm_object_t result;
1598
1599         source = *objectp;
1600
1601         /*
1602          * Don't create the new object if the old object isn't shared.
1603          * We have to chain wait before adding the reference to avoid
1604          * racing a collapse or deallocation.
1605          *
1606          * Add the additional ref to source here to avoid racing a later
1607          * collapse or deallocation. Clear the ONEMAPPING flag whether
1608          * addref is TRUE or not in this case because the original object
1609          * will be shadowed.
1610          */
1611         if (source) {
1612                 vm_object_hold(source);
1613                 vm_object_chain_wait(source);
1614                 if (source->ref_count == 1 &&
1615                     source->handle == NULL &&
1616                     (source->type == OBJT_DEFAULT ||
1617                      source->type == OBJT_SWAP)) {
1618                         vm_object_drop(source);
1619                         if (addref) {
1620                                 vm_object_reference_locked(source);
1621                                 vm_object_clear_flag(source, OBJ_ONEMAPPING);
1622                         }
1623                         return;
1624                 }
1625                 vm_object_reference_locked(source);
1626                 vm_object_clear_flag(source, OBJ_ONEMAPPING);
1627         }
1628
1629         /*
1630          * Allocate a new object with the given length.  The new object
1631          * is returned referenced but we may have to add another one.
1632          * If we are adding a second reference we must clear OBJ_ONEMAPPING.
1633          * (typically because the caller is about to clone a vm_map_entry).
1634          *
1635          * The source object currently has an extra reference to prevent
1636          * collapses into it while we mess with its shadow list, which
1637          * we will remove later in this routine.
1638          */
1639         if ((result = vm_object_allocate(OBJT_DEFAULT, length)) == NULL)
1640                 panic("vm_object_shadow: no object for shadowing");
1641         vm_object_hold(result);
1642         if (addref) {
1643                 vm_object_reference_locked(result);
1644                 vm_object_clear_flag(result, OBJ_ONEMAPPING);
1645         }
1646
1647         /*
1648          * The new object shadows the source object.  Chain wait before
1649          * adjusting shadow_count or the shadow list to avoid races.
1650          *
1651          * Try to optimize the result object's page color when shadowing
1652          * in order to maintain page coloring consistency in the combined 
1653          * shadowed object.
1654          */
1655         KKASSERT(result->backing_object == NULL);
1656         result->backing_object = source;
1657         if (source) {
1658                 vm_object_chain_wait(source);
1659                 LIST_INSERT_HEAD(&source->shadow_head, result, shadow_list);
1660                 source->shadow_count++;
1661                 source->generation++;
1662                 /* cpu localization twist */
1663                 result->pg_color = (int)(intptr_t)curthread;
1664         }
1665
1666         /*
1667          * Adjust the return storage.  Drop the ref on source before
1668          * returning.
1669          */
1670         result->backing_object_offset = *offset;
1671         vm_object_drop(result);
1672         *offset = 0;
1673         if (source) {
1674                 vm_object_deallocate_locked(source);
1675                 vm_object_drop(source);
1676         }
1677
1678         /*
1679          * Return the new things
1680          */
1681         *objectp = result;
1682 }
1683
1684 #define OBSC_TEST_ALL_SHADOWED  0x0001
1685 #define OBSC_COLLAPSE_NOWAIT    0x0002
1686 #define OBSC_COLLAPSE_WAIT      0x0004
1687
1688 static int vm_object_backing_scan_callback(vm_page_t p, void *data);
1689
1690 /*
1691  * The caller must hold the object.
1692  */
1693 static __inline int
1694 vm_object_backing_scan(vm_object_t object, vm_object_t backing_object, int op)
1695 {
1696         struct rb_vm_page_scan_info info;
1697
1698         vm_object_assert_held(object);
1699         vm_object_assert_held(backing_object);
1700
1701         KKASSERT(backing_object == object->backing_object);
1702         info.backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1703
1704         /*
1705          * Initial conditions
1706          */
1707         if (op & OBSC_TEST_ALL_SHADOWED) {
1708                 /*
1709                  * We do not want to have to test for the existence of
1710                  * swap pages in the backing object.  XXX but with the
1711                  * new swapper this would be pretty easy to do.
1712                  *
1713                  * XXX what about anonymous MAP_SHARED memory that hasn't
1714                  * been ZFOD faulted yet?  If we do not test for this, the
1715                  * shadow test may succeed! XXX
1716                  */
1717                 if (backing_object->type != OBJT_DEFAULT)
1718                         return(0);
1719         }
1720         if (op & OBSC_COLLAPSE_WAIT) {
1721                 KKASSERT((backing_object->flags & OBJ_DEAD) == 0);
1722                 vm_object_set_flag(backing_object, OBJ_DEAD);
1723                 lwkt_gettoken(&vmobj_token);
1724                 TAILQ_REMOVE(&vm_object_list, backing_object, object_list);
1725                 vm_object_count--;
1726                 lwkt_reltoken(&vmobj_token);
1727                 vm_object_dead_wakeup(backing_object);
1728         }
1729
1730         /*
1731          * Our scan.   We have to retry if a negative error code is returned,
1732          * otherwise 0 or 1 will be returned in info.error.  0 Indicates that
1733          * the scan had to be stopped because the parent does not completely
1734          * shadow the child.
1735          */
1736         info.object = object;
1737         info.backing_object = backing_object;
1738         info.limit = op;
1739         do {
1740                 info.error = 1;
1741                 vm_page_rb_tree_RB_SCAN(&backing_object->rb_memq, NULL,
1742                                         vm_object_backing_scan_callback,
1743                                         &info);
1744         } while (info.error < 0);
1745
1746         return(info.error);
1747 }
1748
1749 /*
1750  * The caller must hold the object.
1751  */
1752 static int
1753 vm_object_backing_scan_callback(vm_page_t p, void *data)
1754 {
1755         struct rb_vm_page_scan_info *info = data;
1756         vm_object_t backing_object;
1757         vm_object_t object;
1758         vm_pindex_t pindex;
1759         vm_pindex_t new_pindex;
1760         vm_pindex_t backing_offset_index;
1761         int op;
1762
1763         pindex = p->pindex;
1764         new_pindex = pindex - info->backing_offset_index;
1765         op = info->limit;
1766         object = info->object;
1767         backing_object = info->backing_object;
1768         backing_offset_index = info->backing_offset_index;
1769
1770         if (op & OBSC_TEST_ALL_SHADOWED) {
1771                 vm_page_t pp;
1772
1773                 /*
1774                  * Ignore pages outside the parent object's range
1775                  * and outside the parent object's mapping of the 
1776                  * backing object.
1777                  *
1778                  * note that we do not busy the backing object's
1779                  * page.
1780                  */
1781                 if (pindex < backing_offset_index ||
1782                     new_pindex >= object->size
1783                 ) {
1784                         return(0);
1785                 }
1786
1787                 /*
1788                  * See if the parent has the page or if the parent's
1789                  * object pager has the page.  If the parent has the
1790                  * page but the page is not valid, the parent's
1791                  * object pager must have the page.
1792                  *
1793                  * If this fails, the parent does not completely shadow
1794                  * the object and we might as well give up now.
1795                  */
1796                 pp = vm_page_lookup(object, new_pindex);
1797                 if ((pp == NULL || pp->valid == 0) &&
1798                     !vm_pager_has_page(object, new_pindex)
1799                 ) {
1800                         info->error = 0;        /* problemo */
1801                         return(-1);             /* stop the scan */
1802                 }
1803         }
1804
1805         /*
1806          * Check for busy page.  Note that we may have lost (p) when we
1807          * possibly blocked above.
1808          */
1809         if (op & (OBSC_COLLAPSE_WAIT | OBSC_COLLAPSE_NOWAIT)) {
1810                 vm_page_t pp;
1811
1812                 if (vm_page_busy_try(p, TRUE)) {
1813                         if (op & OBSC_COLLAPSE_NOWAIT) {
1814                                 return(0);
1815                         } else {
1816                                 /*
1817                                  * If we slept, anything could have
1818                                  * happened.   Ask that the scan be restarted.
1819                                  *
1820                                  * Since the object is marked dead, the
1821                                  * backing offset should not have changed.  
1822                                  */
1823                                 vm_page_sleep_busy(p, TRUE, "vmocol");
1824                                 info->error = -1;
1825                                 return(-1);
1826                         }
1827                 }
1828
1829                 /*
1830                  * If (p) is no longer valid restart the scan.
1831                  */
1832                 if (p->object != backing_object || p->pindex != pindex) {
1833                         kprintf("vm_object_backing_scan: Warning: page "
1834                                 "%p ripped out from under us\n", p);
1835                         vm_page_wakeup(p);
1836                         info->error = -1;
1837                         return(-1);
1838                 }
1839
1840                 if (op & OBSC_COLLAPSE_NOWAIT) {
1841                         if (p->valid == 0 ||
1842                             p->wire_count ||
1843                             (p->flags & PG_NEED_COMMIT)) {
1844                                 vm_page_wakeup(p);
1845                                 return(0);
1846                         }
1847                 } else {
1848                         /* XXX what if p->valid == 0 , hold_count, etc? */
1849                 }
1850
1851                 KASSERT(
1852                     p->object == backing_object,
1853                     ("vm_object_qcollapse(): object mismatch")
1854                 );
1855
1856                 /*
1857                  * Destroy any associated swap
1858                  */
1859                 if (backing_object->type == OBJT_SWAP)
1860                         swap_pager_freespace(backing_object, p->pindex, 1);
1861
1862                 if (
1863                     p->pindex < backing_offset_index ||
1864                     new_pindex >= object->size
1865                 ) {
1866                         /*
1867                          * Page is out of the parent object's range, we 
1868                          * can simply destroy it. 
1869                          */
1870                         vm_page_protect(p, VM_PROT_NONE);
1871                         vm_page_free(p);
1872                         return(0);
1873                 }
1874
1875                 pp = vm_page_lookup(object, new_pindex);
1876                 if (pp != NULL || vm_pager_has_page(object, new_pindex)) {
1877                         /*
1878                          * page already exists in parent OR swap exists
1879                          * for this location in the parent.  Destroy 
1880                          * the original page from the backing object.
1881                          *
1882                          * Leave the parent's page alone
1883                          */
1884                         vm_page_protect(p, VM_PROT_NONE);
1885                         vm_page_free(p);
1886                         return(0);
1887                 }
1888
1889                 /*
1890                  * Page does not exist in parent, rename the
1891                  * page from the backing object to the main object. 
1892                  *
1893                  * If the page was mapped to a process, it can remain 
1894                  * mapped through the rename.
1895                  */
1896                 if ((p->queue - p->pc) == PQ_CACHE)
1897                         vm_page_deactivate(p);
1898
1899                 vm_page_rename(p, object, new_pindex);
1900                 vm_page_wakeup(p);
1901                 /* page automatically made dirty by rename */
1902         }
1903         return(0);
1904 }
1905
1906 /*
1907  * This version of collapse allows the operation to occur earlier and
1908  * when paging_in_progress is true for an object...  This is not a complete
1909  * operation, but should plug 99.9% of the rest of the leaks.
1910  *
1911  * The caller must hold the object and backing_object and both must be
1912  * chainlocked.
1913  *
1914  * (only called from vm_object_collapse)
1915  */
1916 static void
1917 vm_object_qcollapse(vm_object_t object, vm_object_t backing_object)
1918 {
1919         if (backing_object->ref_count == 1) {
1920                 backing_object->ref_count += 2;
1921                 vm_object_backing_scan(object, backing_object,
1922                                        OBSC_COLLAPSE_NOWAIT);
1923                 backing_object->ref_count -= 2;
1924         }
1925 }
1926
1927 /*
1928  * Collapse an object with the object backing it.  Pages in the backing
1929  * object are moved into the parent, and the backing object is deallocated.
1930  * Any conflict is resolved in favor of the parent's existing pages.
1931  *
1932  * object must be held and chain-locked on call.
1933  *
1934  * The caller must have an extra ref on object to prevent a race from
1935  * destroying it during the collapse.
1936  */
1937 void
1938 vm_object_collapse(vm_object_t object, struct vm_object_dealloc_list **dlistp)
1939 {
1940         struct vm_object_dealloc_list *dlist = NULL;
1941         vm_object_t backing_object;
1942
1943         /*
1944          * Only one thread is attempting a collapse at any given moment.
1945          * There are few restrictions for (object) that callers of this
1946          * function check so reentrancy is likely.
1947          */
1948         KKASSERT(object != NULL);
1949         vm_object_assert_held(object);
1950         KKASSERT(object->flags & OBJ_CHAINLOCK);
1951
1952         for (;;) {
1953                 vm_object_t bbobj;
1954                 int dodealloc;
1955
1956                 /*
1957                  * We have to hold the backing object, check races.
1958                  */
1959                 while ((backing_object = object->backing_object) != NULL) {
1960                         vm_object_hold(backing_object);
1961                         if (backing_object == object->backing_object)
1962                                 break;
1963                         vm_object_drop(backing_object);
1964                 }
1965
1966                 /*
1967                  * No backing object?  Nothing to collapse then.
1968                  */
1969                 if (backing_object == NULL)
1970                         break;
1971
1972                 /*
1973                  * You can't collapse with a non-default/non-swap object.
1974                  */
1975                 if (backing_object->type != OBJT_DEFAULT &&
1976                     backing_object->type != OBJT_SWAP) {
1977                         vm_object_drop(backing_object);
1978                         backing_object = NULL;
1979                         break;
1980                 }
1981
1982                 /*
1983                  * Chain-lock the backing object too because if we
1984                  * successfully merge its pages into the top object we
1985                  * will collapse backing_object->backing_object as the
1986                  * new backing_object.  Re-check that it is still our
1987                  * backing object.
1988                  */
1989                 vm_object_chain_acquire(backing_object);
1990                 if (backing_object != object->backing_object) {
1991                         vm_object_chain_release(backing_object);
1992                         vm_object_drop(backing_object);
1993                         continue;
1994                 }
1995
1996                 /*
1997                  * we check the backing object first, because it is most likely
1998                  * not collapsable.
1999                  */
2000                 if (backing_object->handle != NULL ||
2001                     (backing_object->type != OBJT_DEFAULT &&
2002                      backing_object->type != OBJT_SWAP) ||
2003                     (backing_object->flags & OBJ_DEAD) ||
2004                     object->handle != NULL ||
2005                     (object->type != OBJT_DEFAULT &&
2006                      object->type != OBJT_SWAP) ||
2007                     (object->flags & OBJ_DEAD)) {
2008                         break;
2009                 }
2010
2011                 /*
2012                  * If paging is in progress we can't do a normal collapse.
2013                  */
2014                 if (
2015                     object->paging_in_progress != 0 ||
2016                     backing_object->paging_in_progress != 0
2017                 ) {
2018                         vm_object_qcollapse(object, backing_object);
2019                         break;
2020                 }
2021
2022                 /*
2023                  * We know that we can either collapse the backing object (if
2024                  * the parent is the only reference to it) or (perhaps) have
2025                  * the parent bypass the object if the parent happens to shadow
2026                  * all the resident pages in the entire backing object.
2027                  *
2028                  * This is ignoring pager-backed pages such as swap pages.
2029                  * vm_object_backing_scan fails the shadowing test in this
2030                  * case.
2031                  */
2032                 if (backing_object->ref_count == 1) {
2033                         /*
2034                          * If there is exactly one reference to the backing
2035                          * object, we can collapse it into the parent.  
2036                          */
2037                         KKASSERT(object->backing_object == backing_object);
2038                         vm_object_backing_scan(object, backing_object,
2039                                                OBSC_COLLAPSE_WAIT);
2040
2041                         /*
2042                          * Move the pager from backing_object to object.
2043                          */
2044                         if (backing_object->type == OBJT_SWAP) {
2045                                 vm_object_pip_add(backing_object, 1);
2046
2047                                 /*
2048                                  * scrap the paging_offset junk and do a 
2049                                  * discrete copy.  This also removes major 
2050                                  * assumptions about how the swap-pager 
2051                                  * works from where it doesn't belong.  The
2052                                  * new swapper is able to optimize the
2053                                  * destroy-source case.
2054                                  */
2055                                 vm_object_pip_add(object, 1);
2056                                 swap_pager_copy(backing_object, object,
2057                                     OFF_TO_IDX(object->backing_object_offset),
2058                                     TRUE);
2059                                 vm_object_pip_wakeup(object);
2060                                 vm_object_pip_wakeup(backing_object);
2061                         }
2062
2063                         /*
2064                          * Object now shadows whatever backing_object did.
2065                          * Remove object from backing_object's shadow_list.
2066                          */
2067                         LIST_REMOVE(object, shadow_list);
2068                         KKASSERT(object->backing_object == backing_object);
2069                         backing_object->shadow_count--;
2070                         backing_object->generation++;
2071
2072                         /*
2073                          * backing_object->backing_object moves from within
2074                          * backing_object to within object.
2075                          */
2076                         while ((bbobj = backing_object->backing_object) != NULL) {
2077                                 vm_object_hold(bbobj);
2078                                 if (bbobj == backing_object->backing_object)
2079                                         break;
2080                                 vm_object_drop(bbobj);
2081                         }
2082                         if (bbobj) {
2083                                 LIST_REMOVE(backing_object, shadow_list);
2084                                 bbobj->shadow_count--;
2085                                 bbobj->generation++;
2086                                 backing_object->backing_object = NULL;
2087                         }
2088                         object->backing_object = bbobj;
2089                         if (bbobj) {
2090                                 LIST_INSERT_HEAD(&bbobj->shadow_head,
2091                                                  object, shadow_list);
2092                                 bbobj->shadow_count++;
2093                                 bbobj->generation++;
2094                         }
2095
2096                         object->backing_object_offset +=
2097                                 backing_object->backing_object_offset;
2098
2099                         vm_object_drop(bbobj);
2100
2101                         /*
2102                          * Discard the old backing_object.  Nothing should be
2103                          * able to ref it, other than a vm_map_split(),
2104                          * and vm_map_split() will stall on our chain lock.
2105                          * And we control the parent so it shouldn't be
2106                          * possible for it to go away either.
2107                          *
2108                          * Since the backing object has no pages, no pager
2109                          * left, and no object references within it, all
2110                          * that is necessary is to dispose of it.
2111                          */
2112                         KASSERT(backing_object->ref_count == 1,
2113                                 ("backing_object %p was somehow "
2114                                  "re-referenced during collapse!",
2115                                  backing_object));
2116                         KASSERT(RB_EMPTY(&backing_object->rb_memq),
2117                                 ("backing_object %p somehow has left "
2118                                  "over pages during collapse!",
2119                                  backing_object));
2120
2121                         /*
2122                          * The object can be destroyed.
2123                          *
2124                          * XXX just fall through and dodealloc instead
2125                          *     of forcing destruction?
2126                          */
2127                         --backing_object->ref_count;
2128                         if ((backing_object->flags & OBJ_DEAD) == 0)
2129                                 vm_object_terminate(backing_object);
2130                         object_collapses++;
2131                         dodealloc = 0;
2132                 } else {
2133                         /*
2134                          * If we do not entirely shadow the backing object,
2135                          * there is nothing we can do so we give up.
2136                          */
2137                         if (vm_object_backing_scan(object, backing_object,
2138                                                 OBSC_TEST_ALL_SHADOWED) == 0) {
2139                                 break;
2140                         }
2141
2142                         /*
2143                          * bbobj is backing_object->backing_object.  Since
2144                          * object completely shadows backing_object we can
2145                          * bypass it and become backed by bbobj instead.
2146                          */
2147                         while ((bbobj = backing_object->backing_object) != NULL) {
2148                                 vm_object_hold(bbobj);
2149                                 if (bbobj == backing_object->backing_object)
2150                                         break;
2151                                 vm_object_drop(bbobj);
2152                         }
2153
2154                         /*
2155                          * Make object shadow bbobj instead of backing_object.
2156                          * Remove object from backing_object's shadow list.
2157                          *
2158                          * Deallocating backing_object will not remove
2159                          * it, since its reference count is at least 2.
2160                          */
2161                         KKASSERT(object->backing_object == backing_object);
2162                         LIST_REMOVE(object, shadow_list);
2163                         backing_object->shadow_count--;
2164                         backing_object->generation++;
2165
2166                         /*
2167                          * Add a ref to bbobj, bbobj now shadows object.
2168                          *
2169                          * NOTE: backing_object->backing_object still points
2170                          *       to bbobj.  That relationship remains intact
2171                          *       because backing_object has > 1 ref, so
2172                          *       someone else is pointing to it (hence why
2173                          *       we can't collapse it into object and can
2174                          *       only handle the all-shadowed bypass case).
2175                          */
2176                         if (bbobj) {
2177                                 vm_object_chain_wait(bbobj);
2178                                 vm_object_reference_locked(bbobj);
2179                                 LIST_INSERT_HEAD(&bbobj->shadow_head,
2180                                                  object, shadow_list);
2181                                 bbobj->shadow_count++;
2182                                 bbobj->generation++;
2183                                 object->backing_object_offset +=
2184                                         backing_object->backing_object_offset;
2185                                 object->backing_object = bbobj;
2186                                 vm_object_drop(bbobj);
2187                         } else {
2188                                 object->backing_object = NULL;
2189                         }
2190
2191                         /*
2192                          * Drop the reference count on backing_object.  To
2193                          * handle ref_count races properly we can't assume
2194                          * that the ref_count is still at least 2 so we
2195                          * have to actually call vm_object_deallocate()
2196                          * (after clearing the chainlock).
2197                          */
2198                         object_bypasses++;
2199                         dodealloc = 1;
2200                 }
2201
2202                 /*
2203                  * Ok, we want to loop on the new object->bbobj association,
2204                  * possibly collapsing it further.  However if dodealloc is
2205                  * non-zero we have to deallocate the backing_object which
2206                  * itself can potentially undergo a collapse, creating a
2207                  * recursion depth issue with the LWKT token subsystem.
2208                  *
2209                  * In the case where we must deallocate the backing_object
2210                  * it is possible now that the backing_object has a single
2211                  * shadow count on some other object (not represented here
2212                  * as yet), since it no longer shadows us.  Thus when we
2213                  * call vm_object_deallocate() it may attempt to collapse
2214                  * itself into its remaining parent.
2215                  */
2216                 if (dodealloc) {
2217                         struct vm_object_dealloc_list *dtmp;
2218
2219                         vm_object_chain_release(backing_object);
2220                         vm_object_unlock(backing_object);
2221                         /* backing_object remains held */
2222
2223                         /*
2224                          * Auto-deallocation list for caller convenience.
2225                          */
2226                         if (dlistp == NULL)
2227                                 dlistp = &dlist;
2228
2229                         dtmp = kmalloc(sizeof(*dtmp), M_TEMP, M_WAITOK);
2230                         dtmp->object = backing_object;
2231                         dtmp->next = *dlistp;
2232                         *dlistp = dtmp;
2233                 } else {
2234                         vm_object_chain_release(backing_object);
2235                         vm_object_drop(backing_object);
2236                 }
2237                 /* backing_object = NULL; not needed */
2238                 /* loop */
2239         }
2240
2241         /*
2242          * Clean up any left over backing_object
2243          */
2244         if (backing_object) {
2245                 vm_object_chain_release(backing_object);
2246                 vm_object_drop(backing_object);
2247         }
2248
2249         /*
2250          * Clean up any auto-deallocation list.  This is a convenience
2251          * for top-level callers so they don't have to pass &dlist.
2252          * Do not clean up any caller-passed dlistp, the caller will
2253          * do that.
2254          */
2255         if (dlist)
2256                 vm_object_deallocate_list(&dlist);
2257
2258 }
2259
2260 /*
2261  * vm_object_collapse() may collect additional objects in need of
2262  * deallocation.  This routine deallocates these objects.  The
2263  * deallocation itself can trigger additional collapses (which the
2264  * deallocate function takes care of).  This procedure is used to
2265  * reduce procedural recursion since these vm_object shadow chains
2266  * can become quite long.
2267  */
2268 void
2269 vm_object_deallocate_list(struct vm_object_dealloc_list **dlistp)
2270 {
2271         struct vm_object_dealloc_list *dlist;
2272
2273         while ((dlist = *dlistp) != NULL) {
2274                 *dlistp = dlist->next;
2275                 vm_object_lock(dlist->object);
2276                 vm_object_deallocate_locked(dlist->object);
2277                 vm_object_drop(dlist->object);
2278                 kfree(dlist, M_TEMP);
2279         }
2280 }
2281
2282 /*
2283  * Removes all physical pages in the specified object range from the
2284  * object's list of pages.
2285  *
2286  * No requirements.
2287  */
2288 static int vm_object_page_remove_callback(vm_page_t p, void *data);
2289
2290 void
2291 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
2292                       boolean_t clean_only)
2293 {
2294         struct rb_vm_page_scan_info info;
2295         int all;
2296
2297         /*
2298          * Degenerate cases and assertions
2299          */
2300         vm_object_hold(object);
2301         if (object == NULL ||
2302             (object->resident_page_count == 0 && object->swblock_count == 0)) {
2303                 vm_object_drop(object);
2304                 return;
2305         }
2306         KASSERT(object->type != OBJT_PHYS, 
2307                 ("attempt to remove pages from a physical object"));
2308
2309         /*
2310          * Indicate that paging is occuring on the object
2311          */
2312         vm_object_pip_add(object, 1);
2313
2314         /*
2315          * Figure out the actual removal range and whether we are removing
2316          * the entire contents of the object or not.  If removing the entire
2317          * contents, be sure to get all pages, even those that might be 
2318          * beyond the end of the object.
2319          */
2320         info.start_pindex = start;
2321         if (end == 0)
2322                 info.end_pindex = (vm_pindex_t)-1;
2323         else
2324                 info.end_pindex = end - 1;
2325         info.limit = clean_only;
2326         all = (start == 0 && info.end_pindex >= object->size - 1);
2327
2328         /*
2329          * Loop until we are sure we have gotten them all.
2330          */
2331         do {
2332                 info.error = 0;
2333                 vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
2334                                         vm_object_page_remove_callback, &info);
2335         } while (info.error);
2336
2337         /*
2338          * Remove any related swap if throwing away pages, or for
2339          * non-swap objects (the swap is a clean copy in that case).
2340          */
2341         if (object->type != OBJT_SWAP || clean_only == FALSE) {
2342                 if (all)
2343                         swap_pager_freespace_all(object);
2344                 else
2345                         swap_pager_freespace(object, info.start_pindex,
2346                              info.end_pindex - info.start_pindex + 1);
2347         }
2348
2349         /*
2350          * Cleanup
2351          */
2352         vm_object_pip_wakeup(object);
2353         vm_object_drop(object);
2354 }
2355
2356 /*
2357  * The caller must hold the object
2358  */
2359 static int
2360 vm_object_page_remove_callback(vm_page_t p, void *data)
2361 {
2362         struct rb_vm_page_scan_info *info = data;
2363
2364         if (vm_page_busy_try(p, TRUE)) {
2365                 vm_page_sleep_busy(p, TRUE, "vmopar");
2366                 info->error = 1;
2367                 return(0);
2368         }
2369
2370         /*
2371          * Wired pages cannot be destroyed, but they can be invalidated
2372          * and we do so if clean_only (limit) is not set.
2373          *
2374          * WARNING!  The page may be wired due to being part of a buffer
2375          *           cache buffer, and the buffer might be marked B_CACHE.
2376          *           This is fine as part of a truncation but VFSs must be
2377          *           sure to fix the buffer up when re-extending the file.
2378          *
2379          * NOTE!     PG_NEED_COMMIT is ignored.
2380          */
2381         if (p->wire_count != 0) {
2382                 vm_page_protect(p, VM_PROT_NONE);
2383                 if (info->limit == 0)
2384                         p->valid = 0;
2385                 vm_page_wakeup(p);
2386                 return(0);
2387         }
2388
2389         /*
2390          * limit is our clean_only flag.  If set and the page is dirty or
2391          * requires a commit, do not free it.  If set and the page is being
2392          * held by someone, do not free it.
2393          */
2394         if (info->limit && p->valid) {
2395                 vm_page_test_dirty(p);
2396                 if ((p->valid & p->dirty) || (p->flags & PG_NEED_COMMIT)) {
2397                         vm_page_wakeup(p);
2398                         return(0);
2399                 }
2400 #if 0
2401                 if (p->hold_count) {
2402                         vm_page_wakeup(p);
2403                         return(0);
2404                 }
2405 #endif
2406         }
2407
2408         /*
2409          * Destroy the page
2410          */
2411         vm_page_protect(p, VM_PROT_NONE);
2412         vm_page_free(p);
2413         return(0);
2414 }
2415
2416 /*
2417  * Coalesces two objects backing up adjoining regions of memory into a
2418  * single object.
2419  *
2420  * returns TRUE if objects were combined.
2421  *
2422  * NOTE: Only works at the moment if the second object is NULL -
2423  *       if it's not, which object do we lock first?
2424  *
2425  * Parameters:
2426  *      prev_object     First object to coalesce
2427  *      prev_offset     Offset into prev_object
2428  *      next_object     Second object into coalesce
2429  *      next_offset     Offset into next_object
2430  *
2431  *      prev_size       Size of reference to prev_object
2432  *      next_size       Size of reference to next_object
2433  *
2434  * The caller does not need to hold (prev_object) but must have a stable
2435  * pointer to it (typically by holding the vm_map locked).
2436  */
2437 boolean_t
2438 vm_object_coalesce(vm_object_t prev_object, vm_pindex_t prev_pindex,
2439                    vm_size_t prev_size, vm_size_t next_size)
2440 {
2441         vm_pindex_t next_pindex;
2442
2443         if (prev_object == NULL)
2444                 return (TRUE);
2445
2446         vm_object_hold(prev_object);
2447
2448         if (prev_object->type != OBJT_DEFAULT &&
2449             prev_object->type != OBJT_SWAP) {
2450                 vm_object_drop(prev_object);
2451                 return (FALSE);
2452         }
2453
2454         /*
2455          * Try to collapse the object first
2456          */
2457         vm_object_chain_acquire(prev_object);
2458         vm_object_collapse(prev_object, NULL);
2459
2460         /*
2461          * Can't coalesce if: . more than one reference . paged out . shadows
2462          * another object . has a copy elsewhere (any of which mean that the
2463          * pages not mapped to prev_entry may be in use anyway)
2464          */
2465
2466         if (prev_object->backing_object != NULL) {
2467                 vm_object_chain_release(prev_object);
2468                 vm_object_drop(prev_object);
2469                 return (FALSE);
2470         }
2471
2472         prev_size >>= PAGE_SHIFT;
2473         next_size >>= PAGE_SHIFT;
2474         next_pindex = prev_pindex + prev_size;
2475
2476         if ((prev_object->ref_count > 1) &&
2477             (prev_object->size != next_pindex)) {
2478                 vm_object_chain_release(prev_object);
2479                 vm_object_drop(prev_object);
2480                 return (FALSE);
2481         }
2482
2483         /*
2484          * Remove any pages that may still be in the object from a previous
2485          * deallocation.
2486          */
2487         if (next_pindex < prev_object->size) {
2488                 vm_object_page_remove(prev_object,
2489                                       next_pindex,
2490                                       next_pindex + next_size, FALSE);
2491                 if (prev_object->type == OBJT_SWAP)
2492                         swap_pager_freespace(prev_object,
2493                                              next_pindex, next_size);
2494         }
2495
2496         /*
2497          * Extend the object if necessary.
2498          */
2499         if (next_pindex + next_size > prev_object->size)
2500                 prev_object->size = next_pindex + next_size;
2501
2502         vm_object_chain_release(prev_object);
2503         vm_object_drop(prev_object);
2504         return (TRUE);
2505 }
2506
2507 /*
2508  * Make the object writable and flag is being possibly dirty.
2509  *
2510  * The caller must hold the object. XXX called from vm_page_dirty(),
2511  * There is currently no requirement to hold the object.
2512  */
2513 void
2514 vm_object_set_writeable_dirty(vm_object_t object)
2515 {
2516         struct vnode *vp;
2517
2518         /*vm_object_assert_held(object);*/
2519         /*
2520          * Avoid contention in vm fault path by checking the state before
2521          * issuing an atomic op on it.
2522          */
2523         if ((object->flags & (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) !=
2524             (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) {
2525                 vm_object_set_flag(object, OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
2526         }
2527         if (object->type == OBJT_VNODE &&
2528             (vp = (struct vnode *)object->handle) != NULL) {
2529                 if ((vp->v_flag & VOBJDIRTY) == 0) {
2530                         vsetflags(vp, VOBJDIRTY);
2531                 }
2532         }
2533 }
2534
2535 #include "opt_ddb.h"
2536 #ifdef DDB
2537 #include <sys/kernel.h>
2538
2539 #include <sys/cons.h>
2540
2541 #include <ddb/ddb.h>
2542
2543 static int      _vm_object_in_map (vm_map_t map, vm_object_t object,
2544                                        vm_map_entry_t entry);
2545 static int      vm_object_in_map (vm_object_t object);
2546
2547 /*
2548  * The caller must hold the object.
2549  */
2550 static int
2551 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
2552 {
2553         vm_map_t tmpm;
2554         vm_map_entry_t tmpe;
2555         vm_object_t obj, nobj;
2556         int entcount;
2557
2558         if (map == 0)
2559                 return 0;
2560         if (entry == 0) {
2561                 tmpe = map->header.next;
2562                 entcount = map->nentries;
2563                 while (entcount-- && (tmpe != &map->header)) {
2564                         if( _vm_object_in_map(map, object, tmpe)) {
2565                                 return 1;
2566                         }
2567                         tmpe = tmpe->next;
2568                 }
2569                 return (0);
2570         }
2571         switch(entry->maptype) {
2572         case VM_MAPTYPE_SUBMAP:
2573                 tmpm = entry->object.sub_map;
2574                 tmpe = tmpm->header.next;
2575                 entcount = tmpm->nentries;
2576                 while (entcount-- && tmpe != &tmpm->header) {
2577                         if( _vm_object_in_map(tmpm, object, tmpe)) {
2578                                 return 1;
2579                         }
2580                         tmpe = tmpe->next;
2581                 }
2582                 break;
2583         case VM_MAPTYPE_NORMAL:
2584         case VM_MAPTYPE_VPAGETABLE:
2585                 obj = entry->object.vm_object;
2586                 while (obj) {
2587                         if (obj == object) {
2588                                 if (obj != entry->object.vm_object)
2589                                         vm_object_drop(obj);
2590                                 return 1;
2591                         }
2592                         while ((nobj = obj->backing_object) != NULL) {
2593                                 vm_object_hold(nobj);
2594                                 if (nobj == obj->backing_object)
2595                                         break;
2596                                 vm_object_drop(nobj);
2597                         }
2598                         if (obj != entry->object.vm_object) {
2599                                 if (nobj)
2600                                         vm_object_lock_swap();
2601                                 vm_object_drop(obj);
2602                         }
2603                         obj = nobj;
2604                 }
2605                 break;
2606         default:
2607                 break;
2608         }
2609         return 0;
2610 }
2611
2612 static int vm_object_in_map_callback(struct proc *p, void *data);
2613
2614 struct vm_object_in_map_info {
2615         vm_object_t object;
2616         int rv;
2617 };
2618
2619 /*
2620  * Debugging only
2621  */
2622 static int
2623 vm_object_in_map(vm_object_t object)
2624 {
2625         struct vm_object_in_map_info info;
2626
2627         info.rv = 0;
2628         info.object = object;
2629
2630         allproc_scan(vm_object_in_map_callback, &info);
2631         if (info.rv)
2632                 return 1;
2633         if( _vm_object_in_map(&kernel_map, object, 0))
2634                 return 1;
2635         if( _vm_object_in_map(&pager_map, object, 0))
2636                 return 1;
2637         if( _vm_object_in_map(&buffer_map, object, 0))
2638                 return 1;
2639         return 0;
2640 }
2641
2642 /*
2643  * Debugging only
2644  */
2645 static int
2646 vm_object_in_map_callback(struct proc *p, void *data)
2647 {
2648         struct vm_object_in_map_info *info = data;
2649
2650         if (p->p_vmspace) {
2651                 if (_vm_object_in_map(&p->p_vmspace->vm_map, info->object, 0)) {
2652                         info->rv = 1;
2653                         return -1;
2654                 }
2655         }
2656         return (0);
2657 }
2658
2659 DB_SHOW_COMMAND(vmochk, vm_object_check)
2660 {
2661         vm_object_t object;
2662
2663         /*
2664          * make sure that internal objs are in a map somewhere
2665          * and none have zero ref counts.
2666          */
2667         for (object = TAILQ_FIRST(&vm_object_list);
2668                         object != NULL;
2669                         object = TAILQ_NEXT(object, object_list)) {
2670                 if (object->type == OBJT_MARKER)
2671                         continue;
2672                 if (object->handle == NULL &&
2673                     (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2674                         if (object->ref_count == 0) {
2675                                 db_printf("vmochk: internal obj has zero ref count: %ld\n",
2676                                         (long)object->size);
2677                         }
2678                         if (!vm_object_in_map(object)) {
2679                                 db_printf(
2680                         "vmochk: internal obj is not in a map: "
2681                         "ref: %d, size: %lu: 0x%lx, backing_object: %p\n",
2682                                     object->ref_count, (u_long)object->size, 
2683                                     (u_long)object->size,
2684                                     (void *)object->backing_object);
2685                         }
2686                 }
2687         }
2688 }
2689
2690 /*
2691  * Debugging only
2692  */
2693 DB_SHOW_COMMAND(object, vm_object_print_static)
2694 {
2695         /* XXX convert args. */
2696         vm_object_t object = (vm_object_t)addr;
2697         boolean_t full = have_addr;
2698
2699         vm_page_t p;
2700
2701         /* XXX count is an (unused) arg.  Avoid shadowing it. */
2702 #define count   was_count
2703
2704         int count;
2705
2706         if (object == NULL)
2707                 return;
2708
2709         db_iprintf(
2710             "Object %p: type=%d, size=0x%lx, res=%d, ref=%d, flags=0x%x\n",
2711             object, (int)object->type, (u_long)object->size,
2712             object->resident_page_count, object->ref_count, object->flags);
2713         /*
2714          * XXX no %qd in kernel.  Truncate object->backing_object_offset.
2715          */
2716         db_iprintf(" sref=%d, backing_object(%d)=(%p)+0x%lx\n",
2717             object->shadow_count, 
2718             object->backing_object ? object->backing_object->ref_count : 0,
2719             object->backing_object, (long)object->backing_object_offset);
2720
2721         if (!full)
2722                 return;
2723
2724         db_indent += 2;
2725         count = 0;
2726         RB_FOREACH(p, vm_page_rb_tree, &object->rb_memq) {
2727                 if (count == 0)
2728                         db_iprintf("memory:=");
2729                 else if (count == 6) {
2730                         db_printf("\n");
2731                         db_iprintf(" ...");
2732                         count = 0;
2733                 } else
2734                         db_printf(",");
2735                 count++;
2736
2737                 db_printf("(off=0x%lx,page=0x%lx)",
2738                     (u_long) p->pindex, (u_long) VM_PAGE_TO_PHYS(p));
2739         }
2740         if (count != 0)
2741                 db_printf("\n");
2742         db_indent -= 2;
2743 }
2744
2745 /* XXX. */
2746 #undef count
2747
2748 /*
2749  * XXX need this non-static entry for calling from vm_map_print.
2750  *
2751  * Debugging only
2752  */
2753 void
2754 vm_object_print(/* db_expr_t */ long addr,
2755                 boolean_t have_addr,
2756                 /* db_expr_t */ long count,
2757                 char *modif)
2758 {
2759         vm_object_print_static(addr, have_addr, count, modif);
2760 }
2761
2762 /*
2763  * Debugging only
2764  */
2765 DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
2766 {
2767         vm_object_t object;
2768         int nl = 0;
2769         int c;
2770         for (object = TAILQ_FIRST(&vm_object_list);
2771                         object != NULL;
2772                         object = TAILQ_NEXT(object, object_list)) {
2773                 vm_pindex_t idx, fidx;
2774                 vm_pindex_t osize;
2775                 vm_paddr_t pa = -1, padiff;
2776                 int rcount;
2777                 vm_page_t m;
2778
2779                 if (object->type == OBJT_MARKER)
2780                         continue;
2781                 db_printf("new object: %p\n", (void *)object);
2782                 if ( nl > 18) {
2783                         c = cngetc();
2784                         if (c != ' ')
2785                                 return;
2786                         nl = 0;
2787                 }
2788                 nl++;
2789                 rcount = 0;
2790                 fidx = 0;
2791                 osize = object->size;
2792                 if (osize > 128)
2793                         osize = 128;
2794                 for (idx = 0; idx < osize; idx++) {
2795                         m = vm_page_lookup(object, idx);
2796                         if (m == NULL) {
2797                                 if (rcount) {
2798                                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2799                                                 (long)fidx, rcount, (long)pa);
2800                                         if ( nl > 18) {
2801                                                 c = cngetc();
2802                                                 if (c != ' ')
2803                                                         return;
2804                                                 nl = 0;
2805                                         }
2806                                         nl++;
2807                                         rcount = 0;
2808                                 }
2809                                 continue;
2810                         }
2811
2812                                 
2813                         if (rcount &&
2814                                 (VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
2815                                 ++rcount;
2816                                 continue;
2817                         }
2818                         if (rcount) {
2819                                 padiff = pa + rcount * PAGE_SIZE - VM_PAGE_TO_PHYS(m);
2820                                 padiff >>= PAGE_SHIFT;
2821                                 padiff &= PQ_L2_MASK;
2822                                 if (padiff == 0) {
2823                                         pa = VM_PAGE_TO_PHYS(m) - rcount * PAGE_SIZE;
2824                                         ++rcount;
2825                                         continue;
2826                                 }
2827                                 db_printf(" index(%ld)run(%d)pa(0x%lx)",
2828                                         (long)fidx, rcount, (long)pa);
2829                                 db_printf("pd(%ld)\n", (long)padiff);
2830                                 if ( nl > 18) {
2831                                         c = cngetc();
2832                                         if (c != ' ')
2833                                                 return;
2834                                         nl = 0;
2835                                 }
2836                                 nl++;
2837                         }
2838                         fidx = idx;
2839                         pa = VM_PAGE_TO_PHYS(m);
2840                         rcount = 1;
2841                 }
2842                 if (rcount) {
2843                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2844                                 (long)fidx, rcount, (long)pa);
2845                         if ( nl > 18) {
2846                                 c = cngetc();
2847                                 if (c != ' ')
2848                                         return;
2849                                 nl = 0;
2850                         }
2851                         nl++;
2852                 }
2853         }
2854 }
2855 #endif /* DDB */