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