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