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