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