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