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