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