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