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