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