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