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