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