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