]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/vm/vm_object.c
MFC
[FreeBSD/FreeBSD.git] / sys / vm / vm_object.c
1 /*-
2  * Copyright (c) 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      from: @(#)vm_object.c   8.5 (Berkeley) 3/22/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
39  *
40  * Permission to use, copy, modify and distribute this software and
41  * its documentation is hereby granted, provided that both the copyright
42  * notice and this permission notice appear in all copies of the
43  * software, derivative works or modified versions, and any portions
44  * thereof, and that both notices appear in supporting documentation.
45  *
46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
49  *
50  * Carnegie Mellon requests users of this software to return to
51  *
52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
53  *  School of Computer Science
54  *  Carnegie Mellon University
55  *  Pittsburgh PA 15213-3890
56  *
57  * any improvements or extensions that they make and grant Carnegie the
58  * rights to redistribute these changes.
59  */
60
61 /*
62  *      Virtual memory object module.
63  */
64
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67
68 #include "opt_vm.h"
69
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/lock.h>
73 #include <sys/mman.h>
74 #include <sys/mount.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/mutex.h>
78 #include <sys/proc.h>           /* for curproc, pageproc */
79 #include <sys/socket.h>
80 #include <sys/resourcevar.h>
81 #include <sys/vnode.h>
82 #include <sys/vmmeter.h>
83 #include <sys/sx.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_reserv.h>
97 #include <vm/uma.h>
98
99 static int old_msync;
100 SYSCTL_INT(_vm, OID_AUTO, old_msync, CTLFLAG_RW, &old_msync, 0,
101     "Use old (insecure) msync behavior");
102
103 static int      vm_object_page_collect_flush(vm_object_t object, vm_page_t p,
104                     int pagerflags, int flags, boolean_t *clearobjflags,
105                     boolean_t *eio);
106 static boolean_t vm_object_page_remove_write(vm_page_t p, int flags,
107                     boolean_t *clearobjflags);
108 static void     vm_object_qcollapse(vm_object_t object);
109 static void     vm_object_vndeallocate(vm_object_t object);
110
111 /*
112  *      Virtual memory objects maintain the actual data
113  *      associated with allocated virtual memory.  A given
114  *      page of memory exists within exactly one object.
115  *
116  *      An object is only deallocated when all "references"
117  *      are given up.  Only one "reference" to a given
118  *      region of an object should be writeable.
119  *
120  *      Associated with each object is a list of all resident
121  *      memory pages belonging to that object; this list is
122  *      maintained by the "vm_page" module, and locked by the object's
123  *      lock.
124  *
125  *      Each object also records a "pager" routine which is
126  *      used to retrieve (and store) pages to the proper backing
127  *      storage.  In addition, objects may be backed by other
128  *      objects from which they were virtual-copied.
129  *
130  *      The only items within the object structure which are
131  *      modified after time of creation are:
132  *              reference count         locked by object's lock
133  *              pager routine           locked by object's lock
134  *
135  */
136
137 struct object_q vm_object_list;
138 struct mtx vm_object_list_mtx;  /* lock for object list and count */
139
140 struct vm_object kernel_object_store;
141 struct vm_object kmem_object_store;
142
143 static SYSCTL_NODE(_vm_stats, OID_AUTO, object, CTLFLAG_RD, 0,
144     "VM object stats");
145
146 static long object_collapses;
147 SYSCTL_LONG(_vm_stats_object, OID_AUTO, collapses, CTLFLAG_RD,
148     &object_collapses, 0, "VM object collapses");
149
150 static long object_bypasses;
151 SYSCTL_LONG(_vm_stats_object, OID_AUTO, bypasses, CTLFLAG_RD,
152     &object_bypasses, 0, "VM object bypasses");
153
154 static uma_zone_t obj_zone;
155
156 static int vm_object_zinit(void *mem, int size, int flags);
157
158 #ifdef INVARIANTS
159 static void vm_object_zdtor(void *mem, int size, void *arg);
160
161 static void
162 vm_object_zdtor(void *mem, int size, void *arg)
163 {
164         vm_object_t object;
165
166         object = (vm_object_t)mem;
167         KASSERT(object->resident_page_count == 0,
168             ("object %p resident_page_count = %d",
169             object, object->resident_page_count));
170         KASSERT(TAILQ_EMPTY(&object->memq),
171             ("object %p has resident pages",
172             object));
173 #if VM_NRESERVLEVEL > 0
174         KASSERT(LIST_EMPTY(&object->rvq),
175             ("object %p has reservations",
176             object));
177 #endif
178         KASSERT(object->cached_page_count == 0,
179             ("object %p has cached pages",
180             object));
181         KASSERT(object->paging_in_progress == 0,
182             ("object %p paging_in_progress = %d",
183             object, object->paging_in_progress));
184         KASSERT(object->shadow_count == 0,
185             ("object %p shadow_count = %d",
186             object, object->shadow_count));
187 }
188 #endif
189
190 static int
191 vm_object_zinit(void *mem, int size, int flags)
192 {
193         vm_object_t object;
194
195         object = (vm_object_t)mem;
196         bzero(&object->mtx, sizeof(object->mtx));
197         mtx_init(&object->mtx, "vm object", NULL, MTX_DEF | MTX_DUPOK);
198
199         /* These are true for any object that has been freed */
200         object->paging_in_progress = 0;
201         object->resident_page_count = 0;
202         object->shadow_count = 0;
203         return (0);
204 }
205
206 static void
207 _vm_object_allocate(objtype_t type, vm_pindex_t size, vm_object_t object)
208 {
209
210         TAILQ_INIT(&object->memq);
211         LIST_INIT(&object->shadow_head);
212
213         object->rtree.rt_root = 0;
214         object->type = type;
215         switch (type) {
216         case OBJT_DEAD:
217                 panic("_vm_object_allocate: can't create OBJT_DEAD");
218         case OBJT_DEFAULT:
219         case OBJT_SWAP:
220                 object->flags = OBJ_ONEMAPPING;
221                 break;
222         case OBJT_DEVICE:
223         case OBJT_SG:
224                 object->flags = OBJ_FICTITIOUS | OBJ_UNMANAGED;
225                 break;
226         case OBJT_MGTDEVICE:
227                 object->flags = OBJ_FICTITIOUS;
228                 break;
229         case OBJT_PHYS:
230                 object->flags = OBJ_UNMANAGED;
231                 break;
232         case OBJT_VNODE:
233                 object->flags = 0;
234                 break;
235         default:
236                 panic("_vm_object_allocate: type %d is undefined", type);
237         }
238         object->size = size;
239         object->generation = 1;
240         object->ref_count = 1;
241         object->memattr = VM_MEMATTR_DEFAULT;
242         object->cred = NULL;
243         object->charge = 0;
244         object->handle = NULL;
245         object->backing_object = NULL;
246         object->backing_object_offset = (vm_ooffset_t) 0;
247 #if VM_NRESERVLEVEL > 0
248         LIST_INIT(&object->rvq);
249 #endif
250
251         mtx_lock(&vm_object_list_mtx);
252         TAILQ_INSERT_TAIL(&vm_object_list, object, object_list);
253         mtx_unlock(&vm_object_list_mtx);
254 }
255
256 /*
257  *      vm_object_init:
258  *
259  *      Initialize the VM objects module.
260  */
261 void
262 vm_object_init(void)
263 {
264         TAILQ_INIT(&vm_object_list);
265         mtx_init(&vm_object_list_mtx, "vm object_list", NULL, MTX_DEF);
266         
267         mtx_init(&kernel_object->mtx, "vm object", "kernel object", MTX_DEF);
268         _vm_object_allocate(OBJT_PHYS, OFF_TO_IDX(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS),
269             kernel_object);
270 #if VM_NRESERVLEVEL > 0
271         kernel_object->flags |= OBJ_COLORED;
272         kernel_object->pg_color = (u_short)atop(VM_MIN_KERNEL_ADDRESS);
273 #endif
274
275         mtx_init(&kmem_object->mtx, "vm object", "kmem object", MTX_DEF);
276         _vm_object_allocate(OBJT_PHYS, OFF_TO_IDX(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS),
277             kmem_object);
278 #if VM_NRESERVLEVEL > 0
279         kmem_object->flags |= OBJ_COLORED;
280         kmem_object->pg_color = (u_short)atop(VM_MIN_KERNEL_ADDRESS);
281 #endif
282
283         /*
284          * The lock portion of struct vm_object must be type stable due
285          * to vm_pageout_fallback_object_lock locking a vm object
286          * without holding any references to it.
287          */
288         obj_zone = uma_zcreate("VM OBJECT", sizeof (struct vm_object), NULL,
289 #ifdef INVARIANTS
290             vm_object_zdtor,
291 #else
292             NULL,
293 #endif
294             vm_object_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_VM|UMA_ZONE_NOFREE);
295 }
296
297 void
298 vm_object_clear_flag(vm_object_t object, u_short bits)
299 {
300
301         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
302         object->flags &= ~bits;
303 }
304
305 /*
306  *      Sets the default memory attribute for the specified object.  Pages
307  *      that are allocated to this object are by default assigned this memory
308  *      attribute.
309  *
310  *      Presently, this function must be called before any pages are allocated
311  *      to the object.  In the future, this requirement may be relaxed for
312  *      "default" and "swap" objects.
313  */
314 int
315 vm_object_set_memattr(vm_object_t object, vm_memattr_t memattr)
316 {
317
318         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
319         switch (object->type) {
320         case OBJT_DEFAULT:
321         case OBJT_DEVICE:
322         case OBJT_MGTDEVICE:
323         case OBJT_PHYS:
324         case OBJT_SG:
325         case OBJT_SWAP:
326         case OBJT_VNODE:
327                 if (object->resident_page_count == 0)
328                         return (KERN_FAILURE);
329                 break;
330         case OBJT_DEAD:
331                 return (KERN_INVALID_ARGUMENT);
332         default:
333                 panic("vm_object_set_memattr: object %p is of undefined type",
334                     object);
335         }
336         object->memattr = memattr;
337         return (KERN_SUCCESS);
338 }
339
340 void
341 vm_object_pip_add(vm_object_t object, short i)
342 {
343
344         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
345         object->paging_in_progress += i;
346 }
347
348 void
349 vm_object_pip_subtract(vm_object_t object, short i)
350 {
351
352         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
353         object->paging_in_progress -= i;
354 }
355
356 void
357 vm_object_pip_wakeup(vm_object_t object)
358 {
359
360         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
361         object->paging_in_progress--;
362         if ((object->flags & OBJ_PIPWNT) && object->paging_in_progress == 0) {
363                 vm_object_clear_flag(object, OBJ_PIPWNT);
364                 wakeup(object);
365         }
366 }
367
368 void
369 vm_object_pip_wakeupn(vm_object_t object, short i)
370 {
371
372         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
373         if (i)
374                 object->paging_in_progress -= i;
375         if ((object->flags & OBJ_PIPWNT) && object->paging_in_progress == 0) {
376                 vm_object_clear_flag(object, OBJ_PIPWNT);
377                 wakeup(object);
378         }
379 }
380
381 void
382 vm_object_pip_wait(vm_object_t object, char *waitid)
383 {
384
385         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
386         while (object->paging_in_progress) {
387                 object->flags |= OBJ_PIPWNT;
388                 VM_OBJECT_SLEEP(object, object, PVM, waitid, 0);
389         }
390 }
391
392 /*
393  *      vm_object_allocate:
394  *
395  *      Returns a new object with the given size.
396  */
397 vm_object_t
398 vm_object_allocate(objtype_t type, vm_pindex_t size)
399 {
400         vm_object_t object;
401
402         object = (vm_object_t)uma_zalloc(obj_zone, M_WAITOK);
403         _vm_object_allocate(type, size, object);
404         return (object);
405 }
406
407
408 /*
409  *      vm_object_reference:
410  *
411  *      Gets another reference to the given object.  Note: OBJ_DEAD
412  *      objects can be referenced during final cleaning.
413  */
414 void
415 vm_object_reference(vm_object_t object)
416 {
417         if (object == NULL)
418                 return;
419         VM_OBJECT_LOCK(object);
420         vm_object_reference_locked(object);
421         VM_OBJECT_UNLOCK(object);
422 }
423
424 /*
425  *      vm_object_reference_locked:
426  *
427  *      Gets another reference to the given object.
428  *
429  *      The object must be locked.
430  */
431 void
432 vm_object_reference_locked(vm_object_t object)
433 {
434         struct vnode *vp;
435
436         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
437         object->ref_count++;
438         if (object->type == OBJT_VNODE) {
439                 vp = object->handle;
440                 vref(vp);
441         }
442 }
443
444 /*
445  * Handle deallocating an object of type OBJT_VNODE.
446  */
447 static void
448 vm_object_vndeallocate(vm_object_t object)
449 {
450         struct vnode *vp = (struct vnode *) object->handle;
451
452         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
453         KASSERT(object->type == OBJT_VNODE,
454             ("vm_object_vndeallocate: not a vnode object"));
455         KASSERT(vp != NULL, ("vm_object_vndeallocate: missing vp"));
456 #ifdef INVARIANTS
457         if (object->ref_count == 0) {
458                 vprint("vm_object_vndeallocate", vp);
459                 panic("vm_object_vndeallocate: bad object reference count");
460         }
461 #endif
462
463         if (object->ref_count > 1) {
464                 object->ref_count--;
465                 VM_OBJECT_UNLOCK(object);
466                 /* vrele may need the vnode lock. */
467                 vrele(vp);
468         } else {
469                 vhold(vp);
470                 VM_OBJECT_UNLOCK(object);
471                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
472                 vdrop(vp);
473                 VM_OBJECT_LOCK(object);
474                 object->ref_count--;
475                 if (object->type == OBJT_DEAD) {
476                         VM_OBJECT_UNLOCK(object);
477                         VOP_UNLOCK(vp, 0);
478                 } else {
479                         if (object->ref_count == 0)
480                                 VOP_UNSET_TEXT(vp);
481                         VM_OBJECT_UNLOCK(object);
482                         vput(vp);
483                 }
484         }
485 }
486
487 /*
488  *      vm_object_deallocate:
489  *
490  *      Release a reference to the specified object,
491  *      gained either through a vm_object_allocate
492  *      or a vm_object_reference call.  When all references
493  *      are gone, storage associated with this object
494  *      may be relinquished.
495  *
496  *      No object may be locked.
497  */
498 void
499 vm_object_deallocate(vm_object_t object)
500 {
501         vm_object_t temp;
502
503         while (object != NULL) {
504                 VM_OBJECT_LOCK(object);
505                 if (object->type == OBJT_VNODE) {
506                         vm_object_vndeallocate(object);
507                         return;
508                 }
509
510                 KASSERT(object->ref_count != 0,
511                         ("vm_object_deallocate: object deallocated too many times: %d", object->type));
512
513                 /*
514                  * If the reference count goes to 0 we start calling
515                  * vm_object_terminate() on the object chain.
516                  * A ref count of 1 may be a special case depending on the
517                  * shadow count being 0 or 1.
518                  */
519                 object->ref_count--;
520                 if (object->ref_count > 1) {
521                         VM_OBJECT_UNLOCK(object);
522                         return;
523                 } else if (object->ref_count == 1) {
524                         if (object->shadow_count == 0 &&
525                             object->handle == NULL &&
526                             (object->type == OBJT_DEFAULT ||
527                              object->type == OBJT_SWAP)) {
528                                 vm_object_set_flag(object, OBJ_ONEMAPPING);
529                         } else if ((object->shadow_count == 1) &&
530                             (object->handle == NULL) &&
531                             (object->type == OBJT_DEFAULT ||
532                              object->type == OBJT_SWAP)) {
533                                 vm_object_t robject;
534
535                                 robject = LIST_FIRST(&object->shadow_head);
536                                 KASSERT(robject != NULL,
537                                     ("vm_object_deallocate: ref_count: %d, shadow_count: %d",
538                                          object->ref_count,
539                                          object->shadow_count));
540                                 if (!VM_OBJECT_TRYLOCK(robject)) {
541                                         /*
542                                          * Avoid a potential deadlock.
543                                          */
544                                         object->ref_count++;
545                                         VM_OBJECT_UNLOCK(object);
546                                         /*
547                                          * More likely than not the thread
548                                          * holding robject's lock has lower
549                                          * priority than the current thread.
550                                          * Let the lower priority thread run.
551                                          */
552                                         pause("vmo_de", 1);
553                                         continue;
554                                 }
555                                 /*
556                                  * Collapse object into its shadow unless its
557                                  * shadow is dead.  In that case, object will
558                                  * be deallocated by the thread that is
559                                  * deallocating its shadow.
560                                  */
561                                 if ((robject->flags & OBJ_DEAD) == 0 &&
562                                     (robject->handle == NULL) &&
563                                     (robject->type == OBJT_DEFAULT ||
564                                      robject->type == OBJT_SWAP)) {
565
566                                         robject->ref_count++;
567 retry:
568                                         if (robject->paging_in_progress) {
569                                                 VM_OBJECT_UNLOCK(object);
570                                                 vm_object_pip_wait(robject,
571                                                     "objde1");
572                                                 temp = robject->backing_object;
573                                                 if (object == temp) {
574                                                         VM_OBJECT_LOCK(object);
575                                                         goto retry;
576                                                 }
577                                         } else if (object->paging_in_progress) {
578                                                 VM_OBJECT_UNLOCK(robject);
579                                                 object->flags |= OBJ_PIPWNT;
580                                                 VM_OBJECT_SLEEP(object, object,
581                                                     PDROP | PVM, "objde2", 0);
582                                                 VM_OBJECT_LOCK(robject);
583                                                 temp = robject->backing_object;
584                                                 if (object == temp) {
585                                                         VM_OBJECT_LOCK(object);
586                                                         goto retry;
587                                                 }
588                                         } else
589                                                 VM_OBJECT_UNLOCK(object);
590
591                                         if (robject->ref_count == 1) {
592                                                 robject->ref_count--;
593                                                 object = robject;
594                                                 goto doterm;
595                                         }
596                                         object = robject;
597                                         vm_object_collapse(object);
598                                         VM_OBJECT_UNLOCK(object);
599                                         continue;
600                                 }
601                                 VM_OBJECT_UNLOCK(robject);
602                         }
603                         VM_OBJECT_UNLOCK(object);
604                         return;
605                 }
606 doterm:
607                 temp = object->backing_object;
608                 if (temp != NULL) {
609                         VM_OBJECT_LOCK(temp);
610                         LIST_REMOVE(object, shadow_list);
611                         temp->shadow_count--;
612                         VM_OBJECT_UNLOCK(temp);
613                         object->backing_object = NULL;
614                 }
615                 /*
616                  * Don't double-terminate, we could be in a termination
617                  * recursion due to the terminate having to sync data
618                  * to disk.
619                  */
620                 if ((object->flags & OBJ_DEAD) == 0)
621                         vm_object_terminate(object);
622                 else
623                         VM_OBJECT_UNLOCK(object);
624                 object = temp;
625         }
626 }
627
628 /*
629  *      vm_object_destroy removes the object from the global object list
630  *      and frees the space for the object.
631  */
632 void
633 vm_object_destroy(vm_object_t object)
634 {
635
636         /*
637          * Remove the object from the global object list.
638          */
639         mtx_lock(&vm_object_list_mtx);
640         TAILQ_REMOVE(&vm_object_list, object, object_list);
641         mtx_unlock(&vm_object_list_mtx);
642
643         /*
644          * Release the allocation charge.
645          */
646         if (object->cred != NULL) {
647                 KASSERT(object->type == OBJT_DEFAULT ||
648                     object->type == OBJT_SWAP,
649                     ("vm_object_terminate: non-swap obj %p has cred",
650                      object));
651                 swap_release_by_cred(object->charge, object->cred);
652                 object->charge = 0;
653                 crfree(object->cred);
654                 object->cred = NULL;
655         }
656
657         /*
658          * Free the space for the object.
659          */
660         uma_zfree(obj_zone, object);
661 }
662
663 /*
664  *      vm_object_terminate actually destroys the specified object, freeing
665  *      up all previously used resources.
666  *
667  *      The object must be locked.
668  *      This routine may block.
669  */
670 void
671 vm_object_terminate(vm_object_t object)
672 {
673         vm_page_t pa[VM_RADIX_STACK];
674         vm_page_t p;
675         vm_pindex_t start;
676         u_int exhausted;
677         int n, i;
678
679         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
680
681         /*
682          * Make sure no one uses us.
683          */
684         vm_object_set_flag(object, OBJ_DEAD);
685
686         /*
687          * wait for the pageout daemon to be done with the object
688          */
689         vm_object_pip_wait(object, "objtrm");
690
691         KASSERT(!object->paging_in_progress,
692                 ("vm_object_terminate: pageout in progress"));
693
694         /*
695          * Clean and free the pages, as appropriate. All references to the
696          * object are gone, so we don't need to lock it.
697          */
698         if (object->type == OBJT_VNODE) {
699                 struct vnode *vp = (struct vnode *)object->handle;
700
701                 /*
702                  * Clean pages and flush buffers.
703                  */
704                 vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
705                 VM_OBJECT_UNLOCK(object);
706
707                 vinvalbuf(vp, V_SAVE, 0, 0);
708
709                 VM_OBJECT_LOCK(object);
710         }
711
712         KASSERT(object->ref_count == 0, 
713                 ("vm_object_terminate: object with references, ref_count=%d",
714                 object->ref_count));
715
716         /*
717          * Free any remaining pageable pages.  This also removes them from the
718          * paging queues.  However, don't free wired pages, just remove them
719          * from the object.  Rather than incrementally removing each page from
720          * the object, the page and object are reset to any empty state. 
721          */
722         start = 0;
723         exhausted = 0;
724         while (exhausted == 0 && (n = vm_radix_lookupn(&object->rtree, start,
725             0, VM_RADIX_ANY, (void **)pa, VM_RADIX_STACK, &start,
726             &exhausted)) != 0) {
727                 for (i = 0; i < n; i++) {
728                         p = pa[i];
729                         /*
730                          * Another thread may allocate this cached page from
731                          * the queue before we acquire the page queue free
732                          * mtx.
733                          */
734                         if (p->flags & PG_CACHED) {
735                                 mtx_lock(&vm_page_queue_free_mtx);
736                                 if (p->object == object) {
737                                         p->object = NULL;
738                                         p->valid = 0;
739                                         /* Clear PG_CACHED and set PG_FREE. */
740                                         p->flags ^= PG_CACHED | PG_FREE;
741                                         cnt.v_cache_count--;
742                                         cnt.v_free_count++;
743                                 }
744                                 mtx_unlock(&vm_page_queue_free_mtx);
745                                 continue;
746                         } else if (p->object != object)
747                                 continue;
748                         KASSERT(!p->busy && (p->oflags & VPO_BUSY) == 0,
749                             ("vm_object_terminate: freeing busy page %p", p));
750                         vm_page_lock(p);
751                         /*
752                          * Optimize the page's removal from the object by
753                          * resetting its "object" field.  Specifically, if
754                          * the page is not wired, then the effect of this
755                          * assignment is that vm_page_free()'s call to
756                          * vm_page_remove() will return immediately without
757                          * modifying the page or the object.
758                          * Anyway, the radix tree cannot be accessed anymore
759                          * from within the object, thus all the nodes need
760                          * to be reclaimed later on.
761                          */ 
762                         p->object = NULL;
763                         if (p->wire_count == 0) {
764                                 vm_page_free(p);
765                                 PCPU_INC(cnt.v_pfree);
766                         }
767                         vm_page_unlock(p);
768                 }
769                 if (n < VM_RADIX_STACK)
770                         break;
771         }
772         vm_radix_reclaim_allnodes(&object->rtree);
773         /*
774          * If the object contained any pages, then reset it to an empty state.
775          * None of the object's fields, including "resident_page_count", were
776          * modified by the preceding loop.
777          */
778         if (object->resident_page_count != 0) {
779                 TAILQ_INIT(&object->memq);
780                 object->resident_page_count = 0;
781                 if (object->type == OBJT_VNODE)
782                         vdrop(object->handle);
783         }
784         if (object->cached_page_count != 0) {
785                 object->cached_page_count = 0;
786                 if (object->type == OBJT_VNODE)
787                         vdrop(object->handle);
788         }
789
790 #if VM_NRESERVLEVEL > 0
791         if (__predict_false(!LIST_EMPTY(&object->rvq)))
792                 vm_reserv_break_all(object);
793 #endif
794
795         /*
796          * Let the pager know object is dead.
797          */
798         vm_pager_deallocate(object);
799         VM_OBJECT_UNLOCK(object);
800
801         vm_object_destroy(object);
802 }
803
804 /*
805  * Make the page read-only so that we can clear the object flags.  However, if
806  * this is a nosync mmap then the object is likely to stay dirty so do not
807  * mess with the page and do not clear the object flags.  Returns TRUE if the
808  * page should be flushed, and FALSE otherwise.
809  */
810 static boolean_t
811 vm_object_page_remove_write(vm_page_t p, int flags, boolean_t *clearobjflags)
812 {
813
814         /*
815          * If we have been asked to skip nosync pages and this is a
816          * nosync page, skip it.  Note that the object flags were not
817          * cleared in this case so we do not have to set them.
818          */
819         if ((flags & OBJPC_NOSYNC) != 0 && (p->oflags & VPO_NOSYNC) != 0) {
820                 *clearobjflags = FALSE;
821                 return (FALSE);
822         } else {
823                 pmap_remove_write(p);
824                 return (p->dirty != 0);
825         }
826 }
827
828 /*
829  *      vm_object_page_clean
830  *
831  *      Clean all dirty pages in the specified range of object.  Leaves page 
832  *      on whatever queue it is currently on.   If NOSYNC is set then do not
833  *      write out pages with VPO_NOSYNC set (originally comes from MAP_NOSYNC),
834  *      leaving the object dirty.
835  *
836  *      When stuffing pages asynchronously, allow clustering.  XXX we need a
837  *      synchronous clustering mode implementation.
838  *
839  *      Odd semantics: if start == end, we clean everything.
840  *
841  *      The object must be locked.
842  *
843  *      Returns FALSE if some page from the range was not written, as
844  *      reported by the pager, and TRUE otherwise.
845  */
846 boolean_t
847 vm_object_page_clean(vm_object_t object, vm_ooffset_t start, vm_ooffset_t end,
848     int flags)
849 {
850         vm_page_t np, p;
851         vm_pindex_t pi, tend, tstart;
852         int curgeneration, n, pagerflags;
853         boolean_t clearobjflags, eio, res;
854
855         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
856         KASSERT(object->type == OBJT_VNODE, ("Not a vnode object"));
857         if ((object->flags & OBJ_MIGHTBEDIRTY) == 0 ||
858             object->resident_page_count == 0)
859                 return (TRUE);
860
861         pagerflags = (flags & (OBJPC_SYNC | OBJPC_INVAL)) != 0 ?
862             VM_PAGER_PUT_SYNC : VM_PAGER_CLUSTER_OK;
863         pagerflags |= (flags & OBJPC_INVAL) != 0 ? VM_PAGER_PUT_INVAL : 0;
864
865         tstart = OFF_TO_IDX(start);
866         tend = (end == 0) ? object->size : OFF_TO_IDX(end + PAGE_MASK);
867         clearobjflags = tstart == 0 && tend >= object->size;
868         res = TRUE;
869
870 rescan:
871         curgeneration = object->generation;
872
873         for (p = vm_page_find_least(object, tstart); p != NULL; p = np) {
874                 pi = p->pindex;
875                 if (pi >= tend)
876                         break;
877                 np = TAILQ_NEXT(p, listq);
878                 if (p->valid == 0)
879                         continue;
880                 if (vm_page_sleep_if_busy(p, TRUE, "vpcwai")) {
881                         if (object->generation != curgeneration) {
882                                 if ((flags & OBJPC_SYNC) != 0)
883                                         goto rescan;
884                                 else
885                                         clearobjflags = FALSE;
886                         }
887                         np = vm_page_find_least(object, pi);
888                         continue;
889                 }
890                 if (!vm_object_page_remove_write(p, flags, &clearobjflags))
891                         continue;
892
893                 n = vm_object_page_collect_flush(object, p, pagerflags,
894                     flags, &clearobjflags, &eio);
895                 if (eio) {
896                         res = FALSE;
897                         clearobjflags = FALSE;
898                 }
899                 if (object->generation != curgeneration) {
900                         if ((flags & OBJPC_SYNC) != 0)
901                                 goto rescan;
902                         else
903                                 clearobjflags = FALSE;
904                 }
905
906                 /*
907                  * If the VOP_PUTPAGES() did a truncated write, so
908                  * that even the first page of the run is not fully
909                  * written, vm_pageout_flush() returns 0 as the run
910                  * length.  Since the condition that caused truncated
911                  * write may be permanent, e.g. exhausted free space,
912                  * accepting n == 0 would cause an infinite loop.
913                  *
914                  * Forwarding the iterator leaves the unwritten page
915                  * behind, but there is not much we can do there if
916                  * filesystem refuses to write it.
917                  */
918                 if (n == 0) {
919                         n = 1;
920                         clearobjflags = FALSE;
921                 }
922                 np = vm_page_find_least(object, pi + n);
923         }
924 #if 0
925         VOP_FSYNC(vp, (pagerflags & VM_PAGER_PUT_SYNC) ? MNT_WAIT : 0);
926 #endif
927
928         if (clearobjflags)
929                 vm_object_clear_flag(object, OBJ_MIGHTBEDIRTY);
930         return (res);
931 }
932
933 static int
934 vm_object_page_collect_flush(vm_object_t object, vm_page_t p, int pagerflags,
935     int flags, boolean_t *clearobjflags, boolean_t *eio)
936 {
937         vm_page_t ma[vm_pageout_page_count], p_first, tp;
938         int count, i, mreq, runlen;
939
940         vm_page_lock_assert(p, MA_NOTOWNED);
941         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
942
943         count = 1;
944         mreq = 0;
945
946         for (tp = p; count < vm_pageout_page_count; count++) {
947                 tp = vm_page_next(tp);
948                 if (tp == NULL || tp->busy != 0 || (tp->oflags & VPO_BUSY) != 0)
949                         break;
950                 if (!vm_object_page_remove_write(tp, flags, clearobjflags))
951                         break;
952         }
953
954         for (p_first = p; count < vm_pageout_page_count; count++) {
955                 tp = vm_page_prev(p_first);
956                 if (tp == NULL || tp->busy != 0 || (tp->oflags & VPO_BUSY) != 0)
957                         break;
958                 if (!vm_object_page_remove_write(tp, flags, clearobjflags))
959                         break;
960                 p_first = tp;
961                 mreq++;
962         }
963
964         for (tp = p_first, i = 0; i < count; tp = TAILQ_NEXT(tp, listq), i++)
965                 ma[i] = tp;
966
967         vm_pageout_flush(ma, count, pagerflags, mreq, &runlen, eio);
968         return (runlen);
969 }
970
971 /*
972  * Note that there is absolutely no sense in writing out
973  * anonymous objects, so we track down the vnode object
974  * to write out.
975  * We invalidate (remove) all pages from the address space
976  * for semantic correctness.
977  *
978  * If the backing object is a device object with unmanaged pages, then any
979  * mappings to the specified range of pages must be removed before this
980  * function is called.
981  *
982  * Note: certain anonymous maps, such as MAP_NOSYNC maps,
983  * may start out with a NULL object.
984  */
985 boolean_t
986 vm_object_sync(vm_object_t object, vm_ooffset_t offset, vm_size_t size,
987     boolean_t syncio, boolean_t invalidate)
988 {
989         vm_object_t backing_object;
990         struct vnode *vp;
991         struct mount *mp;
992         int error, flags, fsync_after;
993         boolean_t res;
994
995         if (object == NULL)
996                 return (TRUE);
997         res = TRUE;
998         error = 0;
999         VM_OBJECT_LOCK(object);
1000         while ((backing_object = object->backing_object) != NULL) {
1001                 VM_OBJECT_LOCK(backing_object);
1002                 offset += object->backing_object_offset;
1003                 VM_OBJECT_UNLOCK(object);
1004                 object = backing_object;
1005                 if (object->size < OFF_TO_IDX(offset + size))
1006                         size = IDX_TO_OFF(object->size) - offset;
1007         }
1008         /*
1009          * Flush pages if writing is allowed, invalidate them
1010          * if invalidation requested.  Pages undergoing I/O
1011          * will be ignored by vm_object_page_remove().
1012          *
1013          * We cannot lock the vnode and then wait for paging
1014          * to complete without deadlocking against vm_fault.
1015          * Instead we simply call vm_object_page_remove() and
1016          * allow it to block internally on a page-by-page
1017          * basis when it encounters pages undergoing async
1018          * I/O.
1019          */
1020         if (object->type == OBJT_VNODE &&
1021             (object->flags & OBJ_MIGHTBEDIRTY) != 0) {
1022                 vp = object->handle;
1023                 VM_OBJECT_UNLOCK(object);
1024                 (void) vn_start_write(vp, &mp, V_WAIT);
1025                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1026                 if (syncio && !invalidate && offset == 0 &&
1027                     OFF_TO_IDX(size) == object->size) {
1028                         /*
1029                          * If syncing the whole mapping of the file,
1030                          * it is faster to schedule all the writes in
1031                          * async mode, also allowing the clustering,
1032                          * and then wait for i/o to complete.
1033                          */
1034                         flags = 0;
1035                         fsync_after = TRUE;
1036                 } else {
1037                         flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
1038                         flags |= invalidate ? (OBJPC_SYNC | OBJPC_INVAL) : 0;
1039                         fsync_after = FALSE;
1040                 }
1041                 VM_OBJECT_LOCK(object);
1042                 res = vm_object_page_clean(object, offset, offset + size,
1043                     flags);
1044                 VM_OBJECT_UNLOCK(object);
1045                 if (fsync_after)
1046                         error = VOP_FSYNC(vp, MNT_WAIT, curthread);
1047                 VOP_UNLOCK(vp, 0);
1048                 vn_finished_write(mp);
1049                 if (error != 0)
1050                         res = FALSE;
1051                 VM_OBJECT_LOCK(object);
1052         }
1053         if ((object->type == OBJT_VNODE ||
1054              object->type == OBJT_DEVICE) && invalidate) {
1055                 if (object->type == OBJT_DEVICE)
1056                         /*
1057                          * The option OBJPR_NOTMAPPED must be passed here
1058                          * because vm_object_page_remove() cannot remove
1059                          * unmanaged mappings.
1060                          */
1061                         flags = OBJPR_NOTMAPPED;
1062                 else if (old_msync)
1063                         flags = 0;
1064                 else
1065                         flags = OBJPR_CLEANONLY;
1066                 vm_object_page_remove(object, OFF_TO_IDX(offset),
1067                     OFF_TO_IDX(offset + size + PAGE_MASK), flags);
1068         }
1069         VM_OBJECT_UNLOCK(object);
1070         return (res);
1071 }
1072
1073 /*
1074  *      vm_object_madvise:
1075  *
1076  *      Implements the madvise function at the object/page level.
1077  *
1078  *      MADV_WILLNEED   (any object)
1079  *
1080  *          Activate the specified pages if they are resident.
1081  *
1082  *      MADV_DONTNEED   (any object)
1083  *
1084  *          Deactivate the specified pages if they are resident.
1085  *
1086  *      MADV_FREE       (OBJT_DEFAULT/OBJT_SWAP objects,
1087  *                       OBJ_ONEMAPPING only)
1088  *
1089  *          Deactivate and clean the specified pages if they are
1090  *          resident.  This permits the process to reuse the pages
1091  *          without faulting or the kernel to reclaim the pages
1092  *          without I/O.
1093  */
1094 void
1095 vm_object_madvise(vm_object_t object, vm_pindex_t pindex, vm_pindex_t end,
1096     int advise)
1097 {
1098         vm_pindex_t tpindex;
1099         vm_object_t backing_object, tobject;
1100         vm_page_t m;
1101
1102         if (object == NULL)
1103                 return;
1104         VM_OBJECT_LOCK(object);
1105         /*
1106          * Locate and adjust resident pages
1107          */
1108         for (; pindex < end; pindex += 1) {
1109 relookup:
1110                 tobject = object;
1111                 tpindex = pindex;
1112 shadowlookup:
1113                 /*
1114                  * MADV_FREE only operates on OBJT_DEFAULT or OBJT_SWAP pages
1115                  * and those pages must be OBJ_ONEMAPPING.
1116                  */
1117                 if (advise == MADV_FREE) {
1118                         if ((tobject->type != OBJT_DEFAULT &&
1119                              tobject->type != OBJT_SWAP) ||
1120                             (tobject->flags & OBJ_ONEMAPPING) == 0) {
1121                                 goto unlock_tobject;
1122                         }
1123                 } else if ((tobject->flags & OBJ_UNMANAGED) != 0)
1124                         goto unlock_tobject;
1125                 m = vm_page_lookup(tobject, tpindex);
1126                 if (m == NULL && advise == MADV_WILLNEED) {
1127                         /*
1128                          * If the page is cached, reactivate it.
1129                          */
1130                         m = vm_page_alloc(tobject, tpindex, VM_ALLOC_IFCACHED |
1131                             VM_ALLOC_NOBUSY);
1132                 }
1133                 if (m == NULL) {
1134                         /*
1135                          * There may be swap even if there is no backing page
1136                          */
1137                         if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
1138                                 swap_pager_freespace(tobject, tpindex, 1);
1139                         /*
1140                          * next object
1141                          */
1142                         backing_object = tobject->backing_object;
1143                         if (backing_object == NULL)
1144                                 goto unlock_tobject;
1145                         VM_OBJECT_LOCK(backing_object);
1146                         tpindex += OFF_TO_IDX(tobject->backing_object_offset);
1147                         if (tobject != object)
1148                                 VM_OBJECT_UNLOCK(tobject);
1149                         tobject = backing_object;
1150                         goto shadowlookup;
1151                 } else if (m->valid != VM_PAGE_BITS_ALL)
1152                         goto unlock_tobject;
1153                 /*
1154                  * If the page is not in a normal state, skip it.
1155                  */
1156                 vm_page_lock(m);
1157                 if (m->hold_count != 0 || m->wire_count != 0) {
1158                         vm_page_unlock(m);
1159                         goto unlock_tobject;
1160                 }
1161                 KASSERT((m->flags & PG_FICTITIOUS) == 0,
1162                     ("vm_object_madvise: page %p is fictitious", m));
1163                 KASSERT((m->oflags & VPO_UNMANAGED) == 0,
1164                     ("vm_object_madvise: page %p is not managed", m));
1165                 if ((m->oflags & VPO_BUSY) || m->busy) {
1166                         if (advise == MADV_WILLNEED) {
1167                                 /*
1168                                  * Reference the page before unlocking and
1169                                  * sleeping so that the page daemon is less
1170                                  * likely to reclaim it. 
1171                                  */
1172                                 vm_page_aflag_set(m, PGA_REFERENCED);
1173                         }
1174                         vm_page_unlock(m);
1175                         if (object != tobject)
1176                                 VM_OBJECT_UNLOCK(object);
1177                         m->oflags |= VPO_WANTED;
1178                         VM_OBJECT_SLEEP(tobject, m, PDROP | PVM, "madvpo", 0);
1179                         VM_OBJECT_LOCK(object);
1180                         goto relookup;
1181                 }
1182                 if (advise == MADV_WILLNEED) {
1183                         vm_page_activate(m);
1184                 } else if (advise == MADV_DONTNEED) {
1185                         vm_page_dontneed(m);
1186                 } else if (advise == MADV_FREE) {
1187                         /*
1188                          * Mark the page clean.  This will allow the page
1189                          * to be freed up by the system.  However, such pages
1190                          * are often reused quickly by malloc()/free()
1191                          * so we do not do anything that would cause
1192                          * a page fault if we can help it.
1193                          *
1194                          * Specifically, we do not try to actually free
1195                          * the page now nor do we try to put it in the
1196                          * cache (which would cause a page fault on reuse).
1197                          *
1198                          * But we do make the page is freeable as we
1199                          * can without actually taking the step of unmapping
1200                          * it.
1201                          */
1202                         pmap_clear_modify(m);
1203                         m->dirty = 0;
1204                         m->act_count = 0;
1205                         vm_page_dontneed(m);
1206                 }
1207                 vm_page_unlock(m);
1208                 if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
1209                         swap_pager_freespace(tobject, tpindex, 1);
1210 unlock_tobject:
1211                 if (tobject != object)
1212                         VM_OBJECT_UNLOCK(tobject);
1213         }       
1214         VM_OBJECT_UNLOCK(object);
1215 }
1216
1217 /*
1218  *      vm_object_shadow:
1219  *
1220  *      Create a new object which is backed by the
1221  *      specified existing object range.  The source
1222  *      object reference is deallocated.
1223  *
1224  *      The new object and offset into that object
1225  *      are returned in the source parameters.
1226  */
1227 void
1228 vm_object_shadow(
1229         vm_object_t *object,    /* IN/OUT */
1230         vm_ooffset_t *offset,   /* IN/OUT */
1231         vm_size_t length)
1232 {
1233         vm_object_t source;
1234         vm_object_t result;
1235
1236         source = *object;
1237
1238         /*
1239          * Don't create the new object if the old object isn't shared.
1240          */
1241         if (source != NULL) {
1242                 VM_OBJECT_LOCK(source);
1243                 if (source->ref_count == 1 &&
1244                     source->handle == NULL &&
1245                     (source->type == OBJT_DEFAULT ||
1246                      source->type == OBJT_SWAP)) {
1247                         VM_OBJECT_UNLOCK(source);
1248                         return;
1249                 }
1250                 VM_OBJECT_UNLOCK(source);
1251         }
1252
1253         /*
1254          * Allocate a new object with the given length.
1255          */
1256         result = vm_object_allocate(OBJT_DEFAULT, atop(length));
1257
1258         /*
1259          * The new object shadows the source object, adding a reference to it.
1260          * Our caller changes his reference to point to the new object,
1261          * removing a reference to the source object.  Net result: no change
1262          * of reference count.
1263          *
1264          * Try to optimize the result object's page color when shadowing
1265          * in order to maintain page coloring consistency in the combined 
1266          * shadowed object.
1267          */
1268         result->backing_object = source;
1269         /*
1270          * Store the offset into the source object, and fix up the offset into
1271          * the new object.
1272          */
1273         result->backing_object_offset = *offset;
1274         if (source != NULL) {
1275                 VM_OBJECT_LOCK(source);
1276                 LIST_INSERT_HEAD(&source->shadow_head, result, shadow_list);
1277                 source->shadow_count++;
1278 #if VM_NRESERVLEVEL > 0
1279                 result->flags |= source->flags & OBJ_COLORED;
1280                 result->pg_color = (source->pg_color + OFF_TO_IDX(*offset)) &
1281                     ((1 << (VM_NFREEORDER - 1)) - 1);
1282 #endif
1283                 VM_OBJECT_UNLOCK(source);
1284         }
1285
1286
1287         /*
1288          * Return the new things
1289          */
1290         *offset = 0;
1291         *object = result;
1292 }
1293
1294 /*
1295  *      vm_object_split:
1296  *
1297  * Split the pages in a map entry into a new object.  This affords
1298  * easier removal of unused pages, and keeps object inheritance from
1299  * being a negative impact on memory usage.
1300  */
1301 void
1302 vm_object_split(vm_map_entry_t entry)
1303 {
1304         vm_page_t ma[VM_RADIX_STACK];
1305         vm_page_t m;
1306         vm_object_t orig_object, new_object, source;
1307         vm_pindex_t idx, offidxstart, start;
1308         vm_size_t size;
1309         u_int exhausted;
1310         int i, n;
1311
1312         orig_object = entry->object.vm_object;
1313         if (orig_object->type != OBJT_DEFAULT && orig_object->type != OBJT_SWAP)
1314                 return;
1315         if (orig_object->ref_count <= 1)
1316                 return;
1317         VM_OBJECT_UNLOCK(orig_object);
1318
1319         offidxstart = OFF_TO_IDX(entry->offset);
1320         size = atop(entry->end - entry->start);
1321
1322         /*
1323          * If swap_pager_copy() is later called, it will convert new_object
1324          * into a swap object.
1325          */
1326         new_object = vm_object_allocate(OBJT_DEFAULT, size);
1327
1328         /*
1329          * At this point, the new object is still private, so the order in
1330          * which the original and new objects are locked does not matter.
1331          */
1332         VM_OBJECT_LOCK(new_object);
1333         VM_OBJECT_LOCK(orig_object);
1334         source = orig_object->backing_object;
1335         if (source != NULL) {
1336                 VM_OBJECT_LOCK(source);
1337                 if ((source->flags & OBJ_DEAD) != 0) {
1338                         VM_OBJECT_UNLOCK(source);
1339                         VM_OBJECT_UNLOCK(orig_object);
1340                         VM_OBJECT_UNLOCK(new_object);
1341                         vm_object_deallocate(new_object);
1342                         VM_OBJECT_LOCK(orig_object);
1343                         return;
1344                 }
1345                 LIST_INSERT_HEAD(&source->shadow_head,
1346                                   new_object, shadow_list);
1347                 source->shadow_count++;
1348                 vm_object_reference_locked(source);     /* for new_object */
1349                 vm_object_clear_flag(source, OBJ_ONEMAPPING);
1350                 VM_OBJECT_UNLOCK(source);
1351                 new_object->backing_object_offset = 
1352                         orig_object->backing_object_offset + entry->offset;
1353                 new_object->backing_object = source;
1354         }
1355         if (orig_object->cred != NULL) {
1356                 new_object->cred = orig_object->cred;
1357                 crhold(orig_object->cred);
1358                 new_object->charge = ptoa(size);
1359                 KASSERT(orig_object->charge >= ptoa(size),
1360                     ("orig_object->charge < 0"));
1361                 orig_object->charge -= ptoa(size);
1362         }
1363         start = offidxstart;
1364 retry:
1365         exhausted = 0;
1366         while (exhausted == 0 && (n = vm_radix_lookupn(&orig_object->rtree,
1367             start, offidxstart + size, VM_RADIX_ANY, (void **)ma,
1368             VM_RADIX_STACK, &start, &exhausted)) != 0) {
1369                 for (i = 0; i < n; i++) {
1370                         m = ma[i];
1371                         idx = m->pindex - offidxstart;
1372                         if (m->flags & PG_CACHED) {
1373                                 mtx_lock(&vm_page_queue_free_mtx);
1374                                 if (m->object == orig_object)
1375                                         vm_page_cache_rename(m, new_object,
1376                                             idx);
1377                                 mtx_unlock(&vm_page_queue_free_mtx);
1378                                 continue;
1379                         } else if (m->object != orig_object)
1380                                 continue;
1381                         /*
1382                          * We must wait for pending I/O to complete before
1383                          * we can rename the page.
1384                          *
1385                          * We do not have to VM_PROT_NONE the page as mappings
1386                          * should not be changed by this operation.
1387                          */
1388                         if ((m->oflags & VPO_BUSY) || m->busy) {
1389                                 start = m->pindex;
1390                                 VM_OBJECT_UNLOCK(new_object);
1391                                 m->oflags |= VPO_WANTED;
1392                                 VM_OBJECT_SLEEP(orig_object, m, PVM, "spltwt", 0);
1393                                 VM_OBJECT_LOCK(new_object);
1394                                 goto retry;
1395                         }
1396 #if VM_NRESERVLEVEL > 0
1397                         /*
1398                          * If some of the reservation's allocated pages remain
1399                          * with the original object, then transferring the
1400                          * reservation to the new object is neither
1401                          * particularly beneficial nor particularly harmful as
1402                          * compared to leaving the reservation with the
1403                          * original object.  If, however, all of the
1404                          * reservation's allocated pages are transferred to
1405                          * the new object, then transferring the reservation
1406                          * is typically beneficial.  Determining which of
1407                          * these two cases applies would be more costly than
1408                          * unconditionally renaming the reservation.
1409                          */
1410                         vm_reserv_rename(m, new_object, orig_object,
1411                             offidxstart);
1412 #endif
1413                         vm_page_rename(m, new_object, idx);
1414                         /*
1415                          * page automatically made dirty by rename and
1416                          * cache handled
1417                          */
1418                         vm_page_busy(m);
1419                 }
1420                 if (n < VM_RADIX_STACK)
1421                         break;
1422         }
1423         if (orig_object->type == OBJT_SWAP) {
1424                 /*
1425                  * swap_pager_copy() can sleep, in which case the orig_object's
1426                  * and new_object's locks are released and reacquired. 
1427                  */
1428                 swap_pager_copy(orig_object, new_object, offidxstart, 0);
1429         }
1430         VM_OBJECT_UNLOCK(orig_object);
1431         TAILQ_FOREACH(m, &new_object->memq, listq)
1432                 vm_page_wakeup(m);
1433         VM_OBJECT_UNLOCK(new_object);
1434         entry->object.vm_object = new_object;
1435         entry->offset = 0LL;
1436         vm_object_deallocate(orig_object);
1437         VM_OBJECT_LOCK(new_object);
1438 }
1439
1440 #define OBSC_TEST_ALL_SHADOWED  0x0001
1441 #define OBSC_COLLAPSE_NOWAIT    0x0002
1442 #define OBSC_COLLAPSE_WAIT      0x0004
1443
1444 static int
1445 vm_object_backing_scan(vm_object_t object, int op)
1446 {
1447         vm_page_t pa[VM_RADIX_STACK];
1448         vm_page_t p;
1449         vm_object_t backing_object;
1450         vm_pindex_t backing_offset_index, new_pindex;
1451         vm_pindex_t start;
1452         u_int exhausted;
1453         int color, i, n;
1454         int r = 1;
1455
1456         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1457         VM_OBJECT_LOCK_ASSERT(object->backing_object, MA_OWNED);
1458
1459         backing_object = object->backing_object;
1460         backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1461
1462         /*
1463          * Initial conditions
1464          */
1465         if (op & OBSC_TEST_ALL_SHADOWED) {
1466                 /*
1467                  * We do not want to have to test for the existence of cache
1468                  * or swap pages in the backing object.  XXX but with the
1469                  * new swapper this would be pretty easy to do.
1470                  *
1471                  * XXX what about anonymous MAP_SHARED memory that hasn't
1472                  * been ZFOD faulted yet?  If we do not test for this, the
1473                  * shadow test may succeed! XXX
1474                  */
1475                 if (backing_object->type != OBJT_DEFAULT) {
1476                         return (0);
1477                 }
1478         }
1479         if (op & OBSC_COLLAPSE_WAIT) {
1480                 vm_object_set_flag(backing_object, OBJ_DEAD);
1481         }
1482         color = VM_RADIX_BLACK;
1483         if (op & OBSC_COLLAPSE_WAIT)
1484                 color |= VM_RADIX_RED;
1485         /*
1486          * Our scan
1487          */
1488 restart:
1489         start = 0;
1490         i = n = VM_RADIX_STACK;
1491         exhausted = 0;
1492         for (;;) {
1493                 if (i == n) {
1494                         if (n < VM_RADIX_STACK)
1495                                 break;
1496                         if (exhausted != 0 ||
1497                             (n = vm_radix_lookupn(&backing_object->rtree,
1498                             start, 0, color, (void **)pa, VM_RADIX_STACK,
1499                             &start, &exhausted)) == 0)
1500                                 break;
1501                         i = 0;
1502                 }
1503                 p = pa[i++];
1504                 /*
1505                  * Free cached pages.  XXX Why?  Emulating old behavior here.
1506                  */
1507                 if (p->flags & PG_CACHED) {
1508                         mtx_lock(&vm_page_queue_free_mtx);
1509                         if (p->object == backing_object)
1510                                 vm_page_cache_free(p);
1511                         mtx_unlock(&vm_page_queue_free_mtx);
1512                         continue;
1513                 } else if (p->object != backing_object)
1514                         continue;
1515
1516                 new_pindex = p->pindex - backing_offset_index;
1517                 if (op & OBSC_TEST_ALL_SHADOWED) {
1518                         vm_page_t pp;
1519
1520                         /*
1521                          * Ignore pages outside the parent object's range
1522                          * and outside the parent object's mapping of the 
1523                          * backing object.
1524                          *
1525                          * note that we do not busy the backing object's
1526                          * page.
1527                          */
1528                         if (p->pindex < backing_offset_index ||
1529                             new_pindex >= object->size)
1530                                 continue;
1531
1532                         /*
1533                          * See if the parent has the page or if the parent's
1534                          * object pager has the page.  If the parent has the
1535                          * page but the page is not valid, the parent's
1536                          * object pager must have the page.
1537                          *
1538                          * If this fails, the parent does not completely shadow
1539                          * the object and we might as well give up now.
1540                          */
1541
1542                         pp = vm_page_lookup(object, new_pindex);
1543                         if (
1544                             (pp == NULL || pp->valid == 0) &&
1545                             !vm_pager_has_page(object, new_pindex, NULL, NULL)
1546                         ) {
1547                                 r = 0;
1548                                 break;
1549                         }
1550                 }
1551
1552                 /*
1553                  * Check for busy page
1554                  */
1555                 if (op & (OBSC_COLLAPSE_WAIT | OBSC_COLLAPSE_NOWAIT)) {
1556                         vm_page_t pp;
1557
1558                         if (op & OBSC_COLLAPSE_NOWAIT) {
1559                                 if ((p->oflags & VPO_BUSY) || !p->valid || 
1560                                     p->busy)
1561                                         continue;
1562                         } else if (op & OBSC_COLLAPSE_WAIT) {
1563                                 if ((p->oflags & VPO_BUSY) || p->busy) {
1564                                         VM_OBJECT_UNLOCK(object);
1565                                         p->oflags |= VPO_WANTED;
1566                                         VM_OBJECT_SLEEP(backing_object, p,
1567                                             PDROP | PVM, "vmocol", 0);
1568                                         VM_OBJECT_LOCK(object);
1569                                         VM_OBJECT_LOCK(backing_object);
1570                                         /*
1571                                          * If we slept, anything could have
1572                                          * happened.  Since the object is
1573                                          * marked dead, the backing offset
1574                                          * should not have changed so we
1575                                          * just restart our scan.
1576                                          */
1577                                         goto restart;
1578                                 }
1579                         }
1580
1581                         KASSERT(
1582                             p->object == backing_object,
1583                             ("vm_object_backing_scan: object mismatch")
1584                         );
1585
1586                         /*
1587                          * Destroy any associated swap
1588                          */
1589                         if (backing_object->type == OBJT_SWAP) {
1590                                 swap_pager_freespace(
1591                                     backing_object, 
1592                                     p->pindex,
1593                                     1
1594                                 );
1595                         }
1596
1597                         if (
1598                             p->pindex < backing_offset_index ||
1599                             new_pindex >= object->size
1600                         ) {
1601                                 /*
1602                                  * Page is out of the parent object's range, we 
1603                                  * can simply destroy it. 
1604                                  */
1605                                 vm_page_lock(p);
1606                                 KASSERT(!pmap_page_is_mapped(p),
1607                                     ("freeing mapped page %p", p));
1608                                 if (p->wire_count == 0)
1609                                         vm_page_free(p);
1610                                 else
1611                                         vm_page_remove(p);
1612                                 vm_page_unlock(p);
1613                                 continue;
1614                         }
1615
1616                         pp = vm_page_lookup(object, new_pindex);
1617                         if (
1618                             (op & OBSC_COLLAPSE_NOWAIT) != 0 &&
1619                             (pp != NULL && pp->valid == 0)
1620                         ) {
1621                                 /*
1622                                  * The page in the parent is not (yet) valid.
1623                                  * We don't know anything about the state of
1624                                  * the original page.  It might be mapped,
1625                                  * so we must avoid the next if here.
1626                                  *
1627                                  * This is due to a race in vm_fault() where
1628                                  * we must unbusy the original (backing_obj)
1629                                  * page before we can (re)lock the parent.
1630                                  * Hence we can get here.
1631                                  */
1632                                 continue;
1633                         }
1634                         if (
1635                             pp != NULL ||
1636                             vm_pager_has_page(object, new_pindex, NULL, NULL)
1637                         ) {
1638                                 /*
1639                                  * page already exists in parent OR swap exists
1640                                  * for this location in the parent.  Destroy 
1641                                  * the original page from the backing object.
1642                                  *
1643                                  * Leave the parent's page alone
1644                                  */
1645                                 vm_page_lock(p);
1646                                 KASSERT(!pmap_page_is_mapped(p),
1647                                     ("freeing mapped page %p", p));
1648                                 if (p->wire_count == 0)
1649                                         vm_page_free(p);
1650                                 else
1651                                         vm_page_remove(p);
1652                                 vm_page_unlock(p);
1653                                 continue;
1654                         }
1655
1656 #if VM_NRESERVLEVEL > 0
1657                         /*
1658                          * Rename the reservation.
1659                          */
1660                         vm_reserv_rename(p, object, backing_object,
1661                             backing_offset_index);
1662 #endif
1663
1664                         /*
1665                          * Page does not exist in parent, rename the
1666                          * page from the backing object to the main object. 
1667                          *
1668                          * If the page was mapped to a process, it can remain 
1669                          * mapped through the rename.
1670                          */
1671                         vm_page_rename(p, object, new_pindex);
1672                         /* page automatically made dirty by rename */
1673                 }
1674         }
1675         return (r);
1676 }
1677
1678
1679 /*
1680  * this version of collapse allows the operation to occur earlier and
1681  * when paging_in_progress is true for an object...  This is not a complete
1682  * operation, but should plug 99.9% of the rest of the leaks.
1683  */
1684 static void
1685 vm_object_qcollapse(vm_object_t object)
1686 {
1687         vm_object_t backing_object = object->backing_object;
1688
1689         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1690         VM_OBJECT_LOCK_ASSERT(backing_object, MA_OWNED);
1691
1692         if (backing_object->ref_count != 1)
1693                 return;
1694
1695         vm_object_backing_scan(object, OBSC_COLLAPSE_NOWAIT);
1696 }
1697
1698 /*
1699  *      vm_object_collapse:
1700  *
1701  *      Collapse an object with the object backing it.
1702  *      Pages in the backing object are moved into the
1703  *      parent, and the backing object is deallocated.
1704  */
1705 void
1706 vm_object_collapse(vm_object_t object)
1707 {
1708         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1709         
1710         while (TRUE) {
1711                 vm_object_t backing_object;
1712
1713                 /*
1714                  * Verify that the conditions are right for collapse:
1715                  *
1716                  * The object exists and the backing object exists.
1717                  */
1718                 if ((backing_object = object->backing_object) == NULL)
1719                         break;
1720
1721                 /*
1722                  * we check the backing object first, because it is most likely
1723                  * not collapsable.
1724                  */
1725                 VM_OBJECT_LOCK(backing_object);
1726                 if (backing_object->handle != NULL ||
1727                     (backing_object->type != OBJT_DEFAULT &&
1728                      backing_object->type != OBJT_SWAP) ||
1729                     (backing_object->flags & OBJ_DEAD) ||
1730                     object->handle != NULL ||
1731                     (object->type != OBJT_DEFAULT &&
1732                      object->type != OBJT_SWAP) ||
1733                     (object->flags & OBJ_DEAD)) {
1734                         VM_OBJECT_UNLOCK(backing_object);
1735                         break;
1736                 }
1737
1738                 if (
1739                     object->paging_in_progress != 0 ||
1740                     backing_object->paging_in_progress != 0
1741                 ) {
1742                         vm_object_qcollapse(object);
1743                         VM_OBJECT_UNLOCK(backing_object);
1744                         break;
1745                 }
1746                 /*
1747                  * We know that we can either collapse the backing object (if
1748                  * the parent is the only reference to it) or (perhaps) have
1749                  * the parent bypass the object if the parent happens to shadow
1750                  * all the resident pages in the entire backing object.
1751                  *
1752                  * This is ignoring pager-backed pages such as swap pages.
1753                  * vm_object_backing_scan fails the shadowing test in this
1754                  * case.
1755                  */
1756                 if (backing_object->ref_count == 1) {
1757                         /*
1758                          * If there is exactly one reference to the backing
1759                          * object, we can collapse it into the parent.  
1760                          */
1761                         vm_object_backing_scan(object, OBSC_COLLAPSE_WAIT);
1762
1763 #if VM_NRESERVLEVEL > 0
1764                         /*
1765                          * Break any reservations from backing_object.
1766                          */
1767                         if (__predict_false(!LIST_EMPTY(&backing_object->rvq)))
1768                                 vm_reserv_break_all(backing_object);
1769 #endif
1770
1771                         /*
1772                          * Move the pager from backing_object to object.
1773                          */
1774                         if (backing_object->type == OBJT_SWAP) {
1775                                 /*
1776                                  * swap_pager_copy() can sleep, in which case
1777                                  * the backing_object's and object's locks are
1778                                  * released and reacquired.
1779                                  * Since swap_pager_copy() is being asked to
1780                                  * destroy the source, it will change the
1781                                  * backing_object's type to OBJT_DEFAULT.
1782                                  */
1783                                 swap_pager_copy(
1784                                     backing_object,
1785                                     object,
1786                                     OFF_TO_IDX(object->backing_object_offset), TRUE);
1787                         }
1788                         /*
1789                          * Object now shadows whatever backing_object did.
1790                          * Note that the reference to 
1791                          * backing_object->backing_object moves from within 
1792                          * backing_object to within object.
1793                          */
1794                         LIST_REMOVE(object, shadow_list);
1795                         backing_object->shadow_count--;
1796                         if (backing_object->backing_object) {
1797                                 VM_OBJECT_LOCK(backing_object->backing_object);
1798                                 LIST_REMOVE(backing_object, shadow_list);
1799                                 LIST_INSERT_HEAD(
1800                                     &backing_object->backing_object->shadow_head,
1801                                     object, shadow_list);
1802                                 /*
1803                                  * The shadow_count has not changed.
1804                                  */
1805                                 VM_OBJECT_UNLOCK(backing_object->backing_object);
1806                         }
1807                         object->backing_object = backing_object->backing_object;
1808                         object->backing_object_offset +=
1809                             backing_object->backing_object_offset;
1810
1811                         /*
1812                          * Discard backing_object.
1813                          *
1814                          * Since the backing object has no pages, no pager left,
1815                          * and no object references within it, all that is
1816                          * necessary is to dispose of it.
1817                          */
1818                         KASSERT(backing_object->ref_count == 1, (
1819 "backing_object %p was somehow re-referenced during collapse!",
1820                             backing_object));
1821                         VM_OBJECT_UNLOCK(backing_object);
1822                         vm_object_destroy(backing_object);
1823
1824                         object_collapses++;
1825                 } else {
1826                         vm_object_t new_backing_object;
1827
1828                         /*
1829                          * If we do not entirely shadow the backing object,
1830                          * there is nothing we can do so we give up.
1831                          */
1832                         if (object->resident_page_count != object->size &&
1833                             vm_object_backing_scan(object,
1834                             OBSC_TEST_ALL_SHADOWED) == 0) {
1835                                 VM_OBJECT_UNLOCK(backing_object);
1836                                 break;
1837                         }
1838
1839                         /*
1840                          * Make the parent shadow the next object in the
1841                          * chain.  Deallocating backing_object will not remove
1842                          * it, since its reference count is at least 2.
1843                          */
1844                         LIST_REMOVE(object, shadow_list);
1845                         backing_object->shadow_count--;
1846
1847                         new_backing_object = backing_object->backing_object;
1848                         if ((object->backing_object = new_backing_object) != NULL) {
1849                                 VM_OBJECT_LOCK(new_backing_object);
1850                                 LIST_INSERT_HEAD(
1851                                     &new_backing_object->shadow_head,
1852                                     object,
1853                                     shadow_list
1854                                 );
1855                                 new_backing_object->shadow_count++;
1856                                 vm_object_reference_locked(new_backing_object);
1857                                 VM_OBJECT_UNLOCK(new_backing_object);
1858                                 object->backing_object_offset +=
1859                                         backing_object->backing_object_offset;
1860                         }
1861
1862                         /*
1863                          * Drop the reference count on backing_object. Since
1864                          * its ref_count was at least 2, it will not vanish.
1865                          */
1866                         backing_object->ref_count--;
1867                         VM_OBJECT_UNLOCK(backing_object);
1868                         object_bypasses++;
1869                 }
1870
1871                 /*
1872                  * Try again with this object's new backing object.
1873                  */
1874         }
1875 }
1876
1877 /*
1878  *      vm_object_page_remove:
1879  *
1880  *      For the given object, either frees or invalidates each of the
1881  *      specified pages.  In general, a page is freed.  However, if a page is
1882  *      wired for any reason other than the existence of a managed, wired
1883  *      mapping, then it may be invalidated but not removed from the object.
1884  *      Pages are specified by the given range ["start", "end") and the option
1885  *      OBJPR_CLEANONLY.  As a special case, if "end" is zero, then the range
1886  *      extends from "start" to the end of the object.  If the option
1887  *      OBJPR_CLEANONLY is specified, then only the non-dirty pages within the
1888  *      specified range are affected.  If the option OBJPR_NOTMAPPED is
1889  *      specified, then the pages within the specified range must have no
1890  *      mappings.  Otherwise, if this option is not specified, any mappings to
1891  *      the specified pages are removed before the pages are freed or
1892  *      invalidated.
1893  *
1894  *      In general, this operation should only be performed on objects that
1895  *      contain managed pages.  There are, however, two exceptions.  First, it
1896  *      is performed on the kernel and kmem objects by vm_map_entry_delete().
1897  *      Second, it is used by msync(..., MS_INVALIDATE) to invalidate device-
1898  *      backed pages.  In both of these cases, the option OBJPR_CLEANONLY must
1899  *      not be specified and the option OBJPR_NOTMAPPED must be specified.
1900  *
1901  *      The object must be locked.
1902  */
1903 void
1904 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
1905     int options)
1906 {
1907         struct vnode *vp;
1908         vm_page_t pa[VM_RADIX_STACK];
1909         vm_page_t p;
1910         u_int exhausted;
1911         int i, n;
1912         int wirings;
1913
1914         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
1915         KASSERT((object->flags & OBJ_UNMANAGED) == 0 ||
1916             (options & (OBJPR_CLEANONLY | OBJPR_NOTMAPPED)) == OBJPR_NOTMAPPED,
1917             ("vm_object_page_remove: illegal options for object %p", object));
1918         if (object->resident_page_count == 0 && object->cached_page_count == 0)
1919                 return;
1920         vp = NULL;
1921         vm_object_pip_add(object, 1);
1922 restart:
1923         exhausted = 0;
1924         while (exhausted == 0 && (n = vm_radix_lookupn(&object->rtree, start,
1925             end, VM_RADIX_ANY, (void **)pa, VM_RADIX_STACK, &start,
1926             &exhausted)) != 0) {
1927                 for (i = 0; i < n; i++) {
1928                         p = pa[i];
1929                         /*
1930                          * Another thread may allocate this cached page from
1931                          * the queue before we acquire the page queue free
1932                          * mtx.
1933                          */
1934                         if (p->flags & PG_CACHED) {
1935                                 mtx_lock(&vm_page_queue_free_mtx);
1936                                 if (p->object == object) {
1937                                         vm_page_cache_free(p);
1938                                         if (object->type == OBJT_VNODE &&
1939                                             object->cached_page_count == 0)
1940                                                 vp = object->handle;
1941                                 }
1942                                 mtx_unlock(&vm_page_queue_free_mtx);
1943                                 continue;
1944                         } else if (p->object != object)
1945                                 continue;
1946                         /*
1947                          * If the page is wired for any reason besides
1948                          * the existence of managed, wired mappings, then
1949                          * it cannot be freed.  For example, fictitious
1950                          * pages, which represent device memory, are
1951                          * inherently wired and cannot be freed.  They can,
1952                          * however, be invalidated if the option
1953                          * OBJPR_CLEANONLY is not specified.
1954                          */
1955                         vm_page_lock(p);
1956                         if ((wirings = p->wire_count) != 0 &&
1957                             (wirings = pmap_page_wired_mappings(p)) !=
1958                             p->wire_count) {
1959                                 if ((options & OBJPR_NOTMAPPED) == 0) {
1960                                         pmap_remove_all(p);
1961                                         /*
1962                                          * Account for removal of wired
1963                                          * mappings.
1964                                          */
1965                                         if (wirings != 0)
1966                                                 p->wire_count -= wirings;
1967                                 }
1968                                 if ((options & OBJPR_CLEANONLY) == 0) {
1969                                         p->valid = 0;
1970                                         vm_page_undirty(p);
1971                                 }
1972                                 vm_page_unlock(p);
1973                                 continue;
1974                         }
1975                         if (vm_page_sleep_if_busy(p, TRUE, "vmopar")) {
1976                                 start = p->pindex;
1977                                 goto restart;
1978                         }
1979                         KASSERT((p->flags & PG_FICTITIOUS) == 0,
1980                             ("vm_object_page_remove: page %p is fictitious",
1981                             p));
1982                         if ((options & OBJPR_CLEANONLY) != 0 && p->valid != 0) {
1983                                 if ((options & OBJPR_NOTMAPPED) == 0)
1984                                         pmap_remove_write(p);
1985                                 if (p->dirty) {
1986                                         vm_page_unlock(p);
1987                                         continue;
1988                                 }
1989                         }
1990                         if ((options & OBJPR_NOTMAPPED) == 0) {
1991                                 pmap_remove_all(p);
1992                                 /* Account for removal of wired mappings. */
1993                                 if (wirings != 0) {
1994                                         KASSERT(p->wire_count == wirings,
1995                                             ("inconsistent wire count %d %d %p",
1996                                             p->wire_count, wirings, p));
1997                                         p->wire_count = 0;
1998                                         atomic_subtract_int(&cnt.v_wire_count,
1999                                             1);
2000                                 }
2001                                 if (wirings != 0)
2002                                         p->wire_count -= wirings;
2003                         }
2004                         vm_page_free(p);
2005                         vm_page_unlock(p);
2006                 }
2007                 if (n < VM_RADIX_STACK)
2008                         break;
2009         }
2010         vm_object_pip_wakeup(object);
2011         if (vp)
2012                 vdrop(vp);
2013 }
2014
2015 /*
2016  *      vm_object_page_cache:
2017  *
2018  *      For the given object, attempt to move the specified clean
2019  *      pages to the cache queue.  If a page is wired for any reason,
2020  *      then it will not be changed.  Pages are specified by the given
2021  *      range ["start", "end").  As a special case, if "end" is zero,
2022  *      then the range extends from "start" to the end of the object.
2023  *      Any mappings to the specified pages are removed before the
2024  *      pages are moved to the cache queue.
2025  *
2026  *      This operation should only be performed on objects that
2027  *      contain non-fictitious, managed pages.
2028  *
2029  *      The object must be locked.
2030  */
2031 void
2032 vm_object_page_cache(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
2033 {
2034         struct mtx *mtx, *new_mtx;
2035         vm_page_t p, next;
2036
2037         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2038         KASSERT((object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0,
2039             ("vm_object_page_cache: illegal object %p", object));
2040         if (object->resident_page_count == 0)
2041                 return;
2042         p = vm_page_find_least(object, start);
2043
2044         /*
2045          * Here, the variable "p" is either (1) the page with the least pindex
2046          * greater than or equal to the parameter "start" or (2) NULL. 
2047          */
2048         mtx = NULL;
2049         for (; p != NULL && (p->pindex < end || end == 0); p = next) {
2050                 next = TAILQ_NEXT(p, listq);
2051
2052                 /*
2053                  * Avoid releasing and reacquiring the same page lock.
2054                  */
2055                 new_mtx = vm_page_lockptr(p);
2056                 if (mtx != new_mtx) {
2057                         if (mtx != NULL)
2058                                 mtx_unlock(mtx);
2059                         mtx = new_mtx;
2060                         mtx_lock(mtx);
2061                 }
2062                 vm_page_try_to_cache(p);
2063         }
2064         if (mtx != NULL)
2065                 mtx_unlock(mtx);
2066 }
2067
2068 /*
2069  *      Populate the specified range of the object with valid pages.  Returns
2070  *      TRUE if the range is successfully populated and FALSE otherwise.
2071  *
2072  *      Note: This function should be optimized to pass a larger array of
2073  *      pages to vm_pager_get_pages() before it is applied to a non-
2074  *      OBJT_DEVICE object.
2075  *
2076  *      The object must be locked.
2077  */
2078 boolean_t
2079 vm_object_populate(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
2080 {
2081         vm_page_t m, ma[1];
2082         vm_pindex_t pindex;
2083         int rv;
2084
2085         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2086         for (pindex = start; pindex < end; pindex++) {
2087                 m = vm_page_grab(object, pindex, VM_ALLOC_NORMAL |
2088                     VM_ALLOC_RETRY);
2089                 if (m->valid != VM_PAGE_BITS_ALL) {
2090                         ma[0] = m;
2091                         rv = vm_pager_get_pages(object, ma, 1, 0);
2092                         m = vm_page_lookup(object, pindex);
2093                         if (m == NULL)
2094                                 break;
2095                         if (rv != VM_PAGER_OK) {
2096                                 vm_page_lock(m);
2097                                 vm_page_free(m);
2098                                 vm_page_unlock(m);
2099                                 break;
2100                         }
2101                 }
2102                 /*
2103                  * Keep "m" busy because a subsequent iteration may unlock
2104                  * the object.
2105                  */
2106         }
2107         if (pindex > start) {
2108                 m = vm_page_lookup(object, start);
2109                 while (m != NULL && m->pindex < pindex) {
2110                         vm_page_wakeup(m);
2111                         m = TAILQ_NEXT(m, listq);
2112                 }
2113         }
2114         return (pindex == end);
2115 }
2116
2117 /*
2118  *      Routine:        vm_object_coalesce
2119  *      Function:       Coalesces two objects backing up adjoining
2120  *                      regions of memory into a single object.
2121  *
2122  *      returns TRUE if objects were combined.
2123  *
2124  *      NOTE:   Only works at the moment if the second object is NULL -
2125  *              if it's not, which object do we lock first?
2126  *
2127  *      Parameters:
2128  *              prev_object     First object to coalesce
2129  *              prev_offset     Offset into prev_object
2130  *              prev_size       Size of reference to prev_object
2131  *              next_size       Size of reference to the second object
2132  *              reserved        Indicator that extension region has
2133  *                              swap accounted for
2134  *
2135  *      Conditions:
2136  *      The object must *not* be locked.
2137  */
2138 boolean_t
2139 vm_object_coalesce(vm_object_t prev_object, vm_ooffset_t prev_offset,
2140     vm_size_t prev_size, vm_size_t next_size, boolean_t reserved)
2141 {
2142         vm_pindex_t next_pindex;
2143
2144         if (prev_object == NULL)
2145                 return (TRUE);
2146         VM_OBJECT_LOCK(prev_object);
2147         if (prev_object->type != OBJT_DEFAULT &&
2148             prev_object->type != OBJT_SWAP) {
2149                 VM_OBJECT_UNLOCK(prev_object);
2150                 return (FALSE);
2151         }
2152
2153         /*
2154          * Try to collapse the object first
2155          */
2156         vm_object_collapse(prev_object);
2157
2158         /*
2159          * Can't coalesce if: . more than one reference . paged out . shadows
2160          * another object . has a copy elsewhere (any of which mean that the
2161          * pages not mapped to prev_entry may be in use anyway)
2162          */
2163         if (prev_object->backing_object != NULL) {
2164                 VM_OBJECT_UNLOCK(prev_object);
2165                 return (FALSE);
2166         }
2167
2168         prev_size >>= PAGE_SHIFT;
2169         next_size >>= PAGE_SHIFT;
2170         next_pindex = OFF_TO_IDX(prev_offset) + prev_size;
2171
2172         if ((prev_object->ref_count > 1) &&
2173             (prev_object->size != next_pindex)) {
2174                 VM_OBJECT_UNLOCK(prev_object);
2175                 return (FALSE);
2176         }
2177
2178         /*
2179          * Account for the charge.
2180          */
2181         if (prev_object->cred != NULL) {
2182
2183                 /*
2184                  * If prev_object was charged, then this mapping,
2185                  * althought not charged now, may become writable
2186                  * later. Non-NULL cred in the object would prevent
2187                  * swap reservation during enabling of the write
2188                  * access, so reserve swap now. Failed reservation
2189                  * cause allocation of the separate object for the map
2190                  * entry, and swap reservation for this entry is
2191                  * managed in appropriate time.
2192                  */
2193                 if (!reserved && !swap_reserve_by_cred(ptoa(next_size),
2194                     prev_object->cred)) {
2195                         return (FALSE);
2196                 }
2197                 prev_object->charge += ptoa(next_size);
2198         }
2199
2200         /*
2201          * Remove any pages that may still be in the object from a previous
2202          * deallocation.
2203          */
2204         if (next_pindex < prev_object->size) {
2205                 vm_object_page_remove(prev_object, next_pindex, next_pindex +
2206                     next_size, 0);
2207                 if (prev_object->type == OBJT_SWAP)
2208                         swap_pager_freespace(prev_object,
2209                                              next_pindex, next_size);
2210 #if 0
2211                 if (prev_object->cred != NULL) {
2212                         KASSERT(prev_object->charge >=
2213                             ptoa(prev_object->size - next_pindex),
2214                             ("object %p overcharged 1 %jx %jx", prev_object,
2215                                 (uintmax_t)next_pindex, (uintmax_t)next_size));
2216                         prev_object->charge -= ptoa(prev_object->size -
2217                             next_pindex);
2218                 }
2219 #endif
2220         }
2221
2222         /*
2223          * Extend the object if necessary.
2224          */
2225         if (next_pindex + next_size > prev_object->size)
2226                 prev_object->size = next_pindex + next_size;
2227
2228         VM_OBJECT_UNLOCK(prev_object);
2229         return (TRUE);
2230 }
2231
2232 void
2233 vm_object_set_writeable_dirty(vm_object_t object)
2234 {
2235
2236         VM_OBJECT_LOCK_ASSERT(object, MA_OWNED);
2237         if (object->type != OBJT_VNODE)
2238                 return;
2239         object->generation++;
2240         if ((object->flags & OBJ_MIGHTBEDIRTY) != 0)
2241                 return;
2242         vm_object_set_flag(object, OBJ_MIGHTBEDIRTY);
2243 }
2244
2245 #include "opt_ddb.h"
2246 #ifdef DDB
2247 #include <sys/kernel.h>
2248
2249 #include <sys/cons.h>
2250
2251 #include <ddb/ddb.h>
2252
2253 static int
2254 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
2255 {
2256         vm_map_t tmpm;
2257         vm_map_entry_t tmpe;
2258         vm_object_t obj;
2259         int entcount;
2260
2261         if (map == 0)
2262                 return 0;
2263
2264         if (entry == 0) {
2265                 tmpe = map->header.next;
2266                 entcount = map->nentries;
2267                 while (entcount-- && (tmpe != &map->header)) {
2268                         if (_vm_object_in_map(map, object, tmpe)) {
2269                                 return 1;
2270                         }
2271                         tmpe = tmpe->next;
2272                 }
2273         } else if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
2274                 tmpm = entry->object.sub_map;
2275                 tmpe = tmpm->header.next;
2276                 entcount = tmpm->nentries;
2277                 while (entcount-- && tmpe != &tmpm->header) {
2278                         if (_vm_object_in_map(tmpm, object, tmpe)) {
2279                                 return 1;
2280                         }
2281                         tmpe = tmpe->next;
2282                 }
2283         } else if ((obj = entry->object.vm_object) != NULL) {
2284                 for (; obj; obj = obj->backing_object)
2285                         if (obj == object) {
2286                                 return 1;
2287                         }
2288         }
2289         return 0;
2290 }
2291
2292 static int
2293 vm_object_in_map(vm_object_t object)
2294 {
2295         struct proc *p;
2296
2297         /* sx_slock(&allproc_lock); */
2298         FOREACH_PROC_IN_SYSTEM(p) {
2299                 if (!p->p_vmspace /* || (p->p_flag & (P_SYSTEM|P_WEXIT)) */)
2300                         continue;
2301                 if (_vm_object_in_map(&p->p_vmspace->vm_map, object, 0)) {
2302                         /* sx_sunlock(&allproc_lock); */
2303                         return 1;
2304                 }
2305         }
2306         /* sx_sunlock(&allproc_lock); */
2307         if (_vm_object_in_map(kernel_map, object, 0))
2308                 return 1;
2309         if (_vm_object_in_map(kmem_map, object, 0))
2310                 return 1;
2311         if (_vm_object_in_map(pager_map, object, 0))
2312                 return 1;
2313         if (_vm_object_in_map(buffer_map, object, 0))
2314                 return 1;
2315         return 0;
2316 }
2317
2318 DB_SHOW_COMMAND(vmochk, vm_object_check)
2319 {
2320         vm_object_t object;
2321
2322         /*
2323          * make sure that internal objs are in a map somewhere
2324          * and none have zero ref counts.
2325          */
2326         TAILQ_FOREACH(object, &vm_object_list, object_list) {
2327                 if (object->handle == NULL &&
2328                     (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
2329                         if (object->ref_count == 0) {
2330                                 db_printf("vmochk: internal obj has zero ref count: %ld\n",
2331                                         (long)object->size);
2332                         }
2333                         if (!vm_object_in_map(object)) {
2334                                 db_printf(
2335                         "vmochk: internal obj is not in a map: "
2336                         "ref: %d, size: %lu: 0x%lx, backing_object: %p\n",
2337                                     object->ref_count, (u_long)object->size, 
2338                                     (u_long)object->size,
2339                                     (void *)object->backing_object);
2340                         }
2341                 }
2342         }
2343 }
2344
2345 /*
2346  *      vm_object_print:        [ debug ]
2347  */
2348 DB_SHOW_COMMAND(object, vm_object_print_static)
2349 {
2350         /* XXX convert args. */
2351         vm_object_t object = (vm_object_t)addr;
2352         boolean_t full = have_addr;
2353
2354         vm_page_t p;
2355
2356         /* XXX count is an (unused) arg.  Avoid shadowing it. */
2357 #define count   was_count
2358
2359         int count;
2360
2361         if (object == NULL)
2362                 return;
2363
2364         db_iprintf(
2365             "Object %p: type=%d, size=0x%jx, res=%d, ref=%d, flags=0x%x ruid %d charge %jx\n",
2366             object, (int)object->type, (uintmax_t)object->size,
2367             object->resident_page_count, object->ref_count, object->flags,
2368             object->cred ? object->cred->cr_ruid : -1, (uintmax_t)object->charge);
2369         db_iprintf(" sref=%d, backing_object(%d)=(%p)+0x%jx\n",
2370             object->shadow_count, 
2371             object->backing_object ? object->backing_object->ref_count : 0,
2372             object->backing_object, (uintmax_t)object->backing_object_offset);
2373
2374         if (!full)
2375                 return;
2376
2377         db_indent += 2;
2378         count = 0;
2379         TAILQ_FOREACH(p, &object->memq, listq) {
2380                 if (count == 0)
2381                         db_iprintf("memory:=");
2382                 else if (count == 6) {
2383                         db_printf("\n");
2384                         db_iprintf(" ...");
2385                         count = 0;
2386                 } else
2387                         db_printf(",");
2388                 count++;
2389
2390                 db_printf("(off=0x%jx,page=0x%jx,obj=%p,flags=0x%X)",
2391                     (uintmax_t)p->pindex, (uintmax_t)VM_PAGE_TO_PHYS(p),
2392                     p->object, p->flags);
2393         }
2394         if (count != 0)
2395                 db_printf("\n");
2396         db_indent -= 2;
2397 }
2398
2399 /* XXX. */
2400 #undef count
2401
2402 /* XXX need this non-static entry for calling from vm_map_print. */
2403 void
2404 vm_object_print(
2405         /* db_expr_t */ long addr,
2406         boolean_t have_addr,
2407         /* db_expr_t */ long count,
2408         char *modif)
2409 {
2410         vm_object_print_static(addr, have_addr, count, modif);
2411 }
2412
2413 DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
2414 {
2415         vm_object_t object;
2416         vm_pindex_t fidx;
2417         vm_paddr_t pa;
2418         vm_page_t m, prev_m;
2419         int rcount, nl, c;
2420
2421         nl = 0;
2422         TAILQ_FOREACH(object, &vm_object_list, object_list) {
2423                 db_printf("new object: %p\n", (void *)object);
2424                 if (nl > 18) {
2425                         c = cngetc();
2426                         if (c != ' ')
2427                                 return;
2428                         nl = 0;
2429                 }
2430                 nl++;
2431                 rcount = 0;
2432                 fidx = 0;
2433                 pa = -1;
2434                 TAILQ_FOREACH(m, &object->memq, listq) {
2435                         if (m->pindex > 128)
2436                                 break;
2437                         if ((prev_m = TAILQ_PREV(m, pglist, listq)) != NULL &&
2438                             prev_m->pindex + 1 != m->pindex) {
2439                                 if (rcount) {
2440                                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2441                                                 (long)fidx, rcount, (long)pa);
2442                                         if (nl > 18) {
2443                                                 c = cngetc();
2444                                                 if (c != ' ')
2445                                                         return;
2446                                                 nl = 0;
2447                                         }
2448                                         nl++;
2449                                         rcount = 0;
2450                                 }
2451                         }                               
2452                         if (rcount &&
2453                                 (VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
2454                                 ++rcount;
2455                                 continue;
2456                         }
2457                         if (rcount) {
2458                                 db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2459                                         (long)fidx, rcount, (long)pa);
2460                                 if (nl > 18) {
2461                                         c = cngetc();
2462                                         if (c != ' ')
2463                                                 return;
2464                                         nl = 0;
2465                                 }
2466                                 nl++;
2467                         }
2468                         fidx = m->pindex;
2469                         pa = VM_PAGE_TO_PHYS(m);
2470                         rcount = 1;
2471                 }
2472                 if (rcount) {
2473                         db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2474                                 (long)fidx, rcount, (long)pa);
2475                         if (nl > 18) {
2476                                 c = cngetc();
2477                                 if (c != ' ')
2478                                         return;
2479                                 nl = 0;
2480                         }
2481                         nl++;
2482                 }
2483         }
2484 }
2485 #endif /* DDB */