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