xref: /freebsd/sys/vm/vm_page.c (revision a79b71281cd63ad7a6cc43a6d5673a2510b51630)
1 /*
2  * Copyright (c) 1991 Regents of the University of California.
3  * 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_page.c	7.4 (Berkeley) 5/7/91
37  * $FreeBSD$
38  */
39 
40 /*
41  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42  * All rights reserved.
43  *
44  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
45  *
46  * Permission to use, copy, modify and distribute this software and
47  * its documentation is hereby granted, provided that both the copyright
48  * notice and this permission notice appear in all copies of the
49  * software, derivative works or modified versions, and any portions
50  * thereof, and that both notices appear in supporting documentation.
51  *
52  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
53  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
54  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
55  *
56  * Carnegie Mellon requests users of this software to return to
57  *
58  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
59  *  School of Computer Science
60  *  Carnegie Mellon University
61  *  Pittsburgh PA 15213-3890
62  *
63  * any improvements or extensions that they make and grant Carnegie the
64  * rights to redistribute these changes.
65  */
66 
67 /*
68  *	Resident memory management module.
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/malloc.h>
74 #include <sys/proc.h>
75 #include <sys/vmmeter.h>
76 #include <sys/vnode.h>
77 
78 #include <vm/vm.h>
79 #include <vm/vm_param.h>
80 #include <sys/lock.h>
81 #include <vm/vm_kern.h>
82 #include <vm/vm_object.h>
83 #include <vm/vm_page.h>
84 #include <vm/vm_pageout.h>
85 #include <vm/vm_pager.h>
86 #include <vm/vm_extern.h>
87 
88 static void	vm_page_queue_init __P((void));
89 static vm_page_t vm_page_select_cache __P((vm_object_t, vm_pindex_t));
90 
91 /*
92  *	Associated with page of user-allocatable memory is a
93  *	page structure.
94  */
95 
96 static struct vm_page **vm_page_buckets; /* Array of buckets */
97 static int vm_page_bucket_count;	/* How big is array? */
98 static int vm_page_hash_mask;		/* Mask for hash function */
99 static volatile int vm_page_bucket_generation;
100 
101 struct vpgqueues vm_page_queues[PQ_COUNT];
102 
103 static void
104 vm_page_queue_init(void) {
105 	int i;
106 
107 	for(i=0;i<PQ_L2_SIZE;i++) {
108 		vm_page_queues[PQ_FREE+i].cnt = &cnt.v_free_count;
109 	}
110 	vm_page_queues[PQ_INACTIVE].cnt = &cnt.v_inactive_count;
111 
112 	vm_page_queues[PQ_ACTIVE].cnt = &cnt.v_active_count;
113 	for(i=0;i<PQ_L2_SIZE;i++) {
114 		vm_page_queues[PQ_CACHE+i].cnt = &cnt.v_cache_count;
115 	}
116 	for(i=0;i<PQ_COUNT;i++) {
117 		TAILQ_INIT(&vm_page_queues[i].pl);
118 	}
119 }
120 
121 vm_page_t vm_page_array = 0;
122 int vm_page_array_size = 0;
123 long first_page = 0;
124 int vm_page_zero_count = 0;
125 
126 static __inline int vm_page_hash __P((vm_object_t object, vm_pindex_t pindex));
127 static void vm_page_free_wakeup __P((void));
128 
129 /*
130  *	vm_set_page_size:
131  *
132  *	Sets the page size, perhaps based upon the memory
133  *	size.  Must be called before any use of page-size
134  *	dependent functions.
135  */
136 void
137 vm_set_page_size()
138 {
139 	if (cnt.v_page_size == 0)
140 		cnt.v_page_size = PAGE_SIZE;
141 	if (((cnt.v_page_size - 1) & cnt.v_page_size) != 0)
142 		panic("vm_set_page_size: page size not a power of two");
143 }
144 
145 /*
146  *	vm_add_new_page:
147  *
148  *	Add a new page to the freelist for use by the system.
149  *	Must be called at splhigh().
150  */
151 vm_page_t
152 vm_add_new_page(pa)
153 	vm_offset_t pa;
154 {
155 	vm_page_t m;
156 
157 	++cnt.v_page_count;
158 	++cnt.v_free_count;
159 	m = PHYS_TO_VM_PAGE(pa);
160 	m->phys_addr = pa;
161 	m->flags = 0;
162 	m->pc = (pa >> PAGE_SHIFT) & PQ_L2_MASK;
163 	m->queue = m->pc + PQ_FREE;
164 	TAILQ_INSERT_HEAD(&vm_page_queues[m->queue].pl, m, pageq);
165 	vm_page_queues[m->queue].lcnt++;
166 	return (m);
167 }
168 
169 /*
170  *	vm_page_startup:
171  *
172  *	Initializes the resident memory module.
173  *
174  *	Allocates memory for the page cells, and
175  *	for the object/offset-to-page hash table headers.
176  *	Each page cell is initialized and placed on the free list.
177  */
178 
179 vm_offset_t
180 vm_page_startup(starta, enda, vaddr)
181 	register vm_offset_t starta;
182 	vm_offset_t enda;
183 	register vm_offset_t vaddr;
184 {
185 	register vm_offset_t mapped;
186 	register struct vm_page **bucket;
187 	vm_size_t npages, page_range;
188 	register vm_offset_t new_start;
189 	int i;
190 	vm_offset_t pa;
191 	int nblocks;
192 	vm_offset_t first_managed_page;
193 
194 	/* the biggest memory array is the second group of pages */
195 	vm_offset_t start;
196 	vm_offset_t biggestone, biggestsize;
197 
198 	vm_offset_t total;
199 
200 	total = 0;
201 	biggestsize = 0;
202 	biggestone = 0;
203 	nblocks = 0;
204 	vaddr = round_page(vaddr);
205 
206 	for (i = 0; phys_avail[i + 1]; i += 2) {
207 		phys_avail[i] = round_page(phys_avail[i]);
208 		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
209 	}
210 
211 	for (i = 0; phys_avail[i + 1]; i += 2) {
212 		int size = phys_avail[i + 1] - phys_avail[i];
213 
214 		if (size > biggestsize) {
215 			biggestone = i;
216 			biggestsize = size;
217 		}
218 		++nblocks;
219 		total += size;
220 	}
221 
222 	start = phys_avail[biggestone];
223 
224 	/*
225 	 * Initialize the queue headers for the free queue, the active queue
226 	 * and the inactive queue.
227 	 */
228 
229 	vm_page_queue_init();
230 
231 	/*
232 	 * Allocate (and initialize) the hash table buckets.
233 	 *
234 	 * The number of buckets MUST BE a power of 2, and the actual value is
235 	 * the next power of 2 greater than the number of physical pages in
236 	 * the system.
237 	 *
238 	 * We make the hash table approximately 2x the number of pages to
239 	 * reduce the chain length.  This is about the same size using the
240 	 * singly-linked list as the 1x hash table we were using before
241 	 * using TAILQ but the chain length will be smaller.
242 	 *
243 	 * Note: This computation can be tweaked if desired.
244 	 */
245 	vm_page_buckets = (struct vm_page **)vaddr;
246 	bucket = vm_page_buckets;
247 	if (vm_page_bucket_count == 0) {
248 		vm_page_bucket_count = 1;
249 		while (vm_page_bucket_count < atop(total))
250 			vm_page_bucket_count <<= 1;
251 	}
252 	vm_page_bucket_count <<= 1;
253 	vm_page_hash_mask = vm_page_bucket_count - 1;
254 
255 	/*
256 	 * Validate these addresses.
257 	 */
258 
259 	new_start = start + vm_page_bucket_count * sizeof(struct vm_page *);
260 	new_start = round_page(new_start);
261 	mapped = round_page(vaddr);
262 	vaddr = pmap_map(mapped, start, new_start,
263 	    VM_PROT_READ | VM_PROT_WRITE);
264 	start = new_start;
265 	vaddr = round_page(vaddr);
266 	bzero((caddr_t) mapped, vaddr - mapped);
267 
268 	for (i = 0; i < vm_page_bucket_count; i++) {
269 		*bucket = NULL;
270 		bucket++;
271 	}
272 
273 	/*
274 	 * Compute the number of pages of memory that will be available for
275 	 * use (taking into account the overhead of a page structure per
276 	 * page).
277 	 */
278 
279 	first_page = phys_avail[0] / PAGE_SIZE;
280 
281 	page_range = phys_avail[(nblocks - 1) * 2 + 1] / PAGE_SIZE - first_page;
282 	npages = (total - (page_range * sizeof(struct vm_page)) -
283 	    (start - phys_avail[biggestone])) / PAGE_SIZE;
284 
285 	/*
286 	 * Initialize the mem entry structures now, and put them in the free
287 	 * queue.
288 	 */
289 	vm_page_array = (vm_page_t) vaddr;
290 	mapped = vaddr;
291 
292 	/*
293 	 * Validate these addresses.
294 	 */
295 	new_start = round_page(start + page_range * sizeof(struct vm_page));
296 	mapped = pmap_map(mapped, start, new_start,
297 	    VM_PROT_READ | VM_PROT_WRITE);
298 	start = new_start;
299 
300 	first_managed_page = start / PAGE_SIZE;
301 
302 	/*
303 	 * Clear all of the page structures
304 	 */
305 	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
306 	vm_page_array_size = page_range;
307 
308 	/*
309 	 * Construct the free queue(s) in descending order (by physical
310 	 * address) so that the first 16MB of physical memory is allocated
311 	 * last rather than first.  On large-memory machines, this avoids
312 	 * the exhaustion of low physical memory before isa_dmainit has run.
313 	 */
314 	cnt.v_page_count = 0;
315 	cnt.v_free_count = 0;
316 	for (i = 0; phys_avail[i + 1] && npages > 0; i += 2) {
317 		if (i == biggestone)
318 			pa = ptoa(first_managed_page);
319 		else
320 			pa = phys_avail[i];
321 		while (pa < phys_avail[i + 1] && npages-- > 0) {
322 			vm_add_new_page(pa);
323 			pa += PAGE_SIZE;
324 		}
325 	}
326 	return (mapped);
327 }
328 
329 /*
330  *	vm_page_hash:
331  *
332  *	Distributes the object/offset key pair among hash buckets.
333  *
334  *	NOTE:  This macro depends on vm_page_bucket_count being a power of 2.
335  *	This routine may not block.
336  *
337  *	We try to randomize the hash based on the object to spread the pages
338  *	out in the hash table without it costing us too much.
339  */
340 static __inline int
341 vm_page_hash(object, pindex)
342 	vm_object_t object;
343 	vm_pindex_t pindex;
344 {
345 	int i = ((uintptr_t)object + pindex) ^ object->hash_rand;
346 
347 	return(i & vm_page_hash_mask);
348 }
349 
350 /*
351  *	vm_page_insert:		[ internal use only ]
352  *
353  *	Inserts the given mem entry into the object and object list.
354  *
355  *	The pagetables are not updated but will presumably fault the page
356  *	in if necessary, or if a kernel page the caller will at some point
357  *	enter the page into the kernel's pmap.  We are not allowed to block
358  *	here so we *can't* do this anyway.
359  *
360  *	The object and page must be locked, and must be splhigh.
361  *	This routine may not block.
362  */
363 
364 void
365 vm_page_insert(m, object, pindex)
366 	register vm_page_t m;
367 	register vm_object_t object;
368 	register vm_pindex_t pindex;
369 {
370 	register struct vm_page **bucket;
371 
372 	if (m->object != NULL)
373 		panic("vm_page_insert: already inserted");
374 
375 	/*
376 	 * Record the object/offset pair in this page
377 	 */
378 
379 	m->object = object;
380 	m->pindex = pindex;
381 
382 	/*
383 	 * Insert it into the object_object/offset hash table
384 	 */
385 
386 	bucket = &vm_page_buckets[vm_page_hash(object, pindex)];
387 	m->hnext = *bucket;
388 	*bucket = m;
389 	vm_page_bucket_generation++;
390 
391 	/*
392 	 * Now link into the object's list of backed pages.
393 	 */
394 
395 	TAILQ_INSERT_TAIL(&object->memq, m, listq);
396 	object->generation++;
397 
398 	/*
399 	 * show that the object has one more resident page.
400 	 */
401 
402 	object->resident_page_count++;
403 
404 	/*
405 	 * Since we are inserting a new and possibly dirty page,
406 	 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
407 	 */
408 	if (m->flags & PG_WRITEABLE)
409 	    vm_object_set_flag(object, OBJ_WRITEABLE|OBJ_MIGHTBEDIRTY);
410 }
411 
412 /*
413  *	vm_page_remove:
414  *				NOTE: used by device pager as well -wfj
415  *
416  *	Removes the given mem entry from the object/offset-page
417  *	table and the object page list, but do not invalidate/terminate
418  *	the backing store.
419  *
420  *	The object and page must be locked, and at splhigh.
421  *	The underlying pmap entry (if any) is NOT removed here.
422  *	This routine may not block.
423  */
424 
425 void
426 vm_page_remove(m)
427 	vm_page_t m;
428 {
429 	vm_object_t object;
430 
431 	if (m->object == NULL)
432 		return;
433 
434 	if ((m->flags & PG_BUSY) == 0) {
435 		panic("vm_page_remove: page not busy");
436 	}
437 
438 	/*
439 	 * Basically destroy the page.
440 	 */
441 
442 	vm_page_wakeup(m);
443 
444 	object = m->object;
445 
446 	/*
447 	 * Remove from the object_object/offset hash table.  The object
448 	 * must be on the hash queue, we will panic if it isn't
449 	 *
450 	 * Note: we must NULL-out m->hnext to prevent loops in detached
451 	 * buffers with vm_page_lookup().
452 	 */
453 
454 	{
455 		struct vm_page **bucket;
456 
457 		bucket = &vm_page_buckets[vm_page_hash(m->object, m->pindex)];
458 		while (*bucket != m) {
459 			if (*bucket == NULL)
460 				panic("vm_page_remove(): page not found in hash");
461 			bucket = &(*bucket)->hnext;
462 		}
463 		*bucket = m->hnext;
464 		m->hnext = NULL;
465 		vm_page_bucket_generation++;
466 	}
467 
468 	/*
469 	 * Now remove from the object's list of backed pages.
470 	 */
471 
472 	TAILQ_REMOVE(&object->memq, m, listq);
473 
474 	/*
475 	 * And show that the object has one fewer resident page.
476 	 */
477 
478 	object->resident_page_count--;
479 	object->generation++;
480 
481 	m->object = NULL;
482 }
483 
484 /*
485  *	vm_page_lookup:
486  *
487  *	Returns the page associated with the object/offset
488  *	pair specified; if none is found, NULL is returned.
489  *
490  *	NOTE: the code below does not lock.  It will operate properly if
491  *	an interrupt makes a change, but the generation algorithm will not
492  *	operate properly in an SMP environment where both cpu's are able to run
493  *	kernel code simultaneously.
494  *
495  *	The object must be locked.  No side effects.
496  *	This routine may not block.
497  *	This is a critical path routine
498  */
499 
500 vm_page_t
501 vm_page_lookup(object, pindex)
502 	register vm_object_t object;
503 	register vm_pindex_t pindex;
504 {
505 	register vm_page_t m;
506 	register struct vm_page **bucket;
507 	int generation;
508 
509 	/*
510 	 * Search the hash table for this object/offset pair
511 	 */
512 
513 retry:
514 	generation = vm_page_bucket_generation;
515 	bucket = &vm_page_buckets[vm_page_hash(object, pindex)];
516 	for (m = *bucket; m != NULL; m = m->hnext) {
517 		if ((m->object == object) && (m->pindex == pindex)) {
518 			if (vm_page_bucket_generation != generation)
519 				goto retry;
520 			return (m);
521 		}
522 	}
523 	if (vm_page_bucket_generation != generation)
524 		goto retry;
525 	return (NULL);
526 }
527 
528 /*
529  *	vm_page_rename:
530  *
531  *	Move the given memory entry from its
532  *	current object to the specified target object/offset.
533  *
534  *	The object must be locked.
535  *	This routine may not block.
536  *
537  *	Note: this routine will raise itself to splvm(), the caller need not.
538  *
539  *	Note: swap associated with the page must be invalidated by the move.  We
540  *	      have to do this for several reasons:  (1) we aren't freeing the
541  *	      page, (2) we are dirtying the page, (3) the VM system is probably
542  *	      moving the page from object A to B, and will then later move
543  *	      the backing store from A to B and we can't have a conflict.
544  *
545  *	Note: we *always* dirty the page.  It is necessary both for the
546  *	      fact that we moved it, and because we may be invalidating
547  *	      swap.  If the page is on the cache, we have to deactivate it
548  *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
549  *	      on the cache.
550  */
551 
552 void
553 vm_page_rename(m, new_object, new_pindex)
554 	register vm_page_t m;
555 	register vm_object_t new_object;
556 	vm_pindex_t new_pindex;
557 {
558 	int s;
559 
560 	s = splvm();
561 	vm_page_remove(m);
562 	vm_page_insert(m, new_object, new_pindex);
563 	if (m->queue - m->pc == PQ_CACHE)
564 		vm_page_deactivate(m);
565 	vm_page_dirty(m);
566 	splx(s);
567 }
568 
569 /*
570  * vm_page_unqueue_nowakeup:
571  *
572  * 	vm_page_unqueue() without any wakeup
573  *
574  *	This routine must be called at splhigh().
575  *	This routine may not block.
576  */
577 
578 void
579 vm_page_unqueue_nowakeup(m)
580 	vm_page_t m;
581 {
582 	int queue = m->queue;
583 	struct vpgqueues *pq;
584 	if (queue != PQ_NONE) {
585 		pq = &vm_page_queues[queue];
586 		m->queue = PQ_NONE;
587 		TAILQ_REMOVE(&pq->pl, m, pageq);
588 		(*pq->cnt)--;
589 		pq->lcnt--;
590 	}
591 }
592 
593 /*
594  * vm_page_unqueue:
595  *
596  *	Remove a page from its queue.
597  *
598  *	This routine must be called at splhigh().
599  *	This routine may not block.
600  */
601 
602 void
603 vm_page_unqueue(m)
604 	vm_page_t m;
605 {
606 	int queue = m->queue;
607 	struct vpgqueues *pq;
608 	if (queue != PQ_NONE) {
609 		m->queue = PQ_NONE;
610 		pq = &vm_page_queues[queue];
611 		TAILQ_REMOVE(&pq->pl, m, pageq);
612 		(*pq->cnt)--;
613 		pq->lcnt--;
614 		if ((queue - m->pc) == PQ_CACHE) {
615 			if (vm_paging_needed())
616 				pagedaemon_wakeup();
617 		}
618 	}
619 }
620 
621 #if PQ_L2_SIZE > 1
622 
623 /*
624  *	vm_page_list_find:
625  *
626  *	Find a page on the specified queue with color optimization.
627  *
628  *	The page coloring optimization attempts to locate a page
629  *	that does not overload other nearby pages in the object in
630  *	the cpu's L1 or L2 caches.  We need this optimization because
631  *	cpu caches tend to be physical caches, while object spaces tend
632  *	to be virtual.
633  *
634  *	This routine must be called at splvm().
635  *	This routine may not block.
636  *
637  *	This routine may only be called from the vm_page_list_find() macro
638  *	in vm_page.h
639  */
640 vm_page_t
641 _vm_page_list_find(basequeue, index)
642 	int basequeue, index;
643 {
644 	int i;
645 	vm_page_t m = NULL;
646 	struct vpgqueues *pq;
647 
648 	pq = &vm_page_queues[basequeue];
649 
650 	/*
651 	 * Note that for the first loop, index+i and index-i wind up at the
652 	 * same place.  Even though this is not totally optimal, we've already
653 	 * blown it by missing the cache case so we do not care.
654 	 */
655 
656 	for(i = PQ_L2_SIZE / 2; i > 0; --i) {
657 		if ((m = TAILQ_FIRST(&pq[(index + i) & PQ_L2_MASK].pl)) != NULL)
658 			break;
659 
660 		if ((m = TAILQ_FIRST(&pq[(index - i) & PQ_L2_MASK].pl)) != NULL)
661 			break;
662 	}
663 	return(m);
664 }
665 
666 #endif
667 
668 /*
669  *	vm_page_select_cache:
670  *
671  *	Find a page on the cache queue with color optimization.  As pages
672  *	might be found, but not applicable, they are deactivated.  This
673  *	keeps us from using potentially busy cached pages.
674  *
675  *	This routine must be called at splvm().
676  *	This routine may not block.
677  */
678 vm_page_t
679 vm_page_select_cache(object, pindex)
680 	vm_object_t object;
681 	vm_pindex_t pindex;
682 {
683 	vm_page_t m;
684 
685 	while (TRUE) {
686 		m = vm_page_list_find(
687 		    PQ_CACHE,
688 		    (pindex + object->pg_color) & PQ_L2_MASK,
689 		    FALSE
690 		);
691 		if (m && ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy ||
692 			       m->hold_count || m->wire_count)) {
693 			vm_page_deactivate(m);
694 			continue;
695 		}
696 		return m;
697 	}
698 }
699 
700 /*
701  *	vm_page_select_free:
702  *
703  *	Find a free or zero page, with specified preference.  We attempt to
704  *	inline the nominal case and fall back to _vm_page_select_free()
705  *	otherwise.
706  *
707  *	This routine must be called at splvm().
708  *	This routine may not block.
709  */
710 
711 static __inline vm_page_t
712 vm_page_select_free(vm_object_t object, vm_pindex_t pindex, boolean_t prefer_zero)
713 {
714 	vm_page_t m;
715 
716 	m = vm_page_list_find(
717 		PQ_FREE,
718 		(pindex + object->pg_color) & PQ_L2_MASK,
719 		prefer_zero
720 	);
721 	return(m);
722 }
723 
724 /*
725  *	vm_page_alloc:
726  *
727  *	Allocate and return a memory cell associated
728  *	with this VM object/offset pair.
729  *
730  *	page_req classes:
731  *	VM_ALLOC_NORMAL		normal process request
732  *	VM_ALLOC_SYSTEM		system *really* needs a page
733  *	VM_ALLOC_INTERRUPT	interrupt time request
734  *	VM_ALLOC_ZERO		zero page
735  *
736  *	Object must be locked.
737  *	This routine may not block.
738  *
739  *	Additional special handling is required when called from an
740  *	interrupt (VM_ALLOC_INTERRUPT).  We are not allowed to mess with
741  *	the page cache in this case.
742  */
743 
744 vm_page_t
745 vm_page_alloc(object, pindex, page_req)
746 	vm_object_t object;
747 	vm_pindex_t pindex;
748 	int page_req;
749 {
750 	register vm_page_t m = NULL;
751 	int s;
752 
753 	KASSERT(!vm_page_lookup(object, pindex),
754 		("vm_page_alloc: page already allocated"));
755 
756 	/*
757 	 * The pager is allowed to eat deeper into the free page list.
758 	 */
759 
760 	if ((curproc == pageproc) && (page_req != VM_ALLOC_INTERRUPT)) {
761 		page_req = VM_ALLOC_SYSTEM;
762 	};
763 
764 	s = splvm();
765 
766 loop:
767 	if (cnt.v_free_count > cnt.v_free_reserved) {
768 		/*
769 		 * Allocate from the free queue if there are plenty of pages
770 		 * in it.
771 		 */
772 		if (page_req == VM_ALLOC_ZERO)
773 			m = vm_page_select_free(object, pindex, TRUE);
774 		else
775 			m = vm_page_select_free(object, pindex, FALSE);
776 	} else if (
777 	    (page_req == VM_ALLOC_SYSTEM &&
778 	     cnt.v_cache_count == 0 &&
779 	     cnt.v_free_count > cnt.v_interrupt_free_min) ||
780 	    (page_req == VM_ALLOC_INTERRUPT && cnt.v_free_count > 0)
781 	) {
782 		/*
783 		 * Interrupt or system, dig deeper into the free list.
784 		 */
785 		m = vm_page_select_free(object, pindex, FALSE);
786 	} else if (page_req != VM_ALLOC_INTERRUPT) {
787 		/*
788 		 * Allocatable from cache (non-interrupt only).  On success,
789 		 * we must free the page and try again, thus ensuring that
790 		 * cnt.v_*_free_min counters are replenished.
791 		 */
792 		m = vm_page_select_cache(object, pindex);
793 		if (m == NULL) {
794 			splx(s);
795 #if defined(DIAGNOSTIC)
796 			if (cnt.v_cache_count > 0)
797 				printf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", cnt.v_cache_count);
798 #endif
799 			vm_pageout_deficit++;
800 			pagedaemon_wakeup();
801 			return (NULL);
802 		}
803 		KASSERT(m->dirty == 0, ("Found dirty cache page %p", m));
804 		vm_page_busy(m);
805 		vm_page_protect(m, VM_PROT_NONE);
806 		vm_page_free(m);
807 		goto loop;
808 	} else {
809 		/*
810 		 * Not allocatable from cache from interrupt, give up.
811 		 */
812 		splx(s);
813 		vm_pageout_deficit++;
814 		pagedaemon_wakeup();
815 		return (NULL);
816 	}
817 
818 	/*
819 	 *  At this point we had better have found a good page.
820 	 */
821 
822 	KASSERT(
823 	    m != NULL,
824 	    ("vm_page_alloc(): missing page on free queue\n")
825 	);
826 
827 	/*
828 	 * Remove from free queue
829 	 */
830 
831 	vm_page_unqueue_nowakeup(m);
832 
833 	/*
834 	 * Initialize structure.  Only the PG_ZERO flag is inherited.
835 	 */
836 
837 	if (m->flags & PG_ZERO) {
838 		vm_page_zero_count--;
839 		m->flags = PG_ZERO | PG_BUSY;
840 	} else {
841 		m->flags = PG_BUSY;
842 	}
843 	m->wire_count = 0;
844 	m->hold_count = 0;
845 	m->act_count = 0;
846 	m->busy = 0;
847 	m->valid = 0;
848 	KASSERT(m->dirty == 0, ("vm_page_alloc: free/cache page %p was dirty", m));
849 
850 	/*
851 	 * vm_page_insert() is safe prior to the splx().  Note also that
852 	 * inserting a page here does not insert it into the pmap (which
853 	 * could cause us to block allocating memory).  We cannot block
854 	 * anywhere.
855 	 */
856 
857 	vm_page_insert(m, object, pindex);
858 
859 	/*
860 	 * Don't wakeup too often - wakeup the pageout daemon when
861 	 * we would be nearly out of memory.
862 	 */
863 	if (vm_paging_needed() || cnt.v_free_count < cnt.v_pageout_free_min)
864 		pagedaemon_wakeup();
865 
866 	splx(s);
867 
868 	return (m);
869 }
870 
871 /*
872  *	vm_wait:	(also see VM_WAIT macro)
873  *
874  *	Block until free pages are available for allocation
875  */
876 
877 void
878 vm_wait()
879 {
880 	int s;
881 
882 	s = splvm();
883 	if (curproc == pageproc) {
884 		vm_pageout_pages_needed = 1;
885 		tsleep(&vm_pageout_pages_needed, PSWP, "vmwait", 0);
886 	} else {
887 		if (!vm_pages_needed) {
888 			vm_pages_needed++;
889 			wakeup(&vm_pages_needed);
890 		}
891 		tsleep(&cnt.v_free_count, PVM, "vmwait", 0);
892 	}
893 	splx(s);
894 }
895 
896 /*
897  *	vm_await:	(also see VM_AWAIT macro)
898  *
899  *	asleep on an event that will signal when free pages are available
900  *	for allocation.
901  */
902 
903 void
904 vm_await()
905 {
906 	int s;
907 
908 	s = splvm();
909 	if (curproc == pageproc) {
910 		vm_pageout_pages_needed = 1;
911 		asleep(&vm_pageout_pages_needed, PSWP, "vmwait", 0);
912 	} else {
913 		if (!vm_pages_needed) {
914 			vm_pages_needed++;
915 			wakeup(&vm_pages_needed);
916 		}
917 		asleep(&cnt.v_free_count, PVM, "vmwait", 0);
918 	}
919 	splx(s);
920 }
921 
922 #if 0
923 /*
924  *	vm_page_sleep:
925  *
926  *	Block until page is no longer busy.
927  */
928 
929 int
930 vm_page_sleep(vm_page_t m, char *msg, char *busy) {
931 	int slept = 0;
932 	if ((busy && *busy) || (m->flags & PG_BUSY)) {
933 		int s;
934 		s = splvm();
935 		if ((busy && *busy) || (m->flags & PG_BUSY)) {
936 			vm_page_flag_set(m, PG_WANTED);
937 			tsleep(m, PVM, msg, 0);
938 			slept = 1;
939 		}
940 		splx(s);
941 	}
942 	return slept;
943 }
944 
945 #endif
946 
947 #if 0
948 
949 /*
950  *	vm_page_asleep:
951  *
952  *	Similar to vm_page_sleep(), but does not block.  Returns 0 if
953  *	the page is not busy, or 1 if the page is busy.
954  *
955  *	This routine has the side effect of calling asleep() if the page
956  *	was busy (1 returned).
957  */
958 
959 int
960 vm_page_asleep(vm_page_t m, char *msg, char *busy) {
961 	int slept = 0;
962 	if ((busy && *busy) || (m->flags & PG_BUSY)) {
963 		int s;
964 		s = splvm();
965 		if ((busy && *busy) || (m->flags & PG_BUSY)) {
966 			vm_page_flag_set(m, PG_WANTED);
967 			asleep(m, PVM, msg, 0);
968 			slept = 1;
969 		}
970 		splx(s);
971 	}
972 	return slept;
973 }
974 
975 #endif
976 
977 /*
978  *	vm_page_activate:
979  *
980  *	Put the specified page on the active list (if appropriate).
981  *	Ensure that act_count is at least ACT_INIT but do not otherwise
982  *	mess with it.
983  *
984  *	The page queues must be locked.
985  *	This routine may not block.
986  */
987 void
988 vm_page_activate(m)
989 	register vm_page_t m;
990 {
991 	int s;
992 
993 	s = splvm();
994 	if (m->queue != PQ_ACTIVE) {
995 		if ((m->queue - m->pc) == PQ_CACHE)
996 			cnt.v_reactivated++;
997 
998 		vm_page_unqueue(m);
999 
1000 		if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1001 			m->queue = PQ_ACTIVE;
1002 			vm_page_queues[PQ_ACTIVE].lcnt++;
1003 			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1004 			if (m->act_count < ACT_INIT)
1005 				m->act_count = ACT_INIT;
1006 			cnt.v_active_count++;
1007 		}
1008 	} else {
1009 		if (m->act_count < ACT_INIT)
1010 			m->act_count = ACT_INIT;
1011 	}
1012 
1013 	splx(s);
1014 }
1015 
1016 /*
1017  *	vm_page_free_wakeup:
1018  *
1019  *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
1020  *	routine is called when a page has been added to the cache or free
1021  *	queues.
1022  *
1023  *	This routine may not block.
1024  *	This routine must be called at splvm()
1025  */
1026 static __inline void
1027 vm_page_free_wakeup()
1028 {
1029 	/*
1030 	 * if pageout daemon needs pages, then tell it that there are
1031 	 * some free.
1032 	 */
1033 	if (vm_pageout_pages_needed) {
1034 		wakeup(&vm_pageout_pages_needed);
1035 		vm_pageout_pages_needed = 0;
1036 	}
1037 	/*
1038 	 * wakeup processes that are waiting on memory if we hit a
1039 	 * high water mark. And wakeup scheduler process if we have
1040 	 * lots of memory. this process will swapin processes.
1041 	 */
1042 	if (vm_pages_needed && vm_page_count_min()) {
1043 		wakeup(&cnt.v_free_count);
1044 		vm_pages_needed = 0;
1045 	}
1046 }
1047 
1048 /*
1049  *	vm_page_free_toq:
1050  *
1051  *	Returns the given page to the PQ_FREE list,
1052  *	disassociating it with any VM object.
1053  *
1054  *	Object and page must be locked prior to entry.
1055  *	This routine may not block.
1056  */
1057 
1058 void
1059 vm_page_free_toq(vm_page_t m)
1060 {
1061 	int s;
1062 	struct vpgqueues *pq;
1063 	vm_object_t object = m->object;
1064 
1065 	s = splvm();
1066 
1067 	cnt.v_tfree++;
1068 
1069 	if (m->busy || ((m->queue - m->pc) == PQ_FREE) ||
1070 		(m->hold_count != 0)) {
1071 		printf(
1072 		"vm_page_free: pindex(%lu), busy(%d), PG_BUSY(%d), hold(%d)\n",
1073 		    (u_long)m->pindex, m->busy, (m->flags & PG_BUSY) ? 1 : 0,
1074 		    m->hold_count);
1075 		if ((m->queue - m->pc) == PQ_FREE)
1076 			panic("vm_page_free: freeing free page");
1077 		else
1078 			panic("vm_page_free: freeing busy page");
1079 	}
1080 
1081 	/*
1082 	 * unqueue, then remove page.  Note that we cannot destroy
1083 	 * the page here because we do not want to call the pager's
1084 	 * callback routine until after we've put the page on the
1085 	 * appropriate free queue.
1086 	 */
1087 
1088 	vm_page_unqueue_nowakeup(m);
1089 	vm_page_remove(m);
1090 
1091 	/*
1092 	 * If fictitious remove object association and
1093 	 * return, otherwise delay object association removal.
1094 	 */
1095 
1096 	if ((m->flags & PG_FICTITIOUS) != 0) {
1097 		splx(s);
1098 		return;
1099 	}
1100 
1101 	m->valid = 0;
1102 	vm_page_undirty(m);
1103 
1104 	if (m->wire_count != 0) {
1105 		if (m->wire_count > 1) {
1106 			panic("vm_page_free: invalid wire count (%d), pindex: 0x%lx",
1107 				m->wire_count, (long)m->pindex);
1108 		}
1109 		panic("vm_page_free: freeing wired page\n");
1110 	}
1111 
1112 	/*
1113 	 * If we've exhausted the object's resident pages we want to free
1114 	 * it up.
1115 	 */
1116 
1117 	if (object &&
1118 	    (object->type == OBJT_VNODE) &&
1119 	    ((object->flags & OBJ_DEAD) == 0)
1120 	) {
1121 		struct vnode *vp = (struct vnode *)object->handle;
1122 
1123 		if (vp && VSHOULDFREE(vp)) {
1124 			if ((vp->v_flag & (VTBFREE|VDOOMED|VFREE)) == 0) {
1125 				TAILQ_INSERT_TAIL(&vnode_tobefree_list, vp, v_freelist);
1126 				vp->v_flag |= VTBFREE;
1127 			}
1128 		}
1129 	}
1130 
1131 	/*
1132 	 * Clear the UNMANAGED flag when freeing an unmanaged page.
1133 	 */
1134 
1135 	if (m->flags & PG_UNMANAGED) {
1136 	    m->flags &= ~PG_UNMANAGED;
1137 	} else {
1138 #ifdef __alpha__
1139 	    pmap_page_is_free(m);
1140 #endif
1141 	}
1142 
1143 	m->queue = PQ_FREE + m->pc;
1144 	pq = &vm_page_queues[m->queue];
1145 	pq->lcnt++;
1146 	++(*pq->cnt);
1147 
1148 	/*
1149 	 * Put zero'd pages on the end ( where we look for zero'd pages
1150 	 * first ) and non-zerod pages at the head.
1151 	 */
1152 
1153 	if (m->flags & PG_ZERO) {
1154 		TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1155 		++vm_page_zero_count;
1156 	} else {
1157 		TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1158 	}
1159 
1160 	vm_page_free_wakeup();
1161 
1162 	splx(s);
1163 }
1164 
1165 /*
1166  *	vm_page_unmanage:
1167  *
1168  * 	Prevent PV management from being done on the page.  The page is
1169  *	removed from the paging queues as if it were wired, and as a
1170  *	consequence of no longer being managed the pageout daemon will not
1171  *	touch it (since there is no way to locate the pte mappings for the
1172  *	page).  madvise() calls that mess with the pmap will also no longer
1173  *	operate on the page.
1174  *
1175  *	Beyond that the page is still reasonably 'normal'.  Freeing the page
1176  *	will clear the flag.
1177  *
1178  *	This routine is used by OBJT_PHYS objects - objects using unswappable
1179  *	physical memory as backing store rather then swap-backed memory and
1180  *	will eventually be extended to support 4MB unmanaged physical
1181  *	mappings.
1182  */
1183 
1184 void
1185 vm_page_unmanage(vm_page_t m)
1186 {
1187 	int s;
1188 
1189 	s = splvm();
1190 	if ((m->flags & PG_UNMANAGED) == 0) {
1191 		if (m->wire_count == 0)
1192 			vm_page_unqueue(m);
1193 	}
1194 	vm_page_flag_set(m, PG_UNMANAGED);
1195 	splx(s);
1196 }
1197 
1198 /*
1199  *	vm_page_wire:
1200  *
1201  *	Mark this page as wired down by yet
1202  *	another map, removing it from paging queues
1203  *	as necessary.
1204  *
1205  *	The page queues must be locked.
1206  *	This routine may not block.
1207  */
1208 void
1209 vm_page_wire(m)
1210 	register vm_page_t m;
1211 {
1212 	int s;
1213 
1214 	/*
1215 	 * Only bump the wire statistics if the page is not already wired,
1216 	 * and only unqueue the page if it is on some queue (if it is unmanaged
1217 	 * it is already off the queues).
1218 	 */
1219 	s = splvm();
1220 	if (m->wire_count == 0) {
1221 		if ((m->flags & PG_UNMANAGED) == 0)
1222 			vm_page_unqueue(m);
1223 		cnt.v_wire_count++;
1224 	}
1225 	m->wire_count++;
1226 	splx(s);
1227 	vm_page_flag_set(m, PG_MAPPED);
1228 }
1229 
1230 /*
1231  *	vm_page_unwire:
1232  *
1233  *	Release one wiring of this page, potentially
1234  *	enabling it to be paged again.
1235  *
1236  *	Many pages placed on the inactive queue should actually go
1237  *	into the cache, but it is difficult to figure out which.  What
1238  *	we do instead, if the inactive target is well met, is to put
1239  *	clean pages at the head of the inactive queue instead of the tail.
1240  *	This will cause them to be moved to the cache more quickly and
1241  *	if not actively re-referenced, freed more quickly.  If we just
1242  *	stick these pages at the end of the inactive queue, heavy filesystem
1243  *	meta-data accesses can cause an unnecessary paging load on memory bound
1244  *	processes.  This optimization causes one-time-use metadata to be
1245  *	reused more quickly.
1246  *
1247  *	A number of routines use vm_page_unwire() to guarantee that the page
1248  *	will go into either the inactive or active queues, and will NEVER
1249  *	be placed in the cache - for example, just after dirtying a page.
1250  *	dirty pages in the cache are not allowed.
1251  *
1252  *	The page queues must be locked.
1253  *	This routine may not block.
1254  */
1255 void
1256 vm_page_unwire(m, activate)
1257 	register vm_page_t m;
1258 	int activate;
1259 {
1260 	int s;
1261 
1262 	s = splvm();
1263 
1264 	if (m->wire_count > 0) {
1265 		m->wire_count--;
1266 		if (m->wire_count == 0) {
1267 			cnt.v_wire_count--;
1268 			if (m->flags & PG_UNMANAGED) {
1269 				;
1270 			} else if (activate) {
1271 				TAILQ_INSERT_TAIL(&vm_page_queues[PQ_ACTIVE].pl, m, pageq);
1272 				m->queue = PQ_ACTIVE;
1273 				vm_page_queues[PQ_ACTIVE].lcnt++;
1274 				cnt.v_active_count++;
1275 			} else {
1276 				TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1277 				m->queue = PQ_INACTIVE;
1278 				vm_page_queues[PQ_INACTIVE].lcnt++;
1279 				cnt.v_inactive_count++;
1280 			}
1281 		}
1282 	} else {
1283 		panic("vm_page_unwire: invalid wire count: %d\n", m->wire_count);
1284 	}
1285 	splx(s);
1286 }
1287 
1288 
1289 /*
1290  * Move the specified page to the inactive queue.  If the page has
1291  * any associated swap, the swap is deallocated.
1292  *
1293  * Normally athead is 0 resulting in LRU operation.  athead is set
1294  * to 1 if we want this page to be 'as if it were placed in the cache',
1295  * except without unmapping it from the process address space.
1296  *
1297  * This routine may not block.
1298  */
1299 static __inline void
1300 _vm_page_deactivate(vm_page_t m, int athead)
1301 {
1302 	int s;
1303 
1304 	/*
1305 	 * Ignore if already inactive.
1306 	 */
1307 	if (m->queue == PQ_INACTIVE)
1308 		return;
1309 
1310 	s = splvm();
1311 	if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
1312 		if ((m->queue - m->pc) == PQ_CACHE)
1313 			cnt.v_reactivated++;
1314 		vm_page_unqueue(m);
1315 		if (athead)
1316 			TAILQ_INSERT_HEAD(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1317 		else
1318 			TAILQ_INSERT_TAIL(&vm_page_queues[PQ_INACTIVE].pl, m, pageq);
1319 		m->queue = PQ_INACTIVE;
1320 		vm_page_queues[PQ_INACTIVE].lcnt++;
1321 		cnt.v_inactive_count++;
1322 	}
1323 	splx(s);
1324 }
1325 
1326 void
1327 vm_page_deactivate(vm_page_t m)
1328 {
1329     _vm_page_deactivate(m, 0);
1330 }
1331 
1332 /*
1333  * vm_page_cache
1334  *
1335  * Put the specified page onto the page cache queue (if appropriate).
1336  *
1337  * This routine may not block.
1338  */
1339 void
1340 vm_page_cache(m)
1341 	register vm_page_t m;
1342 {
1343 	int s;
1344 
1345 	if ((m->flags & (PG_BUSY|PG_UNMANAGED)) || m->busy || m->wire_count) {
1346 		printf("vm_page_cache: attempting to cache busy page\n");
1347 		return;
1348 	}
1349 	if ((m->queue - m->pc) == PQ_CACHE)
1350 		return;
1351 
1352 	/*
1353 	 * Remove all pmaps and indicate that the page is not
1354 	 * writeable or mapped.
1355 	 */
1356 
1357 	vm_page_protect(m, VM_PROT_NONE);
1358 	if (m->dirty != 0) {
1359 		panic("vm_page_cache: caching a dirty page, pindex: %ld",
1360 			(long)m->pindex);
1361 	}
1362 	s = splvm();
1363 	vm_page_unqueue_nowakeup(m);
1364 	m->queue = PQ_CACHE + m->pc;
1365 	vm_page_queues[m->queue].lcnt++;
1366 	TAILQ_INSERT_TAIL(&vm_page_queues[m->queue].pl, m, pageq);
1367 	cnt.v_cache_count++;
1368 	vm_page_free_wakeup();
1369 	splx(s);
1370 }
1371 
1372 /*
1373  * vm_page_dontneed
1374  *
1375  *	Cache, deactivate, or do nothing as appropriate.  This routine
1376  *	is typically used by madvise() MADV_DONTNEED.
1377  *
1378  *	Generally speaking we want to move the page into the cache so
1379  *	it gets reused quickly.  However, this can result in a silly syndrome
1380  *	due to the page recycling too quickly.  Small objects will not be
1381  *	fully cached.  On the otherhand, if we move the page to the inactive
1382  *	queue we wind up with a problem whereby very large objects
1383  *	unnecessarily blow away our inactive and cache queues.
1384  *
1385  *	The solution is to move the pages based on a fixed weighting.  We
1386  *	either leave them alone, deactivate them, or move them to the cache,
1387  *	where moving them to the cache has the highest weighting.
1388  *	By forcing some pages into other queues we eventually force the
1389  *	system to balance the queues, potentially recovering other unrelated
1390  *	space from active.  The idea is to not force this to happen too
1391  *	often.
1392  */
1393 
1394 void
1395 vm_page_dontneed(m)
1396 	vm_page_t m;
1397 {
1398 	static int dnweight;
1399 	int dnw;
1400 	int head;
1401 
1402 	dnw = ++dnweight;
1403 
1404 	/*
1405 	 * occassionally leave the page alone
1406 	 */
1407 
1408 	if ((dnw & 0x01F0) == 0 ||
1409 	    m->queue == PQ_INACTIVE ||
1410 	    m->queue - m->pc == PQ_CACHE
1411 	) {
1412 		if (m->act_count >= ACT_INIT)
1413 			--m->act_count;
1414 		return;
1415 	}
1416 
1417 	if (m->dirty == 0)
1418 		vm_page_test_dirty(m);
1419 
1420 	if (m->dirty || (dnw & 0x0070) == 0) {
1421 		/*
1422 		 * Deactivate the page 3 times out of 32.
1423 		 */
1424 		head = 0;
1425 	} else {
1426 		/*
1427 		 * Cache the page 28 times out of every 32.  Note that
1428 		 * the page is deactivated instead of cached, but placed
1429 		 * at the head of the queue instead of the tail.
1430 		 */
1431 		head = 1;
1432 	}
1433 	_vm_page_deactivate(m, head);
1434 }
1435 
1436 /*
1437  * Grab a page, waiting until we are waken up due to the page
1438  * changing state.  We keep on waiting, if the page continues
1439  * to be in the object.  If the page doesn't exist, allocate it.
1440  *
1441  * This routine may block.
1442  */
1443 vm_page_t
1444 vm_page_grab(object, pindex, allocflags)
1445 	vm_object_t object;
1446 	vm_pindex_t pindex;
1447 	int allocflags;
1448 {
1449 
1450 	vm_page_t m;
1451 	int s, generation;
1452 
1453 retrylookup:
1454 	if ((m = vm_page_lookup(object, pindex)) != NULL) {
1455 		if (m->busy || (m->flags & PG_BUSY)) {
1456 			generation = object->generation;
1457 
1458 			s = splvm();
1459 			while ((object->generation == generation) &&
1460 					(m->busy || (m->flags & PG_BUSY))) {
1461 				vm_page_flag_set(m, PG_WANTED | PG_REFERENCED);
1462 				tsleep(m, PVM, "pgrbwt", 0);
1463 				if ((allocflags & VM_ALLOC_RETRY) == 0) {
1464 					splx(s);
1465 					return NULL;
1466 				}
1467 			}
1468 			splx(s);
1469 			goto retrylookup;
1470 		} else {
1471 			vm_page_busy(m);
1472 			return m;
1473 		}
1474 	}
1475 
1476 	m = vm_page_alloc(object, pindex, allocflags & ~VM_ALLOC_RETRY);
1477 	if (m == NULL) {
1478 		VM_WAIT;
1479 		if ((allocflags & VM_ALLOC_RETRY) == 0)
1480 			return NULL;
1481 		goto retrylookup;
1482 	}
1483 
1484 	return m;
1485 }
1486 
1487 /*
1488  * Mapping function for valid bits or for dirty bits in
1489  * a page.  May not block.
1490  *
1491  * Inputs are required to range within a page.
1492  */
1493 
1494 __inline int
1495 vm_page_bits(int base, int size)
1496 {
1497 	int first_bit;
1498 	int last_bit;
1499 
1500 	KASSERT(
1501 	    base + size <= PAGE_SIZE,
1502 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
1503 	);
1504 
1505 	if (size == 0)		/* handle degenerate case */
1506 		return(0);
1507 
1508 	first_bit = base >> DEV_BSHIFT;
1509 	last_bit = (base + size - 1) >> DEV_BSHIFT;
1510 
1511 	return ((2 << last_bit) - (1 << first_bit));
1512 }
1513 
1514 /*
1515  *	vm_page_set_validclean:
1516  *
1517  *	Sets portions of a page valid and clean.  The arguments are expected
1518  *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
1519  *	of any partial chunks touched by the range.  The invalid portion of
1520  *	such chunks will be zero'd.
1521  *
1522  *	This routine may not block.
1523  *
1524  *	(base + size) must be less then or equal to PAGE_SIZE.
1525  */
1526 void
1527 vm_page_set_validclean(m, base, size)
1528 	vm_page_t m;
1529 	int base;
1530 	int size;
1531 {
1532 	int pagebits;
1533 	int frag;
1534 	int endoff;
1535 
1536 	if (size == 0)	/* handle degenerate case */
1537 		return;
1538 
1539 	/*
1540 	 * If the base is not DEV_BSIZE aligned and the valid
1541 	 * bit is clear, we have to zero out a portion of the
1542 	 * first block.
1543 	 */
1544 
1545 	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
1546 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
1547 	) {
1548 		pmap_zero_page_area(
1549 		    VM_PAGE_TO_PHYS(m),
1550 		    frag,
1551 		    base - frag
1552 		);
1553 	}
1554 
1555 	/*
1556 	 * If the ending offset is not DEV_BSIZE aligned and the
1557 	 * valid bit is clear, we have to zero out a portion of
1558 	 * the last block.
1559 	 */
1560 
1561 	endoff = base + size;
1562 
1563 	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
1564 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
1565 	) {
1566 		pmap_zero_page_area(
1567 		    VM_PAGE_TO_PHYS(m),
1568 		    endoff,
1569 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
1570 		);
1571 	}
1572 
1573 	/*
1574 	 * Set valid, clear dirty bits.  If validating the entire
1575 	 * page we can safely clear the pmap modify bit.  We also
1576 	 * use this opportunity to clear the PG_NOSYNC flag.  If a process
1577 	 * takes a write fault on a MAP_NOSYNC memory area the flag will
1578 	 * be set again.
1579 	 */
1580 
1581 	pagebits = vm_page_bits(base, size);
1582 	m->valid |= pagebits;
1583 	m->dirty &= ~pagebits;
1584 	if (base == 0 && size == PAGE_SIZE) {
1585 		pmap_clear_modify(m);
1586 		vm_page_flag_clear(m, PG_NOSYNC);
1587 	}
1588 }
1589 
1590 #if 0
1591 
1592 void
1593 vm_page_set_dirty(m, base, size)
1594 	vm_page_t m;
1595 	int base;
1596 	int size;
1597 {
1598 	m->dirty |= vm_page_bits(base, size);
1599 }
1600 
1601 #endif
1602 
1603 void
1604 vm_page_clear_dirty(m, base, size)
1605 	vm_page_t m;
1606 	int base;
1607 	int size;
1608 {
1609 	m->dirty &= ~vm_page_bits(base, size);
1610 }
1611 
1612 /*
1613  *	vm_page_set_invalid:
1614  *
1615  *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
1616  *	valid and dirty bits for the effected areas are cleared.
1617  *
1618  *	May not block.
1619  */
1620 void
1621 vm_page_set_invalid(m, base, size)
1622 	vm_page_t m;
1623 	int base;
1624 	int size;
1625 {
1626 	int bits;
1627 
1628 	bits = vm_page_bits(base, size);
1629 	m->valid &= ~bits;
1630 	m->dirty &= ~bits;
1631 	m->object->generation++;
1632 }
1633 
1634 /*
1635  * vm_page_zero_invalid()
1636  *
1637  *	The kernel assumes that the invalid portions of a page contain
1638  *	garbage, but such pages can be mapped into memory by user code.
1639  *	When this occurs, we must zero out the non-valid portions of the
1640  *	page so user code sees what it expects.
1641  *
1642  *	Pages are most often semi-valid when the end of a file is mapped
1643  *	into memory and the file's size is not page aligned.
1644  */
1645 
1646 void
1647 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
1648 {
1649 	int b;
1650 	int i;
1651 
1652 	/*
1653 	 * Scan the valid bits looking for invalid sections that
1654 	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
1655 	 * valid bit may be set ) have already been zerod by
1656 	 * vm_page_set_validclean().
1657 	 */
1658 
1659 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
1660 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
1661 		    (m->valid & (1 << i))
1662 		) {
1663 			if (i > b) {
1664 				pmap_zero_page_area(
1665 				    VM_PAGE_TO_PHYS(m),
1666 				    b << DEV_BSHIFT,
1667 				    (i - b) << DEV_BSHIFT
1668 				);
1669 			}
1670 			b = i + 1;
1671 		}
1672 	}
1673 
1674 	/*
1675 	 * setvalid is TRUE when we can safely set the zero'd areas
1676 	 * as being valid.  We can do this if there are no cache consistancy
1677 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
1678 	 */
1679 
1680 	if (setvalid)
1681 		m->valid = VM_PAGE_BITS_ALL;
1682 }
1683 
1684 /*
1685  *	vm_page_is_valid:
1686  *
1687  *	Is (partial) page valid?  Note that the case where size == 0
1688  *	will return FALSE in the degenerate case where the page is
1689  *	entirely invalid, and TRUE otherwise.
1690  *
1691  *	May not block.
1692  */
1693 
1694 int
1695 vm_page_is_valid(m, base, size)
1696 	vm_page_t m;
1697 	int base;
1698 	int size;
1699 {
1700 	int bits = vm_page_bits(base, size);
1701 
1702 	if (m->valid && ((m->valid & bits) == bits))
1703 		return 1;
1704 	else
1705 		return 0;
1706 }
1707 
1708 /*
1709  * update dirty bits from pmap/mmu.  May not block.
1710  */
1711 
1712 void
1713 vm_page_test_dirty(m)
1714 	vm_page_t m;
1715 {
1716 	if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
1717 		vm_page_dirty(m);
1718 	}
1719 }
1720 
1721 /*
1722  * This interface is for merging with malloc() someday.
1723  * Even if we never implement compaction so that contiguous allocation
1724  * works after initialization time, malloc()'s data structures are good
1725  * for statistics and for allocations of less than a page.
1726  */
1727 void *
1728 contigmalloc1(size, type, flags, low, high, alignment, boundary, map)
1729 	unsigned long size;	/* should be size_t here and for malloc() */
1730 	struct malloc_type *type;
1731 	int flags;
1732 	unsigned long low;
1733 	unsigned long high;
1734 	unsigned long alignment;
1735 	unsigned long boundary;
1736 	vm_map_t map;
1737 {
1738 	int i, s, start;
1739 	vm_offset_t addr, phys, tmp_addr;
1740 	int pass;
1741 	vm_page_t pga = vm_page_array;
1742 
1743 	size = round_page(size);
1744 	if (size == 0)
1745 		panic("contigmalloc1: size must not be 0");
1746 	if ((alignment & (alignment - 1)) != 0)
1747 		panic("contigmalloc1: alignment must be a power of 2");
1748 	if ((boundary & (boundary - 1)) != 0)
1749 		panic("contigmalloc1: boundary must be a power of 2");
1750 
1751 	start = 0;
1752 	for (pass = 0; pass <= 1; pass++) {
1753 		s = splvm();
1754 again:
1755 		/*
1756 		 * Find first page in array that is free, within range, aligned, and
1757 		 * such that the boundary won't be crossed.
1758 		 */
1759 		for (i = start; i < cnt.v_page_count; i++) {
1760 			int pqtype;
1761 			phys = VM_PAGE_TO_PHYS(&pga[i]);
1762 			pqtype = pga[i].queue - pga[i].pc;
1763 			if (((pqtype == PQ_FREE) || (pqtype == PQ_CACHE)) &&
1764 			    (phys >= low) && (phys < high) &&
1765 			    ((phys & (alignment - 1)) == 0) &&
1766 			    (((phys ^ (phys + size - 1)) & ~(boundary - 1)) == 0))
1767 				break;
1768 		}
1769 
1770 		/*
1771 		 * If the above failed or we will exceed the upper bound, fail.
1772 		 */
1773 		if ((i == cnt.v_page_count) ||
1774 			((VM_PAGE_TO_PHYS(&pga[i]) + size) > high)) {
1775 			vm_page_t m, next;
1776 
1777 again1:
1778 			for (m = TAILQ_FIRST(&vm_page_queues[PQ_INACTIVE].pl);
1779 				m != NULL;
1780 				m = next) {
1781 
1782 				KASSERT(m->queue == PQ_INACTIVE,
1783 					("contigmalloc1: page %p is not PQ_INACTIVE", m));
1784 
1785 				next = TAILQ_NEXT(m, pageq);
1786 				if (vm_page_sleep_busy(m, TRUE, "vpctw0"))
1787 					goto again1;
1788 				vm_page_test_dirty(m);
1789 				if (m->dirty) {
1790 					if (m->object->type == OBJT_VNODE) {
1791 						vn_lock(m->object->handle, LK_EXCLUSIVE | LK_RETRY, curproc);
1792 						vm_object_page_clean(m->object, 0, 0, OBJPC_SYNC);
1793 						VOP_UNLOCK(m->object->handle, 0, curproc);
1794 						goto again1;
1795 					} else if (m->object->type == OBJT_SWAP ||
1796 								m->object->type == OBJT_DEFAULT) {
1797 						vm_pageout_flush(&m, 1, 0);
1798 						goto again1;
1799 					}
1800 				}
1801 				if ((m->dirty == 0) && (m->busy == 0) && (m->hold_count == 0))
1802 					vm_page_cache(m);
1803 			}
1804 
1805 			for (m = TAILQ_FIRST(&vm_page_queues[PQ_ACTIVE].pl);
1806 				m != NULL;
1807 				m = next) {
1808 
1809 				KASSERT(m->queue == PQ_ACTIVE,
1810 					("contigmalloc1: page %p is not PQ_ACTIVE", m));
1811 
1812 				next = TAILQ_NEXT(m, pageq);
1813 				if (vm_page_sleep_busy(m, TRUE, "vpctw1"))
1814 					goto again1;
1815 				vm_page_test_dirty(m);
1816 				if (m->dirty) {
1817 					if (m->object->type == OBJT_VNODE) {
1818 						vn_lock(m->object->handle, LK_EXCLUSIVE | LK_RETRY, curproc);
1819 						vm_object_page_clean(m->object, 0, 0, OBJPC_SYNC);
1820 						VOP_UNLOCK(m->object->handle, 0, curproc);
1821 						goto again1;
1822 					} else if (m->object->type == OBJT_SWAP ||
1823 								m->object->type == OBJT_DEFAULT) {
1824 						vm_pageout_flush(&m, 1, 0);
1825 						goto again1;
1826 					}
1827 				}
1828 				if ((m->dirty == 0) && (m->busy == 0) && (m->hold_count == 0))
1829 					vm_page_cache(m);
1830 			}
1831 
1832 			splx(s);
1833 			continue;
1834 		}
1835 		start = i;
1836 
1837 		/*
1838 		 * Check successive pages for contiguous and free.
1839 		 */
1840 		for (i = start + 1; i < (start + size / PAGE_SIZE); i++) {
1841 			int pqtype;
1842 			pqtype = pga[i].queue - pga[i].pc;
1843 			if ((VM_PAGE_TO_PHYS(&pga[i]) !=
1844 			    (VM_PAGE_TO_PHYS(&pga[i - 1]) + PAGE_SIZE)) ||
1845 			    ((pqtype != PQ_FREE) && (pqtype != PQ_CACHE))) {
1846 				start++;
1847 				goto again;
1848 			}
1849 		}
1850 
1851 		for (i = start; i < (start + size / PAGE_SIZE); i++) {
1852 			int pqtype;
1853 			vm_page_t m = &pga[i];
1854 
1855 			pqtype = m->queue - m->pc;
1856 			if (pqtype == PQ_CACHE) {
1857 				vm_page_busy(m);
1858 				vm_page_free(m);
1859 			}
1860 
1861 			TAILQ_REMOVE(&vm_page_queues[m->queue].pl, m, pageq);
1862 			vm_page_queues[m->queue].lcnt--;
1863 			cnt.v_free_count--;
1864 			m->valid = VM_PAGE_BITS_ALL;
1865 			m->flags = 0;
1866 			KASSERT(m->dirty == 0, ("contigmalloc1: page %p was dirty", m));
1867 			m->wire_count = 0;
1868 			m->busy = 0;
1869 			m->queue = PQ_NONE;
1870 			m->object = NULL;
1871 			vm_page_wire(m);
1872 		}
1873 
1874 		/*
1875 		 * We've found a contiguous chunk that meets are requirements.
1876 		 * Allocate kernel VM, unfree and assign the physical pages to it and
1877 		 * return kernel VM pointer.
1878 		 */
1879 		tmp_addr = addr = kmem_alloc_pageable(map, size);
1880 		if (addr == 0) {
1881 			/*
1882 			 * XXX We almost never run out of kernel virtual
1883 			 * space, so we don't make the allocated memory
1884 			 * above available.
1885 			 */
1886 			splx(s);
1887 			return (NULL);
1888 		}
1889 
1890 		for (i = start; i < (start + size / PAGE_SIZE); i++) {
1891 			vm_page_t m = &pga[i];
1892 			vm_page_insert(m, kernel_object,
1893 				OFF_TO_IDX(tmp_addr - VM_MIN_KERNEL_ADDRESS));
1894 			pmap_kenter(tmp_addr, VM_PAGE_TO_PHYS(m));
1895 			tmp_addr += PAGE_SIZE;
1896 		}
1897 
1898 		splx(s);
1899 		return ((void *)addr);
1900 	}
1901 	return NULL;
1902 }
1903 
1904 void *
1905 contigmalloc(size, type, flags, low, high, alignment, boundary)
1906 	unsigned long size;	/* should be size_t here and for malloc() */
1907 	struct malloc_type *type;
1908 	int flags;
1909 	unsigned long low;
1910 	unsigned long high;
1911 	unsigned long alignment;
1912 	unsigned long boundary;
1913 {
1914 	return contigmalloc1(size, type, flags, low, high, alignment, boundary,
1915 			     kernel_map);
1916 }
1917 
1918 void
1919 contigfree(addr, size, type)
1920 	void *addr;
1921 	unsigned long size;
1922 	struct malloc_type *type;
1923 {
1924 	kmem_free(kernel_map, (vm_offset_t)addr, size);
1925 }
1926 
1927 vm_offset_t
1928 vm_page_alloc_contig(size, low, high, alignment)
1929 	vm_offset_t size;
1930 	vm_offset_t low;
1931 	vm_offset_t high;
1932 	vm_offset_t alignment;
1933 {
1934 	return ((vm_offset_t)contigmalloc1(size, M_DEVBUF, M_NOWAIT, low, high,
1935 					  alignment, 0ul, kernel_map));
1936 }
1937 
1938 #include "opt_ddb.h"
1939 #ifdef DDB
1940 #include <sys/kernel.h>
1941 
1942 #include <ddb/ddb.h>
1943 
1944 DB_SHOW_COMMAND(page, vm_page_print_page_info)
1945 {
1946 	db_printf("cnt.v_free_count: %d\n", cnt.v_free_count);
1947 	db_printf("cnt.v_cache_count: %d\n", cnt.v_cache_count);
1948 	db_printf("cnt.v_inactive_count: %d\n", cnt.v_inactive_count);
1949 	db_printf("cnt.v_active_count: %d\n", cnt.v_active_count);
1950 	db_printf("cnt.v_wire_count: %d\n", cnt.v_wire_count);
1951 	db_printf("cnt.v_free_reserved: %d\n", cnt.v_free_reserved);
1952 	db_printf("cnt.v_free_min: %d\n", cnt.v_free_min);
1953 	db_printf("cnt.v_free_target: %d\n", cnt.v_free_target);
1954 	db_printf("cnt.v_cache_min: %d\n", cnt.v_cache_min);
1955 	db_printf("cnt.v_inactive_target: %d\n", cnt.v_inactive_target);
1956 }
1957 
1958 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
1959 {
1960 	int i;
1961 	db_printf("PQ_FREE:");
1962 	for(i=0;i<PQ_L2_SIZE;i++) {
1963 		db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
1964 	}
1965 	db_printf("\n");
1966 
1967 	db_printf("PQ_CACHE:");
1968 	for(i=0;i<PQ_L2_SIZE;i++) {
1969 		db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
1970 	}
1971 	db_printf("\n");
1972 
1973 	db_printf("PQ_ACTIVE: %d, PQ_INACTIVE: %d\n",
1974 		vm_page_queues[PQ_ACTIVE].lcnt,
1975 		vm_page_queues[PQ_INACTIVE].lcnt);
1976 }
1977 #endif /* DDB */
1978