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