xref: /freebsd/sys/vm/vm_object.c (revision 32f9c9699a5a56ef8ef1da8e2974a8b34e2b84f5)
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  *
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 "opt_vm.h"
66 
67 #include <sys/systm.h>
68 #include <sys/blockcount.h>
69 #include <sys/conf.h>
70 #include <sys/cpuset.h>
71 #include <sys/ipc.h>
72 #include <sys/jail.h>
73 #include <sys/limits.h>
74 #include <sys/lock.h>
75 #include <sys/mman.h>
76 #include <sys/mount.h>
77 #include <sys/kernel.h>
78 #include <sys/mutex.h>
79 #include <sys/pctrie.h>
80 #include <sys/proc.h>
81 #include <sys/refcount.h>
82 #include <sys/shm.h>
83 #include <sys/sx.h>
84 #include <sys/sysctl.h>
85 #include <sys/resourcevar.h>
86 #include <sys/refcount.h>
87 #include <sys/rwlock.h>
88 #include <sys/user.h>
89 #include <sys/vnode.h>
90 #include <sys/vmmeter.h>
91 
92 #include <vm/vm.h>
93 #include <vm/vm_param.h>
94 #include <vm/pmap.h>
95 #include <vm/vm_map.h>
96 #include <vm/vm_object.h>
97 #include <vm/vm_page.h>
98 #include <vm/vm_pageout.h>
99 #include <vm/vm_pager.h>
100 #include <vm/vm_phys.h>
101 #include <vm/vm_pagequeue.h>
102 #include <vm/swap_pager.h>
103 #include <vm/vm_kern.h>
104 #include <vm/vm_extern.h>
105 #include <vm/vm_radix.h>
106 #include <vm/vm_reserv.h>
107 #include <vm/uma.h>
108 
109 static int old_msync;
110 SYSCTL_INT(_vm, OID_AUTO, old_msync, CTLFLAG_RW, &old_msync, 0,
111     "Use old (insecure) msync behavior");
112 
113 static boolean_t vm_object_page_remove_write(vm_page_t p, int flags,
114 		    boolean_t *allclean);
115 static void	vm_object_backing_remove(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 | CTLFLAG_MPSAFE, 0,
149     "VM object stats");
150 
151 static COUNTER_U64_DEFINE_EARLY(object_collapses);
152 SYSCTL_COUNTER_U64(_vm_stats_object, OID_AUTO, collapses, CTLFLAG_RD,
153     &object_collapses,
154     "VM object collapses");
155 
156 static COUNTER_U64_DEFINE_EARLY(object_bypasses);
157 SYSCTL_COUNTER_U64(_vm_stats_object, OID_AUTO, bypasses, CTLFLAG_RD,
158     &object_bypasses,
159     "VM object bypasses");
160 
161 static COUNTER_U64_DEFINE_EARLY(object_collapse_waits);
162 SYSCTL_COUNTER_U64(_vm_stats_object, OID_AUTO, collapse_waits, CTLFLAG_RD,
163     &object_collapse_waits,
164     "Number of sleeps for collapse");
165 
166 static uma_zone_t obj_zone;
167 
168 static int vm_object_zinit(void *mem, int size, int flags);
169 
170 #ifdef INVARIANTS
171 static void vm_object_zdtor(void *mem, int size, void *arg);
172 
173 static void
vm_object_zdtor(void * mem,int size,void * arg)174 vm_object_zdtor(void *mem, int size, void *arg)
175 {
176 	vm_object_t object;
177 
178 	object = (vm_object_t)mem;
179 	KASSERT(object->ref_count == 0,
180 	    ("object %p ref_count = %d", object, object->ref_count));
181 	KASSERT(vm_radix_is_empty(&object->rtree),
182 	    ("object %p has resident pages in its trie", object));
183 #if VM_NRESERVLEVEL > 0
184 	KASSERT(LIST_EMPTY(&object->rvq),
185 	    ("object %p has reservations",
186 	    object));
187 #endif
188 	KASSERT(!vm_object_busied(object),
189 	    ("object %p busy = %d", object, blockcount_read(&object->busy)));
190 	KASSERT(object->resident_page_count == 0,
191 	    ("object %p resident_page_count = %d",
192 	    object, object->resident_page_count));
193 	KASSERT(atomic_load_int(&object->shadow_count) == 0,
194 	    ("object %p shadow_count = %d",
195 	    object, atomic_load_int(&object->shadow_count)));
196 	KASSERT(object->type == OBJT_DEAD,
197 	    ("object %p has non-dead type %d",
198 	    object, object->type));
199 	KASSERT(object->charge == 0 && object->cred == NULL,
200 	    ("object %p has non-zero charge %ju (%p)",
201 	    object, (uintmax_t)object->charge, object->cred));
202 }
203 #endif
204 
205 static int
vm_object_zinit(void * mem,int size,int flags)206 vm_object_zinit(void *mem, int size, int flags)
207 {
208 	vm_object_t object;
209 
210 	object = (vm_object_t)mem;
211 	rw_init_flags(&object->lock, "vmobject", RW_DUPOK | RW_NEW);
212 
213 	/* These are true for any object that has been freed */
214 	object->type = OBJT_DEAD;
215 	vm_radix_init(&object->rtree);
216 	refcount_init(&object->ref_count, 0);
217 	blockcount_init(&object->paging_in_progress);
218 	blockcount_init(&object->busy);
219 	object->resident_page_count = 0;
220 	atomic_store_int(&object->shadow_count, 0);
221 	object->flags = OBJ_DEAD;
222 
223 	mtx_lock(&vm_object_list_mtx);
224 	TAILQ_INSERT_TAIL(&vm_object_list, object, object_list);
225 	mtx_unlock(&vm_object_list_mtx);
226 	return (0);
227 }
228 
229 static void
_vm_object_allocate(objtype_t type,vm_pindex_t size,u_short flags,vm_object_t object,void * handle)230 _vm_object_allocate(objtype_t type, vm_pindex_t size, u_short flags,
231     vm_object_t object, void *handle)
232 {
233 	LIST_INIT(&object->shadow_head);
234 
235 	object->type = type;
236 	object->flags = flags;
237 	if ((flags & OBJ_SWAP) != 0) {
238 		pctrie_init(&object->un_pager.swp.swp_blks);
239 		object->un_pager.swp.writemappings = 0;
240 	}
241 
242 	/*
243 	 * Ensure that swap_pager_swapoff() iteration over object_list
244 	 * sees up to date type and pctrie head if it observed
245 	 * non-dead object.
246 	 */
247 	atomic_thread_fence_rel();
248 
249 	object->pg_color = 0;
250 	object->size = size;
251 	object->domain.dr_policy = NULL;
252 	object->generation = 1;
253 	object->cleangeneration = 1;
254 	refcount_init(&object->ref_count, 1);
255 	object->memattr = VM_MEMATTR_DEFAULT;
256 	object->cred = NULL;
257 	object->charge = 0;
258 	object->handle = handle;
259 	object->backing_object = NULL;
260 	object->backing_object_offset = (vm_ooffset_t) 0;
261 #if VM_NRESERVLEVEL > 0
262 	LIST_INIT(&object->rvq);
263 #endif
264 	umtx_shm_object_init(object);
265 }
266 
267 /*
268  *	vm_object_init:
269  *
270  *	Initialize the VM objects module.
271  */
272 void
vm_object_init(void)273 vm_object_init(void)
274 {
275 	TAILQ_INIT(&vm_object_list);
276 	mtx_init(&vm_object_list_mtx, "vm object_list", NULL, MTX_DEF);
277 
278 	rw_init(&kernel_object->lock, "kernel vm object");
279 	vm_radix_init(&kernel_object->rtree);
280 	_vm_object_allocate(OBJT_PHYS, atop(VM_MAX_KERNEL_ADDRESS -
281 	    VM_MIN_KERNEL_ADDRESS), OBJ_UNMANAGED, kernel_object, NULL);
282 #if VM_NRESERVLEVEL > 0
283 	kernel_object->flags |= OBJ_COLORED;
284 	kernel_object->pg_color = (u_short)atop(VM_MIN_KERNEL_ADDRESS);
285 #endif
286 	kernel_object->un_pager.phys.ops = &default_phys_pg_ops;
287 
288 	/*
289 	 * The lock portion of struct vm_object must be type stable due
290 	 * to vm_pageout_fallback_object_lock locking a vm object
291 	 * without holding any references to it.
292 	 *
293 	 * paging_in_progress is valid always.  Lockless references to
294 	 * the objects may acquire pip and then check OBJ_DEAD.
295 	 */
296 	obj_zone = uma_zcreate("VM OBJECT", sizeof (struct vm_object), NULL,
297 #ifdef INVARIANTS
298 	    vm_object_zdtor,
299 #else
300 	    NULL,
301 #endif
302 	    vm_object_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
303 
304 	vm_radix_zinit();
305 }
306 
307 void
vm_object_clear_flag(vm_object_t object,u_short bits)308 vm_object_clear_flag(vm_object_t object, u_short bits)
309 {
310 
311 	VM_OBJECT_ASSERT_WLOCKED(object);
312 	object->flags &= ~bits;
313 }
314 
315 /*
316  *	Sets the default memory attribute for the specified object.  Pages
317  *	that are allocated to this object are by default assigned this memory
318  *	attribute.
319  *
320  *	Presently, this function must be called before any pages are allocated
321  *	to the object.  In the future, this requirement may be relaxed for
322  *	"default" and "swap" objects.
323  */
324 int
vm_object_set_memattr(vm_object_t object,vm_memattr_t memattr)325 vm_object_set_memattr(vm_object_t object, vm_memattr_t memattr)
326 {
327 
328 	VM_OBJECT_ASSERT_WLOCKED(object);
329 
330 	if (object->type == OBJT_DEAD)
331 		return (KERN_INVALID_ARGUMENT);
332 	if (!vm_radix_is_empty(&object->rtree))
333 		return (KERN_FAILURE);
334 
335 	object->memattr = memattr;
336 	return (KERN_SUCCESS);
337 }
338 
339 void
vm_object_pip_add(vm_object_t object,short i)340 vm_object_pip_add(vm_object_t object, short i)
341 {
342 
343 	if (i > 0)
344 		blockcount_acquire(&object->paging_in_progress, i);
345 }
346 
347 void
vm_object_pip_wakeup(vm_object_t object)348 vm_object_pip_wakeup(vm_object_t object)
349 {
350 
351 	vm_object_pip_wakeupn(object, 1);
352 }
353 
354 void
vm_object_pip_wakeupn(vm_object_t object,short i)355 vm_object_pip_wakeupn(vm_object_t object, short i)
356 {
357 
358 	if (i > 0)
359 		blockcount_release(&object->paging_in_progress, i);
360 }
361 
362 /*
363  * Atomically drop the object lock and wait for pip to drain.  This protects
364  * from sleep/wakeup races due to identity changes.  The lock is not re-acquired
365  * on return.
366  */
367 static void
vm_object_pip_sleep(vm_object_t object,const char * waitid)368 vm_object_pip_sleep(vm_object_t object, const char *waitid)
369 {
370 
371 	(void)blockcount_sleep(&object->paging_in_progress, &object->lock,
372 	    waitid, PVM | PDROP);
373 }
374 
375 void
vm_object_pip_wait(vm_object_t object,const char * waitid)376 vm_object_pip_wait(vm_object_t object, const char *waitid)
377 {
378 
379 	VM_OBJECT_ASSERT_WLOCKED(object);
380 
381 	blockcount_wait(&object->paging_in_progress, &object->lock, waitid,
382 	    PVM);
383 }
384 
385 void
vm_object_pip_wait_unlocked(vm_object_t object,const char * waitid)386 vm_object_pip_wait_unlocked(vm_object_t object, const char *waitid)
387 {
388 
389 	VM_OBJECT_ASSERT_UNLOCKED(object);
390 
391 	blockcount_wait(&object->paging_in_progress, NULL, waitid, PVM);
392 }
393 
394 /*
395  *	vm_object_allocate:
396  *
397  *	Returns a new object with the given size.
398  */
399 vm_object_t
vm_object_allocate(objtype_t type,vm_pindex_t size)400 vm_object_allocate(objtype_t type, vm_pindex_t size)
401 {
402 	vm_object_t object;
403 	u_short flags;
404 
405 	switch (type) {
406 	case OBJT_DEAD:
407 		panic("vm_object_allocate: can't create OBJT_DEAD");
408 	case OBJT_SWAP:
409 		flags = OBJ_COLORED | OBJ_SWAP;
410 		break;
411 	case OBJT_DEVICE:
412 	case OBJT_SG:
413 		flags = OBJ_FICTITIOUS | OBJ_UNMANAGED;
414 		break;
415 	case OBJT_MGTDEVICE:
416 		flags = OBJ_FICTITIOUS;
417 		break;
418 	case OBJT_PHYS:
419 		flags = OBJ_UNMANAGED;
420 		break;
421 	case OBJT_VNODE:
422 		flags = 0;
423 		break;
424 	default:
425 		panic("vm_object_allocate: type %d is undefined or dynamic",
426 		    type);
427 	}
428 	object = (vm_object_t)uma_zalloc(obj_zone, M_WAITOK);
429 	_vm_object_allocate(type, size, flags, object, NULL);
430 
431 	return (object);
432 }
433 
434 vm_object_t
vm_object_allocate_dyn(objtype_t dyntype,vm_pindex_t size,u_short flags)435 vm_object_allocate_dyn(objtype_t dyntype, vm_pindex_t size, u_short flags)
436 {
437 	vm_object_t object;
438 
439 	MPASS(dyntype >= OBJT_FIRST_DYN /* && dyntype < nitems(pagertab) */);
440 	object = (vm_object_t)uma_zalloc(obj_zone, M_WAITOK);
441 	_vm_object_allocate(dyntype, size, flags, object, NULL);
442 
443 	return (object);
444 }
445 
446 /*
447  *	vm_object_allocate_anon:
448  *
449  *	Returns a new default object of the given size and marked as
450  *	anonymous memory for special split/collapse handling.  Color
451  *	to be initialized by the caller.
452  */
453 vm_object_t
vm_object_allocate_anon(vm_pindex_t size,vm_object_t backing_object,struct ucred * cred,vm_size_t charge)454 vm_object_allocate_anon(vm_pindex_t size, vm_object_t backing_object,
455     struct ucred *cred, vm_size_t charge)
456 {
457 	vm_object_t handle, object;
458 
459 	if (backing_object == NULL)
460 		handle = NULL;
461 	else if ((backing_object->flags & OBJ_ANON) != 0)
462 		handle = backing_object->handle;
463 	else
464 		handle = backing_object;
465 	object = uma_zalloc(obj_zone, M_WAITOK);
466 	_vm_object_allocate(OBJT_SWAP, size,
467 	    OBJ_ANON | OBJ_ONEMAPPING | OBJ_SWAP, object, handle);
468 	object->cred = cred;
469 	object->charge = cred != NULL ? charge : 0;
470 	return (object);
471 }
472 
473 static void
vm_object_reference_vnode(vm_object_t object)474 vm_object_reference_vnode(vm_object_t object)
475 {
476 	u_int old;
477 
478 	/*
479 	 * vnode objects need the lock for the first reference
480 	 * to serialize with vnode_object_deallocate().
481 	 */
482 	if (!refcount_acquire_if_gt(&object->ref_count, 0)) {
483 		VM_OBJECT_RLOCK(object);
484 		old = refcount_acquire(&object->ref_count);
485 		if (object->type == OBJT_VNODE && old == 0)
486 			vref(object->handle);
487 		VM_OBJECT_RUNLOCK(object);
488 	}
489 }
490 
491 /*
492  *	vm_object_reference:
493  *
494  *	Acquires a reference to the given object.
495  */
496 void
vm_object_reference(vm_object_t object)497 vm_object_reference(vm_object_t object)
498 {
499 
500 	if (object == NULL)
501 		return;
502 
503 	if (object->type == OBJT_VNODE)
504 		vm_object_reference_vnode(object);
505 	else
506 		refcount_acquire(&object->ref_count);
507 	KASSERT((object->flags & OBJ_DEAD) == 0,
508 	    ("vm_object_reference: Referenced dead object."));
509 }
510 
511 /*
512  *	vm_object_reference_locked:
513  *
514  *	Gets another reference to the given object.
515  *
516  *	The object must be locked.
517  */
518 void
vm_object_reference_locked(vm_object_t object)519 vm_object_reference_locked(vm_object_t object)
520 {
521 	u_int old;
522 
523 	VM_OBJECT_ASSERT_LOCKED(object);
524 	old = refcount_acquire(&object->ref_count);
525 	if (object->type == OBJT_VNODE && old == 0)
526 		vref(object->handle);
527 	KASSERT((object->flags & OBJ_DEAD) == 0,
528 	    ("vm_object_reference: Referenced dead object."));
529 }
530 
531 /*
532  * Handle deallocating an object of type OBJT_VNODE.
533  */
534 static void
vm_object_deallocate_vnode(vm_object_t object)535 vm_object_deallocate_vnode(vm_object_t object)
536 {
537 	struct vnode *vp = (struct vnode *) object->handle;
538 	bool last;
539 
540 	KASSERT(object->type == OBJT_VNODE,
541 	    ("vm_object_deallocate_vnode: not a vnode object"));
542 	KASSERT(vp != NULL, ("vm_object_deallocate_vnode: missing vp"));
543 
544 	/* Object lock to protect handle lookup. */
545 	last = refcount_release(&object->ref_count);
546 	VM_OBJECT_RUNLOCK(object);
547 
548 	if (!last)
549 		return;
550 
551 	if (!umtx_shm_vnobj_persistent)
552 		umtx_shm_object_terminated(object);
553 
554 	/* vrele may need the vnode lock. */
555 	vrele(vp);
556 }
557 
558 /*
559  * We dropped a reference on an object and discovered that it had a
560  * single remaining shadow.  This is a sibling of the reference we
561  * dropped.  Attempt to collapse the sibling and backing object.
562  */
563 static vm_object_t
vm_object_deallocate_anon(vm_object_t backing_object)564 vm_object_deallocate_anon(vm_object_t backing_object)
565 {
566 	vm_object_t object;
567 
568 	/* Fetch the final shadow.  */
569 	object = LIST_FIRST(&backing_object->shadow_head);
570 	KASSERT(object != NULL &&
571 	    atomic_load_int(&backing_object->shadow_count) == 1,
572 	    ("vm_object_anon_deallocate: ref_count: %d, shadow_count: %d",
573 	    backing_object->ref_count,
574 	    atomic_load_int(&backing_object->shadow_count)));
575 	KASSERT((object->flags & OBJ_ANON) != 0,
576 	    ("invalid shadow object %p", object));
577 
578 	if (!VM_OBJECT_TRYWLOCK(object)) {
579 		/*
580 		 * Prevent object from disappearing since we do not have a
581 		 * reference.
582 		 */
583 		vm_object_pip_add(object, 1);
584 		VM_OBJECT_WUNLOCK(backing_object);
585 		VM_OBJECT_WLOCK(object);
586 		vm_object_pip_wakeup(object);
587 	} else
588 		VM_OBJECT_WUNLOCK(backing_object);
589 
590 	/*
591 	 * Check for a collapse/terminate race with the last reference holder.
592 	 */
593 	if ((object->flags & (OBJ_DEAD | OBJ_COLLAPSING)) != 0 ||
594 	    !refcount_acquire_if_not_zero(&object->ref_count)) {
595 		VM_OBJECT_WUNLOCK(object);
596 		return (NULL);
597 	}
598 	backing_object = object->backing_object;
599 	if (backing_object != NULL && (backing_object->flags & OBJ_ANON) != 0)
600 		vm_object_collapse(object);
601 	VM_OBJECT_WUNLOCK(object);
602 
603 	return (object);
604 }
605 
606 /*
607  *	vm_object_deallocate:
608  *
609  *	Release a reference to the specified object,
610  *	gained either through a vm_object_allocate
611  *	or a vm_object_reference call.  When all references
612  *	are gone, storage associated with this object
613  *	may be relinquished.
614  *
615  *	No object may be locked.
616  */
617 void
vm_object_deallocate(vm_object_t object)618 vm_object_deallocate(vm_object_t object)
619 {
620 	vm_object_t temp;
621 	bool released;
622 
623 	while (object != NULL) {
624 		/*
625 		 * If the reference count goes to 0 we start calling
626 		 * vm_object_terminate() on the object chain.  A ref count
627 		 * of 1 may be a special case depending on the shadow count
628 		 * being 0 or 1.  These cases require a write lock on the
629 		 * object.
630 		 */
631 		if ((object->flags & OBJ_ANON) == 0)
632 			released = refcount_release_if_gt(&object->ref_count, 1);
633 		else
634 			released = refcount_release_if_gt(&object->ref_count, 2);
635 		if (released)
636 			return;
637 
638 		if (object->type == OBJT_VNODE) {
639 			VM_OBJECT_RLOCK(object);
640 			if (object->type == OBJT_VNODE) {
641 				vm_object_deallocate_vnode(object);
642 				return;
643 			}
644 			VM_OBJECT_RUNLOCK(object);
645 		}
646 
647 		VM_OBJECT_WLOCK(object);
648 		KASSERT(object->ref_count > 0,
649 		    ("vm_object_deallocate: object deallocated too many times: %d",
650 		    object->type));
651 
652 		/*
653 		 * If this is not the final reference to an anonymous
654 		 * object we may need to collapse the shadow chain.
655 		 */
656 		if (!refcount_release(&object->ref_count)) {
657 			if (object->ref_count > 1 ||
658 			    atomic_load_int(&object->shadow_count) == 0) {
659 				if ((object->flags & OBJ_ANON) != 0 &&
660 				    object->ref_count == 1)
661 					vm_object_set_flag(object,
662 					    OBJ_ONEMAPPING);
663 				VM_OBJECT_WUNLOCK(object);
664 				return;
665 			}
666 
667 			/* Handle collapsing last ref on anonymous objects. */
668 			object = vm_object_deallocate_anon(object);
669 			continue;
670 		}
671 
672 		/*
673 		 * Handle the final reference to an object.  We restart
674 		 * the loop with the backing object to avoid recursion.
675 		 */
676 		umtx_shm_object_terminated(object);
677 		temp = object->backing_object;
678 		if (temp != NULL) {
679 			KASSERT(object->type == OBJT_SWAP,
680 			    ("shadowed tmpfs v_object 2 %p", object));
681 			vm_object_backing_remove(object);
682 		}
683 
684 		KASSERT((object->flags & OBJ_DEAD) == 0,
685 		    ("vm_object_deallocate: Terminating dead object."));
686 		vm_object_set_flag(object, OBJ_DEAD);
687 		vm_object_terminate(object);
688 		object = temp;
689 	}
690 }
691 
692 void
vm_object_destroy(vm_object_t object)693 vm_object_destroy(vm_object_t object)
694 {
695 	uma_zfree(obj_zone, object);
696 }
697 
698 static void
vm_object_sub_shadow(vm_object_t object)699 vm_object_sub_shadow(vm_object_t object)
700 {
701 	KASSERT(object->shadow_count >= 1,
702 	    ("object %p sub_shadow count zero", object));
703 	atomic_subtract_int(&object->shadow_count, 1);
704 }
705 
706 static void
vm_object_backing_remove_locked(vm_object_t object)707 vm_object_backing_remove_locked(vm_object_t object)
708 {
709 	vm_object_t backing_object;
710 
711 	backing_object = object->backing_object;
712 	VM_OBJECT_ASSERT_WLOCKED(object);
713 	VM_OBJECT_ASSERT_WLOCKED(backing_object);
714 
715 	KASSERT((object->flags & OBJ_COLLAPSING) == 0,
716 	    ("vm_object_backing_remove: Removing collapsing object."));
717 
718 	vm_object_sub_shadow(backing_object);
719 	if ((object->flags & OBJ_SHADOWLIST) != 0) {
720 		LIST_REMOVE(object, shadow_list);
721 		vm_object_clear_flag(object, OBJ_SHADOWLIST);
722 	}
723 	object->backing_object = NULL;
724 }
725 
726 static void
vm_object_backing_remove(vm_object_t object)727 vm_object_backing_remove(vm_object_t object)
728 {
729 	vm_object_t backing_object;
730 
731 	VM_OBJECT_ASSERT_WLOCKED(object);
732 
733 	backing_object = object->backing_object;
734 	if ((object->flags & OBJ_SHADOWLIST) != 0) {
735 		VM_OBJECT_WLOCK(backing_object);
736 		vm_object_backing_remove_locked(object);
737 		VM_OBJECT_WUNLOCK(backing_object);
738 	} else {
739 		object->backing_object = NULL;
740 		vm_object_sub_shadow(backing_object);
741 	}
742 }
743 
744 static void
vm_object_backing_insert_locked(vm_object_t object,vm_object_t backing_object)745 vm_object_backing_insert_locked(vm_object_t object, vm_object_t backing_object)
746 {
747 
748 	VM_OBJECT_ASSERT_WLOCKED(object);
749 
750 	atomic_add_int(&backing_object->shadow_count, 1);
751 	if ((backing_object->flags & OBJ_ANON) != 0) {
752 		VM_OBJECT_ASSERT_WLOCKED(backing_object);
753 		LIST_INSERT_HEAD(&backing_object->shadow_head, object,
754 		    shadow_list);
755 		vm_object_set_flag(object, OBJ_SHADOWLIST);
756 	}
757 	object->backing_object = backing_object;
758 }
759 
760 static void
vm_object_backing_insert(vm_object_t object,vm_object_t backing_object)761 vm_object_backing_insert(vm_object_t object, vm_object_t backing_object)
762 {
763 
764 	VM_OBJECT_ASSERT_WLOCKED(object);
765 
766 	if ((backing_object->flags & OBJ_ANON) != 0) {
767 		VM_OBJECT_WLOCK(backing_object);
768 		vm_object_backing_insert_locked(object, backing_object);
769 		VM_OBJECT_WUNLOCK(backing_object);
770 	} else {
771 		object->backing_object = backing_object;
772 		atomic_add_int(&backing_object->shadow_count, 1);
773 	}
774 }
775 
776 /*
777  * Insert an object into a backing_object's shadow list with an additional
778  * reference to the backing_object added.
779  */
780 static void
vm_object_backing_insert_ref(vm_object_t object,vm_object_t backing_object)781 vm_object_backing_insert_ref(vm_object_t object, vm_object_t backing_object)
782 {
783 
784 	VM_OBJECT_ASSERT_WLOCKED(object);
785 
786 	if ((backing_object->flags & OBJ_ANON) != 0) {
787 		VM_OBJECT_WLOCK(backing_object);
788 		KASSERT((backing_object->flags & OBJ_DEAD) == 0,
789 		    ("shadowing dead anonymous object"));
790 		vm_object_reference_locked(backing_object);
791 		vm_object_backing_insert_locked(object, backing_object);
792 		vm_object_clear_flag(backing_object, OBJ_ONEMAPPING);
793 		VM_OBJECT_WUNLOCK(backing_object);
794 	} else {
795 		vm_object_reference(backing_object);
796 		atomic_add_int(&backing_object->shadow_count, 1);
797 		object->backing_object = backing_object;
798 	}
799 }
800 
801 /*
802  * Transfer a backing reference from backing_object to object.
803  */
804 static void
vm_object_backing_transfer(vm_object_t object,vm_object_t backing_object)805 vm_object_backing_transfer(vm_object_t object, vm_object_t backing_object)
806 {
807 	vm_object_t new_backing_object;
808 
809 	/*
810 	 * Note that the reference to backing_object->backing_object
811 	 * moves from within backing_object to within object.
812 	 */
813 	vm_object_backing_remove_locked(object);
814 	new_backing_object = backing_object->backing_object;
815 	if (new_backing_object == NULL)
816 		return;
817 	if ((new_backing_object->flags & OBJ_ANON) != 0) {
818 		VM_OBJECT_WLOCK(new_backing_object);
819 		vm_object_backing_remove_locked(backing_object);
820 		vm_object_backing_insert_locked(object, new_backing_object);
821 		VM_OBJECT_WUNLOCK(new_backing_object);
822 	} else {
823 		/*
824 		 * shadow_count for new_backing_object is left
825 		 * unchanged, its reference provided by backing_object
826 		 * is replaced by object.
827 		 */
828 		object->backing_object = new_backing_object;
829 		backing_object->backing_object = NULL;
830 	}
831 }
832 
833 /*
834  * Wait for a concurrent collapse to settle.
835  */
836 static void
vm_object_collapse_wait(vm_object_t object)837 vm_object_collapse_wait(vm_object_t object)
838 {
839 
840 	VM_OBJECT_ASSERT_WLOCKED(object);
841 
842 	while ((object->flags & OBJ_COLLAPSING) != 0) {
843 		vm_object_pip_wait(object, "vmcolwait");
844 		counter_u64_add(object_collapse_waits, 1);
845 	}
846 }
847 
848 /*
849  * Waits for a backing object to clear a pending collapse and returns
850  * it locked if it is an ANON object.
851  */
852 static vm_object_t
vm_object_backing_collapse_wait(vm_object_t object)853 vm_object_backing_collapse_wait(vm_object_t object)
854 {
855 	vm_object_t backing_object;
856 
857 	VM_OBJECT_ASSERT_WLOCKED(object);
858 
859 	for (;;) {
860 		backing_object = object->backing_object;
861 		if (backing_object == NULL ||
862 		    (backing_object->flags & OBJ_ANON) == 0)
863 			return (NULL);
864 		VM_OBJECT_WLOCK(backing_object);
865 		if ((backing_object->flags & (OBJ_DEAD | OBJ_COLLAPSING)) == 0)
866 			break;
867 		VM_OBJECT_WUNLOCK(object);
868 		vm_object_pip_sleep(backing_object, "vmbckwait");
869 		counter_u64_add(object_collapse_waits, 1);
870 		VM_OBJECT_WLOCK(object);
871 	}
872 	return (backing_object);
873 }
874 
875 /*
876  *	vm_object_terminate_single_page removes a pageable page from the object,
877  *	and removes it from the paging queues and frees it, if it is not wired.
878  *	It is invoked via callback from vm_object_terminate_pages.
879  */
880 static void
vm_object_terminate_single_page(vm_page_t p,void * objectv)881 vm_object_terminate_single_page(vm_page_t p, void *objectv)
882 {
883 	vm_object_t object __diagused = objectv;
884 
885 	vm_page_assert_unbusied(p);
886 	KASSERT(p->object == object &&
887 	    (p->ref_count & VPRC_OBJREF) != 0,
888 	    ("%s: page %p is inconsistent", __func__, p));
889 	p->object = NULL;
890 	if (vm_page_drop(p, VPRC_OBJREF) == VPRC_OBJREF) {
891 		KASSERT((object->flags & OBJ_UNMANAGED) != 0 ||
892 		    vm_page_astate_load(p).queue != PQ_NONE,
893 		    ("%s: page %p does not belong to a queue", __func__, p));
894 		VM_CNT_INC(v_pfree);
895 		vm_page_free(p);
896 	}
897 }
898 
899 /*
900  *	vm_object_terminate_pages removes any remaining pageable pages
901  *	from the object and resets the object to an empty state.
902  */
903 static void
vm_object_terminate_pages(vm_object_t object)904 vm_object_terminate_pages(vm_object_t object)
905 {
906 	VM_OBJECT_ASSERT_WLOCKED(object);
907 
908 	/*
909 	 * If the object contained any pages, then reset it to an empty state.
910 	 * Rather than incrementally removing each page from the object, the
911 	 * page and object are reset to any empty state.
912 	 */
913 	if (object->resident_page_count == 0)
914 		return;
915 
916 	vm_radix_reclaim_callback(&object->rtree,
917 	    vm_object_terminate_single_page, object);
918 	object->resident_page_count = 0;
919 	if (object->type == OBJT_VNODE)
920 		vdrop(object->handle);
921 }
922 
923 /*
924  *	vm_object_terminate actually destroys the specified object, freeing
925  *	up all previously used resources.
926  *
927  *	The object must be locked.
928  *	This routine may block.
929  */
930 void
vm_object_terminate(vm_object_t object)931 vm_object_terminate(vm_object_t object)
932 {
933 
934 	VM_OBJECT_ASSERT_WLOCKED(object);
935 	KASSERT((object->flags & OBJ_DEAD) != 0,
936 	    ("terminating non-dead obj %p", object));
937 	KASSERT((object->flags & OBJ_COLLAPSING) == 0,
938 	    ("terminating collapsing obj %p", object));
939 	KASSERT(object->backing_object == NULL,
940 	    ("terminating shadow obj %p", object));
941 
942 	/*
943 	 * Wait for the pageout daemon and other current users to be
944 	 * done with the object.  Note that new paging_in_progress
945 	 * users can come after this wait, but they must check
946 	 * OBJ_DEAD flag set (without unlocking the object), and avoid
947 	 * the object being terminated.
948 	 */
949 	vm_object_pip_wait(object, "objtrm");
950 
951 	KASSERT(object->ref_count == 0,
952 	    ("vm_object_terminate: object with references, ref_count=%d",
953 	    object->ref_count));
954 
955 	if ((object->flags & OBJ_PG_DTOR) == 0)
956 		vm_object_terminate_pages(object);
957 
958 #if VM_NRESERVLEVEL > 0
959 	if (__predict_false(!LIST_EMPTY(&object->rvq)))
960 		vm_reserv_break_all(object);
961 #endif
962 
963 	KASSERT(object->cred == NULL || (object->flags & OBJ_SWAP) != 0,
964 	    ("%s: non-swap obj %p has cred", __func__, object));
965 
966 	/*
967 	 * Let the pager know object is dead.
968 	 */
969 	vm_pager_deallocate(object);
970 	VM_OBJECT_WUNLOCK(object);
971 
972 	vm_object_destroy(object);
973 }
974 
975 /*
976  * Make the page read-only so that we can clear the object flags.  However, if
977  * this is a nosync mmap then the object is likely to stay dirty so do not
978  * mess with the page and do not clear the object flags.  Returns TRUE if the
979  * page should be flushed, and FALSE otherwise.
980  */
981 static boolean_t
vm_object_page_remove_write(vm_page_t p,int flags,boolean_t * allclean)982 vm_object_page_remove_write(vm_page_t p, int flags, boolean_t *allclean)
983 {
984 
985 	vm_page_assert_busied(p);
986 
987 	/*
988 	 * If we have been asked to skip nosync pages and this is a
989 	 * nosync page, skip it.  Note that the object flags were not
990 	 * cleared in this case so we do not have to set them.
991 	 */
992 	if ((flags & OBJPC_NOSYNC) != 0 && (p->a.flags & PGA_NOSYNC) != 0) {
993 		*allclean = FALSE;
994 		return (FALSE);
995 	} else {
996 		pmap_remove_write(p);
997 		return (p->dirty != 0);
998 	}
999 }
1000 
1001 static int
vm_object_page_clean_flush(struct pctrie_iter * pages,vm_page_t p,int pagerflags,int flags,boolean_t * allclean,bool * eio)1002 vm_object_page_clean_flush(struct pctrie_iter *pages, vm_page_t p,
1003     int pagerflags, int flags, boolean_t *allclean, bool *eio)
1004 {
1005 	vm_page_t ma[vm_pageout_page_count];
1006 	int count, runlen;
1007 
1008 	vm_page_assert_xbusied(p);
1009 	ma[0] = p;
1010 	runlen = vm_radix_iter_lookup_range(pages, p->pindex + 1,
1011 	    &ma[1], vm_pageout_page_count - 1);
1012 	for (count = 1; count <= runlen; count++) {
1013 		p = ma[count];
1014 		if (vm_page_tryxbusy(p) == 0)
1015 			break;
1016 		if (!vm_object_page_remove_write(p, flags, allclean)) {
1017 			vm_page_xunbusy(p);
1018 			break;
1019 		}
1020 	}
1021 
1022 	return (vm_pageout_flush(ma, count, pagerflags, eio));
1023 }
1024 
1025 /*
1026  *	vm_object_page_clean
1027  *
1028  *	Clean all dirty pages in the specified range of object.  Leaves page
1029  * 	on whatever queue it is currently on.   If NOSYNC is set then do not
1030  *	write out pages with PGA_NOSYNC set (originally comes from MAP_NOSYNC),
1031  *	leaving the object dirty.
1032  *
1033  *	For swap objects backing tmpfs regular files, do not flush anything,
1034  *	but remove write protection on the mapped pages to update mtime through
1035  *	mmaped writes.
1036  *
1037  *	When stuffing pages asynchronously, allow clustering.  XXX we need a
1038  *	synchronous clustering mode implementation.
1039  *
1040  *	Odd semantics: if start == end, we clean everything.
1041  *
1042  *	The object must be locked.
1043  *
1044  *	Returns FALSE if some page from the range was not written, as
1045  *	reported by the pager, and TRUE otherwise.
1046  */
1047 boolean_t
vm_object_page_clean(vm_object_t object,vm_ooffset_t start,vm_ooffset_t end,int flags)1048 vm_object_page_clean(vm_object_t object, vm_ooffset_t start, vm_ooffset_t end,
1049     int flags)
1050 {
1051 	struct pctrie_iter pages;
1052 	vm_page_t np, p;
1053 	vm_pindex_t pi, tend, tstart;
1054 	int curgeneration, n, pagerflags;
1055 	boolean_t res, allclean;
1056 	bool eio;
1057 
1058 	VM_OBJECT_ASSERT_WLOCKED(object);
1059 
1060 	if (!vm_object_mightbedirty(object) || object->resident_page_count == 0)
1061 		return (TRUE);
1062 
1063 	pagerflags = (flags & (OBJPC_SYNC | OBJPC_INVAL)) != 0 ?
1064 	    VM_PAGER_PUT_SYNC : VM_PAGER_CLUSTER_OK;
1065 	pagerflags |= (flags & OBJPC_INVAL) != 0 ? VM_PAGER_PUT_INVAL : 0;
1066 
1067 	tstart = OFF_TO_IDX(start);
1068 	tend = (end == 0) ? object->size : OFF_TO_IDX(end + PAGE_MASK);
1069 	allclean = tstart == 0 && tend >= object->size;
1070 	res = TRUE;
1071 	vm_page_iter_init(&pages, object);
1072 
1073 rescan:
1074 	curgeneration = object->generation;
1075 
1076 	for (p = vm_radix_iter_lookup_ge(&pages, tstart); p != NULL; p = np) {
1077 		pi = p->pindex;
1078 		if (pi >= tend)
1079 			break;
1080 		if (vm_page_none_valid(p)) {
1081 			np = vm_radix_iter_step(&pages);
1082 			continue;
1083 		}
1084 		if (!vm_page_busy_acquire(p, VM_ALLOC_WAITFAIL)) {
1085 			pctrie_iter_reset(&pages);
1086 			if (object->generation != curgeneration &&
1087 			    (flags & OBJPC_SYNC) != 0)
1088 				goto rescan;
1089 			np = vm_radix_iter_lookup_ge(&pages, pi);
1090 			continue;
1091 		}
1092 		if (!vm_object_page_remove_write(p, flags, &allclean)) {
1093 			np = vm_radix_iter_step(&pages);
1094 			vm_page_xunbusy(p);
1095 			continue;
1096 		}
1097 		if (object->type == OBJT_VNODE) {
1098 			n = vm_object_page_clean_flush(&pages, p, pagerflags,
1099 			    flags, &allclean, &eio);
1100 			pctrie_iter_reset(&pages);
1101 			if (eio) {
1102 				res = FALSE;
1103 				allclean = FALSE;
1104 			}
1105 			if (object->generation != curgeneration &&
1106 			    (flags & OBJPC_SYNC) != 0)
1107 				goto rescan;
1108 
1109 			/*
1110 			 * If the VOP_PUTPAGES() did a truncated write, so
1111 			 * that even the first page of the run is not fully
1112 			 * written, vm_pageout_flush() returns 0 as the run
1113 			 * length.  Since the condition that caused truncated
1114 			 * write may be permanent, e.g. exhausted free space,
1115 			 * accepting n == 0 would cause an infinite loop.
1116 			 *
1117 			 * Forwarding the iterator leaves the unwritten page
1118 			 * behind, but there is not much we can do there if
1119 			 * filesystem refuses to write it.
1120 			 */
1121 			if (n == 0) {
1122 				n = 1;
1123 				allclean = FALSE;
1124 			}
1125 		} else {
1126 			n = 1;
1127 			vm_page_xunbusy(p);
1128 		}
1129 		np = vm_radix_iter_lookup_ge(&pages, pi + n);
1130 	}
1131 #if 0
1132 	VOP_FSYNC(vp, (pagerflags & VM_PAGER_PUT_SYNC) ? MNT_WAIT : 0);
1133 #endif
1134 
1135 	/*
1136 	 * Leave updating cleangeneration for tmpfs objects to tmpfs
1137 	 * scan.  It needs to update mtime, which happens for other
1138 	 * filesystems during page writeouts.
1139 	 */
1140 	if (allclean && object->type == OBJT_VNODE)
1141 		object->cleangeneration = curgeneration;
1142 	return (res);
1143 }
1144 
1145 /*
1146  * Note that there is absolutely no sense in writing out
1147  * anonymous objects, so we track down the vnode object
1148  * to write out.
1149  * We invalidate (remove) all pages from the address space
1150  * for semantic correctness.
1151  *
1152  * If the backing object is a device object with unmanaged pages, then any
1153  * mappings to the specified range of pages must be removed before this
1154  * function is called.
1155  *
1156  * Note: certain anonymous maps, such as MAP_NOSYNC maps,
1157  * may start out with a NULL object.
1158  */
1159 boolean_t
vm_object_sync(vm_object_t object,vm_ooffset_t offset,vm_size_t size,boolean_t syncio,boolean_t invalidate)1160 vm_object_sync(vm_object_t object, vm_ooffset_t offset, vm_size_t size,
1161     boolean_t syncio, boolean_t invalidate)
1162 {
1163 	vm_object_t backing_object;
1164 	struct vnode *vp;
1165 	struct mount *mp;
1166 	int error, flags, fsync_after;
1167 	boolean_t res;
1168 
1169 	if (object == NULL)
1170 		return (TRUE);
1171 	res = TRUE;
1172 	error = 0;
1173 	VM_OBJECT_WLOCK(object);
1174 	while ((backing_object = object->backing_object) != NULL) {
1175 		VM_OBJECT_WLOCK(backing_object);
1176 		offset += object->backing_object_offset;
1177 		VM_OBJECT_WUNLOCK(object);
1178 		object = backing_object;
1179 		if (object->size < OFF_TO_IDX(offset + size))
1180 			size = IDX_TO_OFF(object->size) - offset;
1181 	}
1182 	/*
1183 	 * Flush pages if writing is allowed, invalidate them
1184 	 * if invalidation requested.  Pages undergoing I/O
1185 	 * will be ignored by vm_object_page_remove().
1186 	 *
1187 	 * We cannot lock the vnode and then wait for paging
1188 	 * to complete without deadlocking against vm_fault.
1189 	 * Instead we simply call vm_object_page_remove() and
1190 	 * allow it to block internally on a page-by-page
1191 	 * basis when it encounters pages undergoing async
1192 	 * I/O.
1193 	 */
1194 	if (object->type == OBJT_VNODE &&
1195 	    vm_object_mightbedirty(object) != 0 &&
1196 	    ((vp = object->handle)->v_vflag & VV_NOSYNC) == 0) {
1197 		VM_OBJECT_WUNLOCK(object);
1198 		(void)vn_start_write(vp, &mp, V_WAIT);
1199 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1200 		if (syncio && !invalidate && offset == 0 &&
1201 		    atop(size) == object->size) {
1202 			/*
1203 			 * If syncing the whole mapping of the file,
1204 			 * it is faster to schedule all the writes in
1205 			 * async mode, also allowing the clustering,
1206 			 * and then wait for i/o to complete.
1207 			 */
1208 			flags = 0;
1209 			fsync_after = TRUE;
1210 		} else {
1211 			flags = (syncio || invalidate) ? OBJPC_SYNC : 0;
1212 			flags |= invalidate ? (OBJPC_SYNC | OBJPC_INVAL) : 0;
1213 			fsync_after = FALSE;
1214 		}
1215 		VM_OBJECT_WLOCK(object);
1216 		res = vm_object_page_clean(object, offset, offset + size,
1217 		    flags);
1218 		VM_OBJECT_WUNLOCK(object);
1219 		if (fsync_after) {
1220 			for (;;) {
1221 				error = VOP_FSYNC(vp, MNT_WAIT, curthread);
1222 				if (error != ERELOOKUP)
1223 					break;
1224 
1225 				/*
1226 				 * Allow SU/bufdaemon to handle more
1227 				 * dependencies in the meantime.
1228 				 */
1229 				VOP_UNLOCK(vp);
1230 				vn_finished_write(mp);
1231 
1232 				(void)vn_start_write(vp, &mp, V_WAIT);
1233 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1234 			}
1235 		}
1236 		VOP_UNLOCK(vp);
1237 		vn_finished_write(mp);
1238 		if (error != 0)
1239 			res = FALSE;
1240 		VM_OBJECT_WLOCK(object);
1241 	}
1242 	if ((object->type == OBJT_VNODE ||
1243 	     object->type == OBJT_DEVICE) && invalidate) {
1244 		if (object->type == OBJT_DEVICE)
1245 			/*
1246 			 * The option OBJPR_NOTMAPPED must be passed here
1247 			 * because vm_object_page_remove() cannot remove
1248 			 * unmanaged mappings.
1249 			 */
1250 			flags = OBJPR_NOTMAPPED;
1251 		else if (old_msync)
1252 			flags = 0;
1253 		else
1254 			flags = OBJPR_CLEANONLY;
1255 		vm_object_page_remove(object, OFF_TO_IDX(offset),
1256 		    OFF_TO_IDX(offset + size + PAGE_MASK), flags);
1257 	}
1258 	VM_OBJECT_WUNLOCK(object);
1259 	return (res);
1260 }
1261 
1262 /*
1263  * Determine whether the given advice can be applied to the object.  Advice is
1264  * not applied to unmanaged pages since they never belong to page queues, and
1265  * since MADV_FREE is destructive, it can apply only to anonymous pages that
1266  * have been mapped at most once.
1267  */
1268 static bool
vm_object_advice_applies(vm_object_t object,int advice)1269 vm_object_advice_applies(vm_object_t object, int advice)
1270 {
1271 
1272 	if ((object->flags & OBJ_UNMANAGED) != 0)
1273 		return (false);
1274 	if (advice != MADV_FREE)
1275 		return (true);
1276 	return ((object->flags & (OBJ_ONEMAPPING | OBJ_ANON)) ==
1277 	    (OBJ_ONEMAPPING | OBJ_ANON));
1278 }
1279 
1280 static void
vm_object_madvise_freespace(vm_object_t object,int advice,vm_pindex_t pindex,vm_size_t size)1281 vm_object_madvise_freespace(vm_object_t object, int advice, vm_pindex_t pindex,
1282     vm_size_t size)
1283 {
1284 
1285 	if (advice == MADV_FREE)
1286 		vm_pager_freespace(object, pindex, size);
1287 }
1288 
1289 /*
1290  *	vm_object_madvise:
1291  *
1292  *	Implements the madvise function at the object/page level.
1293  *
1294  *	MADV_WILLNEED	(any object)
1295  *
1296  *	    Activate the specified pages if they are resident.
1297  *
1298  *	MADV_DONTNEED	(any object)
1299  *
1300  *	    Deactivate the specified pages if they are resident.
1301  *
1302  *	MADV_FREE	(OBJT_SWAP objects, OBJ_ONEMAPPING only)
1303  *
1304  *	    Deactivate and clean the specified pages if they are
1305  *	    resident.  This permits the process to reuse the pages
1306  *	    without faulting or the kernel to reclaim the pages
1307  *	    without I/O.
1308  */
1309 void
vm_object_madvise(vm_object_t object,vm_pindex_t pindex,vm_pindex_t end,int advice)1310 vm_object_madvise(vm_object_t object, vm_pindex_t pindex, vm_pindex_t end,
1311     int advice)
1312 {
1313 	struct pctrie_iter pages;
1314 	vm_pindex_t tpindex;
1315 	vm_object_t backing_object, tobject;
1316 	vm_page_t m, tm;
1317 
1318 	if (object == NULL)
1319 		return;
1320 
1321 	vm_page_iter_init(&pages, object);
1322 relookup:
1323 	VM_OBJECT_WLOCK(object);
1324 	if (!vm_object_advice_applies(object, advice)) {
1325 		VM_OBJECT_WUNLOCK(object);
1326 		return;
1327 	}
1328 	for (m = vm_radix_iter_lookup_ge(&pages, pindex); pindex < end;
1329 	    pindex++) {
1330 		tobject = object;
1331 
1332 		/*
1333 		 * If the next page isn't resident in the top-level object, we
1334 		 * need to search the shadow chain.  When applying MADV_FREE, we
1335 		 * take care to release any swap space used to store
1336 		 * non-resident pages.
1337 		 */
1338 		if (m == NULL || pindex < m->pindex) {
1339 			/*
1340 			 * Optimize a common case: if the top-level object has
1341 			 * no backing object, we can skip over the non-resident
1342 			 * range in constant time.
1343 			 */
1344 			if (object->backing_object == NULL) {
1345 				tpindex = (m != NULL && m->pindex < end) ?
1346 				    m->pindex : end;
1347 				vm_object_madvise_freespace(object, advice,
1348 				    pindex, tpindex - pindex);
1349 				if ((pindex = tpindex) == end)
1350 					break;
1351 				goto next_page;
1352 			}
1353 
1354 			tpindex = pindex;
1355 			do {
1356 				vm_object_madvise_freespace(tobject, advice,
1357 				    tpindex, 1);
1358 				/*
1359 				 * Prepare to search the next object in the
1360 				 * chain.
1361 				 */
1362 				backing_object = tobject->backing_object;
1363 				if (backing_object == NULL)
1364 					goto next_pindex;
1365 				VM_OBJECT_WLOCK(backing_object);
1366 				tpindex +=
1367 				    OFF_TO_IDX(tobject->backing_object_offset);
1368 				if (tobject != object)
1369 					VM_OBJECT_WUNLOCK(tobject);
1370 				tobject = backing_object;
1371 				if (!vm_object_advice_applies(tobject, advice))
1372 					goto next_pindex;
1373 			} while ((tm = vm_page_lookup(tobject, tpindex)) ==
1374 			    NULL);
1375 		} else {
1376 next_page:
1377 			tm = m;
1378 			m = vm_radix_iter_step(&pages);
1379 		}
1380 
1381 		/*
1382 		 * If the page is not in a normal state, skip it.  The page
1383 		 * can not be invalidated while the object lock is held.
1384 		 */
1385 		if (!vm_page_all_valid(tm) || vm_page_wired(tm))
1386 			goto next_pindex;
1387 		KASSERT((tm->flags & PG_FICTITIOUS) == 0,
1388 		    ("vm_object_madvise: page %p is fictitious", tm));
1389 		KASSERT((tm->oflags & VPO_UNMANAGED) == 0,
1390 		    ("vm_object_madvise: page %p is not managed", tm));
1391 		if (vm_page_tryxbusy(tm) == 0) {
1392 			if (object != tobject)
1393 				VM_OBJECT_WUNLOCK(object);
1394 			if (advice == MADV_WILLNEED) {
1395 				/*
1396 				 * Reference the page before unlocking and
1397 				 * sleeping so that the page daemon is less
1398 				 * likely to reclaim it.
1399 				 */
1400 				vm_page_aflag_set(tm, PGA_REFERENCED);
1401 			}
1402 			if (!vm_page_busy_sleep(tm, "madvpo", 0))
1403 				VM_OBJECT_WUNLOCK(tobject);
1404 			pctrie_iter_reset(&pages);
1405   			goto relookup;
1406 		}
1407 		vm_page_advise(tm, advice);
1408 		vm_page_xunbusy(tm);
1409 		vm_object_madvise_freespace(tobject, advice, tm->pindex, 1);
1410 next_pindex:
1411 		if (tobject != object)
1412 			VM_OBJECT_WUNLOCK(tobject);
1413 	}
1414 	VM_OBJECT_WUNLOCK(object);
1415 }
1416 
1417 /*
1418  *	vm_object_shadow:
1419  *
1420  *	Create a new object which is backed by the
1421  *	specified existing object range.  The source
1422  *	object reference is deallocated.
1423  *
1424  *	The new object and offset into that object
1425  *	are returned in the source parameters.
1426  */
1427 void
vm_object_shadow(vm_object_t * object,vm_ooffset_t * offset,vm_size_t length,struct ucred * cred,bool shared)1428 vm_object_shadow(vm_object_t *object, vm_ooffset_t *offset, vm_size_t length,
1429     struct ucred *cred, bool shared)
1430 {
1431 	vm_object_t source;
1432 	vm_object_t result;
1433 
1434 	source = *object;
1435 
1436 	/*
1437 	 * Don't create the new object if the old object isn't shared.
1438 	 *
1439 	 * If we hold the only reference we can guarantee that it won't
1440 	 * increase while we have the map locked.  Otherwise the race is
1441 	 * harmless and we will end up with an extra shadow object that
1442 	 * will be collapsed later.
1443 	 */
1444 	if (source != NULL && source->ref_count == 1 &&
1445 	    (source->flags & OBJ_ANON) != 0)
1446 		return;
1447 
1448 	/*
1449 	 * Allocate a new object with the given length.
1450 	 */
1451 	result = vm_object_allocate_anon(atop(length), source, cred, length);
1452 
1453 	/*
1454 	 * Store the offset into the source object, and fix up the offset into
1455 	 * the new object.
1456 	 */
1457 	result->backing_object_offset = *offset;
1458 
1459 	if (shared || source != NULL) {
1460 		VM_OBJECT_WLOCK(result);
1461 
1462 		/*
1463 		 * The new object shadows the source object, adding a
1464 		 * reference to it.  Our caller changes his reference
1465 		 * to point to the new object, removing a reference to
1466 		 * the source object.  Net result: no change of
1467 		 * reference count, unless the caller needs to add one
1468 		 * more reference due to forking a shared map entry.
1469 		 */
1470 		if (shared) {
1471 			vm_object_reference_locked(result);
1472 			vm_object_clear_flag(result, OBJ_ONEMAPPING);
1473 		}
1474 
1475 		/*
1476 		 * Try to optimize the result object's page color when
1477 		 * shadowing in order to maintain page coloring
1478 		 * consistency in the combined shadowed object.
1479 		 */
1480 		if (source != NULL) {
1481 			vm_object_backing_insert(result, source);
1482 			result->domain = source->domain;
1483 #if VM_NRESERVLEVEL > 0
1484 			vm_object_set_flag(result,
1485 			    (source->flags & OBJ_COLORED));
1486 			result->pg_color = (source->pg_color +
1487 			    OFF_TO_IDX(*offset)) & ((1 << (VM_NFREEORDER -
1488 			    1)) - 1);
1489 #endif
1490 		}
1491 		VM_OBJECT_WUNLOCK(result);
1492 	}
1493 
1494 	/*
1495 	 * Return the new things
1496 	 */
1497 	*offset = 0;
1498 	*object = result;
1499 }
1500 
1501 /*
1502  *	vm_object_split:
1503  *
1504  * Split the pages in a map entry into a new object.  This affords
1505  * easier removal of unused pages, and keeps object inheritance from
1506  * being a negative impact on memory usage.
1507  */
1508 void
vm_object_split(vm_map_entry_t entry)1509 vm_object_split(vm_map_entry_t entry)
1510 {
1511 	struct pctrie_iter pages;
1512 	vm_page_t m;
1513 	vm_object_t orig_object, new_object, backing_object;
1514 	vm_pindex_t offidxstart;
1515 	vm_size_t size;
1516 
1517 	orig_object = entry->object.vm_object;
1518 	KASSERT((orig_object->flags & OBJ_ONEMAPPING) != 0,
1519 	    ("vm_object_split:  Splitting object with multiple mappings."));
1520 	if ((orig_object->flags & OBJ_ANON) == 0)
1521 		return;
1522 	if (orig_object->ref_count <= 1)
1523 		return;
1524 	VM_OBJECT_WUNLOCK(orig_object);
1525 
1526 	offidxstart = OFF_TO_IDX(entry->offset);
1527 	size = atop(entry->end - entry->start);
1528 
1529 	new_object = vm_object_allocate_anon(size, orig_object,
1530 	    orig_object->cred, ptoa(size));
1531 
1532 	/*
1533 	 * We must wait for the orig_object to complete any in-progress
1534 	 * collapse so that the swap blocks are stable below.  The
1535 	 * additional reference on backing_object by new object will
1536 	 * prevent further collapse operations until split completes.
1537 	 */
1538 	VM_OBJECT_WLOCK(orig_object);
1539 	vm_object_collapse_wait(orig_object);
1540 
1541 	/*
1542 	 * At this point, the new object is still private, so the order in
1543 	 * which the original and new objects are locked does not matter.
1544 	 */
1545 	VM_OBJECT_WLOCK(new_object);
1546 	new_object->domain = orig_object->domain;
1547 	backing_object = orig_object->backing_object;
1548 	if (backing_object != NULL) {
1549 		vm_object_backing_insert_ref(new_object, backing_object);
1550 		new_object->backing_object_offset =
1551 		    orig_object->backing_object_offset + entry->offset;
1552 	}
1553 	if (orig_object->cred != NULL) {
1554 		crhold(orig_object->cred);
1555 		KASSERT(orig_object->charge >= ptoa(size),
1556 		    ("orig_object->charge < 0"));
1557 		orig_object->charge -= ptoa(size);
1558 	}
1559 
1560 	/*
1561 	 * Mark the split operation so that swap_pager_getpages() knows
1562 	 * that the object is in transition.
1563 	 */
1564 	vm_object_set_flag(orig_object, OBJ_SPLIT);
1565 	vm_page_iter_limit_init(&pages, orig_object, offidxstart + size);
1566 retry:
1567 	KASSERT(pctrie_iter_is_reset(&pages),
1568 	    ("%s: pctrie_iter not reset for retry", __func__));
1569 	for (m = vm_radix_iter_lookup_ge(&pages, offidxstart); m != NULL;
1570 	    m = vm_radix_iter_step(&pages)) {
1571 		/*
1572 		 * We must wait for pending I/O to complete before we can
1573 		 * rename the page.
1574 		 *
1575 		 * We do not have to VM_PROT_NONE the page as mappings should
1576 		 * not be changed by this operation.
1577 		 */
1578 		if (vm_page_tryxbusy(m) == 0) {
1579 			VM_OBJECT_WUNLOCK(new_object);
1580 			if (vm_page_busy_sleep(m, "spltwt", 0))
1581 				VM_OBJECT_WLOCK(orig_object);
1582 			pctrie_iter_reset(&pages);
1583 			VM_OBJECT_WLOCK(new_object);
1584 			goto retry;
1585 		}
1586 
1587 		/*
1588 		 * If the page was left invalid, it was likely placed there by
1589 		 * an incomplete fault.  Just remove and ignore.
1590 		 *
1591 		 * One other possibility is that the map entry is wired, in
1592 		 * which case we must hang on to the page to avoid leaking it,
1593 		 * as the map entry owns the wiring.  This case can arise if the
1594 		 * backing object is truncated by the pager.
1595 		 */
1596 		if (vm_page_none_valid(m) && entry->wired_count == 0) {
1597 			if (vm_page_iter_remove(&pages, m))
1598 				vm_page_free(m);
1599 			continue;
1600 		}
1601 
1602 		/* vm_page_iter_rename() will dirty the page if it is valid. */
1603 		if (!vm_page_iter_rename(&pages, m, new_object, m->pindex -
1604 		    offidxstart)) {
1605 			vm_page_xunbusy(m);
1606 			VM_OBJECT_WUNLOCK(new_object);
1607 			VM_OBJECT_WUNLOCK(orig_object);
1608 			vm_radix_wait();
1609 			pctrie_iter_reset(&pages);
1610 			VM_OBJECT_WLOCK(orig_object);
1611 			VM_OBJECT_WLOCK(new_object);
1612 			goto retry;
1613 		}
1614 
1615 #if VM_NRESERVLEVEL > 0
1616 		/*
1617 		 * If some of the reservation's allocated pages remain with
1618 		 * the original object, then transferring the reservation to
1619 		 * the new object is neither particularly beneficial nor
1620 		 * particularly harmful as compared to leaving the reservation
1621 		 * with the original object.  If, however, all of the
1622 		 * reservation's allocated pages are transferred to the new
1623 		 * object, then transferring the reservation is typically
1624 		 * beneficial.  Determining which of these two cases applies
1625 		 * would be more costly than unconditionally renaming the
1626 		 * reservation.
1627 		 */
1628 		vm_reserv_rename(m, new_object, orig_object, offidxstart);
1629 #endif
1630 	}
1631 
1632 	/*
1633 	 * swap_pager_copy() can sleep, in which case the orig_object's
1634 	 * and new_object's locks are released and reacquired.
1635 	 */
1636 	swap_pager_copy(orig_object, new_object, offidxstart, 0);
1637 	vm_page_iter_init(&pages, new_object);
1638 	VM_RADIX_FOREACH(m, &pages)
1639 		vm_page_xunbusy(m);
1640 
1641 	vm_object_clear_flag(orig_object, OBJ_SPLIT);
1642 	VM_OBJECT_WUNLOCK(orig_object);
1643 	VM_OBJECT_WUNLOCK(new_object);
1644 	entry->object.vm_object = new_object;
1645 	entry->offset = 0LL;
1646 	vm_object_deallocate(orig_object);
1647 	VM_OBJECT_WLOCK(new_object);
1648 }
1649 
1650 static vm_page_t
vm_object_collapse_scan_wait(struct pctrie_iter * pages,vm_object_t object,vm_page_t p)1651 vm_object_collapse_scan_wait(struct pctrie_iter *pages, vm_object_t object,
1652     vm_page_t p)
1653 {
1654 	vm_object_t backing_object;
1655 
1656 	VM_OBJECT_ASSERT_WLOCKED(object);
1657 	backing_object = object->backing_object;
1658 	VM_OBJECT_ASSERT_WLOCKED(backing_object);
1659 
1660 	KASSERT(p == NULL || p->object == object || p->object == backing_object,
1661 	    ("invalid ownership %p %p %p", p, object, backing_object));
1662 	/* The page is only NULL when rename fails. */
1663 	if (p == NULL) {
1664 		VM_OBJECT_WUNLOCK(object);
1665 		VM_OBJECT_WUNLOCK(backing_object);
1666 		vm_radix_wait();
1667 		VM_OBJECT_WLOCK(object);
1668 	} else if (p->object == object) {
1669 		VM_OBJECT_WUNLOCK(backing_object);
1670 		if (vm_page_busy_sleep(p, "vmocol", 0))
1671 			VM_OBJECT_WLOCK(object);
1672 	} else {
1673 		VM_OBJECT_WUNLOCK(object);
1674 		if (!vm_page_busy_sleep(p, "vmocol", 0))
1675 			VM_OBJECT_WUNLOCK(backing_object);
1676 		VM_OBJECT_WLOCK(object);
1677 	}
1678 	VM_OBJECT_WLOCK(backing_object);
1679 	vm_page_iter_init(pages, backing_object);
1680 	return (vm_radix_iter_lookup_ge(pages, 0));
1681 }
1682 
1683 static void
vm_object_collapse_scan(vm_object_t object)1684 vm_object_collapse_scan(vm_object_t object)
1685 {
1686 	struct pctrie_iter pages;
1687 	vm_object_t backing_object;
1688 	vm_page_t next, p, pp;
1689 	vm_pindex_t backing_offset_index, new_pindex;
1690 
1691 	VM_OBJECT_ASSERT_WLOCKED(object);
1692 	VM_OBJECT_ASSERT_WLOCKED(object->backing_object);
1693 
1694 	backing_object = object->backing_object;
1695 	backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1696 
1697 	/*
1698 	 * Our scan
1699 	 */
1700 	vm_page_iter_init(&pages, backing_object);
1701 	for (p = vm_radix_iter_lookup_ge(&pages, 0); p != NULL; p = next) {
1702 		/*
1703 		 * Check for busy page
1704 		 */
1705 		if (vm_page_tryxbusy(p) == 0) {
1706 			next = vm_object_collapse_scan_wait(&pages, object, p);
1707 			continue;
1708 		}
1709 
1710 		KASSERT(object->backing_object == backing_object,
1711 		    ("vm_object_collapse_scan: backing object mismatch %p != %p",
1712 		    object->backing_object, backing_object));
1713 		KASSERT(p->object == backing_object,
1714 		    ("vm_object_collapse_scan: object mismatch %p != %p",
1715 		    p->object, backing_object));
1716 
1717 		if (p->pindex < backing_offset_index || object->size <=
1718 		    (new_pindex = p->pindex - backing_offset_index)) {
1719 			vm_pager_freespace(backing_object, p->pindex, 1);
1720 
1721 			KASSERT(!pmap_page_is_mapped(p),
1722 			    ("freeing mapped page %p", p));
1723 			if (vm_page_iter_remove(&pages, p))
1724 				vm_page_free(p);
1725 			next = vm_radix_iter_step(&pages);
1726 			continue;
1727 		}
1728 
1729 		if (!vm_page_all_valid(p)) {
1730 			KASSERT(!pmap_page_is_mapped(p),
1731 			    ("freeing mapped page %p", p));
1732 			if (vm_page_iter_remove(&pages, p))
1733 				vm_page_free(p);
1734 			next = vm_radix_iter_step(&pages);
1735 			continue;
1736 		}
1737 
1738 		pp = vm_page_lookup(object, new_pindex);
1739 		if (pp != NULL && vm_page_tryxbusy(pp) == 0) {
1740 			vm_page_xunbusy(p);
1741 			/*
1742 			 * The page in the parent is busy and possibly not
1743 			 * (yet) valid.  Until its state is finalized by the
1744 			 * busy bit owner, we can't tell whether it shadows the
1745 			 * original page.
1746 			 */
1747 			next = vm_object_collapse_scan_wait(&pages, object, pp);
1748 			continue;
1749 		}
1750 
1751 		if (pp != NULL && vm_page_none_valid(pp)) {
1752 			/*
1753 			 * The page was invalid in the parent.  Likely placed
1754 			 * there by an incomplete fault.  Just remove and
1755 			 * ignore.  p can replace it.
1756 			 */
1757 			if (vm_page_remove(pp))
1758 				vm_page_free(pp);
1759 			pp = NULL;
1760 		}
1761 
1762 		if (pp != NULL || vm_pager_has_page(object, new_pindex, NULL,
1763 			NULL)) {
1764 			/*
1765 			 * The page already exists in the parent OR swap exists
1766 			 * for this location in the parent.  Leave the parent's
1767 			 * page alone.  Destroy the original page from the
1768 			 * backing object.
1769 			 */
1770 			vm_pager_freespace(backing_object, p->pindex, 1);
1771 			KASSERT(!pmap_page_is_mapped(p),
1772 			    ("freeing mapped page %p", p));
1773 			if (pp != NULL)
1774 				vm_page_xunbusy(pp);
1775 			if (vm_page_iter_remove(&pages, p))
1776 				vm_page_free(p);
1777 			next = vm_radix_iter_step(&pages);
1778 			continue;
1779 		}
1780 
1781 		/*
1782 		 * Page does not exist in parent, rename the page from the
1783 		 * backing object to the main object.
1784 		 *
1785 		 * If the page was mapped to a process, it can remain mapped
1786 		 * through the rename.  vm_page_iter_rename() will dirty the
1787 		 * page.
1788 		 */
1789 		if (!vm_page_iter_rename(&pages, p, object, new_pindex)) {
1790 			vm_page_xunbusy(p);
1791 			next = vm_object_collapse_scan_wait(&pages, object,
1792 			    NULL);
1793 			continue;
1794 		}
1795 
1796 		/* Use the old pindex to free the right page. */
1797 		vm_pager_freespace(backing_object, new_pindex +
1798 		    backing_offset_index, 1);
1799 
1800 #if VM_NRESERVLEVEL > 0
1801 		/*
1802 		 * Rename the reservation.
1803 		 */
1804 		vm_reserv_rename(p, object, backing_object,
1805 		    backing_offset_index);
1806 #endif
1807 		vm_page_xunbusy(p);
1808 		next = vm_radix_iter_step(&pages);
1809 	}
1810 	return;
1811 }
1812 
1813 /*
1814  *	vm_object_collapse:
1815  *
1816  *	Collapse an object with the object backing it.
1817  *	Pages in the backing object are moved into the
1818  *	parent, and the backing object is deallocated.
1819  */
1820 void
vm_object_collapse(vm_object_t object)1821 vm_object_collapse(vm_object_t object)
1822 {
1823 	vm_object_t backing_object, new_backing_object;
1824 
1825 	VM_OBJECT_ASSERT_WLOCKED(object);
1826 
1827 	while (TRUE) {
1828 		KASSERT((object->flags & (OBJ_DEAD | OBJ_ANON)) == OBJ_ANON,
1829 		    ("collapsing invalid object"));
1830 
1831 		/*
1832 		 * Wait for the backing_object to finish any pending
1833 		 * collapse so that the caller sees the shortest possible
1834 		 * shadow chain.
1835 		 */
1836 		backing_object = vm_object_backing_collapse_wait(object);
1837 		if (backing_object == NULL)
1838 			return;
1839 
1840 		KASSERT(object->ref_count > 0 &&
1841 		    object->ref_count > atomic_load_int(&object->shadow_count),
1842 		    ("collapse with invalid ref %d or shadow %d count.",
1843 		    object->ref_count, atomic_load_int(&object->shadow_count)));
1844 		KASSERT((backing_object->flags &
1845 		    (OBJ_COLLAPSING | OBJ_DEAD)) == 0,
1846 		    ("vm_object_collapse: Backing object already collapsing."));
1847 		KASSERT((object->flags & (OBJ_COLLAPSING | OBJ_DEAD)) == 0,
1848 		    ("vm_object_collapse: object is already collapsing."));
1849 
1850 		/*
1851 		 * We know that we can either collapse the backing object if
1852 		 * the parent is the only reference to it, or (perhaps) have
1853 		 * the parent bypass the object if the parent happens to shadow
1854 		 * all the resident pages in the entire backing object.
1855 		 */
1856 		if (backing_object->ref_count == 1) {
1857 			KASSERT(atomic_load_int(&backing_object->shadow_count)
1858 			    == 1,
1859 			    ("vm_object_collapse: shadow_count: %d",
1860 			    atomic_load_int(&backing_object->shadow_count)));
1861 			vm_object_pip_add(object, 1);
1862 			vm_object_set_flag(object, OBJ_COLLAPSING);
1863 			vm_object_pip_add(backing_object, 1);
1864 			vm_object_set_flag(backing_object, OBJ_DEAD);
1865 
1866 			/*
1867 			 * If there is exactly one reference to the backing
1868 			 * object, we can collapse it into the parent.
1869 			 */
1870 			vm_object_collapse_scan(object);
1871 
1872 			/*
1873 			 * Move the pager from backing_object to object.
1874 			 *
1875 			 * swap_pager_copy() can sleep, in which case the
1876 			 * backing_object's and object's locks are released and
1877 			 * reacquired.
1878 			 */
1879 			swap_pager_copy(backing_object, object,
1880 			    OFF_TO_IDX(object->backing_object_offset), TRUE);
1881 
1882 			/*
1883 			 * Object now shadows whatever backing_object did.
1884 			 */
1885 			vm_object_clear_flag(object, OBJ_COLLAPSING);
1886 			vm_object_backing_transfer(object, backing_object);
1887 			object->backing_object_offset +=
1888 			    backing_object->backing_object_offset;
1889 			VM_OBJECT_WUNLOCK(object);
1890 			vm_object_pip_wakeup(object);
1891 
1892 			/*
1893 			 * Discard backing_object.
1894 			 *
1895 			 * Since the backing object has no pages, no pager left,
1896 			 * and no object references within it, all that is
1897 			 * necessary is to dispose of it.
1898 			 */
1899 			KASSERT(backing_object->ref_count == 1, (
1900 "backing_object %p was somehow re-referenced during collapse!",
1901 			    backing_object));
1902 			vm_object_pip_wakeup(backing_object);
1903 			(void)refcount_release(&backing_object->ref_count);
1904 			umtx_shm_object_terminated(backing_object);
1905 			vm_object_terminate(backing_object);
1906 			counter_u64_add(object_collapses, 1);
1907 			VM_OBJECT_WLOCK(object);
1908 		} else {
1909 			/*
1910 			 * If we do not entirely shadow the backing object,
1911 			 * there is nothing we can do so we give up.
1912 			 *
1913 			 * The object lock and backing_object lock must not
1914 			 * be dropped during this sequence.
1915 			 */
1916 			if (!swap_pager_scan_all_shadowed(object)) {
1917 				VM_OBJECT_WUNLOCK(backing_object);
1918 				break;
1919 			}
1920 
1921 			/*
1922 			 * Make the parent shadow the next object in the
1923 			 * chain.  Deallocating backing_object will not remove
1924 			 * it, since its reference count is at least 2.
1925 			 */
1926 			vm_object_backing_remove_locked(object);
1927 			new_backing_object = backing_object->backing_object;
1928 			if (new_backing_object != NULL) {
1929 				vm_object_backing_insert_ref(object,
1930 				    new_backing_object);
1931 				object->backing_object_offset +=
1932 				    backing_object->backing_object_offset;
1933 			}
1934 
1935 			/*
1936 			 * Drop the reference count on backing_object. Since
1937 			 * its ref_count was at least 2, it will not vanish.
1938 			 */
1939 			(void)refcount_release(&backing_object->ref_count);
1940 			KASSERT(backing_object->ref_count >= 1, (
1941 "backing_object %p was somehow dereferenced during collapse!",
1942 			    backing_object));
1943 			VM_OBJECT_WUNLOCK(backing_object);
1944 			counter_u64_add(object_bypasses, 1);
1945 		}
1946 
1947 		/*
1948 		 * Try again with this object's new backing object.
1949 		 */
1950 	}
1951 }
1952 
1953 /*
1954  *	vm_object_page_remove:
1955  *
1956  *	For the given object, either frees or invalidates each of the
1957  *	specified pages.  In general, a page is freed.  However, if a page is
1958  *	wired for any reason other than the existence of a managed, wired
1959  *	mapping, then it may be invalidated but not removed from the object.
1960  *	Pages are specified by the given range ["start", "end") and the option
1961  *	OBJPR_CLEANONLY.  As a special case, if "end" is zero, then the range
1962  *	extends from "start" to the end of the object.  If the option
1963  *	OBJPR_CLEANONLY is specified, then only the non-dirty pages within the
1964  *	specified range are affected.  If the option OBJPR_NOTMAPPED is
1965  *	specified, then the pages within the specified range must have no
1966  *	mappings.  Otherwise, if this option is not specified, any mappings to
1967  *	the specified pages are removed before the pages are freed or
1968  *	invalidated.
1969  *
1970  *	In general, this operation should only be performed on objects that
1971  *	contain managed pages.  There are, however, two exceptions.  First, it
1972  *	is performed on the kernel and kmem objects by vm_map_entry_delete().
1973  *	Second, it is used by msync(..., MS_INVALIDATE) to invalidate device-
1974  *	backed pages.  In both of these cases, the option OBJPR_CLEANONLY must
1975  *	not be specified and the option OBJPR_NOTMAPPED must be specified.
1976  *
1977  *	The object must be locked.
1978  */
1979 void
vm_object_page_remove(vm_object_t object,vm_pindex_t start,vm_pindex_t end,int options)1980 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
1981     int options)
1982 {
1983 	struct pctrie_iter pages;
1984 	vm_page_t p;
1985 
1986 	VM_OBJECT_ASSERT_WLOCKED(object);
1987 	KASSERT((object->flags & OBJ_UNMANAGED) == 0 ||
1988 	    (options & (OBJPR_CLEANONLY | OBJPR_NOTMAPPED)) == OBJPR_NOTMAPPED,
1989 	    ("vm_object_page_remove: illegal options for object %p", object));
1990 	if (object->resident_page_count == 0)
1991 		return;
1992 	vm_object_pip_add(object, 1);
1993 	vm_page_iter_limit_init(&pages, object, end);
1994 again:
1995 	KASSERT(pctrie_iter_is_reset(&pages),
1996 	    ("%s: pctrie_iter not reset for retry", __func__));
1997 	for (p = vm_radix_iter_lookup_ge(&pages, start); p != NULL;
1998 	     p = vm_radix_iter_step(&pages)) {
1999 		/*
2000 		 * Skip invalid pages if asked to do so.  Try to avoid acquiring
2001 		 * the busy lock, as some consumers rely on this to avoid
2002 		 * deadlocks.
2003 		 *
2004 		 * A thread may concurrently transition the page from invalid to
2005 		 * valid using only the busy lock, so the result of this check
2006 		 * is immediately stale.  It is up to consumers to handle this,
2007 		 * for instance by ensuring that all invalid->valid transitions
2008 		 * happen with a mutex held, as may be possible for a
2009 		 * filesystem.
2010 		 */
2011 		if ((options & OBJPR_VALIDONLY) != 0 && vm_page_none_valid(p))
2012 			continue;
2013 
2014 		/*
2015 		 * If the page is wired for any reason besides the existence
2016 		 * of managed, wired mappings, then it cannot be freed.  For
2017 		 * example, fictitious pages, which represent device memory,
2018 		 * are inherently wired and cannot be freed.  They can,
2019 		 * however, be invalidated if the option OBJPR_CLEANONLY is
2020 		 * not specified.
2021 		 */
2022 		if (vm_page_tryxbusy(p) == 0) {
2023 			if (vm_page_busy_sleep(p, "vmopar", 0))
2024 				VM_OBJECT_WLOCK(object);
2025 			pctrie_iter_reset(&pages);
2026 			goto again;
2027 		}
2028 		if ((options & OBJPR_VALIDONLY) != 0 && vm_page_none_valid(p)) {
2029 			vm_page_xunbusy(p);
2030 			continue;
2031 		}
2032 		if (vm_page_wired(p)) {
2033 wired:
2034 			if ((options & OBJPR_NOTMAPPED) == 0 &&
2035 			    object->ref_count != 0)
2036 				pmap_remove_all(p);
2037 			if ((options & OBJPR_CLEANONLY) == 0) {
2038 				vm_page_invalid(p);
2039 				vm_page_undirty(p);
2040 			}
2041 			vm_page_xunbusy(p);
2042 			continue;
2043 		}
2044 		KASSERT((p->flags & PG_FICTITIOUS) == 0,
2045 		    ("vm_object_page_remove: page %p is fictitious", p));
2046 		if ((options & OBJPR_CLEANONLY) != 0 &&
2047 		    !vm_page_none_valid(p)) {
2048 			if ((options & OBJPR_NOTMAPPED) == 0 &&
2049 			    object->ref_count != 0 &&
2050 			    !vm_page_try_remove_write(p))
2051 				goto wired;
2052 			if (p->dirty != 0) {
2053 				vm_page_xunbusy(p);
2054 				continue;
2055 			}
2056 		}
2057 		if ((options & OBJPR_NOTMAPPED) == 0 &&
2058 		    object->ref_count != 0 && !vm_page_try_remove_all(p))
2059 			goto wired;
2060 		vm_page_iter_free(&pages, p);
2061 	}
2062 	vm_object_pip_wakeup(object);
2063 
2064 	vm_pager_freespace(object, start, (end == 0 ? object->size : end) -
2065 	    start);
2066 }
2067 
2068 /*
2069  *	vm_object_page_noreuse:
2070  *
2071  *	For the given object, attempt to move the specified pages to
2072  *	the head of the inactive queue.  This bypasses regular LRU
2073  *	operation and allows the pages to be reused quickly under memory
2074  *	pressure.  If a page is wired for any reason, then it will not
2075  *	be queued.  Pages are specified by the range ["start", "end").
2076  *	As a special case, if "end" is zero, then the range extends from
2077  *	"start" to the end of the object.
2078  *
2079  *	This operation should only be performed on objects that
2080  *	contain non-fictitious, managed pages.
2081  *
2082  *	The object must be locked.
2083  */
2084 void
vm_object_page_noreuse(vm_object_t object,vm_pindex_t start,vm_pindex_t end)2085 vm_object_page_noreuse(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
2086 {
2087 	struct pctrie_iter pages;
2088 	vm_page_t p;
2089 
2090 	VM_OBJECT_ASSERT_LOCKED(object);
2091 	KASSERT((object->flags & (OBJ_FICTITIOUS | OBJ_UNMANAGED)) == 0,
2092 	    ("vm_object_page_noreuse: illegal object %p", object));
2093 	if (object->resident_page_count == 0)
2094 		return;
2095 
2096 	vm_page_iter_limit_init(&pages, object, end);
2097 	VM_RADIX_FOREACH_FROM(p, &pages, start)
2098 		vm_page_deactivate_noreuse(p);
2099 }
2100 
2101 /*
2102  *	Populate the specified range of the object with valid pages.  Returns
2103  *	TRUE if the range is successfully populated and FALSE otherwise.
2104  *
2105  *	Note: This function should be optimized to pass a larger array of
2106  *	pages to vm_pager_get_pages() before it is applied to a non-
2107  *	OBJT_DEVICE object.
2108  *
2109  *	The object must be locked.
2110  */
2111 boolean_t
vm_object_populate(vm_object_t object,vm_pindex_t start,vm_pindex_t end)2112 vm_object_populate(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
2113 {
2114 	struct pctrie_iter pages;
2115 	vm_page_t m;
2116 	vm_pindex_t pindex;
2117 	int rv;
2118 
2119 	vm_page_iter_init(&pages, object);
2120 	VM_OBJECT_ASSERT_WLOCKED(object);
2121 	for (pindex = start; pindex < end; pindex++) {
2122 		rv = vm_page_grab_valid_iter(&m, object, pindex,
2123 		    VM_ALLOC_NORMAL, &pages);
2124 		if (rv != VM_PAGER_OK)
2125 			break;
2126 
2127 		/*
2128 		 * Keep "m" busy because a subsequent iteration may unlock
2129 		 * the object.
2130 		 */
2131 	}
2132 	if (pindex > start) {
2133 		pages.limit = pindex;
2134 		VM_RADIX_FORALL_FROM(m, &pages, start)
2135 			vm_page_xunbusy(m);
2136 	}
2137 	return (pindex == end);
2138 }
2139 
2140 /*
2141  *	Routine:	vm_object_coalesce
2142  *	Function:	Coalesces two objects backing up adjoining
2143  *			regions of memory into a single object.
2144  *
2145  *	returns TRUE if objects were combined.
2146  *
2147  *	NOTE:	Only works at the moment if the second object is NULL -
2148  *		if it's not, which object do we lock first?
2149  *
2150  *	Parameters:
2151  *		prev_object	First object to coalesce
2152  *		prev_offset	Offset into prev_object
2153  *		prev_size	Size of reference to prev_object
2154  *		next_size	Size of reference to the second object
2155  *		reserved	Indicator that extension region has
2156  *				swap accounted for
2157  *
2158  *	Conditions:
2159  *	The object must *not* be locked.
2160  */
2161 boolean_t
vm_object_coalesce(vm_object_t prev_object,vm_ooffset_t prev_offset,vm_size_t prev_size,vm_size_t next_size,boolean_t reserved)2162 vm_object_coalesce(vm_object_t prev_object, vm_ooffset_t prev_offset,
2163     vm_size_t prev_size, vm_size_t next_size, boolean_t reserved)
2164 {
2165 	vm_pindex_t next_pindex;
2166 
2167 	if (prev_object == NULL)
2168 		return (TRUE);
2169 	if ((prev_object->flags & OBJ_ANON) == 0)
2170 		return (FALSE);
2171 
2172 	VM_OBJECT_WLOCK(prev_object);
2173 	/*
2174 	 * Try to collapse the object first.
2175 	 */
2176 	vm_object_collapse(prev_object);
2177 
2178 	/*
2179 	 * Can't coalesce if: . more than one reference . paged out . shadows
2180 	 * another object . has a copy elsewhere (any of which mean that the
2181 	 * pages not mapped to prev_entry may be in use anyway)
2182 	 */
2183 	if (prev_object->backing_object != NULL) {
2184 		VM_OBJECT_WUNLOCK(prev_object);
2185 		return (FALSE);
2186 	}
2187 
2188 	prev_size >>= PAGE_SHIFT;
2189 	next_size >>= PAGE_SHIFT;
2190 	next_pindex = OFF_TO_IDX(prev_offset) + prev_size;
2191 
2192 	if (prev_object->ref_count > 1 &&
2193 	    prev_object->size != next_pindex &&
2194 	    (prev_object->flags & OBJ_ONEMAPPING) == 0) {
2195 		VM_OBJECT_WUNLOCK(prev_object);
2196 		return (FALSE);
2197 	}
2198 
2199 	/*
2200 	 * Account for the charge.
2201 	 */
2202 	if (prev_object->cred != NULL) {
2203 		/*
2204 		 * If prev_object was charged, then this mapping,
2205 		 * although not charged now, may become writable
2206 		 * later. Non-NULL cred in the object would prevent
2207 		 * swap reservation during enabling of the write
2208 		 * access, so reserve swap now. Failed reservation
2209 		 * cause allocation of the separate object for the map
2210 		 * entry, and swap reservation for this entry is
2211 		 * managed in appropriate time.
2212 		 */
2213 		if (!reserved && !swap_reserve_by_cred(ptoa(next_size),
2214 		    prev_object->cred)) {
2215 			VM_OBJECT_WUNLOCK(prev_object);
2216 			return (FALSE);
2217 		}
2218 		prev_object->charge += ptoa(next_size);
2219 	}
2220 
2221 	/*
2222 	 * Remove any pages that may still be in the object from a previous
2223 	 * deallocation.
2224 	 */
2225 	if (next_pindex < prev_object->size) {
2226 		vm_object_page_remove(prev_object, next_pindex, next_pindex +
2227 		    next_size, 0);
2228 #if 0
2229 		if (prev_object->cred != NULL) {
2230 			KASSERT(prev_object->charge >=
2231 			    ptoa(prev_object->size - next_pindex),
2232 			    ("object %p overcharged 1 %jx %jx", prev_object,
2233 				(uintmax_t)next_pindex, (uintmax_t)next_size));
2234 			prev_object->charge -= ptoa(prev_object->size -
2235 			    next_pindex);
2236 		}
2237 #endif
2238 	}
2239 
2240 	/*
2241 	 * Extend the object if necessary.
2242 	 */
2243 	if (next_pindex + next_size > prev_object->size)
2244 		prev_object->size = next_pindex + next_size;
2245 
2246 	VM_OBJECT_WUNLOCK(prev_object);
2247 	return (TRUE);
2248 }
2249 
2250 /*
2251  * Fill in the m_dst array with up to *rbehind optional pages before m_src[0]
2252  * and up to *rahead optional pages after m_src[count - 1].  In both cases, stop
2253  * the filling-in short on encountering a cached page, an object boundary limit,
2254  * or an allocation error.  Update *rbehind and *rahead to indicate the number
2255  * of pages allocated.  Copy elements of m_src into array elements from
2256  * m_dst[*rbehind] to m_dst[*rbehind + count -1].
2257  */
2258 void
vm_object_prepare_buf_pages(vm_object_t object,vm_page_t * ma_dst,int count,int * rbehind,int * rahead,vm_page_t * ma_src)2259 vm_object_prepare_buf_pages(vm_object_t object, vm_page_t *ma_dst, int count,
2260     int *rbehind, int *rahead, vm_page_t *ma_src)
2261 {
2262 	struct pctrie_iter pages;
2263 	vm_pindex_t pindex;
2264 	vm_page_t m, mpred, msucc;
2265 
2266 	vm_page_iter_init(&pages, object);
2267 	VM_OBJECT_ASSERT_LOCKED(object);
2268 	if (*rbehind != 0) {
2269 		m = ma_src[0];
2270 		pindex = m->pindex;
2271 		mpred = vm_radix_iter_lookup_lt(&pages, pindex);
2272 		*rbehind = MIN(*rbehind,
2273 		    pindex - (mpred != NULL ? mpred->pindex + 1 : 0));
2274 		for (int i = 0; i < *rbehind; i++) {
2275 			m = vm_page_alloc_iter(object, pindex - i - 1,
2276 			    VM_ALLOC_NORMAL, &pages);
2277 			if (m == NULL) {
2278 				/* Shift the array. */
2279 				for (int j = 0; j < i; j++)
2280 					ma_dst[j] = ma_dst[j + *rbehind - i];
2281 				*rbehind = i;
2282 				*rahead = 0;
2283 				break;
2284 			}
2285 			ma_dst[*rbehind - i - 1] = m;
2286 		}
2287 	}
2288 	for (int i = 0; i < count; i++)
2289 		ma_dst[*rbehind + i] = ma_src[i];
2290 	if (*rahead != 0) {
2291 		m = ma_src[count - 1];
2292 		pindex = m->pindex + 1;
2293 		msucc = vm_radix_iter_lookup_ge(&pages, pindex);
2294 		*rahead = MIN(*rahead,
2295 		    (msucc != NULL ? msucc->pindex : object->size) - pindex);
2296 		for (int i = 0; i < *rahead; i++) {
2297 			m = vm_page_alloc_iter(object, pindex + i,
2298 			    VM_ALLOC_NORMAL, &pages);
2299 			if (m == NULL) {
2300 				*rahead = i;
2301 				break;
2302 			}
2303 			ma_dst[*rbehind + count + i] = m;
2304 		}
2305 	}
2306 }
2307 
2308 void
vm_object_set_writeable_dirty_(vm_object_t object)2309 vm_object_set_writeable_dirty_(vm_object_t object)
2310 {
2311 	atomic_add_int(&object->generation, 1);
2312 }
2313 
2314 bool
vm_object_mightbedirty_(vm_object_t object)2315 vm_object_mightbedirty_(vm_object_t object)
2316 {
2317 	return (object->generation != object->cleangeneration);
2318 }
2319 
2320 /*
2321  *	vm_object_unwire:
2322  *
2323  *	For each page offset within the specified range of the given object,
2324  *	find the highest-level page in the shadow chain and unwire it.  A page
2325  *	must exist at every page offset, and the highest-level page must be
2326  *	wired.
2327  */
2328 void
vm_object_unwire(vm_object_t object,vm_ooffset_t offset,vm_size_t length,uint8_t queue)2329 vm_object_unwire(vm_object_t object, vm_ooffset_t offset, vm_size_t length,
2330     uint8_t queue)
2331 {
2332 	struct pctrie_iter pages;
2333 	vm_object_t tobject, t1object;
2334 	vm_page_t m, tm;
2335 	vm_pindex_t end_pindex, pindex, tpindex;
2336 	int depth, locked_depth;
2337 
2338 	KASSERT((offset & PAGE_MASK) == 0,
2339 	    ("vm_object_unwire: offset is not page aligned"));
2340 	KASSERT((length & PAGE_MASK) == 0,
2341 	    ("vm_object_unwire: length is not a multiple of PAGE_SIZE"));
2342 	/* The wired count of a fictitious page never changes. */
2343 	if ((object->flags & OBJ_FICTITIOUS) != 0)
2344 		return;
2345 	pindex = OFF_TO_IDX(offset);
2346 	end_pindex = pindex + atop(length);
2347 	vm_page_iter_init(&pages, object);
2348 again:
2349 	locked_depth = 1;
2350 	VM_OBJECT_RLOCK(object);
2351 	m = vm_radix_iter_lookup_ge(&pages, pindex);
2352 	while (pindex < end_pindex) {
2353 		if (m == NULL || pindex < m->pindex) {
2354 			/*
2355 			 * The first object in the shadow chain doesn't
2356 			 * contain a page at the current index.  Therefore,
2357 			 * the page must exist in a backing object.
2358 			 */
2359 			tobject = object;
2360 			tpindex = pindex;
2361 			depth = 0;
2362 			do {
2363 				tpindex +=
2364 				    OFF_TO_IDX(tobject->backing_object_offset);
2365 				tobject = tobject->backing_object;
2366 				KASSERT(tobject != NULL,
2367 				    ("vm_object_unwire: missing page"));
2368 				if ((tobject->flags & OBJ_FICTITIOUS) != 0)
2369 					goto next_page;
2370 				depth++;
2371 				if (depth == locked_depth) {
2372 					locked_depth++;
2373 					VM_OBJECT_RLOCK(tobject);
2374 				}
2375 			} while ((tm = vm_page_lookup(tobject, tpindex)) ==
2376 			    NULL);
2377 		} else {
2378 			tm = m;
2379 			m = vm_radix_iter_step(&pages);
2380 		}
2381 		if (vm_page_trysbusy(tm) == 0) {
2382 			for (tobject = object; locked_depth >= 1;
2383 			    locked_depth--) {
2384 				t1object = tobject->backing_object;
2385 				if (tm->object != tobject)
2386 					VM_OBJECT_RUNLOCK(tobject);
2387 				tobject = t1object;
2388 			}
2389 			tobject = tm->object;
2390 			if (!vm_page_busy_sleep(tm, "unwbo",
2391 			    VM_ALLOC_IGN_SBUSY))
2392 				VM_OBJECT_RUNLOCK(tobject);
2393 			pctrie_iter_reset(&pages);
2394 			goto again;
2395 		}
2396 		vm_page_unwire(tm, queue);
2397 		vm_page_sunbusy(tm);
2398 next_page:
2399 		pindex++;
2400 	}
2401 	/* Release the accumulated object locks. */
2402 	for (tobject = object; locked_depth >= 1; locked_depth--) {
2403 		t1object = tobject->backing_object;
2404 		VM_OBJECT_RUNLOCK(tobject);
2405 		tobject = t1object;
2406 	}
2407 }
2408 
2409 /*
2410  * Return the vnode for the given object, or NULL if none exists.
2411  * For tmpfs objects, the function may return NULL if there is
2412  * no vnode allocated at the time of the call.
2413  */
2414 struct vnode *
vm_object_vnode(vm_object_t object)2415 vm_object_vnode(vm_object_t object)
2416 {
2417 	struct vnode *vp;
2418 
2419 	VM_OBJECT_ASSERT_LOCKED(object);
2420 	vm_pager_getvp(object, &vp, NULL);
2421 	return (vp);
2422 }
2423 
2424 /*
2425  * Busy the vm object.  This prevents new pages belonging to the object from
2426  * becoming busy.  Existing pages persist as busy.  Callers are responsible
2427  * for checking page state before proceeding.
2428  */
2429 void
vm_object_busy(vm_object_t obj)2430 vm_object_busy(vm_object_t obj)
2431 {
2432 
2433 	VM_OBJECT_ASSERT_LOCKED(obj);
2434 
2435 	blockcount_acquire(&obj->busy, 1);
2436 	/* The fence is required to order loads of page busy. */
2437 	atomic_thread_fence_acq_rel();
2438 }
2439 
2440 void
vm_object_unbusy(vm_object_t obj)2441 vm_object_unbusy(vm_object_t obj)
2442 {
2443 
2444 	blockcount_release(&obj->busy, 1);
2445 }
2446 
2447 void
vm_object_busy_wait(vm_object_t obj,const char * wmesg)2448 vm_object_busy_wait(vm_object_t obj, const char *wmesg)
2449 {
2450 
2451 	VM_OBJECT_ASSERT_UNLOCKED(obj);
2452 
2453 	(void)blockcount_sleep(&obj->busy, NULL, wmesg, PVM);
2454 }
2455 
2456 /*
2457  * This function aims to determine if the object is mapped,
2458  * specifically, if it is referenced by a vm_map_entry.  Because
2459  * objects occasionally acquire transient references that do not
2460  * represent a mapping, the method used here is inexact.  However, it
2461  * has very low overhead and is good enough for the advisory
2462  * vm.vmtotal sysctl.
2463  */
2464 bool
vm_object_is_active(vm_object_t obj)2465 vm_object_is_active(vm_object_t obj)
2466 {
2467 
2468 	return (obj->ref_count > atomic_load_int(&obj->shadow_count));
2469 }
2470 
2471 static int
vm_object_list_handler(struct sysctl_req * req,bool swap_only)2472 vm_object_list_handler(struct sysctl_req *req, bool swap_only)
2473 {
2474 	struct pctrie_iter pages;
2475 	struct kinfo_vmobject *kvo;
2476 	char *fullpath, *freepath;
2477 	struct vnode *vp;
2478 	struct vattr va;
2479 	vm_object_t obj;
2480 	vm_page_t m;
2481 	u_long sp;
2482 	int count, error;
2483 	key_t key;
2484 	unsigned short seq;
2485 	bool want_path;
2486 
2487 	if (req->oldptr == NULL) {
2488 		/*
2489 		 * If an old buffer has not been provided, generate an
2490 		 * estimate of the space needed for a subsequent call.
2491 		 */
2492 		mtx_lock(&vm_object_list_mtx);
2493 		count = 0;
2494 		TAILQ_FOREACH(obj, &vm_object_list, object_list) {
2495 			if (obj->type == OBJT_DEAD)
2496 				continue;
2497 			count++;
2498 		}
2499 		mtx_unlock(&vm_object_list_mtx);
2500 		return (SYSCTL_OUT(req, NULL, sizeof(struct kinfo_vmobject) *
2501 		    count * 11 / 10));
2502 	}
2503 
2504 	want_path = !(swap_only || jailed(curthread->td_ucred));
2505 	kvo = malloc(sizeof(*kvo), M_TEMP, M_WAITOK | M_ZERO);
2506 	error = 0;
2507 
2508 	/*
2509 	 * VM objects are type stable and are never removed from the
2510 	 * list once added.  This allows us to safely read obj->object_list
2511 	 * after reacquiring the VM object lock.
2512 	 */
2513 	mtx_lock(&vm_object_list_mtx);
2514 	TAILQ_FOREACH(obj, &vm_object_list, object_list) {
2515 		if (obj->type == OBJT_DEAD ||
2516 		    (swap_only && (obj->flags & (OBJ_ANON | OBJ_SWAP)) == 0))
2517 			continue;
2518 		VM_OBJECT_RLOCK(obj);
2519 		if (obj->type == OBJT_DEAD ||
2520 		    (swap_only && (obj->flags & (OBJ_ANON | OBJ_SWAP)) == 0)) {
2521 			VM_OBJECT_RUNLOCK(obj);
2522 			continue;
2523 		}
2524 		mtx_unlock(&vm_object_list_mtx);
2525 		kvo->kvo_size = ptoa(obj->size);
2526 		kvo->kvo_resident = obj->resident_page_count;
2527 		kvo->kvo_ref_count = obj->ref_count;
2528 		kvo->kvo_shadow_count = atomic_load_int(&obj->shadow_count);
2529 		kvo->kvo_memattr = obj->memattr;
2530 		kvo->kvo_active = 0;
2531 		kvo->kvo_inactive = 0;
2532 		kvo->kvo_laundry = 0;
2533 		kvo->kvo_flags = 0;
2534 		if (!swap_only) {
2535 			vm_page_iter_init(&pages, obj);
2536 			VM_RADIX_FOREACH(m, &pages) {
2537 				/*
2538 				 * A page may belong to the object but be
2539 				 * dequeued and set to PQ_NONE while the
2540 				 * object lock is not held.  This makes the
2541 				 * reads of m->queue below racy, and we do not
2542 				 * count pages set to PQ_NONE.  However, this
2543 				 * sysctl is only meant to give an
2544 				 * approximation of the system anyway.
2545 				 */
2546 				if (vm_page_active(m))
2547 					kvo->kvo_active++;
2548 				else if (vm_page_inactive(m))
2549 					kvo->kvo_inactive++;
2550 				else if (vm_page_in_laundry(m))
2551 					kvo->kvo_laundry++;
2552 			}
2553 		}
2554 
2555 		kvo->kvo_vn_fileid = 0;
2556 		kvo->kvo_vn_fsid = 0;
2557 		kvo->kvo_vn_fsid_freebsd11 = 0;
2558 		freepath = NULL;
2559 		fullpath = "";
2560 		vp = NULL;
2561 		kvo->kvo_type = vm_object_kvme_type(obj, want_path ? &vp :
2562 		    NULL);
2563 		if (vp != NULL) {
2564 			vref(vp);
2565 		} else if ((obj->flags & OBJ_ANON) != 0) {
2566 			MPASS(kvo->kvo_type == KVME_TYPE_SWAP);
2567 			kvo->kvo_me = (uintptr_t)obj;
2568 			/* tmpfs objs are reported as vnodes */
2569 			kvo->kvo_backing_obj = (uintptr_t)obj->backing_object;
2570 			sp = swap_pager_swapped_pages(obj);
2571 			kvo->kvo_swapped = sp > UINT32_MAX ? UINT32_MAX : sp;
2572 		}
2573 		if (obj->type == OBJT_DEVICE || obj->type == OBJT_MGTDEVICE) {
2574 			cdev_pager_get_path(obj, kvo->kvo_path,
2575 			    sizeof(kvo->kvo_path));
2576 		}
2577 		VM_OBJECT_RUNLOCK(obj);
2578 		if ((obj->flags & OBJ_SYSVSHM) != 0) {
2579 			kvo->kvo_flags |= KVMO_FLAG_SYSVSHM;
2580 			shmobjinfo(obj, &key, &seq);
2581 			kvo->kvo_vn_fileid = key;
2582 			kvo->kvo_vn_fsid_freebsd11 = seq;
2583 		}
2584 		if ((obj->flags & OBJ_POSIXSHM) != 0) {
2585 			kvo->kvo_flags |= KVMO_FLAG_POSIXSHM;
2586 			shm_get_path(obj, kvo->kvo_path,
2587 			    sizeof(kvo->kvo_path));
2588 		}
2589 		if (vp != NULL) {
2590 			vn_fullpath(vp, &fullpath, &freepath);
2591 			vn_lock(vp, LK_SHARED | LK_RETRY);
2592 			if (VOP_GETATTR(vp, &va, curthread->td_ucred) == 0) {
2593 				kvo->kvo_vn_fileid = va.va_fileid;
2594 				kvo->kvo_vn_fsid = va.va_fsid;
2595 				kvo->kvo_vn_fsid_freebsd11 = va.va_fsid;
2596 								/* truncate */
2597 			}
2598 			vput(vp);
2599 			strlcpy(kvo->kvo_path, fullpath, sizeof(kvo->kvo_path));
2600 			free(freepath, M_TEMP);
2601 		}
2602 
2603 		/* Pack record size down */
2604 		kvo->kvo_structsize = offsetof(struct kinfo_vmobject, kvo_path)
2605 		    + strlen(kvo->kvo_path) + 1;
2606 		kvo->kvo_structsize = roundup(kvo->kvo_structsize,
2607 		    sizeof(uint64_t));
2608 		error = SYSCTL_OUT(req, kvo, kvo->kvo_structsize);
2609 		maybe_yield();
2610 		mtx_lock(&vm_object_list_mtx);
2611 		if (error)
2612 			break;
2613 	}
2614 	mtx_unlock(&vm_object_list_mtx);
2615 	free(kvo, M_TEMP);
2616 	return (error);
2617 }
2618 
2619 static int
sysctl_vm_object_list(SYSCTL_HANDLER_ARGS)2620 sysctl_vm_object_list(SYSCTL_HANDLER_ARGS)
2621 {
2622 	return (vm_object_list_handler(req, false));
2623 }
2624 
2625 SYSCTL_PROC(_vm, OID_AUTO, objects, CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_SKIP |
2626     CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_object_list, "S,kinfo_vmobject",
2627     "List of VM objects");
2628 
2629 static int
sysctl_vm_object_list_swap(SYSCTL_HANDLER_ARGS)2630 sysctl_vm_object_list_swap(SYSCTL_HANDLER_ARGS)
2631 {
2632 	return (vm_object_list_handler(req, true));
2633 }
2634 
2635 /*
2636  * This sysctl returns list of the anonymous or swap objects. Intent
2637  * is to provide stripped optimized list useful to analyze swap use.
2638  * Since technically non-swap (default) objects participate in the
2639  * shadow chains, and are converted to swap type as needed by swap
2640  * pager, we must report them.
2641  */
2642 SYSCTL_PROC(_vm, OID_AUTO, swap_objects,
2643     CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL, 0,
2644     sysctl_vm_object_list_swap, "S,kinfo_vmobject",
2645     "List of swap VM objects");
2646 
2647 #include "opt_ddb.h"
2648 #ifdef DDB
2649 #include <sys/kernel.h>
2650 
2651 #include <sys/cons.h>
2652 
2653 #include <ddb/ddb.h>
2654 
2655 static int
_vm_object_in_map(vm_map_t map,vm_object_t object,vm_map_entry_t entry)2656 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
2657 {
2658 	vm_map_t tmpm;
2659 	vm_map_entry_t tmpe;
2660 	vm_object_t obj;
2661 
2662 	if (map == 0)
2663 		return 0;
2664 
2665 	if (entry == 0) {
2666 		VM_MAP_ENTRY_FOREACH(tmpe, map) {
2667 			if (_vm_object_in_map(map, object, tmpe)) {
2668 				return 1;
2669 			}
2670 		}
2671 	} else if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
2672 		tmpm = entry->object.sub_map;
2673 		VM_MAP_ENTRY_FOREACH(tmpe, tmpm) {
2674 			if (_vm_object_in_map(tmpm, object, tmpe)) {
2675 				return 1;
2676 			}
2677 		}
2678 	} else if ((obj = entry->object.vm_object) != NULL) {
2679 		for (; obj; obj = obj->backing_object)
2680 			if (obj == object) {
2681 				return 1;
2682 			}
2683 	}
2684 	return 0;
2685 }
2686 
2687 static int
vm_object_in_map(vm_object_t object)2688 vm_object_in_map(vm_object_t object)
2689 {
2690 	struct proc *p;
2691 
2692 	/* sx_slock(&allproc_lock); */
2693 	FOREACH_PROC_IN_SYSTEM(p) {
2694 		if (!p->p_vmspace /* || (p->p_flag & (P_SYSTEM|P_WEXIT)) */)
2695 			continue;
2696 		if (_vm_object_in_map(&p->p_vmspace->vm_map, object, 0)) {
2697 			/* sx_sunlock(&allproc_lock); */
2698 			return 1;
2699 		}
2700 	}
2701 	/* sx_sunlock(&allproc_lock); */
2702 	if (_vm_object_in_map(kernel_map, object, 0))
2703 		return 1;
2704 	return 0;
2705 }
2706 
DB_SHOW_COMMAND_FLAGS(vmochk,vm_object_check,DB_CMD_MEMSAFE)2707 DB_SHOW_COMMAND_FLAGS(vmochk, vm_object_check, DB_CMD_MEMSAFE)
2708 {
2709 	vm_object_t object;
2710 
2711 	/*
2712 	 * make sure that internal objs are in a map somewhere
2713 	 * and none have zero ref counts.
2714 	 */
2715 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
2716 		if ((object->flags & OBJ_ANON) != 0) {
2717 			if (object->ref_count == 0) {
2718 				db_printf(
2719 			"vmochk: internal obj has zero ref count: %lu\n",
2720 				    (u_long)object->size);
2721 			}
2722 			if (!vm_object_in_map(object)) {
2723 				db_printf(
2724 			"vmochk: internal obj is not in a map: "
2725 			"ref: %d, size: %lu: 0x%lx, backing_object: %p\n",
2726 				    object->ref_count, (u_long)object->size,
2727 				    (u_long)object->size,
2728 				    (void *)object->backing_object);
2729 			}
2730 		}
2731 		if (db_pager_quit)
2732 			return;
2733 	}
2734 }
2735 
2736 /*
2737  *	vm_object_print:	[ debug ]
2738  */
DB_SHOW_COMMAND(object,vm_object_print_static)2739 DB_SHOW_COMMAND(object, vm_object_print_static)
2740 {
2741 	struct pctrie_iter pages;
2742 	/* XXX convert args. */
2743 	vm_object_t object = (vm_object_t)addr;
2744 	boolean_t full = have_addr;
2745 
2746 	vm_page_t p;
2747 
2748 	/* XXX count is an (unused) arg.  Avoid shadowing it. */
2749 #define	count	was_count
2750 
2751 	int count;
2752 
2753 	if (object == NULL)
2754 		return;
2755 
2756 	db_iprintf("Object %p: type=%d, size=0x%jx, res=%d, ref=%d, flags=0x%x",
2757 	    object, (int)object->type, (uintmax_t)object->size,
2758 	    object->resident_page_count, object->ref_count, object->flags);
2759 	db_iprintf(" ruid %d charge %jx\n",
2760 	    object->cred ? object->cred->cr_ruid : -1,
2761 	    (uintmax_t)object->charge);
2762 	db_iprintf(" sref=%d, backing_object(%d)=(%p)+0x%jx\n",
2763 	    atomic_load_int(&object->shadow_count),
2764 	    object->backing_object ? object->backing_object->ref_count : 0,
2765 	    object->backing_object, (uintmax_t)object->backing_object_offset);
2766 
2767 	if (!full)
2768 		return;
2769 
2770 	db_indent += 2;
2771 	count = 0;
2772 	vm_page_iter_init(&pages, object);
2773 	VM_RADIX_FOREACH(p, &pages) {
2774 		if (count == 0)
2775 			db_iprintf("memory:=");
2776 		else if (count == 6) {
2777 			db_printf("\n");
2778 			db_iprintf(" ...");
2779 			count = 0;
2780 		} else
2781 			db_printf(",");
2782 		count++;
2783 
2784 		db_printf("(off=0x%jx,page=0x%jx)",
2785 		    (uintmax_t)p->pindex, (uintmax_t)VM_PAGE_TO_PHYS(p));
2786 
2787 		if (db_pager_quit)
2788 			break;
2789 	}
2790 	if (count != 0)
2791 		db_printf("\n");
2792 	db_indent -= 2;
2793 }
2794 
2795 /* XXX. */
2796 #undef count
2797 
2798 /* XXX need this non-static entry for calling from vm_map_print. */
2799 void
vm_object_print(long addr,boolean_t have_addr,long count,char * modif)2800 vm_object_print(
2801         /* db_expr_t */ long addr,
2802 	boolean_t have_addr,
2803 	/* db_expr_t */ long count,
2804 	char *modif)
2805 {
2806 	vm_object_print_static(addr, have_addr, count, modif);
2807 }
2808 
DB_SHOW_COMMAND_FLAGS(vmopag,vm_object_print_pages,DB_CMD_MEMSAFE)2809 DB_SHOW_COMMAND_FLAGS(vmopag, vm_object_print_pages, DB_CMD_MEMSAFE)
2810 {
2811 	struct pctrie_iter pages;
2812 	vm_object_t object;
2813 	vm_page_t m, start_m;
2814 	int rcount;
2815 
2816 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
2817 		db_printf("new object: %p\n", (void *)object);
2818 		if (db_pager_quit)
2819 			return;
2820 		start_m = NULL;
2821 		vm_page_iter_init(&pages, object);
2822 		VM_RADIX_FOREACH(m, &pages) {
2823 			if (start_m == NULL) {
2824 				start_m = m;
2825 				rcount = 0;
2826 			} else if (start_m->pindex + rcount != m->pindex ||
2827 			    VM_PAGE_TO_PHYS(start_m)  + ptoa(rcount) !=
2828 			    VM_PAGE_TO_PHYS(m)) {
2829 				db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2830 				    (long)start_m->pindex, rcount,
2831 				    (long)VM_PAGE_TO_PHYS(start_m));
2832 				if (db_pager_quit)
2833 					return;
2834 				start_m = m;
2835 				rcount = 0;
2836 			}
2837 			rcount++;
2838 		}
2839 		if (start_m != NULL) {
2840 			db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2841 			    (long)start_m->pindex, rcount,
2842 			    (long)VM_PAGE_TO_PHYS(start_m));
2843 			if (db_pager_quit)
2844 				return;
2845 		}
2846 	}
2847 }
2848 #endif /* DDB */
2849