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