xref: /freebsd/sys/vm/vm_object.c (revision 729362425c09cf6b362366aabc6fb547eee8035a)
1 /*
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * The Mach Operating System project at Carnegie-Mellon University.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	from: @(#)vm_object.c	8.5 (Berkeley) 3/22/94
37  *
38  *
39  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
40  * All rights reserved.
41  *
42  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
43  *
44  * Permission to use, copy, modify and distribute this software and
45  * its documentation is hereby granted, provided that both the copyright
46  * notice and this permission notice appear in all copies of the
47  * software, derivative works or modified versions, and any portions
48  * thereof, and that both notices appear in supporting documentation.
49  *
50  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
51  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
52  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
53  *
54  * Carnegie Mellon requests users of this software to return to
55  *
56  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
57  *  School of Computer Science
58  *  Carnegie Mellon University
59  *  Pittsburgh PA 15213-3890
60  *
61  * any improvements or extensions that they make and grant Carnegie the
62  * rights to redistribute these changes.
63  *
64  * $FreeBSD$
65  */
66 
67 /*
68  *	Virtual memory object module.
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/lock.h>
74 #include <sys/mman.h>
75 #include <sys/mount.h>
76 #include <sys/kernel.h>
77 #include <sys/sysctl.h>
78 #include <sys/mutex.h>
79 #include <sys/proc.h>		/* for curproc, pageproc */
80 #include <sys/socket.h>
81 #include <sys/vnode.h>
82 #include <sys/vmmeter.h>
83 #include <sys/sx.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_param.h>
87 #include <vm/pmap.h>
88 #include <vm/vm_map.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_pageout.h>
92 #include <vm/vm_pager.h>
93 #include <vm/swap_pager.h>
94 #include <vm/vm_kern.h>
95 #include <vm/vm_extern.h>
96 #include <vm/uma.h>
97 
98 #define EASY_SCAN_FACTOR       8
99 
100 #define MSYNC_FLUSH_HARDSEQ	0x01
101 #define MSYNC_FLUSH_SOFTSEQ	0x02
102 
103 /*
104  * msync / VM object flushing optimizations
105  */
106 static int msync_flush_flags = MSYNC_FLUSH_HARDSEQ | MSYNC_FLUSH_SOFTSEQ;
107 SYSCTL_INT(_vm, OID_AUTO, msync_flush_flags,
108         CTLFLAG_RW, &msync_flush_flags, 0, "");
109 
110 static void	vm_object_qcollapse(vm_object_t object);
111 static int	vm_object_page_collect_flush(vm_object_t object, vm_page_t p, int curgeneration, int pagerflags);
112 
113 /*
114  *	Virtual memory objects maintain the actual data
115  *	associated with allocated virtual memory.  A given
116  *	page of memory exists within exactly one object.
117  *
118  *	An object is only deallocated when all "references"
119  *	are given up.  Only one "reference" to a given
120  *	region of an object should be writeable.
121  *
122  *	Associated with each object is a list of all resident
123  *	memory pages belonging to that object; this list is
124  *	maintained by the "vm_page" module, and locked by the object's
125  *	lock.
126  *
127  *	Each object also records a "pager" routine which is
128  *	used to retrieve (and store) pages to the proper backing
129  *	storage.  In addition, objects may be backed by other
130  *	objects from which they were virtual-copied.
131  *
132  *	The only items within the object structure which are
133  *	modified after time of creation are:
134  *		reference count		locked by object's lock
135  *		pager routine		locked by object's lock
136  *
137  */
138 
139 struct object_q vm_object_list;
140 struct mtx vm_object_list_mtx;	/* lock for object list and count */
141 vm_object_t kernel_object;
142 vm_object_t kmem_object;
143 static struct vm_object kernel_object_store;
144 static struct vm_object kmem_object_store;
145 extern int vm_pageout_page_count;
146 
147 static long object_collapses;
148 static long object_bypasses;
149 static int next_index;
150 static uma_zone_t obj_zone;
151 #define VM_OBJECTS_INIT 256
152 
153 static void vm_object_zinit(void *mem, int size);
154 
155 #ifdef INVARIANTS
156 static void vm_object_zdtor(void *mem, int size, void *arg);
157 
158 static void
159 vm_object_zdtor(void *mem, int size, void *arg)
160 {
161 	vm_object_t object;
162 
163 	object = (vm_object_t)mem;
164 	KASSERT(object->paging_in_progress == 0,
165 	    ("object %p paging_in_progress = %d",
166 	    object, object->paging_in_progress));
167 	KASSERT(object->resident_page_count == 0,
168 	    ("object %p resident_page_count = %d",
169 	    object, object->resident_page_count));
170 	KASSERT(object->shadow_count == 0,
171 	    ("object %p shadow_count = %d",
172 	    object, object->shadow_count));
173 }
174 #endif
175 
176 static void
177 vm_object_zinit(void *mem, int size)
178 {
179 	vm_object_t object;
180 
181 	object = (vm_object_t)mem;
182 	bzero(&object->mtx, sizeof(object->mtx));
183 
184 	/* These are true for any object that has been freed */
185 	object->paging_in_progress = 0;
186 	object->resident_page_count = 0;
187 	object->shadow_count = 0;
188 }
189 
190 void
191 _vm_object_allocate(objtype_t type, vm_pindex_t size, vm_object_t object)
192 {
193 	int incr;
194 
195 	mtx_init(&object->mtx, "vm object", NULL, MTX_DEF);
196 
197 	TAILQ_INIT(&object->memq);
198 	TAILQ_INIT(&object->shadow_head);
199 
200 	object->root = NULL;
201 	object->type = type;
202 	object->size = size;
203 	object->ref_count = 1;
204 	object->flags = 0;
205 	if ((object->type == OBJT_DEFAULT) || (object->type == OBJT_SWAP))
206 		vm_object_set_flag(object, OBJ_ONEMAPPING);
207 	if (size > (PQ_L2_SIZE / 3 + PQ_PRIME1))
208 		incr = PQ_L2_SIZE / 3 + PQ_PRIME1;
209 	else
210 		incr = size;
211 	do
212 		object->pg_color = next_index;
213 	while (!atomic_cmpset_int(&next_index, object->pg_color,
214 				  (object->pg_color + incr) & PQ_L2_MASK));
215 	object->handle = NULL;
216 	object->backing_object = NULL;
217 	object->backing_object_offset = (vm_ooffset_t) 0;
218 
219 	atomic_add_int(&object->generation, 1);
220 
221 	mtx_lock(&vm_object_list_mtx);
222 	TAILQ_INSERT_TAIL(&vm_object_list, object, object_list);
223 	mtx_unlock(&vm_object_list_mtx);
224 }
225 
226 /*
227  *	vm_object_init:
228  *
229  *	Initialize the VM objects module.
230  */
231 void
232 vm_object_init(void)
233 {
234 	TAILQ_INIT(&vm_object_list);
235 	mtx_init(&vm_object_list_mtx, "vm object_list", NULL, MTX_DEF);
236 
237 	kernel_object = &kernel_object_store;
238 	_vm_object_allocate(OBJT_DEFAULT, OFF_TO_IDX(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS),
239 	    kernel_object);
240 
241 	kmem_object = &kmem_object_store;
242 	_vm_object_allocate(OBJT_DEFAULT, OFF_TO_IDX(VM_MAX_KERNEL_ADDRESS - VM_MIN_KERNEL_ADDRESS),
243 	    kmem_object);
244 	obj_zone = uma_zcreate("VM OBJECT", sizeof (struct vm_object), NULL,
245 #ifdef INVARIANTS
246 	    vm_object_zdtor,
247 #else
248 	    NULL,
249 #endif
250 	    vm_object_zinit, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
251 	uma_prealloc(obj_zone, VM_OBJECTS_INIT);
252 }
253 
254 void
255 vm_object_set_flag(vm_object_t object, u_short bits)
256 {
257 	object->flags |= bits;
258 }
259 
260 void
261 vm_object_clear_flag(vm_object_t object, u_short bits)
262 {
263 
264 	mtx_assert(object == kmem_object ? &object->mtx : &Giant, MA_OWNED);
265 	object->flags &= ~bits;
266 }
267 
268 void
269 vm_object_pip_add(vm_object_t object, short i)
270 {
271 	GIANT_REQUIRED;
272 	object->paging_in_progress += i;
273 }
274 
275 void
276 vm_object_pip_subtract(vm_object_t object, short i)
277 {
278 	GIANT_REQUIRED;
279 	object->paging_in_progress -= i;
280 }
281 
282 void
283 vm_object_pip_wakeup(vm_object_t object)
284 {
285 	GIANT_REQUIRED;
286 	object->paging_in_progress--;
287 	if ((object->flags & OBJ_PIPWNT) && object->paging_in_progress == 0) {
288 		vm_object_clear_flag(object, OBJ_PIPWNT);
289 		wakeup(object);
290 	}
291 }
292 
293 void
294 vm_object_pip_wakeupn(vm_object_t object, short i)
295 {
296 	GIANT_REQUIRED;
297 	if (i)
298 		object->paging_in_progress -= i;
299 	if ((object->flags & OBJ_PIPWNT) && object->paging_in_progress == 0) {
300 		vm_object_clear_flag(object, OBJ_PIPWNT);
301 		wakeup(object);
302 	}
303 }
304 
305 void
306 vm_object_pip_sleep(vm_object_t object, char *waitid)
307 {
308 	GIANT_REQUIRED;
309 	if (object->paging_in_progress) {
310 		int s = splvm();
311 		if (object->paging_in_progress) {
312 			vm_object_set_flag(object, OBJ_PIPWNT);
313 			tsleep(object, PVM, waitid, 0);
314 		}
315 		splx(s);
316 	}
317 }
318 
319 void
320 vm_object_pip_wait(vm_object_t object, char *waitid)
321 {
322 	GIANT_REQUIRED;
323 	while (object->paging_in_progress)
324 		vm_object_pip_sleep(object, waitid);
325 }
326 
327 /*
328  *	vm_object_allocate_wait
329  *
330  *	Return a new object with the given size, and give the user the
331  *	option of waiting for it to complete or failing if the needed
332  *	memory isn't available.
333  */
334 vm_object_t
335 vm_object_allocate_wait(objtype_t type, vm_pindex_t size, int flags)
336 {
337 	vm_object_t result;
338 
339 	result = (vm_object_t) uma_zalloc(obj_zone, flags);
340 
341 	if (result != NULL)
342 		_vm_object_allocate(type, size, result);
343 
344 	return (result);
345 }
346 
347 /*
348  *	vm_object_allocate:
349  *
350  *	Returns a new object with the given size.
351  */
352 vm_object_t
353 vm_object_allocate(objtype_t type, vm_pindex_t size)
354 {
355 	return(vm_object_allocate_wait(type, size, M_WAITOK));
356 }
357 
358 
359 /*
360  *	vm_object_reference:
361  *
362  *	Gets another reference to the given object.
363  */
364 void
365 vm_object_reference(vm_object_t object)
366 {
367 	if (object == NULL)
368 		return;
369 
370 	vm_object_lock(object);
371 #if 0
372 	/* object can be re-referenced during final cleaning */
373 	KASSERT(!(object->flags & OBJ_DEAD),
374 	    ("vm_object_reference: attempting to reference dead obj"));
375 #endif
376 
377 	object->ref_count++;
378 	if (object->type == OBJT_VNODE) {
379 		while (vget((struct vnode *) object->handle, LK_RETRY, curthread)) {
380 			printf("vm_object_reference: delay in getting object\n");
381 		}
382 	}
383 	vm_object_unlock(object);
384 }
385 
386 /*
387  * Handle deallocating an object of type OBJT_VNODE.
388  */
389 void
390 vm_object_vndeallocate(vm_object_t object)
391 {
392 	struct vnode *vp = (struct vnode *) object->handle;
393 
394 	GIANT_REQUIRED;
395 	KASSERT(object->type == OBJT_VNODE,
396 	    ("vm_object_vndeallocate: not a vnode object"));
397 	KASSERT(vp != NULL, ("vm_object_vndeallocate: missing vp"));
398 #ifdef INVARIANTS
399 	if (object->ref_count == 0) {
400 		vprint("vm_object_vndeallocate", vp);
401 		panic("vm_object_vndeallocate: bad object reference count");
402 	}
403 #endif
404 
405 	object->ref_count--;
406 	if (object->ref_count == 0) {
407 		mp_fixme("Unlocked vflag access.");
408 		vp->v_vflag &= ~VV_TEXT;
409 	}
410 	/*
411 	 * vrele may need a vop lock
412 	 */
413 	vrele(vp);
414 }
415 
416 /*
417  *	vm_object_deallocate:
418  *
419  *	Release a reference to the specified object,
420  *	gained either through a vm_object_allocate
421  *	or a vm_object_reference call.  When all references
422  *	are gone, storage associated with this object
423  *	may be relinquished.
424  *
425  *	No object may be locked.
426  */
427 void
428 vm_object_deallocate(vm_object_t object)
429 {
430 	vm_object_t temp;
431 
432 	vm_object_lock(object);
433 	while (object != NULL) {
434 
435 		if (object->type == OBJT_VNODE) {
436 			vm_object_vndeallocate(object);
437 			vm_object_unlock(object);
438 			return;
439 		}
440 
441 		KASSERT(object->ref_count != 0,
442 			("vm_object_deallocate: object deallocated too many times: %d", object->type));
443 
444 		/*
445 		 * If the reference count goes to 0 we start calling
446 		 * vm_object_terminate() on the object chain.
447 		 * A ref count of 1 may be a special case depending on the
448 		 * shadow count being 0 or 1.
449 		 */
450 		object->ref_count--;
451 		if (object->ref_count > 1) {
452 			vm_object_unlock(object);
453 			return;
454 		} else if (object->ref_count == 1) {
455 			if (object->shadow_count == 0) {
456 				vm_object_set_flag(object, OBJ_ONEMAPPING);
457 			} else if ((object->shadow_count == 1) &&
458 			    (object->handle == NULL) &&
459 			    (object->type == OBJT_DEFAULT ||
460 			     object->type == OBJT_SWAP)) {
461 				vm_object_t robject;
462 
463 				robject = TAILQ_FIRST(&object->shadow_head);
464 				KASSERT(robject != NULL,
465 				    ("vm_object_deallocate: ref_count: %d, shadow_count: %d",
466 					 object->ref_count,
467 					 object->shadow_count));
468 				if ((robject->handle == NULL) &&
469 				    (robject->type == OBJT_DEFAULT ||
470 				     robject->type == OBJT_SWAP)) {
471 
472 					robject->ref_count++;
473 
474 					while (
475 						robject->paging_in_progress ||
476 						object->paging_in_progress
477 					) {
478 						vm_object_pip_sleep(robject, "objde1");
479 						vm_object_pip_sleep(object, "objde2");
480 					}
481 
482 					if (robject->ref_count == 1) {
483 						robject->ref_count--;
484 						object = robject;
485 						goto doterm;
486 					}
487 
488 					object = robject;
489 					vm_object_collapse(object);
490 					continue;
491 				}
492 			}
493 			vm_object_unlock(object);
494 			return;
495 		}
496 doterm:
497 		temp = object->backing_object;
498 		if (temp) {
499 			TAILQ_REMOVE(&temp->shadow_head, object, shadow_list);
500 			temp->shadow_count--;
501 			temp->generation++;
502 			object->backing_object = NULL;
503 		}
504 		/*
505 		 * Don't double-terminate, we could be in a termination
506 		 * recursion due to the terminate having to sync data
507 		 * to disk.
508 		 */
509 		if ((object->flags & OBJ_DEAD) == 0)
510 			vm_object_terminate(object);
511 		object = temp;
512 	}
513 	vm_object_unlock(object);
514 }
515 
516 /*
517  *	vm_object_terminate actually destroys the specified object, freeing
518  *	up all previously used resources.
519  *
520  *	The object must be locked.
521  *	This routine may block.
522  */
523 void
524 vm_object_terminate(vm_object_t object)
525 {
526 	vm_page_t p;
527 	int s;
528 
529 	GIANT_REQUIRED;
530 
531 	/*
532 	 * Make sure no one uses us.
533 	 */
534 	vm_object_set_flag(object, OBJ_DEAD);
535 
536 	/*
537 	 * wait for the pageout daemon to be done with the object
538 	 */
539 	vm_object_pip_wait(object, "objtrm");
540 
541 	KASSERT(!object->paging_in_progress,
542 		("vm_object_terminate: pageout in progress"));
543 
544 	/*
545 	 * Clean and free the pages, as appropriate. All references to the
546 	 * object are gone, so we don't need to lock it.
547 	 */
548 	if (object->type == OBJT_VNODE) {
549 		struct vnode *vp;
550 
551 		/*
552 		 * Clean pages and flush buffers.
553 		 */
554 		vm_object_page_clean(object, 0, 0, OBJPC_SYNC);
555 
556 		vp = (struct vnode *) object->handle;
557 		vinvalbuf(vp, V_SAVE, NOCRED, NULL, 0, 0);
558 	}
559 
560 	KASSERT(object->ref_count == 0,
561 		("vm_object_terminate: object with references, ref_count=%d",
562 		object->ref_count));
563 
564 	/*
565 	 * Now free any remaining pages. For internal objects, this also
566 	 * removes them from paging queues. Don't free wired pages, just
567 	 * remove them from the object.
568 	 */
569 	s = splvm();
570 	vm_page_lock_queues();
571 	while ((p = TAILQ_FIRST(&object->memq)) != NULL) {
572 		KASSERT(!p->busy && (p->flags & PG_BUSY) == 0,
573 			("vm_object_terminate: freeing busy page %p "
574 			"p->busy = %d, p->flags %x\n", p, p->busy, p->flags));
575 		if (p->wire_count == 0) {
576 			vm_page_busy(p);
577 			vm_page_free(p);
578 			cnt.v_pfree++;
579 		} else {
580 			vm_page_busy(p);
581 			vm_page_remove(p);
582 		}
583 	}
584 	vm_page_unlock_queues();
585 	splx(s);
586 
587 	/*
588 	 * Let the pager know object is dead.
589 	 */
590 	vm_pager_deallocate(object);
591 
592 	/*
593 	 * Remove the object from the global object list.
594 	 */
595 	mtx_lock(&vm_object_list_mtx);
596 	TAILQ_REMOVE(&vm_object_list, object, object_list);
597 	mtx_unlock(&vm_object_list_mtx);
598 
599 	mtx_destroy(&object->mtx);
600 	wakeup(object);
601 
602 	/*
603 	 * Free the space for the object.
604 	 */
605 	uma_zfree(obj_zone, object);
606 }
607 
608 /*
609  *	vm_object_page_clean
610  *
611  *	Clean all dirty pages in the specified range of object.  Leaves page
612  * 	on whatever queue it is currently on.   If NOSYNC is set then do not
613  *	write out pages with PG_NOSYNC set (originally comes from MAP_NOSYNC),
614  *	leaving the object dirty.
615  *
616  *	When stuffing pages asynchronously, allow clustering.  XXX we need a
617  *	synchronous clustering mode implementation.
618  *
619  *	Odd semantics: if start == end, we clean everything.
620  *
621  *	The object must be locked.
622  */
623 void
624 vm_object_page_clean(vm_object_t object, vm_pindex_t start, vm_pindex_t end, int flags)
625 {
626 	vm_page_t p, np;
627 	vm_pindex_t tstart, tend;
628 	vm_pindex_t pi;
629 	struct vnode *vp;
630 	int clearobjflags;
631 	int pagerflags;
632 	int curgeneration;
633 
634 	GIANT_REQUIRED;
635 
636 	if (object->type != OBJT_VNODE ||
637 		(object->flags & OBJ_MIGHTBEDIRTY) == 0)
638 		return;
639 
640 	pagerflags = (flags & (OBJPC_SYNC | OBJPC_INVAL)) ? VM_PAGER_PUT_SYNC : VM_PAGER_CLUSTER_OK;
641 	pagerflags |= (flags & OBJPC_INVAL) ? VM_PAGER_PUT_INVAL : 0;
642 
643 	vp = object->handle;
644 
645 	vm_object_set_flag(object, OBJ_CLEANING);
646 
647 	tstart = start;
648 	if (end == 0) {
649 		tend = object->size;
650 	} else {
651 		tend = end;
652 	}
653 
654 	vm_page_lock_queues();
655 	/*
656 	 * If the caller is smart and only msync()s a range he knows is
657 	 * dirty, we may be able to avoid an object scan.  This results in
658 	 * a phenominal improvement in performance.  We cannot do this
659 	 * as a matter of course because the object may be huge - e.g.
660 	 * the size might be in the gigabytes or terrabytes.
661 	 */
662 	if (msync_flush_flags & MSYNC_FLUSH_HARDSEQ) {
663 		vm_pindex_t tscan;
664 		int scanlimit;
665 		int scanreset;
666 
667 		scanreset = object->resident_page_count / EASY_SCAN_FACTOR;
668 		if (scanreset < 16)
669 			scanreset = 16;
670 		pagerflags |= VM_PAGER_IGNORE_CLEANCHK;
671 
672 		scanlimit = scanreset;
673 		tscan = tstart;
674 		while (tscan < tend) {
675 			curgeneration = object->generation;
676 			p = vm_page_lookup(object, tscan);
677 			if (p == NULL || p->valid == 0 ||
678 			    (p->queue - p->pc) == PQ_CACHE) {
679 				if (--scanlimit == 0)
680 					break;
681 				++tscan;
682 				continue;
683 			}
684 			vm_page_test_dirty(p);
685 			if ((p->dirty & p->valid) == 0) {
686 				if (--scanlimit == 0)
687 					break;
688 				++tscan;
689 				continue;
690 			}
691 			/*
692 			 * If we have been asked to skip nosync pages and
693 			 * this is a nosync page, we can't continue.
694 			 */
695 			if ((flags & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
696 				if (--scanlimit == 0)
697 					break;
698 				++tscan;
699 				continue;
700 			}
701 			scanlimit = scanreset;
702 
703 			/*
704 			 * This returns 0 if it was unable to busy the first
705 			 * page (i.e. had to sleep).
706 			 */
707 			tscan += vm_object_page_collect_flush(object, p, curgeneration, pagerflags);
708 		}
709 
710 		/*
711 		 * If everything was dirty and we flushed it successfully,
712 		 * and the requested range is not the entire object, we
713 		 * don't have to mess with CLEANCHK or MIGHTBEDIRTY and can
714 		 * return immediately.
715 		 */
716 		if (tscan >= tend && (tstart || tend < object->size)) {
717 			vm_page_unlock_queues();
718 			vm_object_clear_flag(object, OBJ_CLEANING);
719 			return;
720 		}
721 		pagerflags &= ~VM_PAGER_IGNORE_CLEANCHK;
722 	}
723 
724 	/*
725 	 * Generally set CLEANCHK interlock and make the page read-only so
726 	 * we can then clear the object flags.
727 	 *
728 	 * However, if this is a nosync mmap then the object is likely to
729 	 * stay dirty so do not mess with the page and do not clear the
730 	 * object flags.
731 	 */
732 	clearobjflags = 1;
733 	TAILQ_FOREACH(p, &object->memq, listq) {
734 		vm_page_flag_set(p, PG_CLEANCHK);
735 		if ((flags & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC))
736 			clearobjflags = 0;
737 		else
738 			pmap_page_protect(p, VM_PROT_READ);
739 	}
740 
741 	if (clearobjflags && (tstart == 0) && (tend == object->size)) {
742 		struct vnode *vp;
743 
744 		vm_object_clear_flag(object, OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
745 		if (object->type == OBJT_VNODE &&
746 		    (vp = (struct vnode *)object->handle) != NULL) {
747 			VI_LOCK(vp);
748 			if (vp->v_iflag & VI_OBJDIRTY)
749 				vp->v_iflag &= ~VI_OBJDIRTY;
750 			VI_UNLOCK(vp);
751 		}
752 	}
753 
754 rescan:
755 	curgeneration = object->generation;
756 
757 	for (p = TAILQ_FIRST(&object->memq); p; p = np) {
758 		int n;
759 
760 		np = TAILQ_NEXT(p, listq);
761 
762 again:
763 		pi = p->pindex;
764 		if (((p->flags & PG_CLEANCHK) == 0) ||
765 			(pi < tstart) || (pi >= tend) ||
766 			(p->valid == 0) ||
767 			((p->queue - p->pc) == PQ_CACHE)) {
768 			vm_page_flag_clear(p, PG_CLEANCHK);
769 			continue;
770 		}
771 
772 		vm_page_test_dirty(p);
773 		if ((p->dirty & p->valid) == 0) {
774 			vm_page_flag_clear(p, PG_CLEANCHK);
775 			continue;
776 		}
777 
778 		/*
779 		 * If we have been asked to skip nosync pages and this is a
780 		 * nosync page, skip it.  Note that the object flags were
781 		 * not cleared in this case so we do not have to set them.
782 		 */
783 		if ((flags & OBJPC_NOSYNC) && (p->flags & PG_NOSYNC)) {
784 			vm_page_flag_clear(p, PG_CLEANCHK);
785 			continue;
786 		}
787 
788 		n = vm_object_page_collect_flush(object, p,
789 			curgeneration, pagerflags);
790 		if (n == 0)
791 			goto rescan;
792 
793 		if (object->generation != curgeneration)
794 			goto rescan;
795 
796 		/*
797 		 * Try to optimize the next page.  If we can't we pick up
798 		 * our (random) scan where we left off.
799 		 */
800 		if (msync_flush_flags & MSYNC_FLUSH_SOFTSEQ) {
801 			if ((p = vm_page_lookup(object, pi + n)) != NULL)
802 				goto again;
803 		}
804 	}
805 	vm_page_unlock_queues();
806 #if 0
807 	VOP_FSYNC(vp, NULL, (pagerflags & VM_PAGER_PUT_SYNC)?MNT_WAIT:0, curproc);
808 #endif
809 
810 	vm_object_clear_flag(object, OBJ_CLEANING);
811 	return;
812 }
813 
814 static int
815 vm_object_page_collect_flush(vm_object_t object, vm_page_t p, int curgeneration, int pagerflags)
816 {
817 	int runlen;
818 	int s;
819 	int maxf;
820 	int chkb;
821 	int maxb;
822 	int i;
823 	vm_pindex_t pi;
824 	vm_page_t maf[vm_pageout_page_count];
825 	vm_page_t mab[vm_pageout_page_count];
826 	vm_page_t ma[vm_pageout_page_count];
827 
828 	s = splvm();
829 	mtx_assert(&vm_page_queue_mtx, MA_OWNED);
830 	pi = p->pindex;
831 	while (vm_page_sleep_if_busy(p, TRUE, "vpcwai")) {
832 		vm_page_lock_queues();
833 		if (object->generation != curgeneration) {
834 			splx(s);
835 			return(0);
836 		}
837 	}
838 	maxf = 0;
839 	for(i = 1; i < vm_pageout_page_count; i++) {
840 		vm_page_t tp;
841 
842 		if ((tp = vm_page_lookup(object, pi + i)) != NULL) {
843 			if ((tp->flags & PG_BUSY) ||
844 				((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
845 				 (tp->flags & PG_CLEANCHK) == 0) ||
846 				(tp->busy != 0))
847 				break;
848 			if((tp->queue - tp->pc) == PQ_CACHE) {
849 				vm_page_flag_clear(tp, PG_CLEANCHK);
850 				break;
851 			}
852 			vm_page_test_dirty(tp);
853 			if ((tp->dirty & tp->valid) == 0) {
854 				vm_page_flag_clear(tp, PG_CLEANCHK);
855 				break;
856 			}
857 			maf[ i - 1 ] = tp;
858 			maxf++;
859 			continue;
860 		}
861 		break;
862 	}
863 
864 	maxb = 0;
865 	chkb = vm_pageout_page_count -  maxf;
866 	if (chkb) {
867 		for(i = 1; i < chkb;i++) {
868 			vm_page_t tp;
869 
870 			if ((tp = vm_page_lookup(object, pi - i)) != NULL) {
871 				if ((tp->flags & PG_BUSY) ||
872 					((pagerflags & VM_PAGER_IGNORE_CLEANCHK) == 0 &&
873 					 (tp->flags & PG_CLEANCHK) == 0) ||
874 					(tp->busy != 0))
875 					break;
876 				if ((tp->queue - tp->pc) == PQ_CACHE) {
877 					vm_page_flag_clear(tp, PG_CLEANCHK);
878 					break;
879 				}
880 				vm_page_test_dirty(tp);
881 				if ((tp->dirty & tp->valid) == 0) {
882 					vm_page_flag_clear(tp, PG_CLEANCHK);
883 					break;
884 				}
885 				mab[ i - 1 ] = tp;
886 				maxb++;
887 				continue;
888 			}
889 			break;
890 		}
891 	}
892 
893 	for(i = 0; i < maxb; i++) {
894 		int index = (maxb - i) - 1;
895 		ma[index] = mab[i];
896 		vm_page_flag_clear(ma[index], PG_CLEANCHK);
897 	}
898 	vm_page_flag_clear(p, PG_CLEANCHK);
899 	ma[maxb] = p;
900 	for(i = 0; i < maxf; i++) {
901 		int index = (maxb + i) + 1;
902 		ma[index] = maf[i];
903 		vm_page_flag_clear(ma[index], PG_CLEANCHK);
904 	}
905 	runlen = maxb + maxf + 1;
906 
907 	splx(s);
908 	vm_pageout_flush(ma, runlen, pagerflags);
909 	for (i = 0; i < runlen; i++) {
910 		if (ma[i]->valid & ma[i]->dirty) {
911 			pmap_page_protect(ma[i], VM_PROT_READ);
912 			vm_page_flag_set(ma[i], PG_CLEANCHK);
913 
914 			/*
915 			 * maxf will end up being the actual number of pages
916 			 * we wrote out contiguously, non-inclusive of the
917 			 * first page.  We do not count look-behind pages.
918 			 */
919 			if (i >= maxb + 1 && (maxf > i - maxb - 1))
920 				maxf = i - maxb - 1;
921 		}
922 	}
923 	return(maxf + 1);
924 }
925 
926 /*
927  *	vm_object_madvise:
928  *
929  *	Implements the madvise function at the object/page level.
930  *
931  *	MADV_WILLNEED	(any object)
932  *
933  *	    Activate the specified pages if they are resident.
934  *
935  *	MADV_DONTNEED	(any object)
936  *
937  *	    Deactivate the specified pages if they are resident.
938  *
939  *	MADV_FREE	(OBJT_DEFAULT/OBJT_SWAP objects,
940  *			 OBJ_ONEMAPPING only)
941  *
942  *	    Deactivate and clean the specified pages if they are
943  *	    resident.  This permits the process to reuse the pages
944  *	    without faulting or the kernel to reclaim the pages
945  *	    without I/O.
946  */
947 void
948 vm_object_madvise(vm_object_t object, vm_pindex_t pindex, int count, int advise)
949 {
950 	vm_pindex_t end, tpindex;
951 	vm_object_t tobject;
952 	vm_page_t m;
953 
954 	if (object == NULL)
955 		return;
956 
957 	vm_object_lock(object);
958 
959 	end = pindex + count;
960 
961 	/*
962 	 * Locate and adjust resident pages
963 	 */
964 	for (; pindex < end; pindex += 1) {
965 relookup:
966 		tobject = object;
967 		tpindex = pindex;
968 shadowlookup:
969 		/*
970 		 * MADV_FREE only operates on OBJT_DEFAULT or OBJT_SWAP pages
971 		 * and those pages must be OBJ_ONEMAPPING.
972 		 */
973 		if (advise == MADV_FREE) {
974 			if ((tobject->type != OBJT_DEFAULT &&
975 			     tobject->type != OBJT_SWAP) ||
976 			    (tobject->flags & OBJ_ONEMAPPING) == 0) {
977 				continue;
978 			}
979 		}
980 
981 		m = vm_page_lookup(tobject, tpindex);
982 
983 		if (m == NULL) {
984 			/*
985 			 * There may be swap even if there is no backing page
986 			 */
987 			if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
988 				swap_pager_freespace(tobject, tpindex, 1);
989 
990 			/*
991 			 * next object
992 			 */
993 			tobject = tobject->backing_object;
994 			if (tobject == NULL)
995 				continue;
996 			tpindex += OFF_TO_IDX(tobject->backing_object_offset);
997 			goto shadowlookup;
998 		}
999 
1000 		/*
1001 		 * If the page is busy or not in a normal active state,
1002 		 * we skip it.  If the page is not managed there are no
1003 		 * page queues to mess with.  Things can break if we mess
1004 		 * with pages in any of the below states.
1005 		 */
1006 		vm_page_lock_queues();
1007 		if (m->hold_count ||
1008 		    m->wire_count ||
1009 		    (m->flags & PG_UNMANAGED) ||
1010 		    m->valid != VM_PAGE_BITS_ALL) {
1011 			vm_page_unlock_queues();
1012 			continue;
1013 		}
1014  		if (vm_page_sleep_if_busy(m, TRUE, "madvpo"))
1015   			goto relookup;
1016 		if (advise == MADV_WILLNEED) {
1017 			vm_page_activate(m);
1018 		} else if (advise == MADV_DONTNEED) {
1019 			vm_page_dontneed(m);
1020 		} else if (advise == MADV_FREE) {
1021 			/*
1022 			 * Mark the page clean.  This will allow the page
1023 			 * to be freed up by the system.  However, such pages
1024 			 * are often reused quickly by malloc()/free()
1025 			 * so we do not do anything that would cause
1026 			 * a page fault if we can help it.
1027 			 *
1028 			 * Specifically, we do not try to actually free
1029 			 * the page now nor do we try to put it in the
1030 			 * cache (which would cause a page fault on reuse).
1031 			 *
1032 			 * But we do make the page is freeable as we
1033 			 * can without actually taking the step of unmapping
1034 			 * it.
1035 			 */
1036 			pmap_clear_modify(m);
1037 			m->dirty = 0;
1038 			m->act_count = 0;
1039 			vm_page_dontneed(m);
1040 		}
1041 		vm_page_unlock_queues();
1042 		if (advise == MADV_FREE && tobject->type == OBJT_SWAP)
1043 			swap_pager_freespace(tobject, tpindex, 1);
1044 	}
1045 	vm_object_unlock(object);
1046 }
1047 
1048 /*
1049  *	vm_object_shadow:
1050  *
1051  *	Create a new object which is backed by the
1052  *	specified existing object range.  The source
1053  *	object reference is deallocated.
1054  *
1055  *	The new object and offset into that object
1056  *	are returned in the source parameters.
1057  */
1058 void
1059 vm_object_shadow(
1060 	vm_object_t *object,	/* IN/OUT */
1061 	vm_ooffset_t *offset,	/* IN/OUT */
1062 	vm_size_t length)
1063 {
1064 	vm_object_t source;
1065 	vm_object_t result;
1066 
1067 	source = *object;
1068 
1069 	vm_object_lock(source);
1070 	/*
1071 	 * Don't create the new object if the old object isn't shared.
1072 	 */
1073 	if (source != NULL &&
1074 	    source->ref_count == 1 &&
1075 	    source->handle == NULL &&
1076 	    (source->type == OBJT_DEFAULT ||
1077 	     source->type == OBJT_SWAP)) {
1078 		vm_object_unlock(source);
1079 		return;
1080 	}
1081 
1082 	/*
1083 	 * Allocate a new object with the given length
1084 	 */
1085 	result = vm_object_allocate(OBJT_DEFAULT, length);
1086 	KASSERT(result != NULL, ("vm_object_shadow: no object for shadowing"));
1087 
1088 	/*
1089 	 * The new object shadows the source object, adding a reference to it.
1090 	 * Our caller changes his reference to point to the new object,
1091 	 * removing a reference to the source object.  Net result: no change
1092 	 * of reference count.
1093 	 *
1094 	 * Try to optimize the result object's page color when shadowing
1095 	 * in order to maintain page coloring consistency in the combined
1096 	 * shadowed object.
1097 	 */
1098 	result->backing_object = source;
1099 	if (source) {
1100 		TAILQ_INSERT_TAIL(&source->shadow_head, result, shadow_list);
1101 		source->shadow_count++;
1102 		source->generation++;
1103 		if (length < source->size)
1104 			length = source->size;
1105 		if (length > PQ_L2_SIZE / 3 + PQ_PRIME1 ||
1106 		    source->generation > 1)
1107 			length = PQ_L2_SIZE / 3 + PQ_PRIME1;
1108 		result->pg_color = (source->pg_color +
1109 		    length * source->generation) & PQ_L2_MASK;
1110 		next_index = (result->pg_color + PQ_L2_SIZE / 3 + PQ_PRIME1) &
1111 		    PQ_L2_MASK;
1112 	}
1113 
1114 	/*
1115 	 * Store the offset into the source object, and fix up the offset into
1116 	 * the new object.
1117 	 */
1118 	result->backing_object_offset = *offset;
1119 
1120 	/*
1121 	 * Return the new things
1122 	 */
1123 	*offset = 0;
1124 	*object = result;
1125 
1126 	vm_object_unlock(source);
1127 }
1128 
1129 /*
1130  *	vm_object_split:
1131  *
1132  * Split the pages in a map entry into a new object.  This affords
1133  * easier removal of unused pages, and keeps object inheritance from
1134  * being a negative impact on memory usage.
1135  */
1136 void
1137 vm_object_split(vm_map_entry_t entry)
1138 {
1139 	vm_page_t m;
1140 	vm_object_t orig_object, new_object, source;
1141 	vm_offset_t s, e;
1142 	vm_pindex_t offidxstart, offidxend;
1143 	vm_size_t idx, size;
1144 	vm_ooffset_t offset;
1145 
1146 	GIANT_REQUIRED;
1147 
1148 	orig_object = entry->object.vm_object;
1149 	if (orig_object->type != OBJT_DEFAULT && orig_object->type != OBJT_SWAP)
1150 		return;
1151 	if (orig_object->ref_count <= 1)
1152 		return;
1153 
1154 	offset = entry->offset;
1155 	s = entry->start;
1156 	e = entry->end;
1157 
1158 	offidxstart = OFF_TO_IDX(offset);
1159 	offidxend = offidxstart + OFF_TO_IDX(e - s);
1160 	size = offidxend - offidxstart;
1161 
1162 	new_object = vm_pager_allocate(orig_object->type,
1163 		NULL, IDX_TO_OFF(size), VM_PROT_ALL, 0LL);
1164 	if (new_object == NULL)
1165 		return;
1166 
1167 	source = orig_object->backing_object;
1168 	if (source != NULL) {
1169 		vm_object_reference(source);	/* Referenced by new_object */
1170 		TAILQ_INSERT_TAIL(&source->shadow_head,
1171 				  new_object, shadow_list);
1172 		vm_object_clear_flag(source, OBJ_ONEMAPPING);
1173 		new_object->backing_object_offset =
1174 			orig_object->backing_object_offset + offset;
1175 		new_object->backing_object = source;
1176 		source->shadow_count++;
1177 		source->generation++;
1178 	}
1179 	for (idx = 0; idx < size; idx++) {
1180 	retry:
1181 		m = vm_page_lookup(orig_object, offidxstart + idx);
1182 		if (m == NULL)
1183 			continue;
1184 
1185 		/*
1186 		 * We must wait for pending I/O to complete before we can
1187 		 * rename the page.
1188 		 *
1189 		 * We do not have to VM_PROT_NONE the page as mappings should
1190 		 * not be changed by this operation.
1191 		 */
1192 		vm_page_lock_queues();
1193 		if (vm_page_sleep_if_busy(m, TRUE, "spltwt"))
1194 			goto retry;
1195 
1196 		vm_page_busy(m);
1197 		vm_page_rename(m, new_object, idx);
1198 		/* page automatically made dirty by rename and cache handled */
1199 		vm_page_busy(m);
1200 		vm_page_unlock_queues();
1201 	}
1202 	if (orig_object->type == OBJT_SWAP) {
1203 		vm_object_pip_add(orig_object, 1);
1204 		/*
1205 		 * copy orig_object pages into new_object
1206 		 * and destroy unneeded pages in
1207 		 * shadow object.
1208 		 */
1209 		swap_pager_copy(orig_object, new_object, offidxstart, 0);
1210 		vm_object_pip_wakeup(orig_object);
1211 	}
1212 	vm_page_lock_queues();
1213 	TAILQ_FOREACH(m, &new_object->memq, listq)
1214 		vm_page_wakeup(m);
1215 	vm_page_unlock_queues();
1216 	entry->object.vm_object = new_object;
1217 	entry->offset = 0LL;
1218 	vm_object_deallocate(orig_object);
1219 }
1220 
1221 #define	OBSC_TEST_ALL_SHADOWED	0x0001
1222 #define	OBSC_COLLAPSE_NOWAIT	0x0002
1223 #define	OBSC_COLLAPSE_WAIT	0x0004
1224 
1225 static __inline int
1226 vm_object_backing_scan(vm_object_t object, int op)
1227 {
1228 	int s;
1229 	int r = 1;
1230 	vm_page_t p;
1231 	vm_object_t backing_object;
1232 	vm_pindex_t backing_offset_index;
1233 
1234 	s = splvm();
1235 	GIANT_REQUIRED;
1236 
1237 	backing_object = object->backing_object;
1238 	backing_offset_index = OFF_TO_IDX(object->backing_object_offset);
1239 
1240 	/*
1241 	 * Initial conditions
1242 	 */
1243 	if (op & OBSC_TEST_ALL_SHADOWED) {
1244 		/*
1245 		 * We do not want to have to test for the existence of
1246 		 * swap pages in the backing object.  XXX but with the
1247 		 * new swapper this would be pretty easy to do.
1248 		 *
1249 		 * XXX what about anonymous MAP_SHARED memory that hasn't
1250 		 * been ZFOD faulted yet?  If we do not test for this, the
1251 		 * shadow test may succeed! XXX
1252 		 */
1253 		if (backing_object->type != OBJT_DEFAULT) {
1254 			splx(s);
1255 			return (0);
1256 		}
1257 	}
1258 	if (op & OBSC_COLLAPSE_WAIT) {
1259 		vm_object_set_flag(backing_object, OBJ_DEAD);
1260 	}
1261 
1262 	/*
1263 	 * Our scan
1264 	 */
1265 	p = TAILQ_FIRST(&backing_object->memq);
1266 	while (p) {
1267 		vm_page_t next = TAILQ_NEXT(p, listq);
1268 		vm_pindex_t new_pindex = p->pindex - backing_offset_index;
1269 
1270 		if (op & OBSC_TEST_ALL_SHADOWED) {
1271 			vm_page_t pp;
1272 
1273 			/*
1274 			 * Ignore pages outside the parent object's range
1275 			 * and outside the parent object's mapping of the
1276 			 * backing object.
1277 			 *
1278 			 * note that we do not busy the backing object's
1279 			 * page.
1280 			 */
1281 			if (
1282 			    p->pindex < backing_offset_index ||
1283 			    new_pindex >= object->size
1284 			) {
1285 				p = next;
1286 				continue;
1287 			}
1288 
1289 			/*
1290 			 * See if the parent has the page or if the parent's
1291 			 * object pager has the page.  If the parent has the
1292 			 * page but the page is not valid, the parent's
1293 			 * object pager must have the page.
1294 			 *
1295 			 * If this fails, the parent does not completely shadow
1296 			 * the object and we might as well give up now.
1297 			 */
1298 
1299 			pp = vm_page_lookup(object, new_pindex);
1300 			if (
1301 			    (pp == NULL || pp->valid == 0) &&
1302 			    !vm_pager_has_page(object, new_pindex, NULL, NULL)
1303 			) {
1304 				r = 0;
1305 				break;
1306 			}
1307 		}
1308 
1309 		/*
1310 		 * Check for busy page
1311 		 */
1312 		if (op & (OBSC_COLLAPSE_WAIT | OBSC_COLLAPSE_NOWAIT)) {
1313 			vm_page_t pp;
1314 
1315 			vm_page_lock_queues();
1316 			if (op & OBSC_COLLAPSE_NOWAIT) {
1317 				if ((p->flags & PG_BUSY) ||
1318 				    !p->valid ||
1319 				    p->hold_count ||
1320 				    p->wire_count ||
1321 				    p->busy) {
1322 					vm_page_unlock_queues();
1323 					p = next;
1324 					continue;
1325 				}
1326 			} else if (op & OBSC_COLLAPSE_WAIT) {
1327 				if (vm_page_sleep_if_busy(p, TRUE, "vmocol")) {
1328 					/*
1329 					 * If we slept, anything could have
1330 					 * happened.  Since the object is
1331 					 * marked dead, the backing offset
1332 					 * should not have changed so we
1333 					 * just restart our scan.
1334 					 */
1335 					p = TAILQ_FIRST(&backing_object->memq);
1336 					continue;
1337 				}
1338 			}
1339 
1340 			/*
1341 			 * Busy the page
1342 			 */
1343 			vm_page_busy(p);
1344 			vm_page_unlock_queues();
1345 
1346 			KASSERT(
1347 			    p->object == backing_object,
1348 			    ("vm_object_qcollapse(): object mismatch")
1349 			);
1350 
1351 			/*
1352 			 * Destroy any associated swap
1353 			 */
1354 			if (backing_object->type == OBJT_SWAP) {
1355 				swap_pager_freespace(
1356 				    backing_object,
1357 				    p->pindex,
1358 				    1
1359 				);
1360 			}
1361 
1362 			if (
1363 			    p->pindex < backing_offset_index ||
1364 			    new_pindex >= object->size
1365 			) {
1366 				/*
1367 				 * Page is out of the parent object's range, we
1368 				 * can simply destroy it.
1369 				 */
1370 				vm_page_lock_queues();
1371 				pmap_remove_all(p);
1372 				vm_page_free(p);
1373 				vm_page_unlock_queues();
1374 				p = next;
1375 				continue;
1376 			}
1377 
1378 			pp = vm_page_lookup(object, new_pindex);
1379 			if (
1380 			    pp != NULL ||
1381 			    vm_pager_has_page(object, new_pindex, NULL, NULL)
1382 			) {
1383 				/*
1384 				 * page already exists in parent OR swap exists
1385 				 * for this location in the parent.  Destroy
1386 				 * the original page from the backing object.
1387 				 *
1388 				 * Leave the parent's page alone
1389 				 */
1390 				vm_page_lock_queues();
1391 				pmap_remove_all(p);
1392 				vm_page_free(p);
1393 				vm_page_unlock_queues();
1394 				p = next;
1395 				continue;
1396 			}
1397 
1398 			/*
1399 			 * Page does not exist in parent, rename the
1400 			 * page from the backing object to the main object.
1401 			 *
1402 			 * If the page was mapped to a process, it can remain
1403 			 * mapped through the rename.
1404 			 */
1405 			vm_page_lock_queues();
1406 			vm_page_rename(p, object, new_pindex);
1407 			vm_page_unlock_queues();
1408 			/* page automatically made dirty by rename */
1409 		}
1410 		p = next;
1411 	}
1412 	splx(s);
1413 	return (r);
1414 }
1415 
1416 
1417 /*
1418  * this version of collapse allows the operation to occur earlier and
1419  * when paging_in_progress is true for an object...  This is not a complete
1420  * operation, but should plug 99.9% of the rest of the leaks.
1421  */
1422 static void
1423 vm_object_qcollapse(vm_object_t object)
1424 {
1425 	vm_object_t backing_object = object->backing_object;
1426 
1427 	GIANT_REQUIRED;
1428 
1429 	if (backing_object->ref_count != 1)
1430 		return;
1431 
1432 	backing_object->ref_count += 2;
1433 
1434 	vm_object_backing_scan(object, OBSC_COLLAPSE_NOWAIT);
1435 
1436 	backing_object->ref_count -= 2;
1437 }
1438 
1439 /*
1440  *	vm_object_collapse:
1441  *
1442  *	Collapse an object with the object backing it.
1443  *	Pages in the backing object are moved into the
1444  *	parent, and the backing object is deallocated.
1445  */
1446 void
1447 vm_object_collapse(vm_object_t object)
1448 {
1449 	GIANT_REQUIRED;
1450 
1451 	while (TRUE) {
1452 		vm_object_t backing_object;
1453 
1454 		/*
1455 		 * Verify that the conditions are right for collapse:
1456 		 *
1457 		 * The object exists and the backing object exists.
1458 		 */
1459 		if (object == NULL)
1460 			break;
1461 
1462 		if ((backing_object = object->backing_object) == NULL)
1463 			break;
1464 
1465 		/*
1466 		 * we check the backing object first, because it is most likely
1467 		 * not collapsable.
1468 		 */
1469 		if (backing_object->handle != NULL ||
1470 		    (backing_object->type != OBJT_DEFAULT &&
1471 		     backing_object->type != OBJT_SWAP) ||
1472 		    (backing_object->flags & OBJ_DEAD) ||
1473 		    object->handle != NULL ||
1474 		    (object->type != OBJT_DEFAULT &&
1475 		     object->type != OBJT_SWAP) ||
1476 		    (object->flags & OBJ_DEAD)) {
1477 			break;
1478 		}
1479 
1480 		if (
1481 		    object->paging_in_progress != 0 ||
1482 		    backing_object->paging_in_progress != 0
1483 		) {
1484 			vm_object_qcollapse(object);
1485 			break;
1486 		}
1487 
1488 		/*
1489 		 * We know that we can either collapse the backing object (if
1490 		 * the parent is the only reference to it) or (perhaps) have
1491 		 * the parent bypass the object if the parent happens to shadow
1492 		 * all the resident pages in the entire backing object.
1493 		 *
1494 		 * This is ignoring pager-backed pages such as swap pages.
1495 		 * vm_object_backing_scan fails the shadowing test in this
1496 		 * case.
1497 		 */
1498 		if (backing_object->ref_count == 1) {
1499 			/*
1500 			 * If there is exactly one reference to the backing
1501 			 * object, we can collapse it into the parent.
1502 			 */
1503 			vm_object_backing_scan(object, OBSC_COLLAPSE_WAIT);
1504 
1505 			/*
1506 			 * Move the pager from backing_object to object.
1507 			 */
1508 			if (backing_object->type == OBJT_SWAP) {
1509 				vm_object_pip_add(backing_object, 1);
1510 
1511 				/*
1512 				 * scrap the paging_offset junk and do a
1513 				 * discrete copy.  This also removes major
1514 				 * assumptions about how the swap-pager
1515 				 * works from where it doesn't belong.  The
1516 				 * new swapper is able to optimize the
1517 				 * destroy-source case.
1518 				 */
1519 				vm_object_pip_add(object, 1);
1520 				swap_pager_copy(
1521 				    backing_object,
1522 				    object,
1523 				    OFF_TO_IDX(object->backing_object_offset), TRUE);
1524 				vm_object_pip_wakeup(object);
1525 
1526 				vm_object_pip_wakeup(backing_object);
1527 			}
1528 			/*
1529 			 * Object now shadows whatever backing_object did.
1530 			 * Note that the reference to
1531 			 * backing_object->backing_object moves from within
1532 			 * backing_object to within object.
1533 			 */
1534 			TAILQ_REMOVE(
1535 			    &object->backing_object->shadow_head,
1536 			    object,
1537 			    shadow_list
1538 			);
1539 			object->backing_object->shadow_count--;
1540 			object->backing_object->generation++;
1541 			if (backing_object->backing_object) {
1542 				TAILQ_REMOVE(
1543 				    &backing_object->backing_object->shadow_head,
1544 				    backing_object,
1545 				    shadow_list
1546 				);
1547 				backing_object->backing_object->shadow_count--;
1548 				backing_object->backing_object->generation++;
1549 			}
1550 			object->backing_object = backing_object->backing_object;
1551 			if (object->backing_object) {
1552 				TAILQ_INSERT_TAIL(
1553 				    &object->backing_object->shadow_head,
1554 				    object,
1555 				    shadow_list
1556 				);
1557 				object->backing_object->shadow_count++;
1558 				object->backing_object->generation++;
1559 			}
1560 
1561 			object->backing_object_offset +=
1562 			    backing_object->backing_object_offset;
1563 
1564 			/*
1565 			 * Discard backing_object.
1566 			 *
1567 			 * Since the backing object has no pages, no pager left,
1568 			 * and no object references within it, all that is
1569 			 * necessary is to dispose of it.
1570 			 */
1571 			KASSERT(backing_object->ref_count == 1, ("backing_object %p was somehow re-referenced during collapse!", backing_object));
1572 			KASSERT(TAILQ_FIRST(&backing_object->memq) == NULL, ("backing_object %p somehow has left over pages during collapse!", backing_object));
1573 
1574 			mtx_lock(&vm_object_list_mtx);
1575 			TAILQ_REMOVE(
1576 			    &vm_object_list,
1577 			    backing_object,
1578 			    object_list
1579 			);
1580 			mtx_unlock(&vm_object_list_mtx);
1581 
1582 			mtx_destroy(&backing_object->mtx);
1583 
1584 			uma_zfree(obj_zone, backing_object);
1585 
1586 			object_collapses++;
1587 		} else {
1588 			vm_object_t new_backing_object;
1589 
1590 			/*
1591 			 * If we do not entirely shadow the backing object,
1592 			 * there is nothing we can do so we give up.
1593 			 */
1594 			if (vm_object_backing_scan(object, OBSC_TEST_ALL_SHADOWED) == 0) {
1595 				break;
1596 			}
1597 
1598 			/*
1599 			 * Make the parent shadow the next object in the
1600 			 * chain.  Deallocating backing_object will not remove
1601 			 * it, since its reference count is at least 2.
1602 			 */
1603 			TAILQ_REMOVE(
1604 			    &backing_object->shadow_head,
1605 			    object,
1606 			    shadow_list
1607 			);
1608 			backing_object->shadow_count--;
1609 			backing_object->generation++;
1610 
1611 			new_backing_object = backing_object->backing_object;
1612 			if ((object->backing_object = new_backing_object) != NULL) {
1613 				vm_object_reference(new_backing_object);
1614 				TAILQ_INSERT_TAIL(
1615 				    &new_backing_object->shadow_head,
1616 				    object,
1617 				    shadow_list
1618 				);
1619 				new_backing_object->shadow_count++;
1620 				new_backing_object->generation++;
1621 				object->backing_object_offset +=
1622 					backing_object->backing_object_offset;
1623 			}
1624 
1625 			/*
1626 			 * Drop the reference count on backing_object. Since
1627 			 * its ref_count was at least 2, it will not vanish;
1628 			 * so we don't need to call vm_object_deallocate, but
1629 			 * we do anyway.
1630 			 */
1631 			vm_object_deallocate(backing_object);
1632 			object_bypasses++;
1633 		}
1634 
1635 		/*
1636 		 * Try again with this object's new backing object.
1637 		 */
1638 	}
1639 }
1640 
1641 /*
1642  *	vm_object_page_remove: [internal]
1643  *
1644  *	Removes all physical pages in the specified
1645  *	object range from the object's list of pages.
1646  *
1647  *	The object must be locked.
1648  */
1649 void
1650 vm_object_page_remove(vm_object_t object, vm_pindex_t start, vm_pindex_t end, boolean_t clean_only)
1651 {
1652 	vm_page_t p, next;
1653 	int all;
1654 
1655 	if (object == NULL ||
1656 	    object->resident_page_count == 0)
1657 		return;
1658 	all = ((end == 0) && (start == 0));
1659 
1660 	/*
1661 	 * Since physically-backed objects do not use managed pages, we can't
1662 	 * remove pages from the object (we must instead remove the page
1663 	 * references, and then destroy the object).
1664 	 */
1665 	KASSERT(object->type != OBJT_PHYS, ("attempt to remove pages from a physical object"));
1666 
1667 	vm_object_pip_add(object, 1);
1668 again:
1669 	vm_page_lock_queues();
1670 	if ((p = TAILQ_FIRST(&object->memq)) != NULL) {
1671 		if (p->pindex < start) {
1672 			p = vm_page_splay(start, object->root);
1673 			if ((object->root = p)->pindex < start)
1674 				p = TAILQ_NEXT(p, listq);
1675 		}
1676 	}
1677 	/*
1678 	 * Assert: the variable p is either (1) the page with the
1679 	 * least pindex greater than or equal to the parameter pindex
1680 	 * or (2) NULL.
1681 	 */
1682 	for (;
1683 	     p != NULL && (all || p->pindex < end);
1684 	     p = next) {
1685 		next = TAILQ_NEXT(p, listq);
1686 
1687 		if (p->wire_count != 0) {
1688 			pmap_remove_all(p);
1689 			if (!clean_only)
1690 				p->valid = 0;
1691 			continue;
1692 		}
1693 		if (vm_page_sleep_if_busy(p, TRUE, "vmopar"))
1694 			goto again;
1695 		if (clean_only && p->valid) {
1696 			vm_page_test_dirty(p);
1697 			if (p->valid & p->dirty)
1698 				continue;
1699 		}
1700 		vm_page_busy(p);
1701 		pmap_remove_all(p);
1702 		vm_page_free(p);
1703 	}
1704 	vm_page_unlock_queues();
1705 	vm_object_pip_wakeup(object);
1706 }
1707 
1708 /*
1709  *	Routine:	vm_object_coalesce
1710  *	Function:	Coalesces two objects backing up adjoining
1711  *			regions of memory into a single object.
1712  *
1713  *	returns TRUE if objects were combined.
1714  *
1715  *	NOTE:	Only works at the moment if the second object is NULL -
1716  *		if it's not, which object do we lock first?
1717  *
1718  *	Parameters:
1719  *		prev_object	First object to coalesce
1720  *		prev_offset	Offset into prev_object
1721  *		next_object	Second object into coalesce
1722  *		next_offset	Offset into next_object
1723  *
1724  *		prev_size	Size of reference to prev_object
1725  *		next_size	Size of reference to next_object
1726  *
1727  *	Conditions:
1728  *	The object must *not* be locked.
1729  */
1730 boolean_t
1731 vm_object_coalesce(vm_object_t prev_object, vm_pindex_t prev_pindex,
1732 	vm_size_t prev_size, vm_size_t next_size)
1733 {
1734 	vm_pindex_t next_pindex;
1735 
1736 	if (prev_object == NULL)
1737 		return (TRUE);
1738 	vm_object_lock(prev_object);
1739 	if (prev_object->type != OBJT_DEFAULT &&
1740 	    prev_object->type != OBJT_SWAP) {
1741 		vm_object_unlock(prev_object);
1742 		return (FALSE);
1743 	}
1744 
1745 	/*
1746 	 * Try to collapse the object first
1747 	 */
1748 	vm_object_collapse(prev_object);
1749 
1750 	/*
1751 	 * Can't coalesce if: . more than one reference . paged out . shadows
1752 	 * another object . has a copy elsewhere (any of which mean that the
1753 	 * pages not mapped to prev_entry may be in use anyway)
1754 	 */
1755 	if (prev_object->backing_object != NULL) {
1756 		vm_object_unlock(prev_object);
1757 		return (FALSE);
1758 	}
1759 
1760 	prev_size >>= PAGE_SHIFT;
1761 	next_size >>= PAGE_SHIFT;
1762 	next_pindex = prev_pindex + prev_size;
1763 
1764 	if ((prev_object->ref_count > 1) &&
1765 	    (prev_object->size != next_pindex)) {
1766 		vm_object_unlock(prev_object);
1767 		return (FALSE);
1768 	}
1769 
1770 	/*
1771 	 * Remove any pages that may still be in the object from a previous
1772 	 * deallocation.
1773 	 */
1774 	if (next_pindex < prev_object->size) {
1775 		vm_object_page_remove(prev_object,
1776 				      next_pindex,
1777 				      next_pindex + next_size, FALSE);
1778 		if (prev_object->type == OBJT_SWAP)
1779 			swap_pager_freespace(prev_object,
1780 					     next_pindex, next_size);
1781 	}
1782 
1783 	/*
1784 	 * Extend the object if necessary.
1785 	 */
1786 	if (next_pindex + next_size > prev_object->size)
1787 		prev_object->size = next_pindex + next_size;
1788 
1789 	vm_object_unlock(prev_object);
1790 	return (TRUE);
1791 }
1792 
1793 void
1794 vm_object_set_writeable_dirty(vm_object_t object)
1795 {
1796 	struct vnode *vp;
1797 
1798 	vm_object_set_flag(object, OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
1799 	if (object->type == OBJT_VNODE &&
1800 	    (vp = (struct vnode *)object->handle) != NULL) {
1801 		VI_LOCK(vp);
1802 		if ((vp->v_iflag & VI_OBJDIRTY) == 0)
1803 			vp->v_iflag |= VI_OBJDIRTY;
1804 		VI_UNLOCK(vp);
1805 	}
1806 }
1807 
1808 #include "opt_ddb.h"
1809 #ifdef DDB
1810 #include <sys/kernel.h>
1811 
1812 #include <sys/cons.h>
1813 
1814 #include <ddb/ddb.h>
1815 
1816 static int
1817 _vm_object_in_map(vm_map_t map, vm_object_t object, vm_map_entry_t entry)
1818 {
1819 	vm_map_t tmpm;
1820 	vm_map_entry_t tmpe;
1821 	vm_object_t obj;
1822 	int entcount;
1823 
1824 	if (map == 0)
1825 		return 0;
1826 
1827 	if (entry == 0) {
1828 		tmpe = map->header.next;
1829 		entcount = map->nentries;
1830 		while (entcount-- && (tmpe != &map->header)) {
1831 			if (_vm_object_in_map(map, object, tmpe)) {
1832 				return 1;
1833 			}
1834 			tmpe = tmpe->next;
1835 		}
1836 	} else if (entry->eflags & MAP_ENTRY_IS_SUB_MAP) {
1837 		tmpm = entry->object.sub_map;
1838 		tmpe = tmpm->header.next;
1839 		entcount = tmpm->nentries;
1840 		while (entcount-- && tmpe != &tmpm->header) {
1841 			if (_vm_object_in_map(tmpm, object, tmpe)) {
1842 				return 1;
1843 			}
1844 			tmpe = tmpe->next;
1845 		}
1846 	} else if ((obj = entry->object.vm_object) != NULL) {
1847 		for (; obj; obj = obj->backing_object)
1848 			if (obj == object) {
1849 				return 1;
1850 			}
1851 	}
1852 	return 0;
1853 }
1854 
1855 static int
1856 vm_object_in_map(vm_object_t object)
1857 {
1858 	struct proc *p;
1859 
1860 	/* sx_slock(&allproc_lock); */
1861 	LIST_FOREACH(p, &allproc, p_list) {
1862 		if (!p->p_vmspace /* || (p->p_flag & (P_SYSTEM|P_WEXIT)) */)
1863 			continue;
1864 		if (_vm_object_in_map(&p->p_vmspace->vm_map, object, 0)) {
1865 			/* sx_sunlock(&allproc_lock); */
1866 			return 1;
1867 		}
1868 	}
1869 	/* sx_sunlock(&allproc_lock); */
1870 	if (_vm_object_in_map(kernel_map, object, 0))
1871 		return 1;
1872 	if (_vm_object_in_map(kmem_map, object, 0))
1873 		return 1;
1874 	if (_vm_object_in_map(pager_map, object, 0))
1875 		return 1;
1876 	if (_vm_object_in_map(buffer_map, object, 0))
1877 		return 1;
1878 	return 0;
1879 }
1880 
1881 DB_SHOW_COMMAND(vmochk, vm_object_check)
1882 {
1883 	vm_object_t object;
1884 
1885 	/*
1886 	 * make sure that internal objs are in a map somewhere
1887 	 * and none have zero ref counts.
1888 	 */
1889 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
1890 		if (object->handle == NULL &&
1891 		    (object->type == OBJT_DEFAULT || object->type == OBJT_SWAP)) {
1892 			if (object->ref_count == 0) {
1893 				db_printf("vmochk: internal obj has zero ref count: %ld\n",
1894 					(long)object->size);
1895 			}
1896 			if (!vm_object_in_map(object)) {
1897 				db_printf(
1898 			"vmochk: internal obj is not in a map: "
1899 			"ref: %d, size: %lu: 0x%lx, backing_object: %p\n",
1900 				    object->ref_count, (u_long)object->size,
1901 				    (u_long)object->size,
1902 				    (void *)object->backing_object);
1903 			}
1904 		}
1905 	}
1906 }
1907 
1908 /*
1909  *	vm_object_print:	[ debug ]
1910  */
1911 DB_SHOW_COMMAND(object, vm_object_print_static)
1912 {
1913 	/* XXX convert args. */
1914 	vm_object_t object = (vm_object_t)addr;
1915 	boolean_t full = have_addr;
1916 
1917 	vm_page_t p;
1918 
1919 	/* XXX count is an (unused) arg.  Avoid shadowing it. */
1920 #define	count	was_count
1921 
1922 	int count;
1923 
1924 	if (object == NULL)
1925 		return;
1926 
1927 	db_iprintf(
1928 	    "Object %p: type=%d, size=0x%jx, res=%d, ref=%d, flags=0x%x\n",
1929 	    object, (int)object->type, (uintmax_t)object->size,
1930 	    object->resident_page_count, object->ref_count, object->flags);
1931 	db_iprintf(" sref=%d, backing_object(%d)=(%p)+0x%jx\n",
1932 	    object->shadow_count,
1933 	    object->backing_object ? object->backing_object->ref_count : 0,
1934 	    object->backing_object, (uintmax_t)object->backing_object_offset);
1935 
1936 	if (!full)
1937 		return;
1938 
1939 	db_indent += 2;
1940 	count = 0;
1941 	TAILQ_FOREACH(p, &object->memq, listq) {
1942 		if (count == 0)
1943 			db_iprintf("memory:=");
1944 		else if (count == 6) {
1945 			db_printf("\n");
1946 			db_iprintf(" ...");
1947 			count = 0;
1948 		} else
1949 			db_printf(",");
1950 		count++;
1951 
1952 		db_printf("(off=0x%jx,page=0x%jx)",
1953 		    (uintmax_t)p->pindex, (uintmax_t)VM_PAGE_TO_PHYS(p));
1954 	}
1955 	if (count != 0)
1956 		db_printf("\n");
1957 	db_indent -= 2;
1958 }
1959 
1960 /* XXX. */
1961 #undef count
1962 
1963 /* XXX need this non-static entry for calling from vm_map_print. */
1964 void
1965 vm_object_print(
1966         /* db_expr_t */ long addr,
1967 	boolean_t have_addr,
1968 	/* db_expr_t */ long count,
1969 	char *modif)
1970 {
1971 	vm_object_print_static(addr, have_addr, count, modif);
1972 }
1973 
1974 DB_SHOW_COMMAND(vmopag, vm_object_print_pages)
1975 {
1976 	vm_object_t object;
1977 	int nl = 0;
1978 	int c;
1979 
1980 	TAILQ_FOREACH(object, &vm_object_list, object_list) {
1981 		vm_pindex_t idx, fidx;
1982 		vm_pindex_t osize;
1983 		vm_paddr_t pa = -1, padiff;
1984 		int rcount;
1985 		vm_page_t m;
1986 
1987 		db_printf("new object: %p\n", (void *)object);
1988 		if (nl > 18) {
1989 			c = cngetc();
1990 			if (c != ' ')
1991 				return;
1992 			nl = 0;
1993 		}
1994 		nl++;
1995 		rcount = 0;
1996 		fidx = 0;
1997 		osize = object->size;
1998 		if (osize > 128)
1999 			osize = 128;
2000 		for (idx = 0; idx < osize; idx++) {
2001 			m = vm_page_lookup(object, idx);
2002 			if (m == NULL) {
2003 				if (rcount) {
2004 					db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2005 						(long)fidx, rcount, (long)pa);
2006 					if (nl > 18) {
2007 						c = cngetc();
2008 						if (c != ' ')
2009 							return;
2010 						nl = 0;
2011 					}
2012 					nl++;
2013 					rcount = 0;
2014 				}
2015 				continue;
2016 			}
2017 
2018 
2019 			if (rcount &&
2020 				(VM_PAGE_TO_PHYS(m) == pa + rcount * PAGE_SIZE)) {
2021 				++rcount;
2022 				continue;
2023 			}
2024 			if (rcount) {
2025 				padiff = pa + rcount * PAGE_SIZE - VM_PAGE_TO_PHYS(m);
2026 				padiff >>= PAGE_SHIFT;
2027 				padiff &= PQ_L2_MASK;
2028 				if (padiff == 0) {
2029 					pa = VM_PAGE_TO_PHYS(m) - rcount * PAGE_SIZE;
2030 					++rcount;
2031 					continue;
2032 				}
2033 				db_printf(" index(%ld)run(%d)pa(0x%lx)",
2034 					(long)fidx, rcount, (long)pa);
2035 				db_printf("pd(%ld)\n", (long)padiff);
2036 				if (nl > 18) {
2037 					c = cngetc();
2038 					if (c != ' ')
2039 						return;
2040 					nl = 0;
2041 				}
2042 				nl++;
2043 			}
2044 			fidx = idx;
2045 			pa = VM_PAGE_TO_PHYS(m);
2046 			rcount = 1;
2047 		}
2048 		if (rcount) {
2049 			db_printf(" index(%ld)run(%d)pa(0x%lx)\n",
2050 				(long)fidx, rcount, (long)pa);
2051 			if (nl > 18) {
2052 				c = cngetc();
2053 				if (c != ' ')
2054 					return;
2055 				nl = 0;
2056 			}
2057 			nl++;
2058 		}
2059 	}
2060 }
2061 #endif /* DDB */
2062