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