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