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