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