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