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