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