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