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