xref: /dragonfly/sys/vm/vm_object.c (revision a639f788)
1 /*
2  * Copyright (c) 1991, 1993, 2013
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	from: @(#)vm_object.c	8.5 (Berkeley) 3/22/94
33  *
34  *
35  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
36  * All rights reserved.
37  *
38  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
39  *
40  * Permission to use, copy, modify and distribute this software and
41  * its documentation is hereby granted, provided that both the copyright
42  * notice and this permission notice appear in all copies of the
43  * software, derivative works or modified versions, and any portions
44  * thereof, and that both notices appear in supporting documentation.
45  *
46  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
47  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
48  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
49  *
50  * Carnegie Mellon requests users of this software to return to
51  *
52  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
53  *  School of Computer Science
54  *  Carnegie Mellon University
55  *  Pittsburgh PA 15213-3890
56  *
57  * any improvements or extensions that they make and grant Carnegie the
58  * rights to redistribute these changes.
59  *
60  * $FreeBSD: src/sys/vm/vm_object.c,v 1.171.2.8 2003/05/26 19:17:56 alc Exp $
61  */
62 
63 /*
64  *	Virtual memory object module.
65  */
66 
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/proc.h>		/* for curproc, pageproc */
70 #include <sys/thread.h>
71 #include <sys/vnode.h>
72 #include <sys/vmmeter.h>
73 #include <sys/mman.h>
74 #include <sys/mount.h>
75 #include <sys/kernel.h>
76 #include <sys/sysctl.h>
77 #include <sys/refcount.h>
78 
79 #include <vm/vm.h>
80 #include <vm/vm_param.h>
81 #include <vm/pmap.h>
82 #include <vm/vm_map.h>
83 #include <vm/vm_object.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_pageout.h>
86 #include <vm/vm_pager.h>
87 #include <vm/swap_pager.h>
88 #include <vm/vm_kern.h>
89 #include <vm/vm_extern.h>
90 #include <vm/vm_zone.h>
91 
92 #include <vm/vm_page2.h>
93 
94 #include <machine/specialreg.h>
95 
96 #define EASY_SCAN_FACTOR	8
97 
98 static void	vm_object_qcollapse(vm_object_t object,
99 				    vm_object_t backing_object);
100 static void	vm_object_page_collect_flush(vm_object_t object, vm_page_t p,
101 					     int pagerflags);
102 static void	vm_object_lock_init(vm_object_t);
103 
104 
105 /*
106  *	Virtual memory objects maintain the actual data
107  *	associated with allocated virtual memory.  A given
108  *	page of memory exists within exactly one object.
109  *
110  *	An object is only deallocated when all "references"
111  *	are given up.  Only one "reference" to a given
112  *	region of an object should be writeable.
113  *
114  *	Associated with each object is a list of all resident
115  *	memory pages belonging to that object; this list is
116  *	maintained by the "vm_page" module, and locked by the object's
117  *	lock.
118  *
119  *	Each object also records a "pager" routine which is
120  *	used to retrieve (and store) pages to the proper backing
121  *	storage.  In addition, objects may be backed by other
122  *	objects from which they were virtual-copied.
123  *
124  *	The only items within the object structure which are
125  *	modified after time of creation are:
126  *		reference count		locked by object's lock
127  *		pager routine		locked by object's lock
128  *
129  */
130 
131 struct vm_object kernel_object;
132 
133 static long object_collapses;
134 static long object_bypasses;
135 
136 struct vm_object_hash vm_object_hash[VMOBJ_HSIZE];
137 
138 MALLOC_DEFINE(M_VM_OBJECT, "vm_object", "vm_object structures");
139 
140 #if defined(DEBUG_LOCKS)
141 
142 #define vm_object_vndeallocate(obj, vpp)	\
143                 debugvm_object_vndeallocate(obj, vpp, __FILE__, __LINE__)
144 
145 /*
146  * Debug helper to track hold/drop/ref/deallocate calls.
147  */
148 static void
149 debugvm_object_add(vm_object_t obj, char *file, int line, int addrem)
150 {
151 	int i;
152 
153 	i = atomic_fetchadd_int(&obj->debug_index, 1);
154 	i = i & (VMOBJ_DEBUG_ARRAY_SIZE - 1);
155 	ksnprintf(obj->debug_hold_thrs[i],
156 		  sizeof(obj->debug_hold_thrs[i]),
157 		  "%c%d:(%d):%s",
158 		  (addrem == -1 ? '-' : (addrem == 1 ? '+' : '=')),
159 		  (curthread->td_proc ? curthread->td_proc->p_pid : -1),
160 		  obj->ref_count,
161 		  curthread->td_comm);
162 	obj->debug_hold_file[i] = file;
163 	obj->debug_hold_line[i] = line;
164 #if 0
165 	/* Uncomment for debugging obj refs/derefs in reproducable cases */
166 	if (strcmp(curthread->td_comm, "sshd") == 0) {
167 		kprintf("%d %p refs=%d ar=%d file: %s/%d\n",
168 			(curthread->td_proc ? curthread->td_proc->p_pid : -1),
169 			obj, obj->ref_count, addrem, file, line);
170 	}
171 #endif
172 }
173 
174 #endif
175 
176 /*
177  * Misc low level routines
178  */
179 static void
180 vm_object_lock_init(vm_object_t obj)
181 {
182 #if defined(DEBUG_LOCKS)
183 	int i;
184 
185 	obj->debug_index = 0;
186 	for (i = 0; i < VMOBJ_DEBUG_ARRAY_SIZE; i++) {
187 		obj->debug_hold_thrs[i][0] = 0;
188 		obj->debug_hold_file[i] = NULL;
189 		obj->debug_hold_line[i] = 0;
190 	}
191 #endif
192 }
193 
194 void
195 vm_object_lock_swap(void)
196 {
197 	lwkt_token_swap();
198 }
199 
200 void
201 vm_object_lock(vm_object_t obj)
202 {
203 	lwkt_gettoken(&obj->token);
204 }
205 
206 /*
207  * Returns TRUE on sucesss
208  */
209 static int
210 vm_object_lock_try(vm_object_t obj)
211 {
212 	return(lwkt_trytoken(&obj->token));
213 }
214 
215 void
216 vm_object_lock_shared(vm_object_t obj)
217 {
218 	lwkt_gettoken_shared(&obj->token);
219 }
220 
221 void
222 vm_object_unlock(vm_object_t obj)
223 {
224 	lwkt_reltoken(&obj->token);
225 }
226 
227 void
228 vm_object_upgrade(vm_object_t obj)
229 {
230 	lwkt_reltoken(&obj->token);
231 	lwkt_gettoken(&obj->token);
232 }
233 
234 void
235 vm_object_downgrade(vm_object_t obj)
236 {
237 	lwkt_reltoken(&obj->token);
238 	lwkt_gettoken_shared(&obj->token);
239 }
240 
241 static __inline void
242 vm_object_assert_held(vm_object_t obj)
243 {
244 	ASSERT_LWKT_TOKEN_HELD(&obj->token);
245 }
246 
247 static __inline int
248 vm_quickcolor(void)
249 {
250 	globaldata_t gd = mycpu;
251 	int pg_color;
252 
253 	pg_color = (int)(intptr_t)gd->gd_curthread >> 10;
254 	pg_color += gd->gd_quick_color;
255 	gd->gd_quick_color += PQ_PRIME2;
256 
257 	return pg_color;
258 }
259 
260 void
261 VMOBJDEBUG(vm_object_hold)(vm_object_t obj VMOBJDBARGS)
262 {
263 	KKASSERT(obj != NULL);
264 
265 	/*
266 	 * Object must be held (object allocation is stable due to callers
267 	 * context, typically already holding the token on a parent object)
268 	 * prior to potentially blocking on the lock, otherwise the object
269 	 * can get ripped away from us.
270 	 */
271 	refcount_acquire(&obj->hold_count);
272 	vm_object_lock(obj);
273 
274 #if defined(DEBUG_LOCKS)
275 	debugvm_object_add(obj, file, line, 1);
276 #endif
277 }
278 
279 int
280 VMOBJDEBUG(vm_object_hold_try)(vm_object_t obj VMOBJDBARGS)
281 {
282 	KKASSERT(obj != NULL);
283 
284 	/*
285 	 * Object must be held (object allocation is stable due to callers
286 	 * context, typically already holding the token on a parent object)
287 	 * prior to potentially blocking on the lock, otherwise the object
288 	 * can get ripped away from us.
289 	 */
290 	refcount_acquire(&obj->hold_count);
291 	if (vm_object_lock_try(obj) == 0) {
292 		if (refcount_release(&obj->hold_count)) {
293 			if (obj->ref_count == 0 && (obj->flags & OBJ_DEAD))
294 				kfree(obj, M_VM_OBJECT);
295 		}
296 		return(0);
297 	}
298 
299 #if defined(DEBUG_LOCKS)
300 	debugvm_object_add(obj, file, line, 1);
301 #endif
302 	return(1);
303 }
304 
305 void
306 VMOBJDEBUG(vm_object_hold_shared)(vm_object_t obj VMOBJDBARGS)
307 {
308 	KKASSERT(obj != NULL);
309 
310 	/*
311 	 * Object must be held (object allocation is stable due to callers
312 	 * context, typically already holding the token on a parent object)
313 	 * prior to potentially blocking on the lock, otherwise the object
314 	 * can get ripped away from us.
315 	 */
316 	refcount_acquire(&obj->hold_count);
317 	vm_object_lock_shared(obj);
318 
319 #if defined(DEBUG_LOCKS)
320 	debugvm_object_add(obj, file, line, 1);
321 #endif
322 }
323 
324 /*
325  * Drop the token and hold_count on the object.
326  *
327  * WARNING! Token might be shared.
328  */
329 void
330 VMOBJDEBUG(vm_object_drop)(vm_object_t obj VMOBJDBARGS)
331 {
332 	if (obj == NULL)
333 		return;
334 
335 	/*
336 	 * No new holders should be possible once we drop hold_count 1->0 as
337 	 * there is no longer any way to reference the object.
338 	 */
339 	KKASSERT(obj->hold_count > 0);
340 	if (refcount_release(&obj->hold_count)) {
341 #if defined(DEBUG_LOCKS)
342 		debugvm_object_add(obj, file, line, -1);
343 #endif
344 
345 		if (obj->ref_count == 0 && (obj->flags & OBJ_DEAD)) {
346 			vm_object_unlock(obj);
347 			kfree(obj, M_VM_OBJECT);
348 		} else {
349 			vm_object_unlock(obj);
350 		}
351 	} else {
352 #if defined(DEBUG_LOCKS)
353 		debugvm_object_add(obj, file, line, -1);
354 #endif
355 		vm_object_unlock(obj);
356 	}
357 }
358 
359 /*
360  * Initialize a freshly allocated object, returning a held object.
361  *
362  * Used only by vm_object_allocate() and zinitna().
363  *
364  * No requirements.
365  */
366 void
367 _vm_object_allocate(objtype_t type, vm_pindex_t size, vm_object_t object)
368 {
369 	struct vm_object_hash *hash;
370 
371 	RB_INIT(&object->rb_memq);
372 	LIST_INIT(&object->shadow_head);
373 	lwkt_token_init(&object->token, "vmobj");
374 
375 	object->type = type;
376 	object->size = size;
377 	object->ref_count = 1;
378 	object->memattr = VM_MEMATTR_DEFAULT;
379 	object->hold_count = 0;
380 	object->flags = 0;
381 	if ((object->type == OBJT_DEFAULT) || (object->type == OBJT_SWAP))
382 		vm_object_set_flag(object, OBJ_ONEMAPPING);
383 	object->paging_in_progress = 0;
384 	object->resident_page_count = 0;
385 	object->agg_pv_list_count = 0;
386 	object->shadow_count = 0;
387 	/* cpu localization twist */
388 	object->pg_color = vm_quickcolor();
389 	object->handle = NULL;
390 	object->backing_object = NULL;
391 	object->backing_object_offset = (vm_ooffset_t)0;
392 
393 	object->generation++;
394 	object->swblock_count = 0;
395 	RB_INIT(&object->swblock_root);
396 	vm_object_lock_init(object);
397 	pmap_object_init(object);
398 
399 	vm_object_hold(object);
400 
401 	hash = VMOBJ_HASH(object);
402 	lwkt_gettoken(&hash->token);
403 	TAILQ_INSERT_TAIL(&hash->list, object, object_list);
404 	lwkt_reltoken(&hash->token);
405 }
406 
407 /*
408  * Initialize the VM objects module.
409  *
410  * Called from the low level boot code only.  Note that this occurs before
411  * kmalloc is initialized so we cannot allocate any VM objects.
412  */
413 void
414 vm_object_init(void)
415 {
416 	int i;
417 
418 	for (i = 0; i < VMOBJ_HSIZE; ++i) {
419 		TAILQ_INIT(&vm_object_hash[i].list);
420 		lwkt_token_init(&vm_object_hash[i].token, "vmobjlst");
421 	}
422 
423 	_vm_object_allocate(OBJT_DEFAULT, OFF_TO_IDX(KvaEnd),
424 			    &kernel_object);
425 	vm_object_drop(&kernel_object);
426 }
427 
428 void
429 vm_object_init2(void)
430 {
431 	kmalloc_set_unlimited(M_VM_OBJECT);
432 }
433 
434 /*
435  * Allocate and return a new object of the specified type and size.
436  *
437  * No requirements.
438  */
439 vm_object_t
440 vm_object_allocate(objtype_t type, vm_pindex_t size)
441 {
442 	vm_object_t obj;
443 
444 	obj = kmalloc(sizeof(*obj), M_VM_OBJECT, M_INTWAIT|M_ZERO);
445 	_vm_object_allocate(type, size, obj);
446 	vm_object_drop(obj);
447 
448 	return (obj);
449 }
450 
451 /*
452  * This version returns a held object, allowing further atomic initialization
453  * of the object.
454  */
455 vm_object_t
456 vm_object_allocate_hold(objtype_t type, vm_pindex_t size)
457 {
458 	vm_object_t obj;
459 
460 	obj = kmalloc(sizeof(*obj), M_VM_OBJECT, M_INTWAIT|M_ZERO);
461 	_vm_object_allocate(type, size, obj);
462 
463 	return (obj);
464 }
465 
466 /*
467  * Add an additional reference to a vm_object.  The object must already be
468  * held.  The original non-lock version is no longer supported.  The object
469  * must NOT be chain locked by anyone at the time the reference is added.
470  *
471  * Referencing a chain-locked object can blow up the fairly sensitive
472  * ref_count and shadow_count tests in the deallocator.  Most callers
473  * will call vm_object_chain_wait() prior to calling
474  * vm_object_reference_locked() to avoid the case.
475  *
476  * The object must be held, but may be held shared if desired (hence why
477  * we use an atomic op).
478  */
479 void
480 VMOBJDEBUG(vm_object_reference_locked)(vm_object_t object VMOBJDBARGS)
481 {
482 	KKASSERT(object != NULL);
483 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
484 	KKASSERT((object->chainlk & (CHAINLK_EXCL | CHAINLK_MASK)) == 0);
485 	atomic_add_int(&object->ref_count, 1);
486 	if (object->type == OBJT_VNODE) {
487 		vref(object->handle);
488 		/* XXX what if the vnode is being destroyed? */
489 	}
490 #if defined(DEBUG_LOCKS)
491 	debugvm_object_add(object, file, line, 1);
492 #endif
493 }
494 
495 /*
496  * This version is only allowed for vnode objects.
497  */
498 void
499 VMOBJDEBUG(vm_object_reference_quick)(vm_object_t object VMOBJDBARGS)
500 {
501 	KKASSERT(object->type == OBJT_VNODE);
502 	atomic_add_int(&object->ref_count, 1);
503 	vref(object->handle);
504 #if defined(DEBUG_LOCKS)
505 	debugvm_object_add(object, file, line, 1);
506 #endif
507 }
508 
509 /*
510  * Object OBJ_CHAINLOCK lock handling.
511  *
512  * The caller can chain-lock backing objects recursively and then
513  * use vm_object_chain_release_all() to undo the whole chain.
514  *
515  * Chain locks are used to prevent collapses and are only applicable
516  * to OBJT_DEFAULT and OBJT_SWAP objects.  Chain locking operations
517  * on other object types are ignored.  This is also important because
518  * it allows e.g. the vnode underlying a memory mapping to take concurrent
519  * faults.
520  *
521  * The object must usually be held on entry, though intermediate
522  * objects need not be held on release.  The object must be held exclusively,
523  * NOT shared.  Note that the prefault path checks the shared state and
524  * avoids using the chain functions.
525  */
526 void
527 vm_object_chain_wait(vm_object_t object, int shared)
528 {
529 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
530 	for (;;) {
531 		uint32_t chainlk = object->chainlk;
532 
533 		cpu_ccfence();
534 		if (shared) {
535 			if (chainlk & (CHAINLK_EXCL | CHAINLK_EXCLREQ)) {
536 				tsleep_interlock(object, 0);
537 				if (atomic_cmpset_int(&object->chainlk,
538 						      chainlk,
539 						      chainlk | CHAINLK_WAIT)) {
540 					tsleep(object, PINTERLOCKED,
541 					       "objchns", 0);
542 				}
543 				/* retry */
544 			} else {
545 				break;
546 			}
547 			/* retry */
548 		} else {
549 			if (chainlk & (CHAINLK_MASK | CHAINLK_EXCL)) {
550 				tsleep_interlock(object, 0);
551 				if (atomic_cmpset_int(&object->chainlk,
552 						      chainlk,
553 						      chainlk | CHAINLK_WAIT))
554 				{
555 					tsleep(object, PINTERLOCKED,
556 					       "objchnx", 0);
557 				}
558 				/* retry */
559 			} else {
560 				if (atomic_cmpset_int(&object->chainlk,
561 						      chainlk,
562 						      chainlk & ~CHAINLK_WAIT))
563 				{
564 					if (chainlk & CHAINLK_WAIT)
565 						wakeup(object);
566 					break;
567 				}
568 				/* retry */
569 			}
570 		}
571 		/* retry */
572 	}
573 }
574 
575 void
576 vm_object_chain_acquire(vm_object_t object, int shared)
577 {
578 	if (object->type != OBJT_DEFAULT && object->type != OBJT_SWAP)
579 		return;
580 	if (vm_shared_fault == 0)
581 		shared = 0;
582 
583 	for (;;) {
584 		uint32_t chainlk = object->chainlk;
585 
586 		cpu_ccfence();
587 		if (shared) {
588 			if (chainlk & (CHAINLK_EXCL | CHAINLK_EXCLREQ)) {
589 				tsleep_interlock(object, 0);
590 				if (atomic_cmpset_int(&object->chainlk,
591 						      chainlk,
592 						      chainlk | CHAINLK_WAIT)) {
593 					tsleep(object, PINTERLOCKED,
594 					       "objchns", 0);
595 				}
596 				/* retry */
597 			} else if (atomic_cmpset_int(&object->chainlk,
598 					      chainlk, chainlk + 1)) {
599 				break;
600 			}
601 			/* retry */
602 		} else {
603 			if (chainlk & (CHAINLK_MASK | CHAINLK_EXCL)) {
604 				tsleep_interlock(object, 0);
605 				if (atomic_cmpset_int(&object->chainlk,
606 						      chainlk,
607 						      chainlk |
608 						       CHAINLK_WAIT |
609 						       CHAINLK_EXCLREQ)) {
610 					tsleep(object, PINTERLOCKED,
611 					       "objchnx", 0);
612 				}
613 				/* retry */
614 			} else {
615 				if (atomic_cmpset_int(&object->chainlk,
616 						      chainlk,
617 						      (chainlk | CHAINLK_EXCL) &
618 						      ~(CHAINLK_EXCLREQ |
619 							CHAINLK_WAIT))) {
620 					if (chainlk & CHAINLK_WAIT)
621 						wakeup(object);
622 					break;
623 				}
624 				/* retry */
625 			}
626 		}
627 		/* retry */
628 	}
629 }
630 
631 void
632 vm_object_chain_release(vm_object_t object)
633 {
634 	/*ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));*/
635 	if (object->type != OBJT_DEFAULT && object->type != OBJT_SWAP)
636 		return;
637 	KKASSERT(object->chainlk & (CHAINLK_MASK | CHAINLK_EXCL));
638 	for (;;) {
639 		uint32_t chainlk = object->chainlk;
640 
641 		cpu_ccfence();
642 		if (chainlk & CHAINLK_MASK) {
643 			if ((chainlk & CHAINLK_MASK) == 1 &&
644 			    atomic_cmpset_int(&object->chainlk,
645 					      chainlk,
646 					      (chainlk - 1) & ~CHAINLK_WAIT)) {
647 				if (chainlk & CHAINLK_WAIT)
648 					wakeup(object);
649 				break;
650 			}
651 			if ((chainlk & CHAINLK_MASK) > 1 &&
652 			    atomic_cmpset_int(&object->chainlk,
653 					      chainlk, chainlk - 1)) {
654 				break;
655 			}
656 			/* retry */
657 		} else {
658 			KKASSERT(chainlk & CHAINLK_EXCL);
659 			if (atomic_cmpset_int(&object->chainlk,
660 					      chainlk,
661 					      chainlk & ~(CHAINLK_EXCL |
662 							  CHAINLK_WAIT))) {
663 				if (chainlk & CHAINLK_WAIT)
664 					wakeup(object);
665 				break;
666 			}
667 		}
668 	}
669 }
670 
671 /*
672  * Release the chain from first_object through and including stopobj.
673  * The caller is typically holding the first and last object locked
674  * (shared or exclusive) to prevent destruction races.
675  *
676  * We release stopobj first as an optimization as this object is most
677  * likely to be shared across multiple processes.
678  */
679 void
680 vm_object_chain_release_all(vm_object_t first_object, vm_object_t stopobj)
681 {
682 	vm_object_t backing_object;
683 	vm_object_t object;
684 
685 	vm_object_chain_release(stopobj);
686 	object = first_object;
687 
688 	while (object != stopobj) {
689 		KKASSERT(object);
690 		backing_object = object->backing_object;
691 		vm_object_chain_release(object);
692 		object = backing_object;
693 	}
694 }
695 
696 /*
697  * Dereference an object and its underlying vnode.  The object may be
698  * held shared.  On return the object will remain held.
699  *
700  * This function may return a vnode in *vpp which the caller must release
701  * after the caller drops its own lock.  If vpp is NULL, we assume that
702  * the caller was holding an exclusive lock on the object and we vrele()
703  * the vp ourselves.
704  */
705 static void
706 VMOBJDEBUG(vm_object_vndeallocate)(vm_object_t object, struct vnode **vpp
707 				   VMOBJDBARGS)
708 {
709 	struct vnode *vp = (struct vnode *) object->handle;
710 
711 	KASSERT(object->type == OBJT_VNODE,
712 	    ("vm_object_vndeallocate: not a vnode object"));
713 	KASSERT(vp != NULL, ("vm_object_vndeallocate: missing vp"));
714 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
715 #ifdef INVARIANTS
716 	if (object->ref_count == 0) {
717 		vprint("vm_object_vndeallocate", vp);
718 		panic("vm_object_vndeallocate: bad object reference count");
719 	}
720 #endif
721 	for (;;) {
722 		int count = object->ref_count;
723 		cpu_ccfence();
724 		if (count == 1) {
725 			vm_object_upgrade(object);
726 			if (atomic_cmpset_int(&object->ref_count, count, 0)) {
727 				vclrflags(vp, VTEXT);
728 				break;
729 			}
730 		} else {
731 			if (atomic_cmpset_int(&object->ref_count,
732 					      count, count - 1)) {
733 				break;
734 			}
735 		}
736 		/* retry */
737 	}
738 #if defined(DEBUG_LOCKS)
739 	debugvm_object_add(object, file, line, -1);
740 #endif
741 
742 	/*
743 	 * vrele or return the vp to vrele.  We can only safely vrele(vp)
744 	 * if the object was locked exclusively.  But there are two races
745 	 * here.
746 	 *
747 	 * We had to upgrade the object above to safely clear VTEXT
748 	 * but the alternative path where the shared lock is retained
749 	 * can STILL race to 0 in other paths and cause our own vrele()
750 	 * to terminate the vnode.  We can't allow that if the VM object
751 	 * is still locked shared.
752 	 */
753 	if (vpp)
754 		*vpp = vp;
755 	else
756 		vrele(vp);
757 }
758 
759 /*
760  * Release a reference to the specified object, gained either through a
761  * vm_object_allocate or a vm_object_reference call.  When all references
762  * are gone, storage associated with this object may be relinquished.
763  *
764  * The caller does not have to hold the object locked but must have control
765  * over the reference in question in order to guarantee that the object
766  * does not get ripped out from under us.
767  *
768  * XXX Currently all deallocations require an exclusive lock.
769  */
770 void
771 VMOBJDEBUG(vm_object_deallocate)(vm_object_t object VMOBJDBARGS)
772 {
773 	struct vnode *vp;
774 	int count;
775 
776 	if (object == NULL)
777 		return;
778 
779 	for (;;) {
780 		count = object->ref_count;
781 		cpu_ccfence();
782 
783 		/*
784 		 * If decrementing the count enters into special handling
785 		 * territory (0, 1, or 2) we have to do it the hard way.
786 		 * Fortunate though, objects with only a few refs like this
787 		 * are not likely to be heavily contended anyway.
788 		 *
789 		 * For vnode objects we only care about 1->0 transitions.
790 		 */
791 		if (count <= 3 || (object->type == OBJT_VNODE && count <= 1)) {
792 #if defined(DEBUG_LOCKS)
793 			debugvm_object_add(object, file, line, 0);
794 #endif
795 			vm_object_hold(object);
796 			vm_object_deallocate_locked(object);
797 			vm_object_drop(object);
798 			break;
799 		}
800 
801 		/*
802 		 * Try to decrement ref_count without acquiring a hold on
803 		 * the object.  This is particularly important for the exec*()
804 		 * and exit*() code paths because the program binary may
805 		 * have a great deal of sharing and an exclusive lock will
806 		 * crowbar performance in those circumstances.
807 		 */
808 		if (object->type == OBJT_VNODE) {
809 			vp = (struct vnode *)object->handle;
810 			if (atomic_cmpset_int(&object->ref_count,
811 					      count, count - 1)) {
812 #if defined(DEBUG_LOCKS)
813 				debugvm_object_add(object, file, line, -1);
814 #endif
815 
816 				vrele(vp);
817 				break;
818 			}
819 			/* retry */
820 		} else {
821 			if (atomic_cmpset_int(&object->ref_count,
822 					      count, count - 1)) {
823 #if defined(DEBUG_LOCKS)
824 				debugvm_object_add(object, file, line, -1);
825 #endif
826 				break;
827 			}
828 			/* retry */
829 		}
830 		/* retry */
831 	}
832 }
833 
834 void
835 VMOBJDEBUG(vm_object_deallocate_locked)(vm_object_t object VMOBJDBARGS)
836 {
837 	struct vm_object_dealloc_list *dlist = NULL;
838 	struct vm_object_dealloc_list *dtmp;
839 	vm_object_t temp;
840 	int must_drop = 0;
841 
842 	/*
843 	 * We may chain deallocate object, but additional objects may
844 	 * collect on the dlist which also have to be deallocated.  We
845 	 * must avoid a recursion, vm_object chains can get deep.
846 	 */
847 
848 again:
849 	while (object != NULL) {
850 		/*
851 		 * vnode case, caller either locked the object exclusively
852 		 * or this is a recursion with must_drop != 0 and the vnode
853 		 * object will be locked shared.
854 		 *
855 		 * If locked shared we have to drop the object before we can
856 		 * call vrele() or risk a shared/exclusive livelock.
857 		 */
858 		if (object->type == OBJT_VNODE) {
859 			ASSERT_LWKT_TOKEN_HELD(&object->token);
860 			if (must_drop) {
861 				struct vnode *tmp_vp;
862 
863 				vm_object_vndeallocate(object, &tmp_vp);
864 				vm_object_drop(object);
865 				must_drop = 0;
866 				object = NULL;
867 				vrele(tmp_vp);
868 			} else {
869 				vm_object_vndeallocate(object, NULL);
870 			}
871 			break;
872 		}
873 		ASSERT_LWKT_TOKEN_HELD_EXCL(&object->token);
874 
875 		/*
876 		 * Normal case (object is locked exclusively)
877 		 */
878 		if (object->ref_count == 0) {
879 			panic("vm_object_deallocate: object deallocated "
880 			      "too many times: %d", object->type);
881 		}
882 		if (object->ref_count > 2) {
883 			atomic_add_int(&object->ref_count, -1);
884 #if defined(DEBUG_LOCKS)
885 			debugvm_object_add(object, file, line, -1);
886 #endif
887 			break;
888 		}
889 
890 		/*
891 		 * Here on ref_count of one or two, which are special cases for
892 		 * objects.
893 		 *
894 		 * Nominal ref_count > 1 case if the second ref is not from
895 		 * a shadow.
896 		 *
897 		 * (ONEMAPPING only applies to DEFAULT AND SWAP objects)
898 		 */
899 		if (object->ref_count == 2 && object->shadow_count == 0) {
900 			if (object->type == OBJT_DEFAULT ||
901 			    object->type == OBJT_SWAP) {
902 				vm_object_set_flag(object, OBJ_ONEMAPPING);
903 			}
904 			atomic_add_int(&object->ref_count, -1);
905 #if defined(DEBUG_LOCKS)
906 			debugvm_object_add(object, file, line, -1);
907 #endif
908 			break;
909 		}
910 
911 		/*
912 		 * If the second ref is from a shadow we chain along it
913 		 * upwards if object's handle is exhausted.
914 		 *
915 		 * We have to decrement object->ref_count before potentially
916 		 * collapsing the first shadow object or the collapse code
917 		 * will not be able to handle the degenerate case to remove
918 		 * object.  However, if we do it too early the object can
919 		 * get ripped out from under us.
920 		 */
921 		if (object->ref_count == 2 && object->shadow_count == 1 &&
922 		    object->handle == NULL && (object->type == OBJT_DEFAULT ||
923 					       object->type == OBJT_SWAP)) {
924 			temp = LIST_FIRST(&object->shadow_head);
925 			KKASSERT(temp != NULL);
926 			vm_object_hold(temp);
927 
928 			/*
929 			 * Wait for any paging to complete so the collapse
930 			 * doesn't (or isn't likely to) qcollapse.  pip
931 			 * waiting must occur before we acquire the
932 			 * chainlock.
933 			 */
934 			while (
935 				temp->paging_in_progress ||
936 				object->paging_in_progress
937 			) {
938 				vm_object_pip_wait(temp, "objde1");
939 				vm_object_pip_wait(object, "objde2");
940 			}
941 
942 			/*
943 			 * If the parent is locked we have to give up, as
944 			 * otherwise we would be acquiring locks in the
945 			 * wrong order and potentially deadlock.
946 			 */
947 			if (temp->chainlk & (CHAINLK_EXCL | CHAINLK_MASK)) {
948 				vm_object_drop(temp);
949 				goto skip;
950 			}
951 			vm_object_chain_acquire(temp, 0);
952 
953 			/*
954 			 * Recheck/retry after the hold and the paging
955 			 * wait, both of which can block us.
956 			 */
957 			if (object->ref_count != 2 ||
958 			    object->shadow_count != 1 ||
959 			    object->handle ||
960 			    LIST_FIRST(&object->shadow_head) != temp ||
961 			    (object->type != OBJT_DEFAULT &&
962 			     object->type != OBJT_SWAP)) {
963 				vm_object_chain_release(temp);
964 				vm_object_drop(temp);
965 				continue;
966 			}
967 
968 			/*
969 			 * We can safely drop object's ref_count now.
970 			 */
971 			KKASSERT(object->ref_count == 2);
972 			atomic_add_int(&object->ref_count, -1);
973 #if defined(DEBUG_LOCKS)
974 			debugvm_object_add(object, file, line, -1);
975 #endif
976 
977 			/*
978 			 * If our single parent is not collapseable just
979 			 * decrement ref_count (2->1) and stop.
980 			 */
981 			if (temp->handle || (temp->type != OBJT_DEFAULT &&
982 					     temp->type != OBJT_SWAP)) {
983 				vm_object_chain_release(temp);
984 				vm_object_drop(temp);
985 				break;
986 			}
987 
988 			/*
989 			 * At this point we have already dropped object's
990 			 * ref_count so it is possible for a race to
991 			 * deallocate obj out from under us.  Any collapse
992 			 * will re-check the situation.  We must not block
993 			 * until we are able to collapse.
994 			 *
995 			 * Bump temp's ref_count to avoid an unwanted
996 			 * degenerate recursion (can't call
997 			 * vm_object_reference_locked() because it asserts
998 			 * that CHAINLOCK is not set).
999 			 */
1000 			atomic_add_int(&temp->ref_count, 1);
1001 			KKASSERT(temp->ref_count > 1);
1002 
1003 			/*
1004 			 * Collapse temp, then deallocate the extra ref
1005 			 * formally.
1006 			 */
1007 			vm_object_collapse(temp, &dlist);
1008 			vm_object_chain_release(temp);
1009 			if (must_drop) {
1010 				vm_object_lock_swap();
1011 				vm_object_drop(object);
1012 			}
1013 			object = temp;
1014 			must_drop = 1;
1015 			continue;
1016 		}
1017 
1018 		/*
1019 		 * Drop the ref and handle termination on the 1->0 transition.
1020 		 * We may have blocked above so we have to recheck.
1021 		 */
1022 skip:
1023 		KKASSERT(object->ref_count != 0);
1024 		if (object->ref_count >= 2) {
1025 			atomic_add_int(&object->ref_count, -1);
1026 #if defined(DEBUG_LOCKS)
1027 			debugvm_object_add(object, file, line, -1);
1028 #endif
1029 			break;
1030 		}
1031 		KKASSERT(object->ref_count == 1);
1032 
1033 		/*
1034 		 * 1->0 transition.  Chain through the backing_object.
1035 		 * Maintain the ref until we've located the backing object,
1036 		 * then re-check.
1037 		 */
1038 		while ((temp = object->backing_object) != NULL) {
1039 			if (temp->type == OBJT_VNODE)
1040 				vm_object_hold_shared(temp);
1041 			else
1042 				vm_object_hold(temp);
1043 			if (temp == object->backing_object)
1044 				break;
1045 			vm_object_drop(temp);
1046 		}
1047 
1048 		/*
1049 		 * 1->0 transition verified, retry if ref_count is no longer
1050 		 * 1.  Otherwise disconnect the backing_object (temp) and
1051 		 * clean up.
1052 		 */
1053 		if (object->ref_count != 1) {
1054 			vm_object_drop(temp);
1055 			continue;
1056 		}
1057 
1058 		/*
1059 		 * It shouldn't be possible for the object to be chain locked
1060 		 * if we're removing the last ref on it.
1061 		 *
1062 		 * Removing object from temp's shadow list requires dropping
1063 		 * temp, which we will do on loop.
1064 		 *
1065 		 * NOTE! vnodes do not use the shadow list, but still have
1066 		 *	 the backing_object reference.
1067 		 */
1068 		KKASSERT((object->chainlk & (CHAINLK_EXCL|CHAINLK_MASK)) == 0);
1069 
1070 		if (temp) {
1071 			if (object->flags & OBJ_ONSHADOW) {
1072 				LIST_REMOVE(object, shadow_list);
1073 				temp->shadow_count--;
1074 				temp->generation++;
1075 				vm_object_clear_flag(object, OBJ_ONSHADOW);
1076 			}
1077 			object->backing_object = NULL;
1078 		}
1079 
1080 		atomic_add_int(&object->ref_count, -1);
1081 		if ((object->flags & OBJ_DEAD) == 0)
1082 			vm_object_terminate(object);
1083 		if (must_drop && temp)
1084 			vm_object_lock_swap();
1085 		if (must_drop)
1086 			vm_object_drop(object);
1087 		object = temp;
1088 		must_drop = 1;
1089 	}
1090 
1091 	if (must_drop && object)
1092 		vm_object_drop(object);
1093 
1094 	/*
1095 	 * Additional tail recursion on dlist.  Avoid a recursion.  Objects
1096 	 * on the dlist have a hold count but are not locked.
1097 	 */
1098 	if ((dtmp = dlist) != NULL) {
1099 		dlist = dtmp->next;
1100 		object = dtmp->object;
1101 		kfree(dtmp, M_TEMP);
1102 
1103 		vm_object_lock(object);	/* already held, add lock */
1104 		must_drop = 1;		/* and we're responsible for it */
1105 		goto again;
1106 	}
1107 }
1108 
1109 /*
1110  * Destroy the specified object, freeing up related resources.
1111  *
1112  * The object must have zero references.
1113  *
1114  * The object must held.  The caller is responsible for dropping the object
1115  * after terminate returns.  Terminate does NOT drop the object.
1116  */
1117 static int vm_object_terminate_callback(vm_page_t p, void *data);
1118 
1119 void
1120 vm_object_terminate(vm_object_t object)
1121 {
1122 	struct rb_vm_page_scan_info info;
1123 	struct vm_object_hash *hash;
1124 
1125 	/*
1126 	 * Make sure no one uses us.  Once we set OBJ_DEAD we should be
1127 	 * able to safely block.
1128 	 */
1129 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1130 	KKASSERT((object->flags & OBJ_DEAD) == 0);
1131 	vm_object_set_flag(object, OBJ_DEAD);
1132 
1133 	/*
1134 	 * Wait for the pageout daemon to be done with the object
1135 	 */
1136 	vm_object_pip_wait(object, "objtrm1");
1137 
1138 	KASSERT(!object->paging_in_progress,
1139 		("vm_object_terminate: pageout in progress"));
1140 
1141 	/*
1142 	 * Clean and free the pages, as appropriate. All references to the
1143 	 * object are gone, so we don't need to lock it.
1144 	 */
1145 	if (object->type == OBJT_VNODE) {
1146 		struct vnode *vp;
1147 
1148 		/*
1149 		 * Clean pages and flush buffers.
1150 		 *
1151 		 * NOTE!  TMPFS buffer flushes do not typically flush the
1152 		 *	  actual page to swap as this would be highly
1153 		 *	  inefficient, and normal filesystems usually wrap
1154 		 *	  page flushes with buffer cache buffers.
1155 		 *
1156 		 *	  To deal with this we have to call vinvalbuf() both
1157 		 *	  before and after the vm_object_page_clean().
1158 		 */
1159 		vp = (struct vnode *) object->handle;
1160 		vinvalbuf(vp, V_SAVE, 0, 0);
1161 		vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
1162 		vinvalbuf(vp, V_SAVE, 0, 0);
1163 	}
1164 
1165 	/*
1166 	 * Wait for any I/O to complete, after which there had better not
1167 	 * be any references left on the object.
1168 	 */
1169 	vm_object_pip_wait(object, "objtrm2");
1170 
1171 	if (object->ref_count != 0) {
1172 		panic("vm_object_terminate: object with references, "
1173 		      "ref_count=%d", object->ref_count);
1174 	}
1175 
1176 	/*
1177 	 * Cleanup any shared pmaps associated with this object.
1178 	 */
1179 	pmap_object_free(object);
1180 
1181 	/*
1182 	 * Now free any remaining pages. For internal objects, this also
1183 	 * removes them from paging queues. Don't free wired pages, just
1184 	 * remove them from the object.
1185 	 */
1186 	info.count = 0;
1187 	info.object = object;
1188 	vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
1189 				vm_object_terminate_callback, &info);
1190 
1191 	/*
1192 	 * Let the pager know object is dead.
1193 	 */
1194 	vm_pager_deallocate(object);
1195 
1196 	/*
1197 	 * Wait for the object hold count to hit 1, clean out pages as
1198 	 * we go.  vmobj_token interlocks any race conditions that might
1199 	 * pick the object up from the vm_object_list after we have cleared
1200 	 * rb_memq.
1201 	 */
1202 	for (;;) {
1203 		if (RB_ROOT(&object->rb_memq) == NULL)
1204 			break;
1205 		kprintf("vm_object_terminate: Warning, object %p "
1206 			"still has %ld pages\n",
1207 			object, object->resident_page_count);
1208 		vm_page_rb_tree_RB_SCAN(&object->rb_memq, NULL,
1209 					vm_object_terminate_callback, &info);
1210 	}
1211 
1212 	/*
1213 	 * There had better not be any pages left
1214 	 */
1215 	KKASSERT(object->resident_page_count == 0);
1216 
1217 	/*
1218 	 * Remove the object from the global object list.
1219 	 */
1220 	hash = VMOBJ_HASH(object);
1221 	lwkt_gettoken(&hash->token);
1222 	TAILQ_REMOVE(&hash->list, object, object_list);
1223 	lwkt_reltoken(&hash->token);
1224 
1225 	if (object->ref_count != 0) {
1226 		panic("vm_object_terminate2: object with references, "
1227 		      "ref_count=%d", object->ref_count);
1228 	}
1229 
1230 	/*
1231 	 * NOTE: The object hold_count is at least 1, so we cannot kfree()
1232 	 *	 the object here.  See vm_object_drop().
1233 	 */
1234 }
1235 
1236 /*
1237  * The caller must hold the object.
1238  */
1239 static int
1240 vm_object_terminate_callback(vm_page_t p, void *data)
1241 {
1242 	struct rb_vm_page_scan_info *info = data;
1243 	vm_object_t object;
1244 
1245 	if ((++info->count & 63) == 0)
1246 		lwkt_user_yield();
1247 	object = p->object;
1248 	if (object != info->object) {
1249 		kprintf("vm_object_terminate_callback: obj/pg race %p/%p\n",
1250 			info->object, p);
1251 		return(0);
1252 	}
1253 	vm_page_busy_wait(p, TRUE, "vmpgtrm");
1254 	if (object != p->object) {
1255 		kprintf("vm_object_terminate: Warning: Encountered "
1256 			"busied page %p on queue %d\n", p, p->queue);
1257 		vm_page_wakeup(p);
1258 	} else if (p->wire_count == 0) {
1259 		/*
1260 		 * NOTE: p->dirty and PG_NEED_COMMIT are ignored.
1261 		 */
1262 		vm_page_free(p);
1263 		mycpu->gd_cnt.v_pfree++;
1264 	} else {
1265 		if (p->queue != PQ_NONE)
1266 			kprintf("vm_object_terminate: Warning: Encountered "
1267 				"wired page %p on queue %d\n", p, p->queue);
1268 		vm_page_remove(p);
1269 		vm_page_wakeup(p);
1270 	}
1271 	return(0);
1272 }
1273 
1274 /*
1275  * Clean all dirty pages in the specified range of object.  Leaves page
1276  * on whatever queue it is currently on.   If NOSYNC is set then do not
1277  * write out pages with PG_NOSYNC set (originally comes from MAP_NOSYNC),
1278  * leaving the object dirty.
1279  *
1280  * When stuffing pages asynchronously, allow clustering.  XXX we need a
1281  * synchronous clustering mode implementation.
1282  *
1283  * Odd semantics: if start == end, we clean everything.
1284  *
1285  * The object must be locked? XXX
1286  */
1287 static int vm_object_page_clean_pass1(struct vm_page *p, void *data);
1288 static int vm_object_page_clean_pass2(struct vm_page *p, void *data);
1289 
1290 void
1291 vm_object_page_clean(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
1292 		     int flags)
1293 {
1294 	struct rb_vm_page_scan_info info;
1295 	struct vnode *vp;
1296 	int wholescan;
1297 	int pagerflags;
1298 	int generation;
1299 
1300 	vm_object_hold(object);
1301 	if (object->type != OBJT_VNODE ||
1302 	    (object->flags & OBJ_MIGHTBEDIRTY) == 0) {
1303 		vm_object_drop(object);
1304 		return;
1305 	}
1306 
1307 	pagerflags = (flags & (OBJPC_SYNC | OBJPC_INVAL)) ?
1308 			VM_PAGER_PUT_SYNC : VM_PAGER_CLUSTER_OK;
1309 	pagerflags |= (flags & OBJPC_INVAL) ? VM_PAGER_PUT_INVAL : 0;
1310 
1311 	vp = object->handle;
1312 
1313 	/*
1314 	 * Interlock other major object operations.  This allows us to
1315 	 * temporarily clear OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY.
1316 	 */
1317 	vm_object_set_flag(object, OBJ_CLEANING);
1318 
1319 	/*
1320 	 * Handle 'entire object' case
1321 	 */
1322 	info.start_pindex = start;
1323 	if (end == 0) {
1324 		info.end_pindex = object->size - 1;
1325 	} else {
1326 		info.end_pindex = end - 1;
1327 	}
1328 	wholescan = (start == 0 && info.end_pindex == object->size - 1);
1329 	info.limit = flags;
1330 	info.pagerflags = pagerflags;
1331 	info.object = object;
1332 
1333 	/*
1334 	 * If cleaning the entire object do a pass to mark the pages read-only.
1335 	 * If everything worked out ok, clear OBJ_WRITEABLE and
1336 	 * OBJ_MIGHTBEDIRTY.
1337 	 */
1338 	if (wholescan) {
1339 		info.error = 0;
1340 		info.count = 0;
1341 		vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1342 					vm_object_page_clean_pass1, &info);
1343 		if (info.error == 0) {
1344 			vm_object_clear_flag(object,
1345 					     OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
1346 			if (object->type == OBJT_VNODE &&
1347 			    (vp = (struct vnode *)object->handle) != NULL) {
1348 				/*
1349 				 * Use new-style interface to clear VISDIRTY
1350 				 * because the vnode is not necessarily removed
1351 				 * from the syncer list(s) as often as it was
1352 				 * under the old interface, which can leave
1353 				 * the vnode on the syncer list after reclaim.
1354 				 */
1355 				vclrobjdirty(vp);
1356 			}
1357 		}
1358 	}
1359 
1360 	/*
1361 	 * Do a pass to clean all the dirty pages we find.
1362 	 */
1363 	do {
1364 		info.error = 0;
1365 		info.count = 0;
1366 		generation = object->generation;
1367 		vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1368 					vm_object_page_clean_pass2, &info);
1369 	} while (info.error || generation != object->generation);
1370 
1371 	vm_object_clear_flag(object, OBJ_CLEANING);
1372 	vm_object_drop(object);
1373 }
1374 
1375 /*
1376  * The caller must hold the object.
1377  */
1378 static
1379 int
1380 vm_object_page_clean_pass1(struct vm_page *p, void *data)
1381 {
1382 	struct rb_vm_page_scan_info *info = data;
1383 
1384 	if ((++info->count & 63) == 0)
1385 		lwkt_user_yield();
1386 	if (p->object != info->object ||
1387 	    p->pindex < info->start_pindex ||
1388 	    p->pindex > info->end_pindex) {
1389 		kprintf("vm_object_page_clean_pass1: obj/pg race %p/%p\n",
1390 			info->object, p);
1391 		return(0);
1392 	}
1393 	vm_page_flag_set(p, PG_CLEANCHK);
1394 	if ((info->limit & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
1395 		info->error = 1;
1396 	} else if (vm_page_busy_try(p, FALSE) == 0) {
1397 		if (p->object == info->object)
1398 			vm_page_protect(p, VM_PROT_READ);
1399 		vm_page_wakeup(p);
1400 	} else {
1401 		info->error = 1;
1402 	}
1403 	return(0);
1404 }
1405 
1406 /*
1407  * The caller must hold the object
1408  */
1409 static
1410 int
1411 vm_object_page_clean_pass2(struct vm_page *p, void *data)
1412 {
1413 	struct rb_vm_page_scan_info *info = data;
1414 	int generation;
1415 
1416 	if (p->object != info->object ||
1417 	    p->pindex < info->start_pindex ||
1418 	    p->pindex > info->end_pindex) {
1419 		kprintf("vm_object_page_clean_pass2: obj/pg race %p/%p\n",
1420 			info->object, p);
1421 		return(0);
1422 	}
1423 
1424 	/*
1425 	 * Do not mess with pages that were inserted after we started
1426 	 * the cleaning pass.
1427 	 */
1428 	if ((p->flags & PG_CLEANCHK) == 0)
1429 		goto done;
1430 
1431 	generation = info->object->generation;
1432 	vm_page_busy_wait(p, TRUE, "vpcwai");
1433 
1434 	if (p->object != info->object ||
1435 	    p->pindex < info->start_pindex ||
1436 	    p->pindex > info->end_pindex ||
1437 	    info->object->generation != generation) {
1438 		info->error = 1;
1439 		vm_page_wakeup(p);
1440 		goto done;
1441 	}
1442 
1443 	/*
1444 	 * Before wasting time traversing the pmaps, check for trivial
1445 	 * cases where the page cannot be dirty.
1446 	 */
1447 	if (p->valid == 0 || (p->queue - p->pc) == PQ_CACHE) {
1448 		KKASSERT((p->dirty & p->valid) == 0 &&
1449 			 (p->flags & PG_NEED_COMMIT) == 0);
1450 		vm_page_wakeup(p);
1451 		goto done;
1452 	}
1453 
1454 	/*
1455 	 * Check whether the page is dirty or not.  The page has been set
1456 	 * to be read-only so the check will not race a user dirtying the
1457 	 * page.
1458 	 */
1459 	vm_page_test_dirty(p);
1460 	if ((p->dirty & p->valid) == 0 && (p->flags & PG_NEED_COMMIT) == 0) {
1461 		vm_page_flag_clear(p, PG_CLEANCHK);
1462 		vm_page_wakeup(p);
1463 		goto done;
1464 	}
1465 
1466 	/*
1467 	 * If we have been asked to skip nosync pages and this is a
1468 	 * nosync page, skip it.  Note that the object flags were
1469 	 * not cleared in this case (because pass1 will have returned an
1470 	 * error), so we do not have to set them.
1471 	 */
1472 	if ((info->limit & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
1473 		vm_page_flag_clear(p, PG_CLEANCHK);
1474 		vm_page_wakeup(p);
1475 		goto done;
1476 	}
1477 
1478 	/*
1479 	 * Flush as many pages as we can.  PG_CLEANCHK will be cleared on
1480 	 * the pages that get successfully flushed.  Set info->error if
1481 	 * we raced an object modification.
1482 	 */
1483 	vm_object_page_collect_flush(info->object, p, info->pagerflags);
1484 	/* vm_wait_nominal(); this can deadlock the system in syncer/pageout */
1485 done:
1486 	if ((++info->count & 63) == 0)
1487 		lwkt_user_yield();
1488 
1489 	return(0);
1490 }
1491 
1492 /*
1493  * Collect the specified page and nearby pages and flush them out.
1494  * The number of pages flushed is returned.  The passed page is busied
1495  * by the caller and we are responsible for its disposition.
1496  *
1497  * The caller must hold the object.
1498  */
1499 static void
1500 vm_object_page_collect_flush(vm_object_t object, vm_page_t p, int pagerflags)
1501 {
1502 	int error;
1503 	int is;
1504 	int ib;
1505 	int i;
1506 	int page_base;
1507 	vm_pindex_t pi;
1508 	vm_page_t ma[BLIST_MAX_ALLOC];
1509 
1510 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1511 
1512 	pi = p->pindex;
1513 	page_base = pi % BLIST_MAX_ALLOC;
1514 	ma[page_base] = p;
1515 	ib = page_base - 1;
1516 	is = page_base + 1;
1517 
1518 	while (ib >= 0) {
1519 		vm_page_t tp;
1520 
1521 		tp = vm_page_lookup_busy_try(object, pi - page_base + ib,
1522 					     TRUE, &error);
1523 		if (error)
1524 			break;
1525 		if (tp == NULL)
1526 			break;
1527 		if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1528 		    (tp->flags & PG_CLEANCHK) == 0) {
1529 			vm_page_wakeup(tp);
1530 			break;
1531 		}
1532 		if ((tp->queue - tp->pc) == PQ_CACHE) {
1533 			vm_page_flag_clear(tp, PG_CLEANCHK);
1534 			vm_page_wakeup(tp);
1535 			break;
1536 		}
1537 		vm_page_test_dirty(tp);
1538 		if ((tp->dirty & tp->valid) == 0 &&
1539 		    (tp->flags & PG_NEED_COMMIT) == 0) {
1540 			vm_page_flag_clear(tp, PG_CLEANCHK);
1541 			vm_page_wakeup(tp);
1542 			break;
1543 		}
1544 		ma[ib] = tp;
1545 		--ib;
1546 	}
1547 	++ib;	/* fixup */
1548 
1549 	while (is < BLIST_MAX_ALLOC &&
1550 	       pi - page_base + is < object->size) {
1551 		vm_page_t tp;
1552 
1553 		tp = vm_page_lookup_busy_try(object, pi - page_base + is,
1554 					     TRUE, &error);
1555 		if (error)
1556 			break;
1557 		if (tp == NULL)
1558 			break;
1559 		if ((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
1560 		    (tp->flags & PG_CLEANCHK) == 0) {
1561 			vm_page_wakeup(tp);
1562 			break;
1563 		}
1564 		if ((tp->queue - tp->pc) == PQ_CACHE) {
1565 			vm_page_flag_clear(tp, PG_CLEANCHK);
1566 			vm_page_wakeup(tp);
1567 			break;
1568 		}
1569 		vm_page_test_dirty(tp);
1570 		if ((tp->dirty & tp->valid) == 0 &&
1571 		    (tp->flags & PG_NEED_COMMIT) == 0) {
1572 			vm_page_flag_clear(tp, PG_CLEANCHK);
1573 			vm_page_wakeup(tp);
1574 			break;
1575 		}
1576 		ma[is] = tp;
1577 		++is;
1578 	}
1579 
1580 	/*
1581 	 * All pages in the ma[] array are busied now
1582 	 */
1583 	for (i = ib; i < is; ++i) {
1584 		vm_page_flag_clear(ma[i], PG_CLEANCHK);
1585 		vm_page_hold(ma[i]);	/* XXX need this any more? */
1586 	}
1587 	vm_pageout_flush(&ma[ib], is - ib, pagerflags);
1588 	for (i = ib; i < is; ++i)	/* XXX need this any more? */
1589 		vm_page_unhold(ma[i]);
1590 }
1591 
1592 /*
1593  * Same as vm_object_pmap_copy, except range checking really
1594  * works, and is meant for small sections of an object.
1595  *
1596  * This code protects resident pages by making them read-only
1597  * and is typically called on a fork or split when a page
1598  * is converted to copy-on-write.
1599  *
1600  * NOTE: If the page is already at VM_PROT_NONE, calling
1601  * vm_page_protect will have no effect.
1602  */
1603 void
1604 vm_object_pmap_copy_1(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1605 {
1606 	vm_pindex_t idx;
1607 	vm_page_t p;
1608 
1609 	if (object == NULL || (object->flags & OBJ_WRITEABLE) == 0)
1610 		return;
1611 
1612 	vm_object_hold(object);
1613 	for (idx = start; idx < end; idx++) {
1614 		p = vm_page_lookup(object, idx);
1615 		if (p == NULL)
1616 			continue;
1617 		vm_page_protect(p, VM_PROT_READ);
1618 	}
1619 	vm_object_drop(object);
1620 }
1621 
1622 /*
1623  * Removes all physical pages in the specified object range from all
1624  * physical maps.
1625  *
1626  * The object must *not* be locked.
1627  */
1628 
1629 static int vm_object_pmap_remove_callback(vm_page_t p, void *data);
1630 
1631 void
1632 vm_object_pmap_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1633 {
1634 	struct rb_vm_page_scan_info info;
1635 
1636 	if (object == NULL)
1637 		return;
1638 	info.start_pindex = start;
1639 	info.end_pindex = end - 1;
1640 	info.count = 0;
1641 	info.object = object;
1642 
1643 	vm_object_hold(object);
1644 	vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
1645 				vm_object_pmap_remove_callback, &info);
1646 	if (start == 0 && end == object->size)
1647 		vm_object_clear_flag(object, OBJ_WRITEABLE);
1648 	vm_object_drop(object);
1649 }
1650 
1651 /*
1652  * The caller must hold the object
1653  */
1654 static int
1655 vm_object_pmap_remove_callback(vm_page_t p, void *data)
1656 {
1657 	struct rb_vm_page_scan_info *info = data;
1658 
1659 	if ((++info->count & 63) == 0)
1660 		lwkt_user_yield();
1661 
1662 	if (info->object != p->object ||
1663 	    p->pindex < info->start_pindex ||
1664 	    p->pindex > info->end_pindex) {
1665 		kprintf("vm_object_pmap_remove_callback: obj/pg race %p/%p\n",
1666 			info->object, p);
1667 		return(0);
1668 	}
1669 
1670 	vm_page_protect(p, VM_PROT_NONE);
1671 
1672 	return(0);
1673 }
1674 
1675 /*
1676  * Implements the madvise function at the object/page level.
1677  *
1678  * MADV_WILLNEED	(any object)
1679  *
1680  *	Activate the specified pages if they are resident.
1681  *
1682  * MADV_DONTNEED	(any object)
1683  *
1684  *	Deactivate the specified pages if they are resident.
1685  *
1686  * MADV_FREE	(OBJT_DEFAULT/OBJT_SWAP objects, OBJ_ONEMAPPING only)
1687  *
1688  *	Deactivate and clean the specified pages if they are
1689  *	resident.  This permits the process to reuse the pages
1690  *	without faulting or the kernel to reclaim the pages
1691  *	without I/O.
1692  *
1693  * No requirements.
1694  */
1695 void
1696 vm_object_madvise(vm_object_t object, vm_pindex_t pindex, int count, int advise)
1697 {
1698 	vm_pindex_t end, tpindex;
1699 	vm_object_t tobject;
1700 	vm_object_t xobj;
1701 	vm_page_t m;
1702 	int error;
1703 
1704 	if (object == NULL)
1705 		return;
1706 
1707 	end = pindex + count;
1708 
1709 	vm_object_hold(object);
1710 	tobject = object;
1711 
1712 	/*
1713 	 * Locate and adjust resident pages
1714 	 */
1715 	for (; pindex < end; pindex += 1) {
1716 relookup:
1717 		if (tobject != object)
1718 			vm_object_drop(tobject);
1719 		tobject = object;
1720 		tpindex = pindex;
1721 shadowlookup:
1722 		/*
1723 		 * MADV_FREE only operates on OBJT_DEFAULT or OBJT_SWAP pages
1724 		 * and those pages must be OBJ_ONEMAPPING.
1725 		 */
1726 		if (advise == MADV_FREE) {
1727 			if ((tobject->type != OBJT_DEFAULT &&
1728 			     tobject->type != OBJT_SWAP) ||
1729 			    (tobject->flags & OBJ_ONEMAPPING) == 0) {
1730 				continue;
1731 			}
1732 		}
1733 
1734 		m = vm_page_lookup_busy_try(tobject, tpindex, TRUE, &error);
1735 
1736 		if (error) {
1737 			vm_page_sleep_busy(m, TRUE, "madvpo");
1738 			goto relookup;
1739 		}
1740 		if (m == NULL) {
1741 			/*
1742 			 * There may be swap even if there is no backing page
1743 			 */
1744 			if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
1745 				swap_pager_freespace(tobject, tpindex, 1);
1746 
1747 			/*
1748 			 * next object
1749 			 */
1750 			while ((xobj = tobject->backing_object) != NULL) {
1751 				KKASSERT(xobj != object);
1752 				vm_object_hold(xobj);
1753 				if (xobj == tobject->backing_object)
1754 					break;
1755 				vm_object_drop(xobj);
1756 			}
1757 			if (xobj == NULL)
1758 				continue;
1759 			tpindex += OFF_TO_IDX(tobject->backing_object_offset);
1760 			if (tobject != object) {
1761 				vm_object_lock_swap();
1762 				vm_object_drop(tobject);
1763 			}
1764 			tobject = xobj;
1765 			goto shadowlookup;
1766 		}
1767 
1768 		/*
1769 		 * If the page is not in a normal active state, we skip it.
1770 		 * If the page is not managed there are no page queues to
1771 		 * mess with.  Things can break if we mess with pages in
1772 		 * any of the below states.
1773 		 */
1774 		if (m->wire_count ||
1775 		    (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
1776 		    m->valid != VM_PAGE_BITS_ALL
1777 		) {
1778 			vm_page_wakeup(m);
1779 			continue;
1780 		}
1781 
1782 		/*
1783 		 * Theoretically once a page is known not to be busy, an
1784 		 * interrupt cannot come along and rip it out from under us.
1785 		 */
1786 
1787 		if (advise == MADV_WILLNEED) {
1788 			vm_page_activate(m);
1789 		} else if (advise == MADV_DONTNEED) {
1790 			vm_page_dontneed(m);
1791 		} else if (advise == MADV_FREE) {
1792 			/*
1793 			 * Mark the page clean.  This will allow the page
1794 			 * to be freed up by the system.  However, such pages
1795 			 * are often reused quickly by malloc()/free()
1796 			 * so we do not do anything that would cause
1797 			 * a page fault if we can help it.
1798 			 *
1799 			 * Specifically, we do not try to actually free
1800 			 * the page now nor do we try to put it in the
1801 			 * cache (which would cause a page fault on reuse).
1802 			 *
1803 			 * But we do make the page is freeable as we
1804 			 * can without actually taking the step of unmapping
1805 			 * it.
1806 			 */
1807 			pmap_clear_modify(m);
1808 			m->dirty = 0;
1809 			m->act_count = 0;
1810 			vm_page_dontneed(m);
1811 			if (tobject->type == OBJT_SWAP)
1812 				swap_pager_freespace(tobject, tpindex, 1);
1813 		}
1814 		vm_page_wakeup(m);
1815 	}
1816 	if (tobject != object)
1817 		vm_object_drop(tobject);
1818 	vm_object_drop(object);
1819 }
1820 
1821 /*
1822  * Create a new object which is backed by the specified existing object
1823  * range.  Replace the pointer and offset that was pointing at the existing
1824  * object with the pointer/offset for the new object.
1825  *
1826  * If addref is non-zero the returned object is given an additional reference.
1827  * This mechanic exists to avoid the situation where refs might be 1 and
1828  * race against a collapse when the caller intends to bump it.  So the
1829  * caller cannot add the ref after the fact.  Used when the caller is
1830  * duplicating a vm_map_entry.
1831  *
1832  * No other requirements.
1833  */
1834 void
1835 vm_object_shadow(vm_object_t *objectp, vm_ooffset_t *offset, vm_size_t length,
1836 		 int addref)
1837 {
1838 	vm_object_t source;
1839 	vm_object_t result;
1840 	int useshadowlist;
1841 
1842 	source = *objectp;
1843 
1844 	/*
1845 	 * Don't create the new object if the old object isn't shared.
1846 	 * We have to chain wait before adding the reference to avoid
1847 	 * racing a collapse or deallocation.
1848 	 *
1849 	 * Clear OBJ_ONEMAPPING flag when shadowing.
1850 	 *
1851 	 * The caller owns a ref on source via *objectp which we are going
1852 	 * to replace.  This ref is inherited by the backing_object assignment.
1853 	 * from nobject and does not need to be incremented here.
1854 	 *
1855 	 * However, we add a temporary extra reference to the original source
1856 	 * prior to holding nobject in case we block, to avoid races where
1857 	 * someone else might believe that the source can be collapsed.
1858 	 */
1859 	useshadowlist = 0;
1860 	if (source) {
1861 		if (source->type != OBJT_VNODE) {
1862 			useshadowlist = 1;
1863 			vm_object_hold(source);
1864 			vm_object_chain_wait(source, 0);
1865 			if (source->ref_count == 1 &&
1866 			    source->handle == NULL &&
1867 			    (source->type == OBJT_DEFAULT ||
1868 			     source->type == OBJT_SWAP)) {
1869 				if (addref) {
1870 					vm_object_reference_locked(source);
1871 					vm_object_clear_flag(source,
1872 							     OBJ_ONEMAPPING);
1873 				}
1874 				vm_object_drop(source);
1875 				return;
1876 			}
1877 			vm_object_reference_locked(source);
1878 			vm_object_clear_flag(source, OBJ_ONEMAPPING);
1879 		} else {
1880 			vm_object_reference_quick(source);
1881 			vm_object_clear_flag(source, OBJ_ONEMAPPING);
1882 		}
1883 	}
1884 
1885 	/*
1886 	 * Allocate a new object with the given length.  The new object
1887 	 * is returned referenced but we may have to add another one.
1888 	 * If we are adding a second reference we must clear OBJ_ONEMAPPING.
1889 	 * (typically because the caller is about to clone a vm_map_entry).
1890 	 *
1891 	 * The source object currently has an extra reference to prevent
1892 	 * collapses into it while we mess with its shadow list, which
1893 	 * we will remove later in this routine.
1894 	 *
1895 	 * The target object may require a second reference if asked for one
1896 	 * by the caller.
1897 	 */
1898 	result = vm_object_allocate(OBJT_DEFAULT, length);
1899 	if (result == NULL)
1900 		panic("vm_object_shadow: no object for shadowing");
1901 	vm_object_hold(result);
1902 	if (addref) {
1903 		vm_object_reference_locked(result);
1904 		vm_object_clear_flag(result, OBJ_ONEMAPPING);
1905 	}
1906 
1907 	/*
1908 	 * The new object shadows the source object.  Chain wait before
1909 	 * adjusting shadow_count or the shadow list to avoid races.
1910 	 *
1911 	 * Try to optimize the result object's page color when shadowing
1912 	 * in order to maintain page coloring consistency in the combined
1913 	 * shadowed object.
1914 	 *
1915 	 * The backing_object reference to source requires adding a ref to
1916 	 * source.  We simply inherit the ref from the original *objectp
1917 	 * (which we are replacing) so no additional refs need to be added.
1918 	 * (we must still clean up the extra ref we had to prevent collapse
1919 	 * races).
1920 	 *
1921 	 * SHADOWING IS NOT APPLICABLE TO OBJT_VNODE OBJECTS
1922 	 */
1923 	KKASSERT(result->backing_object == NULL);
1924 	result->backing_object = source;
1925 	if (source) {
1926 		if (useshadowlist) {
1927 			vm_object_chain_wait(source, 0);
1928 			LIST_INSERT_HEAD(&source->shadow_head,
1929 					 result, shadow_list);
1930 			source->shadow_count++;
1931 			source->generation++;
1932 			vm_object_set_flag(result, OBJ_ONSHADOW);
1933 		}
1934 		/* cpu localization twist */
1935 		result->pg_color = vm_quickcolor();
1936 	}
1937 
1938 	/*
1939 	 * Adjust the return storage.  Drop the ref on source before
1940 	 * returning.
1941 	 */
1942 	result->backing_object_offset = *offset;
1943 	vm_object_drop(result);
1944 	*offset = 0;
1945 	if (source) {
1946 		if (useshadowlist) {
1947 			vm_object_deallocate_locked(source);
1948 			vm_object_drop(source);
1949 		} else {
1950 			vm_object_deallocate(source);
1951 		}
1952 	}
1953 
1954 	/*
1955 	 * Return the new things
1956 	 */
1957 	*objectp = result;
1958 }
1959 
1960 #define	OBSC_TEST_ALL_SHADOWED	0x0001
1961 #define	OBSC_COLLAPSE_NOWAIT	0x0002
1962 #define	OBSC_COLLAPSE_WAIT	0x0004
1963 
1964 static int vm_object_backing_scan_callback(vm_page_t p, void *data);
1965 
1966 /*
1967  * The caller must hold the object.
1968  */
1969 static __inline int
1970 vm_object_backing_scan(vm_object_t object, vm_object_t backing_object, int op)
1971 {
1972 	struct rb_vm_page_scan_info info;
1973 	struct vm_object_hash *hash;
1974 
1975 	vm_object_assert_held(object);
1976 	vm_object_assert_held(backing_object);
1977 
1978 	KKASSERT(backing_object == object->backing_object);
1979 	info.backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1980 
1981 	/*
1982 	 * Initial conditions
1983 	 */
1984 	if (op & OBSC_TEST_ALL_SHADOWED) {
1985 		/*
1986 		 * We do not want to have to test for the existence of
1987 		 * swap pages in the backing object.  XXX but with the
1988 		 * new swapper this would be pretty easy to do.
1989 		 *
1990 		 * XXX what about anonymous MAP_SHARED memory that hasn't
1991 		 * been ZFOD faulted yet?  If we do not test for this, the
1992 		 * shadow test may succeed! XXX
1993 		 */
1994 		if (backing_object->type != OBJT_DEFAULT)
1995 			return(0);
1996 	}
1997 	if (op & OBSC_COLLAPSE_WAIT) {
1998 		KKASSERT((backing_object->flags & OBJ_DEAD) == 0);
1999 		vm_object_set_flag(backing_object, OBJ_DEAD);
2000 
2001 		hash = VMOBJ_HASH(backing_object);
2002 		lwkt_gettoken(&hash->token);
2003 		TAILQ_REMOVE(&hash->list, backing_object, object_list);
2004 		lwkt_reltoken(&hash->token);
2005 	}
2006 
2007 	/*
2008 	 * Our scan.   We have to retry if a negative error code is returned,
2009 	 * otherwise 0 or 1 will be returned in info.error.  0 Indicates that
2010 	 * the scan had to be stopped because the parent does not completely
2011 	 * shadow the child.
2012 	 */
2013 	info.object = object;
2014 	info.backing_object = backing_object;
2015 	info.limit = op;
2016 	info.count = 0;
2017 	do {
2018 		info.error = 1;
2019 		vm_page_rb_tree_RB_SCAN(&backing_object->rb_memq, NULL,
2020 					vm_object_backing_scan_callback,
2021 					&info);
2022 	} while (info.error < 0);
2023 
2024 	return(info.error);
2025 }
2026 
2027 /*
2028  * The caller must hold the object.
2029  */
2030 static int
2031 vm_object_backing_scan_callback(vm_page_t p, void *data)
2032 {
2033 	struct rb_vm_page_scan_info *info = data;
2034 	vm_object_t backing_object;
2035 	vm_object_t object;
2036 	vm_pindex_t pindex;
2037 	vm_pindex_t new_pindex;
2038 	vm_pindex_t backing_offset_index;
2039 	int op;
2040 
2041 	pindex = p->pindex;
2042 	new_pindex = pindex - info->backing_offset_index;
2043 	op = info->limit;
2044 	object = info->object;
2045 	backing_object = info->backing_object;
2046 	backing_offset_index = info->backing_offset_index;
2047 
2048 	if (op & OBSC_TEST_ALL_SHADOWED) {
2049 		vm_page_t pp;
2050 
2051 		/*
2052 		 * Ignore pages outside the parent object's range
2053 		 * and outside the parent object's mapping of the
2054 		 * backing object.
2055 		 *
2056 		 * note that we do not busy the backing object's
2057 		 * page.
2058 		 */
2059 		if (pindex < backing_offset_index ||
2060 		    new_pindex >= object->size
2061 		) {
2062 			return(0);
2063 		}
2064 
2065 		/*
2066 		 * See if the parent has the page or if the parent's
2067 		 * object pager has the page.  If the parent has the
2068 		 * page but the page is not valid, the parent's
2069 		 * object pager must have the page.
2070 		 *
2071 		 * If this fails, the parent does not completely shadow
2072 		 * the object and we might as well give up now.
2073 		 */
2074 		pp = vm_page_lookup(object, new_pindex);
2075 		if ((pp == NULL || pp->valid == 0) &&
2076 		    !vm_pager_has_page(object, new_pindex)
2077 		) {
2078 			info->error = 0;	/* problemo */
2079 			return(-1);		/* stop the scan */
2080 		}
2081 	}
2082 
2083 	/*
2084 	 * Check for busy page.  Note that we may have lost (p) when we
2085 	 * possibly blocked above.
2086 	 */
2087 	if (op & (OBSC_COLLAPSE_WAIT | OBSC_COLLAPSE_NOWAIT)) {
2088 		vm_page_t pp;
2089 
2090 		if (vm_page_busy_try(p, TRUE)) {
2091 			if (op & OBSC_COLLAPSE_NOWAIT) {
2092 				return(0);
2093 			} else {
2094 				/*
2095 				 * If we slept, anything could have
2096 				 * happened.   Ask that the scan be restarted.
2097 				 *
2098 				 * Since the object is marked dead, the
2099 				 * backing offset should not have changed.
2100 				 */
2101 				vm_page_sleep_busy(p, TRUE, "vmocol");
2102 				info->error = -1;
2103 				return(-1);
2104 			}
2105 		}
2106 
2107 		/*
2108 		 * If (p) is no longer valid restart the scan.
2109 		 */
2110 		if (p->object != backing_object || p->pindex != pindex) {
2111 			kprintf("vm_object_backing_scan: Warning: page "
2112 				"%p ripped out from under us\n", p);
2113 			vm_page_wakeup(p);
2114 			info->error = -1;
2115 			return(-1);
2116 		}
2117 
2118 		if (op & OBSC_COLLAPSE_NOWAIT) {
2119 			if (p->valid == 0 ||
2120 			    p->wire_count ||
2121 			    (p->flags & PG_NEED_COMMIT)) {
2122 				vm_page_wakeup(p);
2123 				return(0);
2124 			}
2125 		} else {
2126 			/* XXX what if p->valid == 0 , hold_count, etc? */
2127 		}
2128 
2129 		KASSERT(
2130 		    p->object == backing_object,
2131 		    ("vm_object_qcollapse(): object mismatch")
2132 		);
2133 
2134 		/*
2135 		 * Destroy any associated swap
2136 		 */
2137 		if (backing_object->type == OBJT_SWAP)
2138 			swap_pager_freespace(backing_object, p->pindex, 1);
2139 
2140 		if (
2141 		    p->pindex < backing_offset_index ||
2142 		    new_pindex >= object->size
2143 		) {
2144 			/*
2145 			 * Page is out of the parent object's range, we
2146 			 * can simply destroy it.
2147 			 */
2148 			vm_page_protect(p, VM_PROT_NONE);
2149 			vm_page_free(p);
2150 			return(0);
2151 		}
2152 
2153 		pp = vm_page_lookup(object, new_pindex);
2154 		if (pp != NULL || vm_pager_has_page(object, new_pindex)) {
2155 			/*
2156 			 * page already exists in parent OR swap exists
2157 			 * for this location in the parent.  Destroy
2158 			 * the original page from the backing object.
2159 			 *
2160 			 * Leave the parent's page alone
2161 			 */
2162 			vm_page_protect(p, VM_PROT_NONE);
2163 			vm_page_free(p);
2164 			return(0);
2165 		}
2166 
2167 		/*
2168 		 * Page does not exist in parent, rename the
2169 		 * page from the backing object to the main object.
2170 		 *
2171 		 * If the page was mapped to a process, it can remain
2172 		 * mapped through the rename.
2173 		 */
2174 		if ((p->queue - p->pc) == PQ_CACHE)
2175 			vm_page_deactivate(p);
2176 
2177 		vm_page_rename(p, object, new_pindex);
2178 		vm_page_wakeup(p);
2179 		/* page automatically made dirty by rename */
2180 	}
2181 	return(0);
2182 }
2183 
2184 /*
2185  * This version of collapse allows the operation to occur earlier and
2186  * when paging_in_progress is true for an object...  This is not a complete
2187  * operation, but should plug 99.9% of the rest of the leaks.
2188  *
2189  * The caller must hold the object and backing_object and both must be
2190  * chainlocked.
2191  *
2192  * (only called from vm_object_collapse)
2193  */
2194 static void
2195 vm_object_qcollapse(vm_object_t object, vm_object_t backing_object)
2196 {
2197 	if (backing_object->ref_count == 1) {
2198 		atomic_add_int(&backing_object->ref_count, 2);
2199 #if defined(DEBUG_LOCKS)
2200 		debugvm_object_add(backing_object, "qcollapse", 1, 2);
2201 #endif
2202 		vm_object_backing_scan(object, backing_object,
2203 				       OBSC_COLLAPSE_NOWAIT);
2204 		atomic_add_int(&backing_object->ref_count, -2);
2205 #if defined(DEBUG_LOCKS)
2206 		debugvm_object_add(backing_object, "qcollapse", 2, -2);
2207 #endif
2208 	}
2209 }
2210 
2211 /*
2212  * Collapse an object with the object backing it.  Pages in the backing
2213  * object are moved into the parent, and the backing object is deallocated.
2214  * Any conflict is resolved in favor of the parent's existing pages.
2215  *
2216  * object must be held and chain-locked on call.
2217  *
2218  * The caller must have an extra ref on object to prevent a race from
2219  * destroying it during the collapse.
2220  */
2221 void
2222 vm_object_collapse(vm_object_t object, struct vm_object_dealloc_list **dlistp)
2223 {
2224 	struct vm_object_dealloc_list *dlist = NULL;
2225 	vm_object_t backing_object;
2226 
2227 	/*
2228 	 * Only one thread is attempting a collapse at any given moment.
2229 	 * There are few restrictions for (object) that callers of this
2230 	 * function check so reentrancy is likely.
2231 	 */
2232 	KKASSERT(object != NULL);
2233 	vm_object_assert_held(object);
2234 	KKASSERT(object->chainlk & (CHAINLK_MASK | CHAINLK_EXCL));
2235 
2236 	for (;;) {
2237 		vm_object_t bbobj;
2238 		int dodealloc;
2239 
2240 		/*
2241 		 * We can only collapse a DEFAULT/SWAP object with a
2242 		 * DEFAULT/SWAP object.
2243 		 */
2244 		if (object->type != OBJT_DEFAULT && object->type != OBJT_SWAP) {
2245 			backing_object = NULL;
2246 			break;
2247 		}
2248 
2249 		backing_object = object->backing_object;
2250 		if (backing_object == NULL)
2251 			break;
2252 		if (backing_object->type != OBJT_DEFAULT &&
2253 		    backing_object->type != OBJT_SWAP) {
2254 			backing_object = NULL;
2255 			break;
2256 		}
2257 
2258 		/*
2259 		 * Hold the backing_object and check for races
2260 		 */
2261 		vm_object_hold(backing_object);
2262 		if (backing_object != object->backing_object ||
2263 		    (backing_object->type != OBJT_DEFAULT &&
2264 		     backing_object->type != OBJT_SWAP)) {
2265 			vm_object_drop(backing_object);
2266 			continue;
2267 		}
2268 
2269 		/*
2270 		 * Chain-lock the backing object too because if we
2271 		 * successfully merge its pages into the top object we
2272 		 * will collapse backing_object->backing_object as the
2273 		 * new backing_object.  Re-check that it is still our
2274 		 * backing object.
2275 		 */
2276 		vm_object_chain_acquire(backing_object, 0);
2277 		if (backing_object != object->backing_object) {
2278 			vm_object_chain_release(backing_object);
2279 			vm_object_drop(backing_object);
2280 			continue;
2281 		}
2282 
2283 		/*
2284 		 * we check the backing object first, because it is most likely
2285 		 * not collapsable.
2286 		 */
2287 		if (backing_object->handle != NULL ||
2288 		    (backing_object->type != OBJT_DEFAULT &&
2289 		     backing_object->type != OBJT_SWAP) ||
2290 		    (backing_object->flags & OBJ_DEAD) ||
2291 		    object->handle != NULL ||
2292 		    (object->type != OBJT_DEFAULT &&
2293 		     object->type != OBJT_SWAP) ||
2294 		    (object->flags & OBJ_DEAD)) {
2295 			break;
2296 		}
2297 
2298 		/*
2299 		 * If paging is in progress we can't do a normal collapse.
2300 		 */
2301 		if (
2302 		    object->paging_in_progress != 0 ||
2303 		    backing_object->paging_in_progress != 0
2304 		) {
2305 			vm_object_qcollapse(object, backing_object);
2306 			break;
2307 		}
2308 
2309 		/*
2310 		 * We know that we can either collapse the backing object (if
2311 		 * the parent is the only reference to it) or (perhaps) have
2312 		 * the parent bypass the object if the parent happens to shadow
2313 		 * all the resident pages in the entire backing object.
2314 		 *
2315 		 * This is ignoring pager-backed pages such as swap pages.
2316 		 * vm_object_backing_scan fails the shadowing test in this
2317 		 * case.
2318 		 */
2319 		if (backing_object->ref_count == 1) {
2320 			/*
2321 			 * If there is exactly one reference to the backing
2322 			 * object, we can collapse it into the parent.
2323 			 */
2324 			KKASSERT(object->backing_object == backing_object);
2325 			vm_object_backing_scan(object, backing_object,
2326 					       OBSC_COLLAPSE_WAIT);
2327 
2328 			/*
2329 			 * Move the pager from backing_object to object.
2330 			 */
2331 			if (backing_object->type == OBJT_SWAP) {
2332 				vm_object_pip_add(backing_object, 1);
2333 
2334 				/*
2335 				 * scrap the paging_offset junk and do a
2336 				 * discrete copy.  This also removes major
2337 				 * assumptions about how the swap-pager
2338 				 * works from where it doesn't belong.  The
2339 				 * new swapper is able to optimize the
2340 				 * destroy-source case.
2341 				 */
2342 				vm_object_pip_add(object, 1);
2343 				swap_pager_copy(backing_object, object,
2344 				    OFF_TO_IDX(object->backing_object_offset),
2345 				    TRUE);
2346 				vm_object_pip_wakeup(object);
2347 				vm_object_pip_wakeup(backing_object);
2348 			}
2349 
2350 			/*
2351 			 * Object now shadows whatever backing_object did.
2352 			 * Remove object from backing_object's shadow_list.
2353 			 *
2354 			 * Removing object from backing_objects shadow list
2355 			 * requires releasing object, which we will do below.
2356 			 */
2357 			KKASSERT(object->backing_object == backing_object);
2358 			if (object->flags & OBJ_ONSHADOW) {
2359 				LIST_REMOVE(object, shadow_list);
2360 				backing_object->shadow_count--;
2361 				backing_object->generation++;
2362 				vm_object_clear_flag(object, OBJ_ONSHADOW);
2363 			}
2364 
2365 			/*
2366 			 * backing_object->backing_object moves from within
2367 			 * backing_object to within object.
2368 			 *
2369 			 * OBJT_VNODE bbobj's should have empty shadow lists.
2370 			 */
2371 			while ((bbobj = backing_object->backing_object) != NULL) {
2372 				if (bbobj->type == OBJT_VNODE)
2373 					vm_object_hold_shared(bbobj);
2374 				else
2375 					vm_object_hold(bbobj);
2376 				if (bbobj == backing_object->backing_object)
2377 					break;
2378 				vm_object_drop(bbobj);
2379 			}
2380 
2381 			/*
2382 			 * We are removing backing_object from bbobj's
2383 			 * shadow list and adding object to bbobj's shadow
2384 			 * list, so the ref_count on bbobj is unchanged.
2385 			 */
2386 			if (bbobj) {
2387 				if (backing_object->flags & OBJ_ONSHADOW) {
2388 					/* not locked exclusively if vnode */
2389 					KKASSERT(bbobj->type != OBJT_VNODE);
2390 					LIST_REMOVE(backing_object,
2391 						    shadow_list);
2392 					bbobj->shadow_count--;
2393 					bbobj->generation++;
2394 					vm_object_clear_flag(backing_object,
2395 							     OBJ_ONSHADOW);
2396 				}
2397 				backing_object->backing_object = NULL;
2398 			}
2399 			object->backing_object = bbobj;
2400 			if (bbobj) {
2401 				if (bbobj->type != OBJT_VNODE) {
2402 					LIST_INSERT_HEAD(&bbobj->shadow_head,
2403 							 object, shadow_list);
2404 					bbobj->shadow_count++;
2405 					bbobj->generation++;
2406 					vm_object_set_flag(object,
2407 							   OBJ_ONSHADOW);
2408 				}
2409 			}
2410 
2411 			object->backing_object_offset +=
2412 				backing_object->backing_object_offset;
2413 
2414 			vm_object_drop(bbobj);
2415 
2416 			/*
2417 			 * Discard the old backing_object.  Nothing should be
2418 			 * able to ref it, other than a vm_map_split(),
2419 			 * and vm_map_split() will stall on our chain lock.
2420 			 * And we control the parent so it shouldn't be
2421 			 * possible for it to go away either.
2422 			 *
2423 			 * Since the backing object has no pages, no pager
2424 			 * left, and no object references within it, all
2425 			 * that is necessary is to dispose of it.
2426 			 */
2427 			KASSERT(backing_object->ref_count == 1,
2428 				("backing_object %p was somehow "
2429 				 "re-referenced during collapse!",
2430 				 backing_object));
2431 			KASSERT(RB_EMPTY(&backing_object->rb_memq),
2432 				("backing_object %p somehow has left "
2433 				 "over pages during collapse!",
2434 				 backing_object));
2435 
2436 			/*
2437 			 * The object can be destroyed.
2438 			 *
2439 			 * XXX just fall through and dodealloc instead
2440 			 *     of forcing destruction?
2441 			 */
2442 			atomic_add_int(&backing_object->ref_count, -1);
2443 #if defined(DEBUG_LOCKS)
2444 			debugvm_object_add(backing_object, "collapse", 1, -1);
2445 #endif
2446 			if ((backing_object->flags & OBJ_DEAD) == 0)
2447 				vm_object_terminate(backing_object);
2448 			object_collapses++;
2449 			dodealloc = 0;
2450 		} else {
2451 			/*
2452 			 * If we do not entirely shadow the backing object,
2453 			 * there is nothing we can do so we give up.
2454 			 */
2455 			if (vm_object_backing_scan(object, backing_object,
2456 						OBSC_TEST_ALL_SHADOWED) == 0) {
2457 				break;
2458 			}
2459 
2460 			/*
2461 			 * bbobj is backing_object->backing_object.  Since
2462 			 * object completely shadows backing_object we can
2463 			 * bypass it and become backed by bbobj instead.
2464 			 *
2465 			 * The shadow list for vnode backing objects is not
2466 			 * used and a shared hold is allowed.
2467 			 */
2468 			while ((bbobj = backing_object->backing_object) != NULL) {
2469 				if (bbobj->type == OBJT_VNODE)
2470 					vm_object_hold_shared(bbobj);
2471 				else
2472 					vm_object_hold(bbobj);
2473 				if (bbobj == backing_object->backing_object)
2474 					break;
2475 				vm_object_drop(bbobj);
2476 			}
2477 
2478 			/*
2479 			 * Make object shadow bbobj instead of backing_object.
2480 			 * Remove object from backing_object's shadow list.
2481 			 *
2482 			 * Deallocating backing_object will not remove
2483 			 * it, since its reference count is at least 2.
2484 			 *
2485 			 * Removing object from backing_object's shadow
2486 			 * list requires releasing a ref, which we do
2487 			 * below by setting dodealloc to 1.
2488 			 */
2489 			KKASSERT(object->backing_object == backing_object);
2490 			if (object->flags & OBJ_ONSHADOW) {
2491 				LIST_REMOVE(object, shadow_list);
2492 				backing_object->shadow_count--;
2493 				backing_object->generation++;
2494 				vm_object_clear_flag(object, OBJ_ONSHADOW);
2495 			}
2496 
2497 			/*
2498 			 * Add a ref to bbobj, bbobj now shadows object.
2499 			 *
2500 			 * NOTE: backing_object->backing_object still points
2501 			 *	 to bbobj.  That relationship remains intact
2502 			 *	 because backing_object has > 1 ref, so
2503 			 *	 someone else is pointing to it (hence why
2504 			 *	 we can't collapse it into object and can
2505 			 *	 only handle the all-shadowed bypass case).
2506 			 */
2507 			if (bbobj) {
2508 				if (bbobj->type != OBJT_VNODE) {
2509 					vm_object_chain_wait(bbobj, 0);
2510 					vm_object_reference_locked(bbobj);
2511 					LIST_INSERT_HEAD(&bbobj->shadow_head,
2512 							 object, shadow_list);
2513 					bbobj->shadow_count++;
2514 					bbobj->generation++;
2515 					vm_object_set_flag(object,
2516 							   OBJ_ONSHADOW);
2517 				} else {
2518 					vm_object_reference_quick(bbobj);
2519 				}
2520 				object->backing_object_offset +=
2521 					backing_object->backing_object_offset;
2522 				object->backing_object = bbobj;
2523 				vm_object_drop(bbobj);
2524 			} else {
2525 				object->backing_object = NULL;
2526 			}
2527 
2528 			/*
2529 			 * Drop the reference count on backing_object.  To
2530 			 * handle ref_count races properly we can't assume
2531 			 * that the ref_count is still at least 2 so we
2532 			 * have to actually call vm_object_deallocate()
2533 			 * (after clearing the chainlock).
2534 			 */
2535 			object_bypasses++;
2536 			dodealloc = 1;
2537 		}
2538 
2539 		/*
2540 		 * Ok, we want to loop on the new object->bbobj association,
2541 		 * possibly collapsing it further.  However if dodealloc is
2542 		 * non-zero we have to deallocate the backing_object which
2543 		 * itself can potentially undergo a collapse, creating a
2544 		 * recursion depth issue with the LWKT token subsystem.
2545 		 *
2546 		 * In the case where we must deallocate the backing_object
2547 		 * it is possible now that the backing_object has a single
2548 		 * shadow count on some other object (not represented here
2549 		 * as yet), since it no longer shadows us.  Thus when we
2550 		 * call vm_object_deallocate() it may attempt to collapse
2551 		 * itself into its remaining parent.
2552 		 */
2553 		if (dodealloc) {
2554 			struct vm_object_dealloc_list *dtmp;
2555 
2556 			vm_object_chain_release(backing_object);
2557 			vm_object_unlock(backing_object);
2558 			/* backing_object remains held */
2559 
2560 			/*
2561 			 * Auto-deallocation list for caller convenience.
2562 			 */
2563 			if (dlistp == NULL)
2564 				dlistp = &dlist;
2565 
2566 			dtmp = kmalloc(sizeof(*dtmp), M_TEMP, M_WAITOK);
2567 			dtmp->object = backing_object;
2568 			dtmp->next = *dlistp;
2569 			*dlistp = dtmp;
2570 		} else {
2571 			vm_object_chain_release(backing_object);
2572 			vm_object_drop(backing_object);
2573 		}
2574 		/* backing_object = NULL; not needed */
2575 		/* loop */
2576 	}
2577 
2578 	/*
2579 	 * Clean up any left over backing_object
2580 	 */
2581 	if (backing_object) {
2582 		vm_object_chain_release(backing_object);
2583 		vm_object_drop(backing_object);
2584 	}
2585 
2586 	/*
2587 	 * Clean up any auto-deallocation list.  This is a convenience
2588 	 * for top-level callers so they don't have to pass &dlist.
2589 	 * Do not clean up any caller-passed dlistp, the caller will
2590 	 * do that.
2591 	 */
2592 	if (dlist)
2593 		vm_object_deallocate_list(&dlist);
2594 
2595 }
2596 
2597 /*
2598  * vm_object_collapse() may collect additional objects in need of
2599  * deallocation.  This routine deallocates these objects.  The
2600  * deallocation itself can trigger additional collapses (which the
2601  * deallocate function takes care of).  This procedure is used to
2602  * reduce procedural recursion since these vm_object shadow chains
2603  * can become quite long.
2604  */
2605 void
2606 vm_object_deallocate_list(struct vm_object_dealloc_list **dlistp)
2607 {
2608 	struct vm_object_dealloc_list *dlist;
2609 
2610 	while ((dlist = *dlistp) != NULL) {
2611 		*dlistp = dlist->next;
2612 		vm_object_lock(dlist->object);
2613 		vm_object_deallocate_locked(dlist->object);
2614 		vm_object_drop(dlist->object);
2615 		kfree(dlist, M_TEMP);
2616 	}
2617 }
2618 
2619 /*
2620  * Removes all physical pages in the specified object range from the
2621  * object's list of pages.
2622  *
2623  * No requirements.
2624  */
2625 static int vm_object_page_remove_callback(vm_page_t p, void *data);
2626 
2627 void
2628 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end,
2629 		      boolean_t clean_only)
2630 {
2631 	struct rb_vm_page_scan_info info;
2632 	int all;
2633 
2634 	/*
2635 	 * Degenerate cases and assertions
2636 	 */
2637 	vm_object_hold(object);
2638 	if (object == NULL ||
2639 	    (object->resident_page_count == 0 && object->swblock_count == 0)) {
2640 		vm_object_drop(object);
2641 		return;
2642 	}
2643 	KASSERT(object->type != OBJT_PHYS,
2644 		("attempt to remove pages from a physical object"));
2645 
2646 	/*
2647 	 * Indicate that paging is occuring on the object
2648 	 */
2649 	vm_object_pip_add(object, 1);
2650 
2651 	/*
2652 	 * Figure out the actual removal range and whether we are removing
2653 	 * the entire contents of the object or not.  If removing the entire
2654 	 * contents, be sure to get all pages, even those that might be
2655 	 * beyond the end of the object.
2656 	 */
2657 	info.object = object;
2658 	info.start_pindex = start;
2659 	if (end == 0)
2660 		info.end_pindex = (vm_pindex_t)-1;
2661 	else
2662 		info.end_pindex = end - 1;
2663 	info.limit = clean_only;
2664 	info.count = 0;
2665 	all = (start == 0 && info.end_pindex >= object->size - 1);
2666 
2667 	/*
2668 	 * Loop until we are sure we have gotten them all.
2669 	 */
2670 	do {
2671 		info.error = 0;
2672 		vm_page_rb_tree_RB_SCAN(&object->rb_memq, rb_vm_page_scancmp,
2673 					vm_object_page_remove_callback, &info);
2674 	} while (info.error);
2675 
2676 	/*
2677 	 * Remove any related swap if throwing away pages, or for
2678 	 * non-swap objects (the swap is a clean copy in that case).
2679 	 */
2680 	if (object->type != OBJT_SWAP || clean_only == FALSE) {
2681 		if (all)
2682 			swap_pager_freespace_all(object);
2683 		else
2684 			swap_pager_freespace(object, info.start_pindex,
2685 			     info.end_pindex - info.start_pindex + 1);
2686 	}
2687 
2688 	/*
2689 	 * Cleanup
2690 	 */
2691 	vm_object_pip_wakeup(object);
2692 	vm_object_drop(object);
2693 }
2694 
2695 /*
2696  * The caller must hold the object.
2697  *
2698  * NOTE: User yields are allowed when removing more than one page, but not
2699  *	 allowed if only removing one page (the path for single page removals
2700  *	 might hold a spinlock).
2701  */
2702 static int
2703 vm_object_page_remove_callback(vm_page_t p, void *data)
2704 {
2705 	struct rb_vm_page_scan_info *info = data;
2706 
2707 	if ((++info->count & 63) == 0)
2708 		lwkt_user_yield();
2709 
2710 	if (info->object != p->object ||
2711 	    p->pindex < info->start_pindex ||
2712 	    p->pindex > info->end_pindex) {
2713 		kprintf("vm_object_page_remove_callbackA: obj/pg race %p/%p\n",
2714 			info->object, p);
2715 		return(0);
2716 	}
2717 	if (vm_page_busy_try(p, TRUE)) {
2718 		vm_page_sleep_busy(p, TRUE, "vmopar");
2719 		info->error = 1;
2720 		return(0);
2721 	}
2722 	if (info->object != p->object) {
2723 		/* this should never happen */
2724 		kprintf("vm_object_page_remove_callbackB: obj/pg race %p/%p\n",
2725 			info->object, p);
2726 		vm_page_wakeup(p);
2727 		return(0);
2728 	}
2729 
2730 	/*
2731 	 * Wired pages cannot be destroyed, but they can be invalidated
2732 	 * and we do so if clean_only (limit) is not set.
2733 	 *
2734 	 * WARNING!  The page may be wired due to being part of a buffer
2735 	 *	     cache buffer, and the buffer might be marked B_CACHE.
2736 	 *	     This is fine as part of a truncation but VFSs must be
2737 	 *	     sure to fix the buffer up when re-extending the file.
2738 	 *
2739 	 * NOTE!     PG_NEED_COMMIT is ignored.
2740 	 */
2741 	if (p->wire_count != 0) {
2742 		vm_page_protect(p, VM_PROT_NONE);
2743 		if (info->limit == 0)
2744 			p->valid = 0;
2745 		vm_page_wakeup(p);
2746 		return(0);
2747 	}
2748 
2749 	/*
2750 	 * limit is our clean_only flag.  If set and the page is dirty or
2751 	 * requires a commit, do not free it.  If set and the page is being
2752 	 * held by someone, do not free it.
2753 	 */
2754 	if (info->limit && p->valid) {
2755 		vm_page_test_dirty(p);
2756 		if ((p->valid & p->dirty) || (p->flags & PG_NEED_COMMIT)) {
2757 			vm_page_wakeup(p);
2758 			return(0);
2759 		}
2760 	}
2761 
2762 	/*
2763 	 * Destroy the page
2764 	 */
2765 	vm_page_protect(p, VM_PROT_NONE);
2766 	vm_page_free(p);
2767 
2768 	return(0);
2769 }
2770 
2771 /*
2772  * Coalesces two objects backing up adjoining regions of memory into a
2773  * single object.
2774  *
2775  * returns TRUE if objects were combined.
2776  *
2777  * NOTE: Only works at the moment if the second object is NULL -
2778  *	 if it's not, which object do we lock first?
2779  *
2780  * Parameters:
2781  *	prev_object	First object to coalesce
2782  *	prev_offset	Offset into prev_object
2783  *	next_object	Second object into coalesce
2784  *	next_offset	Offset into next_object
2785  *
2786  *	prev_size	Size of reference to prev_object
2787  *	next_size	Size of reference to next_object
2788  *
2789  * The caller does not need to hold (prev_object) but must have a stable
2790  * pointer to it (typically by holding the vm_map locked).
2791  */
2792 boolean_t
2793 vm_object_coalesce(vm_object_t prev_object, vm_pindex_t prev_pindex,
2794 		   vm_size_t prev_size, vm_size_t next_size)
2795 {
2796 	vm_pindex_t next_pindex;
2797 
2798 	if (prev_object == NULL)
2799 		return (TRUE);
2800 
2801 	vm_object_hold(prev_object);
2802 
2803 	if (prev_object->type != OBJT_DEFAULT &&
2804 	    prev_object->type != OBJT_SWAP) {
2805 		vm_object_drop(prev_object);
2806 		return (FALSE);
2807 	}
2808 
2809 	/*
2810 	 * Try to collapse the object first
2811 	 */
2812 	vm_object_chain_acquire(prev_object, 0);
2813 	vm_object_collapse(prev_object, NULL);
2814 
2815 	/*
2816 	 * Can't coalesce if: . more than one reference . paged out . shadows
2817 	 * another object . has a copy elsewhere (any of which mean that the
2818 	 * pages not mapped to prev_entry may be in use anyway)
2819 	 */
2820 
2821 	if (prev_object->backing_object != NULL) {
2822 		vm_object_chain_release(prev_object);
2823 		vm_object_drop(prev_object);
2824 		return (FALSE);
2825 	}
2826 
2827 	prev_size >>= PAGE_SHIFT;
2828 	next_size >>= PAGE_SHIFT;
2829 	next_pindex = prev_pindex + prev_size;
2830 
2831 	if ((prev_object->ref_count > 1) &&
2832 	    (prev_object->size != next_pindex)) {
2833 		vm_object_chain_release(prev_object);
2834 		vm_object_drop(prev_object);
2835 		return (FALSE);
2836 	}
2837 
2838 	/*
2839 	 * Remove any pages that may still be in the object from a previous
2840 	 * deallocation.
2841 	 */
2842 	if (next_pindex < prev_object->size) {
2843 		vm_object_page_remove(prev_object,
2844 				      next_pindex,
2845 				      next_pindex + next_size, FALSE);
2846 		if (prev_object->type == OBJT_SWAP)
2847 			swap_pager_freespace(prev_object,
2848 					     next_pindex, next_size);
2849 	}
2850 
2851 	/*
2852 	 * Extend the object if necessary.
2853 	 */
2854 	if (next_pindex + next_size > prev_object->size)
2855 		prev_object->size = next_pindex + next_size;
2856 
2857 	vm_object_chain_release(prev_object);
2858 	vm_object_drop(prev_object);
2859 	return (TRUE);
2860 }
2861 
2862 /*
2863  * Make the object writable and flag is being possibly dirty.
2864  *
2865  * The object might not be held (or might be held but held shared),
2866  * the related vnode is probably not held either.  Object and vnode are
2867  * stable by virtue of the vm_page busied by the caller preventing
2868  * destruction.
2869  *
2870  * If the related mount is flagged MNTK_THR_SYNC we need to call
2871  * vsetobjdirty().  Filesystems using this option usually shortcut
2872  * synchronization by only scanning the syncer list.
2873  */
2874 void
2875 vm_object_set_writeable_dirty(vm_object_t object)
2876 {
2877 	struct vnode *vp;
2878 
2879 	/*vm_object_assert_held(object);*/
2880 	/*
2881 	 * Avoid contention in vm fault path by checking the state before
2882 	 * issuing an atomic op on it.
2883 	 */
2884 	if ((object->flags & (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) !=
2885 	    (OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY)) {
2886 		vm_object_set_flag(object, OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
2887 	}
2888 	if (object->type == OBJT_VNODE &&
2889 	    (vp = (struct vnode *)object->handle) != NULL) {
2890 		if ((vp->v_flag & VOBJDIRTY) == 0) {
2891 			if (vp->v_mount &&
2892 			    (vp->v_mount->mnt_kern_flag & MNTK_THR_SYNC)) {
2893 				/*
2894 				 * New style THR_SYNC places vnodes on the
2895 				 * syncer list more deterministically.
2896 				 */
2897 				vsetobjdirty(vp);
2898 			} else {
2899 				/*
2900 				 * Old style scan would not necessarily place
2901 				 * a vnode on the syncer list when possibly
2902 				 * modified via mmap.
2903 				 */
2904 				vsetflags(vp, VOBJDIRTY);
2905 			}
2906 		}
2907 	}
2908 }
2909 
2910 #include "opt_ddb.h"
2911 #ifdef DDB
2912 #include <sys/kernel.h>
2913 
2914 #include <sys/cons.h>
2915 
2916 #include <ddb/ddb.h>
2917 
2918 static int	_vm_object_in_map (vm_map_t map, vm_object_t object,
2919 				       vm_map_entry_t entry);
2920 static int	vm_object_in_map (vm_object_t object);
2921 
2922 /*
2923  * The caller must hold the object.
2924  */
2925 static int
2926 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
2927 {
2928 	vm_map_t tmpm;
2929 	vm_map_entry_t tmpe;
2930 	vm_object_t obj, nobj;
2931 	int entcount;
2932 
2933 	if (map == 0)
2934 		return 0;
2935 	if (entry == 0) {
2936 		tmpe = map->header.next;
2937 		entcount = map->nentries;
2938 		while (entcount-- && (tmpe != &map->header)) {
2939 			if( _vm_object_in_map(map, object, tmpe)) {
2940 				return 1;
2941 			}
2942 			tmpe = tmpe->next;
2943 		}
2944 		return (0);
2945 	}
2946 	switch(entry->maptype) {
2947 	case VM_MAPTYPE_SUBMAP:
2948 		tmpm = entry->object.sub_map;
2949 		tmpe = tmpm->header.next;
2950 		entcount = tmpm->nentries;
2951 		while (entcount-- && tmpe != &tmpm->header) {
2952 			if( _vm_object_in_map(tmpm, object, tmpe)) {
2953 				return 1;
2954 			}
2955 			tmpe = tmpe->next;
2956 		}
2957 		break;
2958 	case VM_MAPTYPE_NORMAL:
2959 	case VM_MAPTYPE_VPAGETABLE:
2960 		obj = entry->object.vm_object;
2961 		while (obj) {
2962 			if (obj == object) {
2963 				if (obj != entry->object.vm_object)
2964 					vm_object_drop(obj);
2965 				return 1;
2966 			}
2967 			while ((nobj = obj->backing_object) != NULL) {
2968 				vm_object_hold(nobj);
2969 				if (nobj == obj->backing_object)
2970 					break;
2971 				vm_object_drop(nobj);
2972 			}
2973 			if (obj != entry->object.vm_object) {
2974 				if (nobj)
2975 					vm_object_lock_swap();
2976 				vm_object_drop(obj);
2977 			}
2978 			obj = nobj;
2979 		}
2980 		break;
2981 	default:
2982 		break;
2983 	}
2984 	return 0;
2985 }
2986 
2987 static int vm_object_in_map_callback(struct proc *p, void *data);
2988 
2989 struct vm_object_in_map_info {
2990 	vm_object_t object;
2991 	int rv;
2992 };
2993 
2994 /*
2995  * Debugging only
2996  */
2997 static int
2998 vm_object_in_map(vm_object_t object)
2999 {
3000 	struct vm_object_in_map_info info;
3001 
3002 	info.rv = 0;
3003 	info.object = object;
3004 
3005 	allproc_scan(vm_object_in_map_callback, &info);
3006 	if (info.rv)
3007 		return 1;
3008 	if( _vm_object_in_map(&kernel_map, object, 0))
3009 		return 1;
3010 	if( _vm_object_in_map(&pager_map, object, 0))
3011 		return 1;
3012 	if( _vm_object_in_map(&buffer_map, object, 0))
3013 		return 1;
3014 	return 0;
3015 }
3016 
3017 /*
3018  * Debugging only
3019  */
3020 static int
3021 vm_object_in_map_callback(struct proc *p, void *data)
3022 {
3023 	struct vm_object_in_map_info *info = data;
3024 
3025 	if (p->p_vmspace) {
3026 		if (_vm_object_in_map(&p->p_vmspace->vm_map, info->object, 0)) {
3027 			info->rv = 1;
3028 			return -1;
3029 		}
3030 	}
3031 	return (0);
3032 }
3033 
3034 DB_SHOW_COMMAND(vmochk, vm_object_check)
3035 {
3036 	struct vm_object_hash *hash;
3037 	vm_object_t object;
3038 	int n;
3039 
3040 	/*
3041 	 * make sure that internal objs are in a map somewhere
3042 	 * and none have zero ref counts.
3043 	 */
3044 	for (n = 0; n < VMOBJ_HSIZE; ++n) {
3045 		hash = &vm_object_hash[n];
3046 		for (object = TAILQ_FIRST(&hash->list);
3047 				object != NULL;
3048 				object = TAILQ_NEXT(object, object_list)) {
3049 			if (object->type == OBJT_MARKER)
3050 				continue;
3051 			if (object->handle != NULL ||
3052 			    (object->type != OBJT_DEFAULT &&
3053 			     object->type != OBJT_SWAP)) {
3054 				continue;
3055 			}
3056 			if (object->ref_count == 0) {
3057 				db_printf("vmochk: internal obj has "
3058 					  "zero ref count: %ld\n",
3059 					  (long)object->size);
3060 			}
3061 			if (vm_object_in_map(object))
3062 				continue;
3063 			db_printf("vmochk: internal obj is not in a map: "
3064 				  "ref: %d, size: %lu: 0x%lx, "
3065 				  "backing_object: %p\n",
3066 				  object->ref_count, (u_long)object->size,
3067 				  (u_long)object->size,
3068 				  (void *)object->backing_object);
3069 		}
3070 	}
3071 }
3072 
3073 /*
3074  * Debugging only
3075  */
3076 DB_SHOW_COMMAND(object, vm_object_print_static)
3077 {
3078 	/* XXX convert args. */
3079 	vm_object_t object = (vm_object_t)addr;
3080 	boolean_t full = have_addr;
3081 
3082 	vm_page_t p;
3083 
3084 	/* XXX count is an (unused) arg.  Avoid shadowing it. */
3085 #define	count	was_count
3086 
3087 	int count;
3088 
3089 	if (object == NULL)
3090 		return;
3091 
3092 	db_iprintf(
3093 	    "Object %p: type=%d, size=0x%lx, res=%ld, ref=%d, flags=0x%x\n",
3094 	    object, (int)object->type, (u_long)object->size,
3095 	    object->resident_page_count, object->ref_count, object->flags);
3096 	/*
3097 	 * XXX no %qd in kernel.  Truncate object->backing_object_offset.
3098 	 */
3099 	db_iprintf(" sref=%d, backing_object(%d)=(%p)+0x%lx\n",
3100 	    object->shadow_count,
3101 	    object->backing_object ? object->backing_object->ref_count : 0,
3102 	    object->backing_object, (long)object->backing_object_offset);
3103 
3104 	if (!full)
3105 		return;
3106 
3107 	db_indent += 2;
3108 	count = 0;
3109 	RB_FOREACH(p, vm_page_rb_tree, &object->rb_memq) {
3110 		if (count == 0)
3111 			db_iprintf("memory:=");
3112 		else if (count == 6) {
3113 			db_printf("\n");
3114 			db_iprintf(" ...");
3115 			count = 0;
3116 		} else
3117 			db_printf(",");
3118 		count++;
3119 
3120 		db_printf("(off=0x%lx,page=0x%lx)",
3121 		    (u_long) p->pindex, (u_long) VM_PAGE_TO_PHYS(p));
3122 	}
3123 	if (count != 0)
3124 		db_printf("\n");
3125 	db_indent -= 2;
3126 }
3127 
3128 /* XXX. */
3129 #undef count
3130 
3131 /*
3132  * XXX need this non-static entry for calling from vm_map_print.
3133  *
3134  * Debugging only
3135  */
3136 void
3137 vm_object_print(/* db_expr_t */ long addr,
3138 		boolean_t have_addr,
3139 		/* db_expr_t */ long count,
3140 		char *modif)
3141 {
3142 	vm_object_print_static(addr, have_addr, count, modif);
3143 }
3144 
3145 /*
3146  * Debugging only
3147  */
3148 DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
3149 {
3150 	struct vm_object_hash *hash;
3151 	vm_object_t object;
3152 	int nl = 0;
3153 	int c;
3154 	int n;
3155 
3156 	for (n = 0; n < VMOBJ_HSIZE; ++n) {
3157 		hash = &vm_object_hash[n];
3158 		for (object = TAILQ_FIRST(&hash->list);
3159 				object != NULL;
3160 				object = TAILQ_NEXT(object, object_list)) {
3161 			vm_pindex_t idx, fidx;
3162 			vm_pindex_t osize;
3163 			vm_paddr_t pa = -1, padiff;
3164 			int rcount;
3165 			vm_page_t m;
3166 
3167 			if (object->type == OBJT_MARKER)
3168 				continue;
3169 			db_printf("new object: %p\n", (void *)object);
3170 			if ( nl > 18) {
3171 				c = cngetc();
3172 				if (c != ' ')
3173 					return;
3174 				nl = 0;
3175 			}
3176 			nl++;
3177 			rcount = 0;
3178 			fidx = 0;
3179 			osize = object->size;
3180 			if (osize > 128)
3181 				osize = 128;
3182 			for (idx = 0; idx < osize; idx++) {
3183 				m = vm_page_lookup(object, idx);
3184 				if (m == NULL) {
3185 					if (rcount) {
3186 						db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
3187 							(long)fidx, rcount, (long)pa);
3188 						if ( nl > 18) {
3189 							c = cngetc();
3190 							if (c != ' ')
3191 								return;
3192 							nl = 0;
3193 						}
3194 						nl++;
3195 						rcount = 0;
3196 					}
3197 					continue;
3198 				}
3199 
3200 				if (rcount &&
3201 					(VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
3202 					++rcount;
3203 					continue;
3204 				}
3205 				if (rcount) {
3206 					padiff = pa + rcount * PAGE_SIZE - VM_PAGE_TO_PHYS(m);
3207 					padiff >>= PAGE_SHIFT;
3208 					padiff &= PQ_L2_MASK;
3209 					if (padiff == 0) {
3210 						pa = VM_PAGE_TO_PHYS(m) - rcount * PAGE_SIZE;
3211 						++rcount;
3212 						continue;
3213 					}
3214 					db_printf(" index(%ld)run(%d)pa(0x%lx)",
3215 						(long)fidx, rcount, (long)pa);
3216 					db_printf("pd(%ld)\n", (long)padiff);
3217 					if ( nl > 18) {
3218 						c = cngetc();
3219 						if (c != ' ')
3220 							return;
3221 						nl = 0;
3222 					}
3223 					nl++;
3224 				}
3225 				fidx = idx;
3226 				pa = VM_PAGE_TO_PHYS(m);
3227 				rcount = 1;
3228 			}
3229 			if (rcount) {
3230 				db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
3231 					(long)fidx, rcount, (long)pa);
3232 				if ( nl > 18) {
3233 					c = cngetc();
3234 					if (c != ' ')
3235 						return;
3236 					nl = 0;
3237 				}
3238 				nl++;
3239 			}
3240 		}
3241 	}
3242 }
3243 #endif /* DDB */
3244