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