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