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