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