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