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