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