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