vm_page.c revision 280456
11590Srgrimes/*-
21590Srgrimes * Copyright (c) 1991 Regents of the University of California.
31590Srgrimes * All rights reserved.
41590Srgrimes * Copyright (c) 1998 Matthew Dillon.  All Rights Reserved.
51590Srgrimes *
61590Srgrimes * This code is derived from software contributed to Berkeley by
71590Srgrimes * The Mach Operating System project at Carnegie-Mellon University.
81590Srgrimes *
91590Srgrimes * Redistribution and use in source and binary forms, with or without
101590Srgrimes * modification, are permitted provided that the following conditions
111590Srgrimes * are met:
121590Srgrimes * 1. Redistributions of source code must retain the above copyright
131590Srgrimes *    notice, this list of conditions and the following disclaimer.
141590Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
151590Srgrimes *    notice, this list of conditions and the following disclaimer in the
161590Srgrimes *    documentation and/or other materials provided with the distribution.
171590Srgrimes * 4. Neither the name of the University nor the names of its contributors
181590Srgrimes *    may be used to endorse or promote products derived from this software
191590Srgrimes *    without specific prior written permission.
201590Srgrimes *
211590Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
221590Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
231590Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
241590Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
251590Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
261590Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
271590Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
281590Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
291590Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
301590Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311590Srgrimes * SUCH DAMAGE.
321590Srgrimes *
331590Srgrimes *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
341590Srgrimes */
3527753Scharnier
361590Srgrimes/*-
3727753Scharnier * Copyright (c) 1987, 1990 Carnegie-Mellon University.
3827753Scharnier * All rights reserved.
3944091Sfenner *
401590Srgrimes * Authors: Avadis Tevanian, Jr., Michael Wayne Young
411590Srgrimes *
421590Srgrimes * Permission to use, copy, modify and distribute this software and
431590Srgrimes * its documentation is hereby granted, provided that both the copyright
441590Srgrimes * notice and this permission notice appear in all copies of the
451590Srgrimes * software, derivative works or modified versions, and any portions
4614543Sdg * thereof, and that both notices appear in supporting documentation.
471590Srgrimes *
481590Srgrimes * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
491590Srgrimes * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
501590Srgrimes * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
511590Srgrimes *
521590Srgrimes * Carnegie Mellon requests users of this software to return to
531590Srgrimes *
541590Srgrimes *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
551590Srgrimes *  School of Computer Science
561590Srgrimes *  Carnegie Mellon University
5736080Swollman *  Pittsburgh PA 15213-3890
5838185Sphk *
5936103Swollman * any improvements or extensions that they make and grant Carnegie the
601590Srgrimes * rights to redistribute these changes.
611590Srgrimes */
6236080Swollman
631590Srgrimes/*
641590Srgrimes *			GENERAL RULES ON VM_PAGE MANIPULATION
6536080Swollman *
661590Srgrimes *	- A page queue lock is required when adding or removing a page from a
6736080Swollman *	  page queue regardless of other locks or the busy state of a page.
6836080Swollman *
691590Srgrimes *		* In general, no thread besides the page daemon can acquire or
701590Srgrimes *		  hold more than one page queue lock at a time.
7136080Swollman *
721590Srgrimes *		* The page daemon can acquire and hold any pair of page queue
7336080Swollman *		  locks in any order.
7436080Swollman *
7536080Swollman *	- The object lock is required when inserting or removing
7636080Swollman *	  pages from an object (vm_page_insert() or vm_page_remove()).
7736080Swollman *
7836080Swollman */
7936080Swollman
801590Srgrimes/*
8144091Sfenner *	Resident memory management module.
8236080Swollman */
8336080Swollman
8436080Swollman#include <sys/cdefs.h>
8536080Swollman__FBSDID("$FreeBSD: head/sys/vm/vm_page.c 280456 2015-03-24 20:07:27Z rpaulo $");
8636080Swollman
8736080Swollman#include "opt_vm.h"
881590Srgrimes
8936080Swollman#include <sys/param.h>
9036080Swollman#include <sys/systm.h>
9136080Swollman#include <sys/lock.h>
9236080Swollman#include <sys/kernel.h>
9336080Swollman#include <sys/limits.h>
9436080Swollman#include <sys/malloc.h>
9536080Swollman#include <sys/mman.h>
9636080Swollman#include <sys/msgbuf.h>
9736080Swollman#include <sys/mutex.h>
9836080Swollman#include <sys/proc.h>
9936080Swollman#include <sys/rwlock.h>
10036080Swollman#include <sys/sysctl.h>
10136080Swollman#include <sys/vmmeter.h>
10236080Swollman#include <sys/vnode.h>
10336080Swollman
10436080Swollman#include <vm/vm.h>
10536080Swollman#include <vm/pmap.h>
10636080Swollman#include <vm/vm_param.h>
10736080Swollman#include <vm/vm_kern.h>
10836080Swollman#include <vm/vm_object.h>
10936080Swollman#include <vm/vm_page.h>
11036080Swollman#include <vm/vm_pageout.h>
11136080Swollman#include <vm/vm_pager.h>
11236080Swollman#include <vm/vm_phys.h>
11336080Swollman#include <vm/vm_radix.h>
11436080Swollman#include <vm/vm_reserv.h>
11536080Swollman#include <vm/vm_extern.h>
11636080Swollman#include <vm/uma.h>
11736080Swollman#include <vm/uma_int.h>
11836080Swollman
11936080Swollman#include <machine/md_var.h>
12036080Swollman
12136080Swollman/*
12236080Swollman *	Associated with page of user-allocatable memory is a
12336080Swollman *	page structure.
12436080Swollman */
1251590Srgrimes
1261590Srgrimesstruct vm_domain vm_dom[MAXMEMDOM];
1271590Srgrimesstruct mtx_padalign vm_page_queue_free_mtx;
1281590Srgrimes
12936080Swollmanstruct mtx_padalign pa_lock[PA_LOCK_COUNT];
13036080Swollman
13136080Swollmanvm_page_t vm_page_array;
1321590Srgrimeslong vm_page_array_size;
13336080Swollmanlong first_page;
13436080Swollmanint vm_page_zero_count;
1351590Srgrimes
1361590Srgrimesstatic int boot_pages = UMA_BOOT_PAGES;
13736080SwollmanSYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN, &boot_pages, 0,
13836080Swollman	"number of pages allocated for bootstrapping the VM system");
13936080Swollman
14036080Swollmanstatic int pa_tryrelock_restart;
14128726SwollmanSYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
14236080Swollman    &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
1431590Srgrimes
1441590Srgrimesstatic uma_zone_t fakepg_zone;
1451590Srgrimes
1461590Srgrimesstatic struct vnode *vm_page_alloc_init(vm_page_t m);
1471590Srgrimesstatic void vm_page_cache_turn_free(vm_page_t m);
1481590Srgrimesstatic void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
1491590Srgrimesstatic void vm_page_enqueue(uint8_t queue, vm_page_t m);
1501590Srgrimesstatic void vm_page_init_fakepg(void *dummy);
15136080Swollmanstatic int vm_page_insert_after(vm_page_t m, vm_object_t object,
15236080Swollman    vm_pindex_t pindex, vm_page_t mpred);
15336080Swollmanstatic void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
15436080Swollman    vm_page_t mpred);
15536080Swollman
15628726SwollmanSYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
15736091Sache
15837453Sbdestatic void
15936091Sachevm_page_init_fakepg(void *dummy)
1601590Srgrimes{
1611590Srgrimes
162	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
163	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
164}
165
166/* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
167#if PAGE_SIZE == 32768
168#ifdef CTASSERT
169CTASSERT(sizeof(u_long) >= 8);
170#endif
171#endif
172
173/*
174 * Try to acquire a physical address lock while a pmap is locked.  If we
175 * fail to trylock we unlock and lock the pmap directly and cache the
176 * locked pa in *locked.  The caller should then restart their loop in case
177 * the virtual to physical mapping has changed.
178 */
179int
180vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
181{
182	vm_paddr_t lockpa;
183
184	lockpa = *locked;
185	*locked = pa;
186	if (lockpa) {
187		PA_LOCK_ASSERT(lockpa, MA_OWNED);
188		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
189			return (0);
190		PA_UNLOCK(lockpa);
191	}
192	if (PA_TRYLOCK(pa))
193		return (0);
194	PMAP_UNLOCK(pmap);
195	atomic_add_int(&pa_tryrelock_restart, 1);
196	PA_LOCK(pa);
197	PMAP_LOCK(pmap);
198	return (EAGAIN);
199}
200
201/*
202 *	vm_set_page_size:
203 *
204 *	Sets the page size, perhaps based upon the memory
205 *	size.  Must be called before any use of page-size
206 *	dependent functions.
207 */
208void
209vm_set_page_size(void)
210{
211	if (vm_cnt.v_page_size == 0)
212		vm_cnt.v_page_size = PAGE_SIZE;
213	if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
214		panic("vm_set_page_size: page size not a power of two");
215}
216
217/*
218 *	vm_page_blacklist_lookup:
219 *
220 *	See if a physical address in this page has been listed
221 *	in the blacklist tunable.  Entries in the tunable are
222 *	separated by spaces or commas.  If an invalid integer is
223 *	encountered then the rest of the string is skipped.
224 */
225static int
226vm_page_blacklist_lookup(char *list, vm_paddr_t pa)
227{
228	vm_paddr_t bad;
229	char *cp, *pos;
230
231	for (pos = list; *pos != '\0'; pos = cp) {
232		bad = strtoq(pos, &cp, 0);
233		if (*cp != '\0') {
234			if (*cp == ' ' || *cp == ',') {
235				cp++;
236				if (cp == pos)
237					continue;
238			} else
239				break;
240		}
241		if (pa == trunc_page(bad))
242			return (1);
243	}
244	return (0);
245}
246
247static void
248vm_page_domain_init(struct vm_domain *vmd)
249{
250	struct vm_pagequeue *pq;
251	int i;
252
253	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
254	    "vm inactive pagequeue";
255	*__DECONST(int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
256	    &vm_cnt.v_inactive_count;
257	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
258	    "vm active pagequeue";
259	*__DECONST(int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
260	    &vm_cnt.v_active_count;
261	vmd->vmd_page_count = 0;
262	vmd->vmd_free_count = 0;
263	vmd->vmd_segs = 0;
264	vmd->vmd_oom = FALSE;
265	vmd->vmd_pass = 0;
266	for (i = 0; i < PQ_COUNT; i++) {
267		pq = &vmd->vmd_pagequeues[i];
268		TAILQ_INIT(&pq->pq_pl);
269		mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
270		    MTX_DEF | MTX_DUPOK);
271	}
272}
273
274/*
275 *	vm_page_startup:
276 *
277 *	Initializes the resident memory module.
278 *
279 *	Allocates memory for the page cells, and
280 *	for the object/offset-to-page hash table headers.
281 *	Each page cell is initialized and placed on the free list.
282 */
283vm_offset_t
284vm_page_startup(vm_offset_t vaddr)
285{
286	vm_offset_t mapped;
287	vm_paddr_t page_range;
288	vm_paddr_t new_end;
289	int i;
290	vm_paddr_t pa;
291	vm_paddr_t last_pa;
292	char *list;
293	vm_paddr_t end;
294	vm_paddr_t biggestsize;
295	vm_paddr_t low_water, high_water;
296	int biggestone;
297
298	biggestsize = 0;
299	biggestone = 0;
300	vaddr = round_page(vaddr);
301
302	for (i = 0; phys_avail[i + 1]; i += 2) {
303		phys_avail[i] = round_page(phys_avail[i]);
304		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
305	}
306
307#ifdef XEN
308	/*
309	 * There is no obvious reason why i386 PV Xen needs vm_page structs
310	 * created for these pseudo-physical addresses.  XXX
311	 */
312	vm_phys_add_seg(0, phys_avail[0]);
313#endif
314
315	low_water = phys_avail[0];
316	high_water = phys_avail[1];
317
318	for (i = 0; i < vm_phys_nsegs; i++) {
319		if (vm_phys_segs[i].start < low_water)
320			low_water = vm_phys_segs[i].start;
321		if (vm_phys_segs[i].end > high_water)
322			high_water = vm_phys_segs[i].end;
323	}
324	for (i = 0; phys_avail[i + 1]; i += 2) {
325		vm_paddr_t size = phys_avail[i + 1] - phys_avail[i];
326
327		if (size > biggestsize) {
328			biggestone = i;
329			biggestsize = size;
330		}
331		if (phys_avail[i] < low_water)
332			low_water = phys_avail[i];
333		if (phys_avail[i + 1] > high_water)
334			high_water = phys_avail[i + 1];
335	}
336
337	end = phys_avail[biggestone+1];
338
339	/*
340	 * Initialize the page and queue locks.
341	 */
342	mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
343	for (i = 0; i < PA_LOCK_COUNT; i++)
344		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
345	for (i = 0; i < vm_ndomains; i++)
346		vm_page_domain_init(&vm_dom[i]);
347
348	/*
349	 * Allocate memory for use when boot strapping the kernel memory
350	 * allocator.
351	 */
352	new_end = end - (boot_pages * UMA_SLAB_SIZE);
353	new_end = trunc_page(new_end);
354	mapped = pmap_map(&vaddr, new_end, end,
355	    VM_PROT_READ | VM_PROT_WRITE);
356	bzero((void *)mapped, end - new_end);
357	uma_startup((void *)mapped, boot_pages);
358
359#if defined(__amd64__) || defined(__i386__) || defined(__arm__) || \
360    defined(__mips__)
361	/*
362	 * Allocate a bitmap to indicate that a random physical page
363	 * needs to be included in a minidump.
364	 *
365	 * The amd64 port needs this to indicate which direct map pages
366	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
367	 *
368	 * However, i386 still needs this workspace internally within the
369	 * minidump code.  In theory, they are not needed on i386, but are
370	 * included should the sf_buf code decide to use them.
371	 */
372	last_pa = 0;
373	for (i = 0; dump_avail[i + 1] != 0; i += 2)
374		if (dump_avail[i + 1] > last_pa)
375			last_pa = dump_avail[i + 1];
376	page_range = last_pa / PAGE_SIZE;
377	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
378	new_end -= vm_page_dump_size;
379	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
380	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
381	bzero((void *)vm_page_dump, vm_page_dump_size);
382#endif
383#ifdef __amd64__
384	/*
385	 * Request that the physical pages underlying the message buffer be
386	 * included in a crash dump.  Since the message buffer is accessed
387	 * through the direct map, they are not automatically included.
388	 */
389	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
390	last_pa = pa + round_page(msgbufsize);
391	while (pa < last_pa) {
392		dump_add_page(pa);
393		pa += PAGE_SIZE;
394	}
395#endif
396	/*
397	 * Compute the number of pages of memory that will be available for
398	 * use (taking into account the overhead of a page structure per
399	 * page).
400	 */
401	first_page = low_water / PAGE_SIZE;
402#ifdef VM_PHYSSEG_SPARSE
403	page_range = 0;
404	for (i = 0; i < vm_phys_nsegs; i++) {
405		page_range += atop(vm_phys_segs[i].end -
406		    vm_phys_segs[i].start);
407	}
408	for (i = 0; phys_avail[i + 1] != 0; i += 2)
409		page_range += atop(phys_avail[i + 1] - phys_avail[i]);
410#elif defined(VM_PHYSSEG_DENSE)
411	page_range = high_water / PAGE_SIZE - first_page;
412#else
413#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
414#endif
415	end = new_end;
416
417	/*
418	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
419	 */
420	vaddr += PAGE_SIZE;
421
422	/*
423	 * Initialize the mem entry structures now, and put them in the free
424	 * queue.
425	 */
426	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
427	mapped = pmap_map(&vaddr, new_end, end,
428	    VM_PROT_READ | VM_PROT_WRITE);
429	vm_page_array = (vm_page_t) mapped;
430#if VM_NRESERVLEVEL > 0
431	/*
432	 * Allocate memory for the reservation management system's data
433	 * structures.
434	 */
435	new_end = vm_reserv_startup(&vaddr, new_end, high_water);
436#endif
437#if defined(__amd64__) || defined(__mips__)
438	/*
439	 * pmap_map on amd64 and mips can come out of the direct-map, not kvm
440	 * like i386, so the pages must be tracked for a crashdump to include
441	 * this data.  This includes the vm_page_array and the early UMA
442	 * bootstrap pages.
443	 */
444	for (pa = new_end; pa < phys_avail[biggestone + 1]; pa += PAGE_SIZE)
445		dump_add_page(pa);
446#endif
447	phys_avail[biggestone + 1] = new_end;
448
449	/*
450	 * Add physical memory segments corresponding to the available
451	 * physical pages.
452	 */
453	for (i = 0; phys_avail[i + 1] != 0; i += 2)
454		vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
455
456	/*
457	 * Clear all of the page structures
458	 */
459	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
460	for (i = 0; i < page_range; i++)
461		vm_page_array[i].order = VM_NFREEORDER;
462	vm_page_array_size = page_range;
463
464	/*
465	 * Initialize the physical memory allocator.
466	 */
467	vm_phys_init();
468
469	/*
470	 * Add every available physical page that is not blacklisted to
471	 * the free lists.
472	 */
473	vm_cnt.v_page_count = 0;
474	vm_cnt.v_free_count = 0;
475	list = kern_getenv("vm.blacklist");
476	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
477		pa = phys_avail[i];
478		last_pa = phys_avail[i + 1];
479		while (pa < last_pa) {
480			if (list != NULL &&
481			    vm_page_blacklist_lookup(list, pa))
482				printf("Skipping page with pa 0x%jx\n",
483				    (uintmax_t)pa);
484			else
485				vm_phys_add_page(pa);
486			pa += PAGE_SIZE;
487		}
488	}
489	freeenv(list);
490#if VM_NRESERVLEVEL > 0
491	/*
492	 * Initialize the reservation management system.
493	 */
494	vm_reserv_init();
495#endif
496	return (vaddr);
497}
498
499void
500vm_page_reference(vm_page_t m)
501{
502
503	vm_page_aflag_set(m, PGA_REFERENCED);
504}
505
506/*
507 *	vm_page_busy_downgrade:
508 *
509 *	Downgrade an exclusive busy page into a single shared busy page.
510 */
511void
512vm_page_busy_downgrade(vm_page_t m)
513{
514	u_int x;
515
516	vm_page_assert_xbusied(m);
517
518	for (;;) {
519		x = m->busy_lock;
520		x &= VPB_BIT_WAITERS;
521		if (atomic_cmpset_rel_int(&m->busy_lock,
522		    VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1) | x))
523			break;
524	}
525}
526
527/*
528 *	vm_page_sbusied:
529 *
530 *	Return a positive value if the page is shared busied, 0 otherwise.
531 */
532int
533vm_page_sbusied(vm_page_t m)
534{
535	u_int x;
536
537	x = m->busy_lock;
538	return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
539}
540
541/*
542 *	vm_page_sunbusy:
543 *
544 *	Shared unbusy a page.
545 */
546void
547vm_page_sunbusy(vm_page_t m)
548{
549	u_int x;
550
551	vm_page_assert_sbusied(m);
552
553	for (;;) {
554		x = m->busy_lock;
555		if (VPB_SHARERS(x) > 1) {
556			if (atomic_cmpset_int(&m->busy_lock, x,
557			    x - VPB_ONE_SHARER))
558				break;
559			continue;
560		}
561		if ((x & VPB_BIT_WAITERS) == 0) {
562			KASSERT(x == VPB_SHARERS_WORD(1),
563			    ("vm_page_sunbusy: invalid lock state"));
564			if (atomic_cmpset_int(&m->busy_lock,
565			    VPB_SHARERS_WORD(1), VPB_UNBUSIED))
566				break;
567			continue;
568		}
569		KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
570		    ("vm_page_sunbusy: invalid lock state for waiters"));
571
572		vm_page_lock(m);
573		if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
574			vm_page_unlock(m);
575			continue;
576		}
577		wakeup(m);
578		vm_page_unlock(m);
579		break;
580	}
581}
582
583/*
584 *	vm_page_busy_sleep:
585 *
586 *	Sleep and release the page lock, using the page pointer as wchan.
587 *	This is used to implement the hard-path of busying mechanism.
588 *
589 *	The given page must be locked.
590 */
591void
592vm_page_busy_sleep(vm_page_t m, const char *wmesg)
593{
594	u_int x;
595
596	vm_page_lock_assert(m, MA_OWNED);
597
598	x = m->busy_lock;
599	if (x == VPB_UNBUSIED) {
600		vm_page_unlock(m);
601		return;
602	}
603	if ((x & VPB_BIT_WAITERS) == 0 &&
604	    !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS)) {
605		vm_page_unlock(m);
606		return;
607	}
608	msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
609}
610
611/*
612 *	vm_page_trysbusy:
613 *
614 *	Try to shared busy a page.
615 *	If the operation succeeds 1 is returned otherwise 0.
616 *	The operation never sleeps.
617 */
618int
619vm_page_trysbusy(vm_page_t m)
620{
621	u_int x;
622
623	for (;;) {
624		x = m->busy_lock;
625		if ((x & VPB_BIT_SHARED) == 0)
626			return (0);
627		if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
628			return (1);
629	}
630}
631
632/*
633 *	vm_page_xunbusy_hard:
634 *
635 *	Called after the first try the exclusive unbusy of a page failed.
636 *	It is assumed that the waiters bit is on.
637 */
638void
639vm_page_xunbusy_hard(vm_page_t m)
640{
641
642	vm_page_assert_xbusied(m);
643
644	vm_page_lock(m);
645	atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
646	wakeup(m);
647	vm_page_unlock(m);
648}
649
650/*
651 *	vm_page_flash:
652 *
653 *	Wakeup anyone waiting for the page.
654 *	The ownership bits do not change.
655 *
656 *	The given page must be locked.
657 */
658void
659vm_page_flash(vm_page_t m)
660{
661	u_int x;
662
663	vm_page_lock_assert(m, MA_OWNED);
664
665	for (;;) {
666		x = m->busy_lock;
667		if ((x & VPB_BIT_WAITERS) == 0)
668			return;
669		if (atomic_cmpset_int(&m->busy_lock, x,
670		    x & (~VPB_BIT_WAITERS)))
671			break;
672	}
673	wakeup(m);
674}
675
676/*
677 * Keep page from being freed by the page daemon
678 * much of the same effect as wiring, except much lower
679 * overhead and should be used only for *very* temporary
680 * holding ("wiring").
681 */
682void
683vm_page_hold(vm_page_t mem)
684{
685
686	vm_page_lock_assert(mem, MA_OWNED);
687        mem->hold_count++;
688}
689
690void
691vm_page_unhold(vm_page_t mem)
692{
693
694	vm_page_lock_assert(mem, MA_OWNED);
695	KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
696	--mem->hold_count;
697	if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
698		vm_page_free_toq(mem);
699}
700
701/*
702 *	vm_page_unhold_pages:
703 *
704 *	Unhold each of the pages that is referenced by the given array.
705 */
706void
707vm_page_unhold_pages(vm_page_t *ma, int count)
708{
709	struct mtx *mtx, *new_mtx;
710
711	mtx = NULL;
712	for (; count != 0; count--) {
713		/*
714		 * Avoid releasing and reacquiring the same page lock.
715		 */
716		new_mtx = vm_page_lockptr(*ma);
717		if (mtx != new_mtx) {
718			if (mtx != NULL)
719				mtx_unlock(mtx);
720			mtx = new_mtx;
721			mtx_lock(mtx);
722		}
723		vm_page_unhold(*ma);
724		ma++;
725	}
726	if (mtx != NULL)
727		mtx_unlock(mtx);
728}
729
730vm_page_t
731PHYS_TO_VM_PAGE(vm_paddr_t pa)
732{
733	vm_page_t m;
734
735#ifdef VM_PHYSSEG_SPARSE
736	m = vm_phys_paddr_to_vm_page(pa);
737	if (m == NULL)
738		m = vm_phys_fictitious_to_vm_page(pa);
739	return (m);
740#elif defined(VM_PHYSSEG_DENSE)
741	long pi;
742
743	pi = atop(pa);
744	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
745		m = &vm_page_array[pi - first_page];
746		return (m);
747	}
748	return (vm_phys_fictitious_to_vm_page(pa));
749#else
750#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
751#endif
752}
753
754/*
755 *	vm_page_getfake:
756 *
757 *	Create a fictitious page with the specified physical address and
758 *	memory attribute.  The memory attribute is the only the machine-
759 *	dependent aspect of a fictitious page that must be initialized.
760 */
761vm_page_t
762vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
763{
764	vm_page_t m;
765
766	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
767	vm_page_initfake(m, paddr, memattr);
768	return (m);
769}
770
771void
772vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
773{
774
775	if ((m->flags & PG_FICTITIOUS) != 0) {
776		/*
777		 * The page's memattr might have changed since the
778		 * previous initialization.  Update the pmap to the
779		 * new memattr.
780		 */
781		goto memattr;
782	}
783	m->phys_addr = paddr;
784	m->queue = PQ_NONE;
785	/* Fictitious pages don't use "segind". */
786	m->flags = PG_FICTITIOUS;
787	/* Fictitious pages don't use "order" or "pool". */
788	m->oflags = VPO_UNMANAGED;
789	m->busy_lock = VPB_SINGLE_EXCLUSIVER;
790	m->wire_count = 1;
791	pmap_page_init(m);
792memattr:
793	pmap_page_set_memattr(m, memattr);
794}
795
796/*
797 *	vm_page_putfake:
798 *
799 *	Release a fictitious page.
800 */
801void
802vm_page_putfake(vm_page_t m)
803{
804
805	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
806	KASSERT((m->flags & PG_FICTITIOUS) != 0,
807	    ("vm_page_putfake: bad page %p", m));
808	uma_zfree(fakepg_zone, m);
809}
810
811/*
812 *	vm_page_updatefake:
813 *
814 *	Update the given fictitious page to the specified physical address and
815 *	memory attribute.
816 */
817void
818vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
819{
820
821	KASSERT((m->flags & PG_FICTITIOUS) != 0,
822	    ("vm_page_updatefake: bad page %p", m));
823	m->phys_addr = paddr;
824	pmap_page_set_memattr(m, memattr);
825}
826
827/*
828 *	vm_page_free:
829 *
830 *	Free a page.
831 */
832void
833vm_page_free(vm_page_t m)
834{
835
836	m->flags &= ~PG_ZERO;
837	vm_page_free_toq(m);
838}
839
840/*
841 *	vm_page_free_zero:
842 *
843 *	Free a page to the zerod-pages queue
844 */
845void
846vm_page_free_zero(vm_page_t m)
847{
848
849	m->flags |= PG_ZERO;
850	vm_page_free_toq(m);
851}
852
853/*
854 * Unbusy and handle the page queueing for a page from the VOP_GETPAGES()
855 * array which is not the request page.
856 */
857void
858vm_page_readahead_finish(vm_page_t m)
859{
860
861	if (m->valid != 0) {
862		/*
863		 * Since the page is not the requested page, whether
864		 * it should be activated or deactivated is not
865		 * obvious.  Empirical results have shown that
866		 * deactivating the page is usually the best choice,
867		 * unless the page is wanted by another thread.
868		 */
869		vm_page_lock(m);
870		if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
871			vm_page_activate(m);
872		else
873			vm_page_deactivate(m);
874		vm_page_unlock(m);
875		vm_page_xunbusy(m);
876	} else {
877		/*
878		 * Free the completely invalid page.  Such page state
879		 * occurs due to the short read operation which did
880		 * not covered our page at all, or in case when a read
881		 * error happens.
882		 */
883		vm_page_lock(m);
884		vm_page_free(m);
885		vm_page_unlock(m);
886	}
887}
888
889/*
890 *	vm_page_sleep_if_busy:
891 *
892 *	Sleep and release the page queues lock if the page is busied.
893 *	Returns TRUE if the thread slept.
894 *
895 *	The given page must be unlocked and object containing it must
896 *	be locked.
897 */
898int
899vm_page_sleep_if_busy(vm_page_t m, const char *msg)
900{
901	vm_object_t obj;
902
903	vm_page_lock_assert(m, MA_NOTOWNED);
904	VM_OBJECT_ASSERT_WLOCKED(m->object);
905
906	if (vm_page_busied(m)) {
907		/*
908		 * The page-specific object must be cached because page
909		 * identity can change during the sleep, causing the
910		 * re-lock of a different object.
911		 * It is assumed that a reference to the object is already
912		 * held by the callers.
913		 */
914		obj = m->object;
915		vm_page_lock(m);
916		VM_OBJECT_WUNLOCK(obj);
917		vm_page_busy_sleep(m, msg);
918		VM_OBJECT_WLOCK(obj);
919		return (TRUE);
920	}
921	return (FALSE);
922}
923
924/*
925 *	vm_page_dirty_KBI:		[ internal use only ]
926 *
927 *	Set all bits in the page's dirty field.
928 *
929 *	The object containing the specified page must be locked if the
930 *	call is made from the machine-independent layer.
931 *
932 *	See vm_page_clear_dirty_mask().
933 *
934 *	This function should only be called by vm_page_dirty().
935 */
936void
937vm_page_dirty_KBI(vm_page_t m)
938{
939
940	/* These assertions refer to this operation by its public name. */
941	KASSERT((m->flags & PG_CACHED) == 0,
942	    ("vm_page_dirty: page in cache!"));
943	KASSERT(m->valid == VM_PAGE_BITS_ALL,
944	    ("vm_page_dirty: page is invalid!"));
945	m->dirty = VM_PAGE_BITS_ALL;
946}
947
948/*
949 *	vm_page_insert:		[ internal use only ]
950 *
951 *	Inserts the given mem entry into the object and object list.
952 *
953 *	The object must be locked.
954 */
955int
956vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
957{
958	vm_page_t mpred;
959
960	VM_OBJECT_ASSERT_WLOCKED(object);
961	mpred = vm_radix_lookup_le(&object->rtree, pindex);
962	return (vm_page_insert_after(m, object, pindex, mpred));
963}
964
965/*
966 *	vm_page_insert_after:
967 *
968 *	Inserts the page "m" into the specified object at offset "pindex".
969 *
970 *	The page "mpred" must immediately precede the offset "pindex" within
971 *	the specified object.
972 *
973 *	The object must be locked.
974 */
975static int
976vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
977    vm_page_t mpred)
978{
979	vm_pindex_t sidx;
980	vm_object_t sobj;
981	vm_page_t msucc;
982
983	VM_OBJECT_ASSERT_WLOCKED(object);
984	KASSERT(m->object == NULL,
985	    ("vm_page_insert_after: page already inserted"));
986	if (mpred != NULL) {
987		KASSERT(mpred->object == object,
988		    ("vm_page_insert_after: object doesn't contain mpred"));
989		KASSERT(mpred->pindex < pindex,
990		    ("vm_page_insert_after: mpred doesn't precede pindex"));
991		msucc = TAILQ_NEXT(mpred, listq);
992	} else
993		msucc = TAILQ_FIRST(&object->memq);
994	if (msucc != NULL)
995		KASSERT(msucc->pindex > pindex,
996		    ("vm_page_insert_after: msucc doesn't succeed pindex"));
997
998	/*
999	 * Record the object/offset pair in this page
1000	 */
1001	sobj = m->object;
1002	sidx = m->pindex;
1003	m->object = object;
1004	m->pindex = pindex;
1005
1006	/*
1007	 * Now link into the object's ordered list of backed pages.
1008	 */
1009	if (vm_radix_insert(&object->rtree, m)) {
1010		m->object = sobj;
1011		m->pindex = sidx;
1012		return (1);
1013	}
1014	vm_page_insert_radixdone(m, object, mpred);
1015	return (0);
1016}
1017
1018/*
1019 *	vm_page_insert_radixdone:
1020 *
1021 *	Complete page "m" insertion into the specified object after the
1022 *	radix trie hooking.
1023 *
1024 *	The page "mpred" must precede the offset "m->pindex" within the
1025 *	specified object.
1026 *
1027 *	The object must be locked.
1028 */
1029static void
1030vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1031{
1032
1033	VM_OBJECT_ASSERT_WLOCKED(object);
1034	KASSERT(object != NULL && m->object == object,
1035	    ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1036	if (mpred != NULL) {
1037		KASSERT(mpred->object == object,
1038		    ("vm_page_insert_after: object doesn't contain mpred"));
1039		KASSERT(mpred->pindex < m->pindex,
1040		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1041	}
1042
1043	if (mpred != NULL)
1044		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1045	else
1046		TAILQ_INSERT_HEAD(&object->memq, m, listq);
1047
1048	/*
1049	 * Show that the object has one more resident page.
1050	 */
1051	object->resident_page_count++;
1052
1053	/*
1054	 * Hold the vnode until the last page is released.
1055	 */
1056	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1057		vhold(object->handle);
1058
1059	/*
1060	 * Since we are inserting a new and possibly dirty page,
1061	 * update the object's OBJ_MIGHTBEDIRTY flag.
1062	 */
1063	if (pmap_page_is_write_mapped(m))
1064		vm_object_set_writeable_dirty(object);
1065}
1066
1067/*
1068 *	vm_page_remove:
1069 *
1070 *	Removes the given mem entry from the object/offset-page
1071 *	table and the object page list, but do not invalidate/terminate
1072 *	the backing store.
1073 *
1074 *	The object must be locked.  The page must be locked if it is managed.
1075 */
1076void
1077vm_page_remove(vm_page_t m)
1078{
1079	vm_object_t object;
1080	boolean_t lockacq;
1081
1082	if ((m->oflags & VPO_UNMANAGED) == 0)
1083		vm_page_lock_assert(m, MA_OWNED);
1084	if ((object = m->object) == NULL)
1085		return;
1086	VM_OBJECT_ASSERT_WLOCKED(object);
1087	if (vm_page_xbusied(m)) {
1088		lockacq = FALSE;
1089		if ((m->oflags & VPO_UNMANAGED) != 0 &&
1090		    !mtx_owned(vm_page_lockptr(m))) {
1091			lockacq = TRUE;
1092			vm_page_lock(m);
1093		}
1094		vm_page_flash(m);
1095		atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
1096		if (lockacq)
1097			vm_page_unlock(m);
1098	}
1099
1100	/*
1101	 * Now remove from the object's list of backed pages.
1102	 */
1103	vm_radix_remove(&object->rtree, m->pindex);
1104	TAILQ_REMOVE(&object->memq, m, listq);
1105
1106	/*
1107	 * And show that the object has one fewer resident page.
1108	 */
1109	object->resident_page_count--;
1110
1111	/*
1112	 * The vnode may now be recycled.
1113	 */
1114	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1115		vdrop(object->handle);
1116
1117	m->object = NULL;
1118}
1119
1120/*
1121 *	vm_page_lookup:
1122 *
1123 *	Returns the page associated with the object/offset
1124 *	pair specified; if none is found, NULL is returned.
1125 *
1126 *	The object must be locked.
1127 */
1128vm_page_t
1129vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1130{
1131
1132	VM_OBJECT_ASSERT_LOCKED(object);
1133	return (vm_radix_lookup(&object->rtree, pindex));
1134}
1135
1136/*
1137 *	vm_page_find_least:
1138 *
1139 *	Returns the page associated with the object with least pindex
1140 *	greater than or equal to the parameter pindex, or NULL.
1141 *
1142 *	The object must be locked.
1143 */
1144vm_page_t
1145vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1146{
1147	vm_page_t m;
1148
1149	VM_OBJECT_ASSERT_LOCKED(object);
1150	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1151		m = vm_radix_lookup_ge(&object->rtree, pindex);
1152	return (m);
1153}
1154
1155/*
1156 * Returns the given page's successor (by pindex) within the object if it is
1157 * resident; if none is found, NULL is returned.
1158 *
1159 * The object must be locked.
1160 */
1161vm_page_t
1162vm_page_next(vm_page_t m)
1163{
1164	vm_page_t next;
1165
1166	VM_OBJECT_ASSERT_WLOCKED(m->object);
1167	if ((next = TAILQ_NEXT(m, listq)) != NULL &&
1168	    next->pindex != m->pindex + 1)
1169		next = NULL;
1170	return (next);
1171}
1172
1173/*
1174 * Returns the given page's predecessor (by pindex) within the object if it is
1175 * resident; if none is found, NULL is returned.
1176 *
1177 * The object must be locked.
1178 */
1179vm_page_t
1180vm_page_prev(vm_page_t m)
1181{
1182	vm_page_t prev;
1183
1184	VM_OBJECT_ASSERT_WLOCKED(m->object);
1185	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL &&
1186	    prev->pindex != m->pindex - 1)
1187		prev = NULL;
1188	return (prev);
1189}
1190
1191/*
1192 * Uses the page mnew as a replacement for an existing page at index
1193 * pindex which must be already present in the object.
1194 *
1195 * The existing page must not be on a paging queue.
1196 */
1197vm_page_t
1198vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1199{
1200	vm_page_t mold, mpred;
1201
1202	VM_OBJECT_ASSERT_WLOCKED(object);
1203
1204	/*
1205	 * This function mostly follows vm_page_insert() and
1206	 * vm_page_remove() without the radix, object count and vnode
1207	 * dance.  Double check such functions for more comments.
1208	 */
1209	mpred = vm_radix_lookup(&object->rtree, pindex);
1210	KASSERT(mpred != NULL,
1211	    ("vm_page_replace: replacing page not present with pindex"));
1212	mpred = TAILQ_PREV(mpred, respgs, listq);
1213	if (mpred != NULL)
1214		KASSERT(mpred->pindex < pindex,
1215		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1216
1217	mnew->object = object;
1218	mnew->pindex = pindex;
1219	mold = vm_radix_replace(&object->rtree, mnew);
1220	KASSERT(mold->queue == PQ_NONE,
1221	    ("vm_page_replace: mold is on a paging queue"));
1222
1223	/* Detach the old page from the resident tailq. */
1224	TAILQ_REMOVE(&object->memq, mold, listq);
1225
1226	mold->object = NULL;
1227	vm_page_xunbusy(mold);
1228
1229	/* Insert the new page in the resident tailq. */
1230	if (mpred != NULL)
1231		TAILQ_INSERT_AFTER(&object->memq, mpred, mnew, listq);
1232	else
1233		TAILQ_INSERT_HEAD(&object->memq, mnew, listq);
1234	if (pmap_page_is_write_mapped(mnew))
1235		vm_object_set_writeable_dirty(object);
1236	return (mold);
1237}
1238
1239/*
1240 *	vm_page_rename:
1241 *
1242 *	Move the given memory entry from its
1243 *	current object to the specified target object/offset.
1244 *
1245 *	Note: swap associated with the page must be invalidated by the move.  We
1246 *	      have to do this for several reasons:  (1) we aren't freeing the
1247 *	      page, (2) we are dirtying the page, (3) the VM system is probably
1248 *	      moving the page from object A to B, and will then later move
1249 *	      the backing store from A to B and we can't have a conflict.
1250 *
1251 *	Note: we *always* dirty the page.  It is necessary both for the
1252 *	      fact that we moved it, and because we may be invalidating
1253 *	      swap.  If the page is on the cache, we have to deactivate it
1254 *	      or vm_page_dirty() will panic.  Dirty pages are not allowed
1255 *	      on the cache.
1256 *
1257 *	The objects must be locked.
1258 */
1259int
1260vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1261{
1262	vm_page_t mpred;
1263	vm_pindex_t opidx;
1264
1265	VM_OBJECT_ASSERT_WLOCKED(new_object);
1266
1267	mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1268	KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1269	    ("vm_page_rename: pindex already renamed"));
1270
1271	/*
1272	 * Create a custom version of vm_page_insert() which does not depend
1273	 * by m_prev and can cheat on the implementation aspects of the
1274	 * function.
1275	 */
1276	opidx = m->pindex;
1277	m->pindex = new_pindex;
1278	if (vm_radix_insert(&new_object->rtree, m)) {
1279		m->pindex = opidx;
1280		return (1);
1281	}
1282
1283	/*
1284	 * The operation cannot fail anymore.  The removal must happen before
1285	 * the listq iterator is tainted.
1286	 */
1287	m->pindex = opidx;
1288	vm_page_lock(m);
1289	vm_page_remove(m);
1290
1291	/* Return back to the new pindex to complete vm_page_insert(). */
1292	m->pindex = new_pindex;
1293	m->object = new_object;
1294	vm_page_unlock(m);
1295	vm_page_insert_radixdone(m, new_object, mpred);
1296	vm_page_dirty(m);
1297	return (0);
1298}
1299
1300/*
1301 *	Convert all of the given object's cached pages that have a
1302 *	pindex within the given range into free pages.  If the value
1303 *	zero is given for "end", then the range's upper bound is
1304 *	infinity.  If the given object is backed by a vnode and it
1305 *	transitions from having one or more cached pages to none, the
1306 *	vnode's hold count is reduced.
1307 */
1308void
1309vm_page_cache_free(vm_object_t object, vm_pindex_t start, vm_pindex_t end)
1310{
1311	vm_page_t m;
1312	boolean_t empty;
1313
1314	mtx_lock(&vm_page_queue_free_mtx);
1315	if (__predict_false(vm_radix_is_empty(&object->cache))) {
1316		mtx_unlock(&vm_page_queue_free_mtx);
1317		return;
1318	}
1319	while ((m = vm_radix_lookup_ge(&object->cache, start)) != NULL) {
1320		if (end != 0 && m->pindex >= end)
1321			break;
1322		vm_radix_remove(&object->cache, m->pindex);
1323		vm_page_cache_turn_free(m);
1324	}
1325	empty = vm_radix_is_empty(&object->cache);
1326	mtx_unlock(&vm_page_queue_free_mtx);
1327	if (object->type == OBJT_VNODE && empty)
1328		vdrop(object->handle);
1329}
1330
1331/*
1332 *	Returns the cached page that is associated with the given
1333 *	object and offset.  If, however, none exists, returns NULL.
1334 *
1335 *	The free page queue must be locked.
1336 */
1337static inline vm_page_t
1338vm_page_cache_lookup(vm_object_t object, vm_pindex_t pindex)
1339{
1340
1341	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1342	return (vm_radix_lookup(&object->cache, pindex));
1343}
1344
1345/*
1346 *	Remove the given cached page from its containing object's
1347 *	collection of cached pages.
1348 *
1349 *	The free page queue must be locked.
1350 */
1351static void
1352vm_page_cache_remove(vm_page_t m)
1353{
1354
1355	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1356	KASSERT((m->flags & PG_CACHED) != 0,
1357	    ("vm_page_cache_remove: page %p is not cached", m));
1358	vm_radix_remove(&m->object->cache, m->pindex);
1359	m->object = NULL;
1360	vm_cnt.v_cache_count--;
1361}
1362
1363/*
1364 *	Transfer all of the cached pages with offset greater than or
1365 *	equal to 'offidxstart' from the original object's cache to the
1366 *	new object's cache.  However, any cached pages with offset
1367 *	greater than or equal to the new object's size are kept in the
1368 *	original object.  Initially, the new object's cache must be
1369 *	empty.  Offset 'offidxstart' in the original object must
1370 *	correspond to offset zero in the new object.
1371 *
1372 *	The new object must be locked.
1373 */
1374void
1375vm_page_cache_transfer(vm_object_t orig_object, vm_pindex_t offidxstart,
1376    vm_object_t new_object)
1377{
1378	vm_page_t m;
1379
1380	/*
1381	 * Insertion into an object's collection of cached pages
1382	 * requires the object to be locked.  In contrast, removal does
1383	 * not.
1384	 */
1385	VM_OBJECT_ASSERT_WLOCKED(new_object);
1386	KASSERT(vm_radix_is_empty(&new_object->cache),
1387	    ("vm_page_cache_transfer: object %p has cached pages",
1388	    new_object));
1389	mtx_lock(&vm_page_queue_free_mtx);
1390	while ((m = vm_radix_lookup_ge(&orig_object->cache,
1391	    offidxstart)) != NULL) {
1392		/*
1393		 * Transfer all of the pages with offset greater than or
1394		 * equal to 'offidxstart' from the original object's
1395		 * cache to the new object's cache.
1396		 */
1397		if ((m->pindex - offidxstart) >= new_object->size)
1398			break;
1399		vm_radix_remove(&orig_object->cache, m->pindex);
1400		/* Update the page's object and offset. */
1401		m->object = new_object;
1402		m->pindex -= offidxstart;
1403		if (vm_radix_insert(&new_object->cache, m))
1404			vm_page_cache_turn_free(m);
1405	}
1406	mtx_unlock(&vm_page_queue_free_mtx);
1407}
1408
1409/*
1410 *	Returns TRUE if a cached page is associated with the given object and
1411 *	offset, and FALSE otherwise.
1412 *
1413 *	The object must be locked.
1414 */
1415boolean_t
1416vm_page_is_cached(vm_object_t object, vm_pindex_t pindex)
1417{
1418	vm_page_t m;
1419
1420	/*
1421	 * Insertion into an object's collection of cached pages requires the
1422	 * object to be locked.  Therefore, if the object is locked and the
1423	 * object's collection is empty, there is no need to acquire the free
1424	 * page queues lock in order to prove that the specified page doesn't
1425	 * exist.
1426	 */
1427	VM_OBJECT_ASSERT_WLOCKED(object);
1428	if (__predict_true(vm_object_cache_is_empty(object)))
1429		return (FALSE);
1430	mtx_lock(&vm_page_queue_free_mtx);
1431	m = vm_page_cache_lookup(object, pindex);
1432	mtx_unlock(&vm_page_queue_free_mtx);
1433	return (m != NULL);
1434}
1435
1436/*
1437 *	vm_page_alloc:
1438 *
1439 *	Allocate and return a page that is associated with the specified
1440 *	object and offset pair.  By default, this page is exclusive busied.
1441 *
1442 *	The caller must always specify an allocation class.
1443 *
1444 *	allocation classes:
1445 *	VM_ALLOC_NORMAL		normal process request
1446 *	VM_ALLOC_SYSTEM		system *really* needs a page
1447 *	VM_ALLOC_INTERRUPT	interrupt time request
1448 *
1449 *	optional allocation flags:
1450 *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1451 *				intends to allocate
1452 *	VM_ALLOC_IFCACHED	return page only if it is cached
1453 *	VM_ALLOC_IFNOTCACHED	return NULL, do not reactivate if the page
1454 *				is cached
1455 *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1456 *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1457 *	VM_ALLOC_NOOBJ		page is not associated with an object and
1458 *				should not be exclusive busy
1459 *	VM_ALLOC_SBUSY		shared busy the allocated page
1460 *	VM_ALLOC_WIRED		wire the allocated page
1461 *	VM_ALLOC_ZERO		prefer a zeroed page
1462 *
1463 *	This routine may not sleep.
1464 */
1465vm_page_t
1466vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1467{
1468	struct vnode *vp = NULL;
1469	vm_object_t m_object;
1470	vm_page_t m, mpred;
1471	int flags, req_class;
1472
1473	mpred = 0;	/* XXX: pacify gcc */
1474	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1475	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1476	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1477	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1478	    ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1479	    req));
1480	if (object != NULL)
1481		VM_OBJECT_ASSERT_WLOCKED(object);
1482
1483	req_class = req & VM_ALLOC_CLASS_MASK;
1484
1485	/*
1486	 * The page daemon is allowed to dig deeper into the free page list.
1487	 */
1488	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1489		req_class = VM_ALLOC_SYSTEM;
1490
1491	if (object != NULL) {
1492		mpred = vm_radix_lookup_le(&object->rtree, pindex);
1493		KASSERT(mpred == NULL || mpred->pindex != pindex,
1494		   ("vm_page_alloc: pindex already allocated"));
1495	}
1496
1497	/*
1498	 * The page allocation request can came from consumers which already
1499	 * hold the free page queue mutex, like vm_page_insert() in
1500	 * vm_page_cache().
1501	 */
1502	mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1503	if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1504	    (req_class == VM_ALLOC_SYSTEM &&
1505	    vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1506	    (req_class == VM_ALLOC_INTERRUPT &&
1507	    vm_cnt.v_free_count + vm_cnt.v_cache_count > 0)) {
1508		/*
1509		 * Allocate from the free queue if the number of free pages
1510		 * exceeds the minimum for the request class.
1511		 */
1512		if (object != NULL &&
1513		    (m = vm_page_cache_lookup(object, pindex)) != NULL) {
1514			if ((req & VM_ALLOC_IFNOTCACHED) != 0) {
1515				mtx_unlock(&vm_page_queue_free_mtx);
1516				return (NULL);
1517			}
1518			if (vm_phys_unfree_page(m))
1519				vm_phys_set_pool(VM_FREEPOOL_DEFAULT, m, 0);
1520#if VM_NRESERVLEVEL > 0
1521			else if (!vm_reserv_reactivate_page(m))
1522#else
1523			else
1524#endif
1525				panic("vm_page_alloc: cache page %p is missing"
1526				    " from the free queue", m);
1527		} else if ((req & VM_ALLOC_IFCACHED) != 0) {
1528			mtx_unlock(&vm_page_queue_free_mtx);
1529			return (NULL);
1530#if VM_NRESERVLEVEL > 0
1531		} else if (object == NULL || (object->flags & (OBJ_COLORED |
1532		    OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1533		    vm_reserv_alloc_page(object, pindex, mpred)) == NULL) {
1534#else
1535		} else {
1536#endif
1537			m = vm_phys_alloc_pages(object != NULL ?
1538			    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1539#if VM_NRESERVLEVEL > 0
1540			if (m == NULL && vm_reserv_reclaim_inactive()) {
1541				m = vm_phys_alloc_pages(object != NULL ?
1542				    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1543				    0);
1544			}
1545#endif
1546		}
1547	} else {
1548		/*
1549		 * Not allocatable, give up.
1550		 */
1551		mtx_unlock(&vm_page_queue_free_mtx);
1552		atomic_add_int(&vm_pageout_deficit,
1553		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1554		pagedaemon_wakeup();
1555		return (NULL);
1556	}
1557
1558	/*
1559	 *  At this point we had better have found a good page.
1560	 */
1561	KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1562	KASSERT(m->queue == PQ_NONE,
1563	    ("vm_page_alloc: page %p has unexpected queue %d", m, m->queue));
1564	KASSERT(m->wire_count == 0, ("vm_page_alloc: page %p is wired", m));
1565	KASSERT(m->hold_count == 0, ("vm_page_alloc: page %p is held", m));
1566	KASSERT(!vm_page_sbusied(m),
1567	    ("vm_page_alloc: page %p is busy", m));
1568	KASSERT(m->dirty == 0, ("vm_page_alloc: page %p is dirty", m));
1569	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1570	    ("vm_page_alloc: page %p has unexpected memattr %d", m,
1571	    pmap_page_get_memattr(m)));
1572	if ((m->flags & PG_CACHED) != 0) {
1573		KASSERT((m->flags & PG_ZERO) == 0,
1574		    ("vm_page_alloc: cached page %p is PG_ZERO", m));
1575		KASSERT(m->valid != 0,
1576		    ("vm_page_alloc: cached page %p is invalid", m));
1577		if (m->object == object && m->pindex == pindex)
1578			vm_cnt.v_reactivated++;
1579		else
1580			m->valid = 0;
1581		m_object = m->object;
1582		vm_page_cache_remove(m);
1583		if (m_object->type == OBJT_VNODE &&
1584		    vm_object_cache_is_empty(m_object))
1585			vp = m_object->handle;
1586	} else {
1587		KASSERT(m->valid == 0,
1588		    ("vm_page_alloc: free page %p is valid", m));
1589		vm_phys_freecnt_adj(m, -1);
1590		if ((m->flags & PG_ZERO) != 0)
1591			vm_page_zero_count--;
1592	}
1593	mtx_unlock(&vm_page_queue_free_mtx);
1594
1595	/*
1596	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1597	 */
1598	flags = 0;
1599	if ((req & VM_ALLOC_ZERO) != 0)
1600		flags = PG_ZERO;
1601	flags &= m->flags;
1602	if ((req & VM_ALLOC_NODUMP) != 0)
1603		flags |= PG_NODUMP;
1604	m->flags = flags;
1605	m->aflags = 0;
1606	m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1607	    VPO_UNMANAGED : 0;
1608	m->busy_lock = VPB_UNBUSIED;
1609	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1610		m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1611	if ((req & VM_ALLOC_SBUSY) != 0)
1612		m->busy_lock = VPB_SHARERS_WORD(1);
1613	if (req & VM_ALLOC_WIRED) {
1614		/*
1615		 * The page lock is not required for wiring a page until that
1616		 * page is inserted into the object.
1617		 */
1618		atomic_add_int(&vm_cnt.v_wire_count, 1);
1619		m->wire_count = 1;
1620	}
1621	m->act_count = 0;
1622
1623	if (object != NULL) {
1624		if (vm_page_insert_after(m, object, pindex, mpred)) {
1625			/* See the comment below about hold count. */
1626			if (vp != NULL)
1627				vdrop(vp);
1628			pagedaemon_wakeup();
1629			if (req & VM_ALLOC_WIRED) {
1630				atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1631				m->wire_count = 0;
1632			}
1633			m->object = NULL;
1634			vm_page_free(m);
1635			return (NULL);
1636		}
1637
1638		/* Ignore device objects; the pager sets "memattr" for them. */
1639		if (object->memattr != VM_MEMATTR_DEFAULT &&
1640		    (object->flags & OBJ_FICTITIOUS) == 0)
1641			pmap_page_set_memattr(m, object->memattr);
1642	} else
1643		m->pindex = pindex;
1644
1645	/*
1646	 * The following call to vdrop() must come after the above call
1647	 * to vm_page_insert() in case both affect the same object and
1648	 * vnode.  Otherwise, the affected vnode's hold count could
1649	 * temporarily become zero.
1650	 */
1651	if (vp != NULL)
1652		vdrop(vp);
1653
1654	/*
1655	 * Don't wakeup too often - wakeup the pageout daemon when
1656	 * we would be nearly out of memory.
1657	 */
1658	if (vm_paging_needed())
1659		pagedaemon_wakeup();
1660
1661	return (m);
1662}
1663
1664static void
1665vm_page_alloc_contig_vdrop(struct spglist *lst)
1666{
1667
1668	while (!SLIST_EMPTY(lst)) {
1669		vdrop((struct vnode *)SLIST_FIRST(lst)-> plinks.s.pv);
1670		SLIST_REMOVE_HEAD(lst, plinks.s.ss);
1671	}
1672}
1673
1674/*
1675 *	vm_page_alloc_contig:
1676 *
1677 *	Allocate a contiguous set of physical pages of the given size "npages"
1678 *	from the free lists.  All of the physical pages must be at or above
1679 *	the given physical address "low" and below the given physical address
1680 *	"high".  The given value "alignment" determines the alignment of the
1681 *	first physical page in the set.  If the given value "boundary" is
1682 *	non-zero, then the set of physical pages cannot cross any physical
1683 *	address boundary that is a multiple of that value.  Both "alignment"
1684 *	and "boundary" must be a power of two.
1685 *
1686 *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1687 *	then the memory attribute setting for the physical pages is configured
1688 *	to the object's memory attribute setting.  Otherwise, the memory
1689 *	attribute setting for the physical pages is configured to "memattr",
1690 *	overriding the object's memory attribute setting.  However, if the
1691 *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1692 *	memory attribute setting for the physical pages cannot be configured
1693 *	to VM_MEMATTR_DEFAULT.
1694 *
1695 *	The caller must always specify an allocation class.
1696 *
1697 *	allocation classes:
1698 *	VM_ALLOC_NORMAL		normal process request
1699 *	VM_ALLOC_SYSTEM		system *really* needs a page
1700 *	VM_ALLOC_INTERRUPT	interrupt time request
1701 *
1702 *	optional allocation flags:
1703 *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1704 *	VM_ALLOC_NOOBJ		page is not associated with an object and
1705 *				should not be exclusive busy
1706 *	VM_ALLOC_SBUSY		shared busy the allocated page
1707 *	VM_ALLOC_WIRED		wire the allocated page
1708 *	VM_ALLOC_ZERO		prefer a zeroed page
1709 *
1710 *	This routine may not sleep.
1711 */
1712vm_page_t
1713vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1714    u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1715    vm_paddr_t boundary, vm_memattr_t memattr)
1716{
1717	struct vnode *drop;
1718	struct spglist deferred_vdrop_list;
1719	vm_page_t m, m_tmp, m_ret;
1720	u_int flags;
1721	int req_class;
1722
1723	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1724	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1725	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1726	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1727	    ("vm_page_alloc: inconsistent object(%p)/req(%x)", (void *)object,
1728	    req));
1729	if (object != NULL) {
1730		VM_OBJECT_ASSERT_WLOCKED(object);
1731		KASSERT(object->type == OBJT_PHYS,
1732		    ("vm_page_alloc_contig: object %p isn't OBJT_PHYS",
1733		    object));
1734	}
1735	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1736	req_class = req & VM_ALLOC_CLASS_MASK;
1737
1738	/*
1739	 * The page daemon is allowed to dig deeper into the free page list.
1740	 */
1741	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1742		req_class = VM_ALLOC_SYSTEM;
1743
1744	SLIST_INIT(&deferred_vdrop_list);
1745	mtx_lock(&vm_page_queue_free_mtx);
1746	if (vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1747	    vm_cnt.v_free_reserved || (req_class == VM_ALLOC_SYSTEM &&
1748	    vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages +
1749	    vm_cnt.v_interrupt_free_min) || (req_class == VM_ALLOC_INTERRUPT &&
1750	    vm_cnt.v_free_count + vm_cnt.v_cache_count >= npages)) {
1751#if VM_NRESERVLEVEL > 0
1752retry:
1753		if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1754		    (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1755		    low, high, alignment, boundary)) == NULL)
1756#endif
1757			m_ret = vm_phys_alloc_contig(npages, low, high,
1758			    alignment, boundary);
1759	} else {
1760		mtx_unlock(&vm_page_queue_free_mtx);
1761		atomic_add_int(&vm_pageout_deficit, npages);
1762		pagedaemon_wakeup();
1763		return (NULL);
1764	}
1765	if (m_ret != NULL)
1766		for (m = m_ret; m < &m_ret[npages]; m++) {
1767			drop = vm_page_alloc_init(m);
1768			if (drop != NULL) {
1769				/*
1770				 * Enqueue the vnode for deferred vdrop().
1771				 */
1772				m->plinks.s.pv = drop;
1773				SLIST_INSERT_HEAD(&deferred_vdrop_list, m,
1774				    plinks.s.ss);
1775			}
1776		}
1777	else {
1778#if VM_NRESERVLEVEL > 0
1779		if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1780		    boundary))
1781			goto retry;
1782#endif
1783	}
1784	mtx_unlock(&vm_page_queue_free_mtx);
1785	if (m_ret == NULL)
1786		return (NULL);
1787
1788	/*
1789	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
1790	 */
1791	flags = 0;
1792	if ((req & VM_ALLOC_ZERO) != 0)
1793		flags = PG_ZERO;
1794	if ((req & VM_ALLOC_NODUMP) != 0)
1795		flags |= PG_NODUMP;
1796	if ((req & VM_ALLOC_WIRED) != 0)
1797		atomic_add_int(&vm_cnt.v_wire_count, npages);
1798	if (object != NULL) {
1799		if (object->memattr != VM_MEMATTR_DEFAULT &&
1800		    memattr == VM_MEMATTR_DEFAULT)
1801			memattr = object->memattr;
1802	}
1803	for (m = m_ret; m < &m_ret[npages]; m++) {
1804		m->aflags = 0;
1805		m->flags = (m->flags | PG_NODUMP) & flags;
1806		m->busy_lock = VPB_UNBUSIED;
1807		if (object != NULL) {
1808			if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
1809				m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1810			if ((req & VM_ALLOC_SBUSY) != 0)
1811				m->busy_lock = VPB_SHARERS_WORD(1);
1812		}
1813		if ((req & VM_ALLOC_WIRED) != 0)
1814			m->wire_count = 1;
1815		/* Unmanaged pages don't use "act_count". */
1816		m->oflags = VPO_UNMANAGED;
1817		if (object != NULL) {
1818			if (vm_page_insert(m, object, pindex)) {
1819				vm_page_alloc_contig_vdrop(
1820				    &deferred_vdrop_list);
1821				if (vm_paging_needed())
1822					pagedaemon_wakeup();
1823				if ((req & VM_ALLOC_WIRED) != 0)
1824					atomic_subtract_int(&vm_cnt.v_wire_count,
1825					    npages);
1826				for (m_tmp = m, m = m_ret;
1827				    m < &m_ret[npages]; m++) {
1828					if ((req & VM_ALLOC_WIRED) != 0)
1829						m->wire_count = 0;
1830					if (m >= m_tmp)
1831						m->object = NULL;
1832					vm_page_free(m);
1833				}
1834				return (NULL);
1835			}
1836		} else
1837			m->pindex = pindex;
1838		if (memattr != VM_MEMATTR_DEFAULT)
1839			pmap_page_set_memattr(m, memattr);
1840		pindex++;
1841	}
1842	vm_page_alloc_contig_vdrop(&deferred_vdrop_list);
1843	if (vm_paging_needed())
1844		pagedaemon_wakeup();
1845	return (m_ret);
1846}
1847
1848/*
1849 * Initialize a page that has been freshly dequeued from a freelist.
1850 * The caller has to drop the vnode returned, if it is not NULL.
1851 *
1852 * This function may only be used to initialize unmanaged pages.
1853 *
1854 * To be called with vm_page_queue_free_mtx held.
1855 */
1856static struct vnode *
1857vm_page_alloc_init(vm_page_t m)
1858{
1859	struct vnode *drop;
1860	vm_object_t m_object;
1861
1862	KASSERT(m->queue == PQ_NONE,
1863	    ("vm_page_alloc_init: page %p has unexpected queue %d",
1864	    m, m->queue));
1865	KASSERT(m->wire_count == 0,
1866	    ("vm_page_alloc_init: page %p is wired", m));
1867	KASSERT(m->hold_count == 0,
1868	    ("vm_page_alloc_init: page %p is held", m));
1869	KASSERT(!vm_page_sbusied(m),
1870	    ("vm_page_alloc_init: page %p is busy", m));
1871	KASSERT(m->dirty == 0,
1872	    ("vm_page_alloc_init: page %p is dirty", m));
1873	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1874	    ("vm_page_alloc_init: page %p has unexpected memattr %d",
1875	    m, pmap_page_get_memattr(m)));
1876	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
1877	drop = NULL;
1878	if ((m->flags & PG_CACHED) != 0) {
1879		KASSERT((m->flags & PG_ZERO) == 0,
1880		    ("vm_page_alloc_init: cached page %p is PG_ZERO", m));
1881		m->valid = 0;
1882		m_object = m->object;
1883		vm_page_cache_remove(m);
1884		if (m_object->type == OBJT_VNODE &&
1885		    vm_object_cache_is_empty(m_object))
1886			drop = m_object->handle;
1887	} else {
1888		KASSERT(m->valid == 0,
1889		    ("vm_page_alloc_init: free page %p is valid", m));
1890		vm_phys_freecnt_adj(m, -1);
1891		if ((m->flags & PG_ZERO) != 0)
1892			vm_page_zero_count--;
1893	}
1894	return (drop);
1895}
1896
1897/*
1898 * 	vm_page_alloc_freelist:
1899 *
1900 *	Allocate a physical page from the specified free page list.
1901 *
1902 *	The caller must always specify an allocation class.
1903 *
1904 *	allocation classes:
1905 *	VM_ALLOC_NORMAL		normal process request
1906 *	VM_ALLOC_SYSTEM		system *really* needs a page
1907 *	VM_ALLOC_INTERRUPT	interrupt time request
1908 *
1909 *	optional allocation flags:
1910 *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1911 *				intends to allocate
1912 *	VM_ALLOC_WIRED		wire the allocated page
1913 *	VM_ALLOC_ZERO		prefer a zeroed page
1914 *
1915 *	This routine may not sleep.
1916 */
1917vm_page_t
1918vm_page_alloc_freelist(int flind, int req)
1919{
1920	struct vnode *drop;
1921	vm_page_t m;
1922	u_int flags;
1923	int req_class;
1924
1925	req_class = req & VM_ALLOC_CLASS_MASK;
1926
1927	/*
1928	 * The page daemon is allowed to dig deeper into the free page list.
1929	 */
1930	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1931		req_class = VM_ALLOC_SYSTEM;
1932
1933	/*
1934	 * Do not allocate reserved pages unless the req has asked for it.
1935	 */
1936	mtx_lock_flags(&vm_page_queue_free_mtx, MTX_RECURSE);
1937	if (vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_free_reserved ||
1938	    (req_class == VM_ALLOC_SYSTEM &&
1939	    vm_cnt.v_free_count + vm_cnt.v_cache_count > vm_cnt.v_interrupt_free_min) ||
1940	    (req_class == VM_ALLOC_INTERRUPT &&
1941	    vm_cnt.v_free_count + vm_cnt.v_cache_count > 0))
1942		m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1943	else {
1944		mtx_unlock(&vm_page_queue_free_mtx);
1945		atomic_add_int(&vm_pageout_deficit,
1946		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1947		pagedaemon_wakeup();
1948		return (NULL);
1949	}
1950	if (m == NULL) {
1951		mtx_unlock(&vm_page_queue_free_mtx);
1952		return (NULL);
1953	}
1954	drop = vm_page_alloc_init(m);
1955	mtx_unlock(&vm_page_queue_free_mtx);
1956
1957	/*
1958	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1959	 */
1960	m->aflags = 0;
1961	flags = 0;
1962	if ((req & VM_ALLOC_ZERO) != 0)
1963		flags = PG_ZERO;
1964	m->flags &= flags;
1965	if ((req & VM_ALLOC_WIRED) != 0) {
1966		/*
1967		 * The page lock is not required for wiring a page that does
1968		 * not belong to an object.
1969		 */
1970		atomic_add_int(&vm_cnt.v_wire_count, 1);
1971		m->wire_count = 1;
1972	}
1973	/* Unmanaged pages don't use "act_count". */
1974	m->oflags = VPO_UNMANAGED;
1975	if (drop != NULL)
1976		vdrop(drop);
1977	if (vm_paging_needed())
1978		pagedaemon_wakeup();
1979	return (m);
1980}
1981
1982/*
1983 *	vm_wait:	(also see VM_WAIT macro)
1984 *
1985 *	Sleep until free pages are available for allocation.
1986 *	- Called in various places before memory allocations.
1987 */
1988void
1989vm_wait(void)
1990{
1991
1992	mtx_lock(&vm_page_queue_free_mtx);
1993	if (curproc == pageproc) {
1994		vm_pageout_pages_needed = 1;
1995		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
1996		    PDROP | PSWP, "VMWait", 0);
1997	} else {
1998		if (!vm_pages_needed) {
1999			vm_pages_needed = 1;
2000			wakeup(&vm_pages_needed);
2001		}
2002		msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2003		    "vmwait", 0);
2004	}
2005}
2006
2007/*
2008 *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
2009 *
2010 *	Sleep until free pages are available for allocation.
2011 *	- Called only in vm_fault so that processes page faulting
2012 *	  can be easily tracked.
2013 *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2014 *	  processes will be able to grab memory first.  Do not change
2015 *	  this balance without careful testing first.
2016 */
2017void
2018vm_waitpfault(void)
2019{
2020
2021	mtx_lock(&vm_page_queue_free_mtx);
2022	if (!vm_pages_needed) {
2023		vm_pages_needed = 1;
2024		wakeup(&vm_pages_needed);
2025	}
2026	msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2027	    "pfault", 0);
2028}
2029
2030struct vm_pagequeue *
2031vm_page_pagequeue(vm_page_t m)
2032{
2033
2034	return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2035}
2036
2037/*
2038 *	vm_page_dequeue:
2039 *
2040 *	Remove the given page from its current page queue.
2041 *
2042 *	The page must be locked.
2043 */
2044void
2045vm_page_dequeue(vm_page_t m)
2046{
2047	struct vm_pagequeue *pq;
2048
2049	vm_page_assert_locked(m);
2050	KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2051	    m));
2052	pq = vm_page_pagequeue(m);
2053	vm_pagequeue_lock(pq);
2054	m->queue = PQ_NONE;
2055	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2056	vm_pagequeue_cnt_dec(pq);
2057	vm_pagequeue_unlock(pq);
2058}
2059
2060/*
2061 *	vm_page_dequeue_locked:
2062 *
2063 *	Remove the given page from its current page queue.
2064 *
2065 *	The page and page queue must be locked.
2066 */
2067void
2068vm_page_dequeue_locked(vm_page_t m)
2069{
2070	struct vm_pagequeue *pq;
2071
2072	vm_page_lock_assert(m, MA_OWNED);
2073	pq = vm_page_pagequeue(m);
2074	vm_pagequeue_assert_locked(pq);
2075	m->queue = PQ_NONE;
2076	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2077	vm_pagequeue_cnt_dec(pq);
2078}
2079
2080/*
2081 *	vm_page_enqueue:
2082 *
2083 *	Add the given page to the specified page queue.
2084 *
2085 *	The page must be locked.
2086 */
2087static void
2088vm_page_enqueue(uint8_t queue, vm_page_t m)
2089{
2090	struct vm_pagequeue *pq;
2091
2092	vm_page_lock_assert(m, MA_OWNED);
2093	KASSERT(queue < PQ_COUNT,
2094	    ("vm_page_enqueue: invalid queue %u request for page %p",
2095	    queue, m));
2096	pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2097	vm_pagequeue_lock(pq);
2098	m->queue = queue;
2099	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2100	vm_pagequeue_cnt_inc(pq);
2101	vm_pagequeue_unlock(pq);
2102}
2103
2104/*
2105 *	vm_page_requeue:
2106 *
2107 *	Move the given page to the tail of its current page queue.
2108 *
2109 *	The page must be locked.
2110 */
2111void
2112vm_page_requeue(vm_page_t m)
2113{
2114	struct vm_pagequeue *pq;
2115
2116	vm_page_lock_assert(m, MA_OWNED);
2117	KASSERT(m->queue != PQ_NONE,
2118	    ("vm_page_requeue: page %p is not queued", m));
2119	pq = vm_page_pagequeue(m);
2120	vm_pagequeue_lock(pq);
2121	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2122	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2123	vm_pagequeue_unlock(pq);
2124}
2125
2126/*
2127 *	vm_page_requeue_locked:
2128 *
2129 *	Move the given page to the tail of its current page queue.
2130 *
2131 *	The page queue must be locked.
2132 */
2133void
2134vm_page_requeue_locked(vm_page_t m)
2135{
2136	struct vm_pagequeue *pq;
2137
2138	KASSERT(m->queue != PQ_NONE,
2139	    ("vm_page_requeue_locked: page %p is not queued", m));
2140	pq = vm_page_pagequeue(m);
2141	vm_pagequeue_assert_locked(pq);
2142	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2143	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2144}
2145
2146/*
2147 *	vm_page_activate:
2148 *
2149 *	Put the specified page on the active list (if appropriate).
2150 *	Ensure that act_count is at least ACT_INIT but do not otherwise
2151 *	mess with it.
2152 *
2153 *	The page must be locked.
2154 */
2155void
2156vm_page_activate(vm_page_t m)
2157{
2158	int queue;
2159
2160	vm_page_lock_assert(m, MA_OWNED);
2161	if ((queue = m->queue) != PQ_ACTIVE) {
2162		if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2163			if (m->act_count < ACT_INIT)
2164				m->act_count = ACT_INIT;
2165			if (queue != PQ_NONE)
2166				vm_page_dequeue(m);
2167			vm_page_enqueue(PQ_ACTIVE, m);
2168		} else
2169			KASSERT(queue == PQ_NONE,
2170			    ("vm_page_activate: wired page %p is queued", m));
2171	} else {
2172		if (m->act_count < ACT_INIT)
2173			m->act_count = ACT_INIT;
2174	}
2175}
2176
2177/*
2178 *	vm_page_free_wakeup:
2179 *
2180 *	Helper routine for vm_page_free_toq() and vm_page_cache().  This
2181 *	routine is called when a page has been added to the cache or free
2182 *	queues.
2183 *
2184 *	The page queues must be locked.
2185 */
2186static inline void
2187vm_page_free_wakeup(void)
2188{
2189
2190	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2191	/*
2192	 * if pageout daemon needs pages, then tell it that there are
2193	 * some free.
2194	 */
2195	if (vm_pageout_pages_needed &&
2196	    vm_cnt.v_cache_count + vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2197		wakeup(&vm_pageout_pages_needed);
2198		vm_pageout_pages_needed = 0;
2199	}
2200	/*
2201	 * wakeup processes that are waiting on memory if we hit a
2202	 * high water mark. And wakeup scheduler process if we have
2203	 * lots of memory. this process will swapin processes.
2204	 */
2205	if (vm_pages_needed && !vm_page_count_min()) {
2206		vm_pages_needed = 0;
2207		wakeup(&vm_cnt.v_free_count);
2208	}
2209}
2210
2211/*
2212 *	Turn a cached page into a free page, by changing its attributes.
2213 *	Keep the statistics up-to-date.
2214 *
2215 *	The free page queue must be locked.
2216 */
2217static void
2218vm_page_cache_turn_free(vm_page_t m)
2219{
2220
2221	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2222
2223	m->object = NULL;
2224	m->valid = 0;
2225	KASSERT((m->flags & PG_CACHED) != 0,
2226	    ("vm_page_cache_turn_free: page %p is not cached", m));
2227	m->flags &= ~PG_CACHED;
2228	vm_cnt.v_cache_count--;
2229	vm_phys_freecnt_adj(m, 1);
2230}
2231
2232/*
2233 *	vm_page_free_toq:
2234 *
2235 *	Returns the given page to the free list,
2236 *	disassociating it with any VM object.
2237 *
2238 *	The object must be locked.  The page must be locked if it is managed.
2239 */
2240void
2241vm_page_free_toq(vm_page_t m)
2242{
2243
2244	if ((m->oflags & VPO_UNMANAGED) == 0) {
2245		vm_page_lock_assert(m, MA_OWNED);
2246		KASSERT(!pmap_page_is_mapped(m),
2247		    ("vm_page_free_toq: freeing mapped page %p", m));
2248	} else
2249		KASSERT(m->queue == PQ_NONE,
2250		    ("vm_page_free_toq: unmanaged page %p is queued", m));
2251	PCPU_INC(cnt.v_tfree);
2252
2253	if (vm_page_sbusied(m))
2254		panic("vm_page_free: freeing busy page %p", m);
2255
2256	/*
2257	 * Unqueue, then remove page.  Note that we cannot destroy
2258	 * the page here because we do not want to call the pager's
2259	 * callback routine until after we've put the page on the
2260	 * appropriate free queue.
2261	 */
2262	vm_page_remque(m);
2263	vm_page_remove(m);
2264
2265	/*
2266	 * If fictitious remove object association and
2267	 * return, otherwise delay object association removal.
2268	 */
2269	if ((m->flags & PG_FICTITIOUS) != 0) {
2270		return;
2271	}
2272
2273	m->valid = 0;
2274	vm_page_undirty(m);
2275
2276	if (m->wire_count != 0)
2277		panic("vm_page_free: freeing wired page %p", m);
2278	if (m->hold_count != 0) {
2279		m->flags &= ~PG_ZERO;
2280		KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2281		    ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2282		m->flags |= PG_UNHOLDFREE;
2283	} else {
2284		/*
2285		 * Restore the default memory attribute to the page.
2286		 */
2287		if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2288			pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2289
2290		/*
2291		 * Insert the page into the physical memory allocator's
2292		 * cache/free page queues.
2293		 */
2294		mtx_lock(&vm_page_queue_free_mtx);
2295		vm_phys_freecnt_adj(m, 1);
2296#if VM_NRESERVLEVEL > 0
2297		if (!vm_reserv_free_page(m))
2298#else
2299		if (TRUE)
2300#endif
2301			vm_phys_free_pages(m, 0);
2302		if ((m->flags & PG_ZERO) != 0)
2303			++vm_page_zero_count;
2304		else
2305			vm_page_zero_idle_wakeup();
2306		vm_page_free_wakeup();
2307		mtx_unlock(&vm_page_queue_free_mtx);
2308	}
2309}
2310
2311/*
2312 *	vm_page_wire:
2313 *
2314 *	Mark this page as wired down by yet
2315 *	another map, removing it from paging queues
2316 *	as necessary.
2317 *
2318 *	If the page is fictitious, then its wire count must remain one.
2319 *
2320 *	The page must be locked.
2321 */
2322void
2323vm_page_wire(vm_page_t m)
2324{
2325
2326	/*
2327	 * Only bump the wire statistics if the page is not already wired,
2328	 * and only unqueue the page if it is on some queue (if it is unmanaged
2329	 * it is already off the queues).
2330	 */
2331	vm_page_lock_assert(m, MA_OWNED);
2332	if ((m->flags & PG_FICTITIOUS) != 0) {
2333		KASSERT(m->wire_count == 1,
2334		    ("vm_page_wire: fictitious page %p's wire count isn't one",
2335		    m));
2336		return;
2337	}
2338	if (m->wire_count == 0) {
2339		KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2340		    m->queue == PQ_NONE,
2341		    ("vm_page_wire: unmanaged page %p is queued", m));
2342		vm_page_remque(m);
2343		atomic_add_int(&vm_cnt.v_wire_count, 1);
2344	}
2345	m->wire_count++;
2346	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2347}
2348
2349/*
2350 * vm_page_unwire:
2351 *
2352 * Release one wiring of the specified page, potentially enabling it to be
2353 * paged again.  If paging is enabled, then the value of the parameter
2354 * "queue" determines the queue to which the page is added.
2355 *
2356 * However, unless the page belongs to an object, it is not enqueued because
2357 * it cannot be paged out.
2358 *
2359 * If a page is fictitious, then its wire count must always be one.
2360 *
2361 * A managed page must be locked.
2362 */
2363void
2364vm_page_unwire(vm_page_t m, uint8_t queue)
2365{
2366
2367	KASSERT(queue < PQ_COUNT,
2368	    ("vm_page_unwire: invalid queue %u request for page %p",
2369	    queue, m));
2370	if ((m->oflags & VPO_UNMANAGED) == 0)
2371		vm_page_lock_assert(m, MA_OWNED);
2372	if ((m->flags & PG_FICTITIOUS) != 0) {
2373		KASSERT(m->wire_count == 1,
2374	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2375		return;
2376	}
2377	if (m->wire_count > 0) {
2378		m->wire_count--;
2379		if (m->wire_count == 0) {
2380			atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2381			if ((m->oflags & VPO_UNMANAGED) != 0 ||
2382			    m->object == NULL)
2383				return;
2384			if (queue == PQ_INACTIVE)
2385				m->flags &= ~PG_WINATCFLS;
2386			vm_page_enqueue(queue, m);
2387		}
2388	} else
2389		panic("vm_page_unwire: page %p's wire count is zero", m);
2390}
2391
2392/*
2393 * Move the specified page to the inactive queue.
2394 *
2395 * Many pages placed on the inactive queue should actually go
2396 * into the cache, but it is difficult to figure out which.  What
2397 * we do instead, if the inactive target is well met, is to put
2398 * clean pages at the head of the inactive queue instead of the tail.
2399 * This will cause them to be moved to the cache more quickly and
2400 * if not actively re-referenced, reclaimed more quickly.  If we just
2401 * stick these pages at the end of the inactive queue, heavy filesystem
2402 * meta-data accesses can cause an unnecessary paging load on memory bound
2403 * processes.  This optimization causes one-time-use metadata to be
2404 * reused more quickly.
2405 *
2406 * Normally athead is 0 resulting in LRU operation.  athead is set
2407 * to 1 if we want this page to be 'as if it were placed in the cache',
2408 * except without unmapping it from the process address space.
2409 *
2410 * The page must be locked.
2411 */
2412static inline void
2413_vm_page_deactivate(vm_page_t m, int athead)
2414{
2415	struct vm_pagequeue *pq;
2416	int queue;
2417
2418	vm_page_lock_assert(m, MA_OWNED);
2419
2420	/*
2421	 * Ignore if already inactive.
2422	 */
2423	if ((queue = m->queue) == PQ_INACTIVE)
2424		return;
2425	if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2426		if (queue != PQ_NONE)
2427			vm_page_dequeue(m);
2428		m->flags &= ~PG_WINATCFLS;
2429		pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2430		vm_pagequeue_lock(pq);
2431		m->queue = PQ_INACTIVE;
2432		if (athead)
2433			TAILQ_INSERT_HEAD(&pq->pq_pl, m, plinks.q);
2434		else
2435			TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2436		vm_pagequeue_cnt_inc(pq);
2437		vm_pagequeue_unlock(pq);
2438	}
2439}
2440
2441/*
2442 * Move the specified page to the inactive queue.
2443 *
2444 * The page must be locked.
2445 */
2446void
2447vm_page_deactivate(vm_page_t m)
2448{
2449
2450	_vm_page_deactivate(m, 0);
2451}
2452
2453/*
2454 * vm_page_try_to_cache:
2455 *
2456 * Returns 0 on failure, 1 on success
2457 */
2458int
2459vm_page_try_to_cache(vm_page_t m)
2460{
2461
2462	vm_page_lock_assert(m, MA_OWNED);
2463	VM_OBJECT_ASSERT_WLOCKED(m->object);
2464	if (m->dirty || m->hold_count || m->wire_count ||
2465	    (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2466		return (0);
2467	pmap_remove_all(m);
2468	if (m->dirty)
2469		return (0);
2470	vm_page_cache(m);
2471	return (1);
2472}
2473
2474/*
2475 * vm_page_try_to_free()
2476 *
2477 *	Attempt to free the page.  If we cannot free it, we do nothing.
2478 *	1 is returned on success, 0 on failure.
2479 */
2480int
2481vm_page_try_to_free(vm_page_t m)
2482{
2483
2484	vm_page_lock_assert(m, MA_OWNED);
2485	if (m->object != NULL)
2486		VM_OBJECT_ASSERT_WLOCKED(m->object);
2487	if (m->dirty || m->hold_count || m->wire_count ||
2488	    (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
2489		return (0);
2490	pmap_remove_all(m);
2491	if (m->dirty)
2492		return (0);
2493	vm_page_free(m);
2494	return (1);
2495}
2496
2497/*
2498 * vm_page_cache
2499 *
2500 * Put the specified page onto the page cache queue (if appropriate).
2501 *
2502 * The object and page must be locked.
2503 */
2504void
2505vm_page_cache(vm_page_t m)
2506{
2507	vm_object_t object;
2508	boolean_t cache_was_empty;
2509
2510	vm_page_lock_assert(m, MA_OWNED);
2511	object = m->object;
2512	VM_OBJECT_ASSERT_WLOCKED(object);
2513	if (vm_page_busied(m) || (m->oflags & VPO_UNMANAGED) ||
2514	    m->hold_count || m->wire_count)
2515		panic("vm_page_cache: attempting to cache busy page");
2516	KASSERT(!pmap_page_is_mapped(m),
2517	    ("vm_page_cache: page %p is mapped", m));
2518	KASSERT(m->dirty == 0, ("vm_page_cache: page %p is dirty", m));
2519	if (m->valid == 0 || object->type == OBJT_DEFAULT ||
2520	    (object->type == OBJT_SWAP &&
2521	    !vm_pager_has_page(object, m->pindex, NULL, NULL))) {
2522		/*
2523		 * Hypothesis: A cache-eligible page belonging to a
2524		 * default object or swap object but without a backing
2525		 * store must be zero filled.
2526		 */
2527		vm_page_free(m);
2528		return;
2529	}
2530	KASSERT((m->flags & PG_CACHED) == 0,
2531	    ("vm_page_cache: page %p is already cached", m));
2532
2533	/*
2534	 * Remove the page from the paging queues.
2535	 */
2536	vm_page_remque(m);
2537
2538	/*
2539	 * Remove the page from the object's collection of resident
2540	 * pages.
2541	 */
2542	vm_radix_remove(&object->rtree, m->pindex);
2543	TAILQ_REMOVE(&object->memq, m, listq);
2544	object->resident_page_count--;
2545
2546	/*
2547	 * Restore the default memory attribute to the page.
2548	 */
2549	if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2550		pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2551
2552	/*
2553	 * Insert the page into the object's collection of cached pages
2554	 * and the physical memory allocator's cache/free page queues.
2555	 */
2556	m->flags &= ~PG_ZERO;
2557	mtx_lock(&vm_page_queue_free_mtx);
2558	cache_was_empty = vm_radix_is_empty(&object->cache);
2559	if (vm_radix_insert(&object->cache, m)) {
2560		mtx_unlock(&vm_page_queue_free_mtx);
2561		if (object->resident_page_count == 0)
2562			vdrop(object->handle);
2563		m->object = NULL;
2564		vm_page_free(m);
2565		return;
2566	}
2567
2568	/*
2569	 * The above call to vm_radix_insert() could reclaim the one pre-
2570	 * existing cached page from this object, resulting in a call to
2571	 * vdrop().
2572	 */
2573	if (!cache_was_empty)
2574		cache_was_empty = vm_radix_is_singleton(&object->cache);
2575
2576	m->flags |= PG_CACHED;
2577	vm_cnt.v_cache_count++;
2578	PCPU_INC(cnt.v_tcached);
2579#if VM_NRESERVLEVEL > 0
2580	if (!vm_reserv_free_page(m)) {
2581#else
2582	if (TRUE) {
2583#endif
2584		vm_phys_set_pool(VM_FREEPOOL_CACHE, m, 0);
2585		vm_phys_free_pages(m, 0);
2586	}
2587	vm_page_free_wakeup();
2588	mtx_unlock(&vm_page_queue_free_mtx);
2589
2590	/*
2591	 * Increment the vnode's hold count if this is the object's only
2592	 * cached page.  Decrement the vnode's hold count if this was
2593	 * the object's only resident page.
2594	 */
2595	if (object->type == OBJT_VNODE) {
2596		if (cache_was_empty && object->resident_page_count != 0)
2597			vhold(object->handle);
2598		else if (!cache_was_empty && object->resident_page_count == 0)
2599			vdrop(object->handle);
2600	}
2601}
2602
2603/*
2604 * vm_page_advise
2605 *
2606 *	Cache, deactivate, or do nothing as appropriate.  This routine
2607 *	is used by madvise().
2608 *
2609 *	Generally speaking we want to move the page into the cache so
2610 *	it gets reused quickly.  However, this can result in a silly syndrome
2611 *	due to the page recycling too quickly.  Small objects will not be
2612 *	fully cached.  On the other hand, if we move the page to the inactive
2613 *	queue we wind up with a problem whereby very large objects
2614 *	unnecessarily blow away our inactive and cache queues.
2615 *
2616 *	The solution is to move the pages based on a fixed weighting.  We
2617 *	either leave them alone, deactivate them, or move them to the cache,
2618 *	where moving them to the cache has the highest weighting.
2619 *	By forcing some pages into other queues we eventually force the
2620 *	system to balance the queues, potentially recovering other unrelated
2621 *	space from active.  The idea is to not force this to happen too
2622 *	often.
2623 *
2624 *	The object and page must be locked.
2625 */
2626void
2627vm_page_advise(vm_page_t m, int advice)
2628{
2629	int dnw, head;
2630
2631	vm_page_assert_locked(m);
2632	VM_OBJECT_ASSERT_WLOCKED(m->object);
2633	if (advice == MADV_FREE) {
2634		/*
2635		 * Mark the page clean.  This will allow the page to be freed
2636		 * up by the system.  However, such pages are often reused
2637		 * quickly by malloc() so we do not do anything that would
2638		 * cause a page fault if we can help it.
2639		 *
2640		 * Specifically, we do not try to actually free the page now
2641		 * nor do we try to put it in the cache (which would cause a
2642		 * page fault on reuse).
2643		 *
2644		 * But we do make the page is freeable as we can without
2645		 * actually taking the step of unmapping it.
2646		 */
2647		m->dirty = 0;
2648		m->act_count = 0;
2649	} else if (advice != MADV_DONTNEED)
2650		return;
2651	dnw = PCPU_GET(dnweight);
2652	PCPU_INC(dnweight);
2653
2654	/*
2655	 * Occasionally leave the page alone.
2656	 */
2657	if ((dnw & 0x01F0) == 0 || m->queue == PQ_INACTIVE) {
2658		if (m->act_count >= ACT_INIT)
2659			--m->act_count;
2660		return;
2661	}
2662
2663	/*
2664	 * Clear any references to the page.  Otherwise, the page daemon will
2665	 * immediately reactivate the page.
2666	 */
2667	vm_page_aflag_clear(m, PGA_REFERENCED);
2668
2669	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
2670		vm_page_dirty(m);
2671
2672	if (m->dirty || (dnw & 0x0070) == 0) {
2673		/*
2674		 * Deactivate the page 3 times out of 32.
2675		 */
2676		head = 0;
2677	} else {
2678		/*
2679		 * Cache the page 28 times out of every 32.  Note that
2680		 * the page is deactivated instead of cached, but placed
2681		 * at the head of the queue instead of the tail.
2682		 */
2683		head = 1;
2684	}
2685	_vm_page_deactivate(m, head);
2686}
2687
2688/*
2689 * Grab a page, waiting until we are waken up due to the page
2690 * changing state.  We keep on waiting, if the page continues
2691 * to be in the object.  If the page doesn't exist, first allocate it
2692 * and then conditionally zero it.
2693 *
2694 * This routine may sleep.
2695 *
2696 * The object must be locked on entry.  The lock will, however, be released
2697 * and reacquired if the routine sleeps.
2698 */
2699vm_page_t
2700vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2701{
2702	vm_page_t m;
2703	int sleep;
2704
2705	VM_OBJECT_ASSERT_WLOCKED(object);
2706	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
2707	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
2708	    ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
2709retrylookup:
2710	if ((m = vm_page_lookup(object, pindex)) != NULL) {
2711		sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
2712		    vm_page_xbusied(m) : vm_page_busied(m);
2713		if (sleep) {
2714			if ((allocflags & VM_ALLOC_NOWAIT) != 0)
2715				return (NULL);
2716			/*
2717			 * Reference the page before unlocking and
2718			 * sleeping so that the page daemon is less
2719			 * likely to reclaim it.
2720			 */
2721			vm_page_aflag_set(m, PGA_REFERENCED);
2722			vm_page_lock(m);
2723			VM_OBJECT_WUNLOCK(object);
2724			vm_page_busy_sleep(m, "pgrbwt");
2725			VM_OBJECT_WLOCK(object);
2726			goto retrylookup;
2727		} else {
2728			if ((allocflags & VM_ALLOC_WIRED) != 0) {
2729				vm_page_lock(m);
2730				vm_page_wire(m);
2731				vm_page_unlock(m);
2732			}
2733			if ((allocflags &
2734			    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
2735				vm_page_xbusy(m);
2736			if ((allocflags & VM_ALLOC_SBUSY) != 0)
2737				vm_page_sbusy(m);
2738			return (m);
2739		}
2740	}
2741	m = vm_page_alloc(object, pindex, allocflags);
2742	if (m == NULL) {
2743		if ((allocflags & VM_ALLOC_NOWAIT) != 0)
2744			return (NULL);
2745		VM_OBJECT_WUNLOCK(object);
2746		VM_WAIT;
2747		VM_OBJECT_WLOCK(object);
2748		goto retrylookup;
2749	} else if (m->valid != 0)
2750		return (m);
2751	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
2752		pmap_zero_page(m);
2753	return (m);
2754}
2755
2756/*
2757 * Mapping function for valid or dirty bits in a page.
2758 *
2759 * Inputs are required to range within a page.
2760 */
2761vm_page_bits_t
2762vm_page_bits(int base, int size)
2763{
2764	int first_bit;
2765	int last_bit;
2766
2767	KASSERT(
2768	    base + size <= PAGE_SIZE,
2769	    ("vm_page_bits: illegal base/size %d/%d", base, size)
2770	);
2771
2772	if (size == 0)		/* handle degenerate case */
2773		return (0);
2774
2775	first_bit = base >> DEV_BSHIFT;
2776	last_bit = (base + size - 1) >> DEV_BSHIFT;
2777
2778	return (((vm_page_bits_t)2 << last_bit) -
2779	    ((vm_page_bits_t)1 << first_bit));
2780}
2781
2782/*
2783 *	vm_page_set_valid_range:
2784 *
2785 *	Sets portions of a page valid.  The arguments are expected
2786 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2787 *	of any partial chunks touched by the range.  The invalid portion of
2788 *	such chunks will be zeroed.
2789 *
2790 *	(base + size) must be less then or equal to PAGE_SIZE.
2791 */
2792void
2793vm_page_set_valid_range(vm_page_t m, int base, int size)
2794{
2795	int endoff, frag;
2796
2797	VM_OBJECT_ASSERT_WLOCKED(m->object);
2798	if (size == 0)	/* handle degenerate case */
2799		return;
2800
2801	/*
2802	 * If the base is not DEV_BSIZE aligned and the valid
2803	 * bit is clear, we have to zero out a portion of the
2804	 * first block.
2805	 */
2806	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2807	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
2808		pmap_zero_page_area(m, frag, base - frag);
2809
2810	/*
2811	 * If the ending offset is not DEV_BSIZE aligned and the
2812	 * valid bit is clear, we have to zero out a portion of
2813	 * the last block.
2814	 */
2815	endoff = base + size;
2816	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2817	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
2818		pmap_zero_page_area(m, endoff,
2819		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2820
2821	/*
2822	 * Assert that no previously invalid block that is now being validated
2823	 * is already dirty.
2824	 */
2825	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
2826	    ("vm_page_set_valid_range: page %p is dirty", m));
2827
2828	/*
2829	 * Set valid bits inclusive of any overlap.
2830	 */
2831	m->valid |= vm_page_bits(base, size);
2832}
2833
2834/*
2835 * Clear the given bits from the specified page's dirty field.
2836 */
2837static __inline void
2838vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
2839{
2840	uintptr_t addr;
2841#if PAGE_SIZE < 16384
2842	int shift;
2843#endif
2844
2845	/*
2846	 * If the object is locked and the page is neither exclusive busy nor
2847	 * write mapped, then the page's dirty field cannot possibly be
2848	 * set by a concurrent pmap operation.
2849	 */
2850	VM_OBJECT_ASSERT_WLOCKED(m->object);
2851	if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
2852		m->dirty &= ~pagebits;
2853	else {
2854		/*
2855		 * The pmap layer can call vm_page_dirty() without
2856		 * holding a distinguished lock.  The combination of
2857		 * the object's lock and an atomic operation suffice
2858		 * to guarantee consistency of the page dirty field.
2859		 *
2860		 * For PAGE_SIZE == 32768 case, compiler already
2861		 * properly aligns the dirty field, so no forcible
2862		 * alignment is needed. Only require existence of
2863		 * atomic_clear_64 when page size is 32768.
2864		 */
2865		addr = (uintptr_t)&m->dirty;
2866#if PAGE_SIZE == 32768
2867		atomic_clear_64((uint64_t *)addr, pagebits);
2868#elif PAGE_SIZE == 16384
2869		atomic_clear_32((uint32_t *)addr, pagebits);
2870#else		/* PAGE_SIZE <= 8192 */
2871		/*
2872		 * Use a trick to perform a 32-bit atomic on the
2873		 * containing aligned word, to not depend on the existence
2874		 * of atomic_clear_{8, 16}.
2875		 */
2876		shift = addr & (sizeof(uint32_t) - 1);
2877#if BYTE_ORDER == BIG_ENDIAN
2878		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
2879#else
2880		shift *= NBBY;
2881#endif
2882		addr &= ~(sizeof(uint32_t) - 1);
2883		atomic_clear_32((uint32_t *)addr, pagebits << shift);
2884#endif		/* PAGE_SIZE */
2885	}
2886}
2887
2888/*
2889 *	vm_page_set_validclean:
2890 *
2891 *	Sets portions of a page valid and clean.  The arguments are expected
2892 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2893 *	of any partial chunks touched by the range.  The invalid portion of
2894 *	such chunks will be zero'd.
2895 *
2896 *	(base + size) must be less then or equal to PAGE_SIZE.
2897 */
2898void
2899vm_page_set_validclean(vm_page_t m, int base, int size)
2900{
2901	vm_page_bits_t oldvalid, pagebits;
2902	int endoff, frag;
2903
2904	VM_OBJECT_ASSERT_WLOCKED(m->object);
2905	if (size == 0)	/* handle degenerate case */
2906		return;
2907
2908	/*
2909	 * If the base is not DEV_BSIZE aligned and the valid
2910	 * bit is clear, we have to zero out a portion of the
2911	 * first block.
2912	 */
2913	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2914	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
2915		pmap_zero_page_area(m, frag, base - frag);
2916
2917	/*
2918	 * If the ending offset is not DEV_BSIZE aligned and the
2919	 * valid bit is clear, we have to zero out a portion of
2920	 * the last block.
2921	 */
2922	endoff = base + size;
2923	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2924	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
2925		pmap_zero_page_area(m, endoff,
2926		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
2927
2928	/*
2929	 * Set valid, clear dirty bits.  If validating the entire
2930	 * page we can safely clear the pmap modify bit.  We also
2931	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
2932	 * takes a write fault on a MAP_NOSYNC memory area the flag will
2933	 * be set again.
2934	 *
2935	 * We set valid bits inclusive of any overlap, but we can only
2936	 * clear dirty bits for DEV_BSIZE chunks that are fully within
2937	 * the range.
2938	 */
2939	oldvalid = m->valid;
2940	pagebits = vm_page_bits(base, size);
2941	m->valid |= pagebits;
2942#if 0	/* NOT YET */
2943	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
2944		frag = DEV_BSIZE - frag;
2945		base += frag;
2946		size -= frag;
2947		if (size < 0)
2948			size = 0;
2949	}
2950	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
2951#endif
2952	if (base == 0 && size == PAGE_SIZE) {
2953		/*
2954		 * The page can only be modified within the pmap if it is
2955		 * mapped, and it can only be mapped if it was previously
2956		 * fully valid.
2957		 */
2958		if (oldvalid == VM_PAGE_BITS_ALL)
2959			/*
2960			 * Perform the pmap_clear_modify() first.  Otherwise,
2961			 * a concurrent pmap operation, such as
2962			 * pmap_protect(), could clear a modification in the
2963			 * pmap and set the dirty field on the page before
2964			 * pmap_clear_modify() had begun and after the dirty
2965			 * field was cleared here.
2966			 */
2967			pmap_clear_modify(m);
2968		m->dirty = 0;
2969		m->oflags &= ~VPO_NOSYNC;
2970	} else if (oldvalid != VM_PAGE_BITS_ALL)
2971		m->dirty &= ~pagebits;
2972	else
2973		vm_page_clear_dirty_mask(m, pagebits);
2974}
2975
2976void
2977vm_page_clear_dirty(vm_page_t m, int base, int size)
2978{
2979
2980	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
2981}
2982
2983/*
2984 *	vm_page_set_invalid:
2985 *
2986 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
2987 *	valid and dirty bits for the effected areas are cleared.
2988 */
2989void
2990vm_page_set_invalid(vm_page_t m, int base, int size)
2991{
2992	vm_page_bits_t bits;
2993	vm_object_t object;
2994
2995	object = m->object;
2996	VM_OBJECT_ASSERT_WLOCKED(object);
2997	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
2998	    size >= object->un_pager.vnp.vnp_size)
2999		bits = VM_PAGE_BITS_ALL;
3000	else
3001		bits = vm_page_bits(base, size);
3002	if (m->valid == VM_PAGE_BITS_ALL && bits != 0)
3003		pmap_remove_all(m);
3004	KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3005	    !pmap_page_is_mapped(m),
3006	    ("vm_page_set_invalid: page %p is mapped", m));
3007	m->valid &= ~bits;
3008	m->dirty &= ~bits;
3009}
3010
3011/*
3012 * vm_page_zero_invalid()
3013 *
3014 *	The kernel assumes that the invalid portions of a page contain
3015 *	garbage, but such pages can be mapped into memory by user code.
3016 *	When this occurs, we must zero out the non-valid portions of the
3017 *	page so user code sees what it expects.
3018 *
3019 *	Pages are most often semi-valid when the end of a file is mapped
3020 *	into memory and the file's size is not page aligned.
3021 */
3022void
3023vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3024{
3025	int b;
3026	int i;
3027
3028	VM_OBJECT_ASSERT_WLOCKED(m->object);
3029	/*
3030	 * Scan the valid bits looking for invalid sections that
3031	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
3032	 * valid bit may be set ) have already been zerod by
3033	 * vm_page_set_validclean().
3034	 */
3035	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3036		if (i == (PAGE_SIZE / DEV_BSIZE) ||
3037		    (m->valid & ((vm_page_bits_t)1 << i))) {
3038			if (i > b) {
3039				pmap_zero_page_area(m,
3040				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3041			}
3042			b = i + 1;
3043		}
3044	}
3045
3046	/*
3047	 * setvalid is TRUE when we can safely set the zero'd areas
3048	 * as being valid.  We can do this if there are no cache consistancy
3049	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
3050	 */
3051	if (setvalid)
3052		m->valid = VM_PAGE_BITS_ALL;
3053}
3054
3055/*
3056 *	vm_page_is_valid:
3057 *
3058 *	Is (partial) page valid?  Note that the case where size == 0
3059 *	will return FALSE in the degenerate case where the page is
3060 *	entirely invalid, and TRUE otherwise.
3061 */
3062int
3063vm_page_is_valid(vm_page_t m, int base, int size)
3064{
3065	vm_page_bits_t bits;
3066
3067	VM_OBJECT_ASSERT_LOCKED(m->object);
3068	bits = vm_page_bits(base, size);
3069	return (m->valid != 0 && (m->valid & bits) == bits);
3070}
3071
3072/*
3073 *	vm_page_ps_is_valid:
3074 *
3075 *	Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3076 */
3077boolean_t
3078vm_page_ps_is_valid(vm_page_t m)
3079{
3080	int i, npages;
3081
3082	VM_OBJECT_ASSERT_LOCKED(m->object);
3083	npages = atop(pagesizes[m->psind]);
3084
3085	/*
3086	 * The physically contiguous pages that make up a superpage, i.e., a
3087	 * page with a page size index ("psind") greater than zero, will
3088	 * occupy adjacent entries in vm_page_array[].
3089	 */
3090	for (i = 0; i < npages; i++) {
3091		if (m[i].valid != VM_PAGE_BITS_ALL)
3092			return (FALSE);
3093	}
3094	return (TRUE);
3095}
3096
3097/*
3098 * Set the page's dirty bits if the page is modified.
3099 */
3100void
3101vm_page_test_dirty(vm_page_t m)
3102{
3103
3104	VM_OBJECT_ASSERT_WLOCKED(m->object);
3105	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3106		vm_page_dirty(m);
3107}
3108
3109void
3110vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3111{
3112
3113	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3114}
3115
3116void
3117vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3118{
3119
3120	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3121}
3122
3123int
3124vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3125{
3126
3127	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3128}
3129
3130#if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3131void
3132vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3133{
3134
3135	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3136}
3137
3138void
3139vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3140{
3141
3142	mtx_assert_(vm_page_lockptr(m), a, file, line);
3143}
3144#endif
3145
3146#ifdef INVARIANTS
3147void
3148vm_page_object_lock_assert(vm_page_t m)
3149{
3150
3151	/*
3152	 * Certain of the page's fields may only be modified by the
3153	 * holder of the containing object's lock or the exclusive busy.
3154	 * holder.  Unfortunately, the holder of the write busy is
3155	 * not recorded, and thus cannot be checked here.
3156	 */
3157	if (m->object != NULL && !vm_page_xbusied(m))
3158		VM_OBJECT_ASSERT_WLOCKED(m->object);
3159}
3160
3161void
3162vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3163{
3164
3165	if ((bits & PGA_WRITEABLE) == 0)
3166		return;
3167
3168	/*
3169	 * The PGA_WRITEABLE flag can only be set if the page is
3170	 * managed, is exclusively busied or the object is locked.
3171	 * Currently, this flag is only set by pmap_enter().
3172	 */
3173	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3174	    ("PGA_WRITEABLE on unmanaged page"));
3175	if (!vm_page_xbusied(m))
3176		VM_OBJECT_ASSERT_LOCKED(m->object);
3177}
3178#endif
3179
3180#include "opt_ddb.h"
3181#ifdef DDB
3182#include <sys/kernel.h>
3183
3184#include <ddb/ddb.h>
3185
3186DB_SHOW_COMMAND(page, vm_page_print_page_info)
3187{
3188	db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3189	db_printf("vm_cnt.v_cache_count: %d\n", vm_cnt.v_cache_count);
3190	db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3191	db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3192	db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3193	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3194	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3195	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3196	db_printf("vm_cnt.v_cache_min: %d\n", vm_cnt.v_cache_min);
3197	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3198}
3199
3200DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3201{
3202	int dom;
3203
3204	db_printf("pq_free %d pq_cache %d\n",
3205	    vm_cnt.v_free_count, vm_cnt.v_cache_count);
3206	for (dom = 0; dom < vm_ndomains; dom++) {
3207		db_printf(
3208	"dom %d page_cnt %d free %d pq_act %d pq_inact %d pass %d\n",
3209		    dom,
3210		    vm_dom[dom].vmd_page_count,
3211		    vm_dom[dom].vmd_free_count,
3212		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3213		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3214		    vm_dom[dom].vmd_pass);
3215	}
3216}
3217
3218DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3219{
3220	vm_page_t m;
3221	boolean_t phys;
3222
3223	if (!have_addr) {
3224		db_printf("show pginfo addr\n");
3225		return;
3226	}
3227
3228	phys = strchr(modif, 'p') != NULL;
3229	if (phys)
3230		m = PHYS_TO_VM_PAGE(addr);
3231	else
3232		m = (vm_page_t)addr;
3233	db_printf(
3234    "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3235    "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3236	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3237	    m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3238	    m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);
3239}
3240#endif /* DDB */
3241