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