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