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